]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Controller/ConfigController.php
Merge pull request #4151 from ldidry/fix-4060
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Controller / ConfigController.php
1 <?php
2
3 namespace Wallabag\CoreBundle\Controller;
4
5 use JMS\Serializer\SerializationContext;
6 use JMS\Serializer\SerializerBuilder;
7 use PragmaRX\Recovery\Recovery as BackupCodes;
8 use Symfony\Bundle\FrameworkBundle\Controller\Controller;
9 use Symfony\Component\HttpFoundation\JsonResponse;
10 use Symfony\Component\HttpFoundation\RedirectResponse;
11 use Symfony\Component\HttpFoundation\Request;
12 use Symfony\Component\HttpFoundation\Response;
13 use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
14 use Symfony\Component\Routing\Annotation\Route;
15 use Symfony\Component\Validator\Constraints\Locale as LocaleConstraint;
16 use Wallabag\CoreBundle\Entity\Config;
17 use Wallabag\CoreBundle\Entity\TaggingRule;
18 use Wallabag\CoreBundle\Form\Type\ChangePasswordType;
19 use Wallabag\CoreBundle\Form\Type\ConfigType;
20 use Wallabag\CoreBundle\Form\Type\FeedType;
21 use Wallabag\CoreBundle\Form\Type\TaggingRuleImportType;
22 use Wallabag\CoreBundle\Form\Type\TaggingRuleType;
23 use Wallabag\CoreBundle\Form\Type\UserInformationType;
24 use Wallabag\CoreBundle\Tools\Utils;
25
26 class ConfigController extends Controller
27 {
28 /**
29 * @Route("/config", name="config")
30 */
31 public function indexAction(Request $request)
32 {
33 $em = $this->getDoctrine()->getManager();
34 $config = $this->getConfig();
35 $userManager = $this->container->get('fos_user.user_manager');
36 $user = $this->getUser();
37
38 // handle basic config detail (this form is defined as a service)
39 $configForm = $this->createForm(ConfigType::class, $config, ['action' => $this->generateUrl('config')]);
40 $configForm->handleRequest($request);
41
42 if ($configForm->isSubmitted() && $configForm->isValid()) {
43 $em->persist($config);
44 $em->flush();
45
46 $request->getSession()->set('_locale', $config->getLanguage());
47
48 // switch active theme
49 $activeTheme = $this->get('liip_theme.active_theme');
50 $activeTheme->setName($config->getTheme());
51
52 $this->addFlash(
53 'notice',
54 'flashes.config.notice.config_saved'
55 );
56
57 return $this->redirect($this->generateUrl('config'));
58 }
59
60 // handle changing password
61 $pwdForm = $this->createForm(ChangePasswordType::class, null, ['action' => $this->generateUrl('config') . '#set4']);
62 $pwdForm->handleRequest($request);
63
64 if ($pwdForm->isSubmitted() && $pwdForm->isValid()) {
65 if ($this->get('craue_config')->get('demo_mode_enabled') && $this->get('craue_config')->get('demo_mode_username') === $user->getUsername()) {
66 $message = 'flashes.config.notice.password_not_updated_demo';
67 } else {
68 $message = 'flashes.config.notice.password_updated';
69
70 $user->setPlainPassword($pwdForm->get('new_password')->getData());
71 $userManager->updateUser($user, true);
72 }
73
74 $this->addFlash('notice', $message);
75
76 return $this->redirect($this->generateUrl('config') . '#set4');
77 }
78
79 // handle changing user information
80 $userForm = $this->createForm(UserInformationType::class, $user, [
81 'validation_groups' => ['Profile'],
82 'action' => $this->generateUrl('config') . '#set3',
83 ]);
84 $userForm->handleRequest($request);
85
86 if ($userForm->isSubmitted() && $userForm->isValid()) {
87 $userManager->updateUser($user, true);
88
89 $this->addFlash(
90 'notice',
91 'flashes.config.notice.user_updated'
92 );
93
94 return $this->redirect($this->generateUrl('config') . '#set3');
95 }
96
97 // handle feed information
98 $feedForm = $this->createForm(FeedType::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
99 $feedForm->handleRequest($request);
100
101 if ($feedForm->isSubmitted() && $feedForm->isValid()) {
102 $em->persist($config);
103 $em->flush();
104
105 $this->addFlash(
106 'notice',
107 'flashes.config.notice.feed_updated'
108 );
109
110 return $this->redirect($this->generateUrl('config') . '#set2');
111 }
112
113 // handle tagging rule
114 $taggingRule = new TaggingRule();
115 $action = $this->generateUrl('config') . '#set5';
116
117 if ($request->query->has('tagging-rule')) {
118 $taggingRule = $this->getDoctrine()
119 ->getRepository('WallabagCoreBundle:TaggingRule')
120 ->find($request->query->get('tagging-rule'));
121
122 if ($this->getUser()->getId() !== $taggingRule->getConfig()->getUser()->getId()) {
123 return $this->redirect($action);
124 }
125
126 $action = $this->generateUrl('config') . '?tagging-rule=' . $taggingRule->getId() . '#set5';
127 }
128
129 $newTaggingRule = $this->createForm(TaggingRuleType::class, $taggingRule, ['action' => $action]);
130 $newTaggingRule->handleRequest($request);
131
132 if ($newTaggingRule->isSubmitted() && $newTaggingRule->isValid()) {
133 $taggingRule->setConfig($config);
134 $em->persist($taggingRule);
135 $em->flush();
136
137 $this->addFlash(
138 'notice',
139 'flashes.config.notice.tagging_rules_updated'
140 );
141
142 return $this->redirect($this->generateUrl('config') . '#set5');
143 }
144
145 // handle tagging rules import
146 $taggingRulesImportform = $this->createForm(TaggingRuleImportType::class);
147 $taggingRulesImportform->handleRequest($request);
148
149 if ($taggingRulesImportform->isSubmitted() && $taggingRulesImportform->isValid()) {
150 $message = 'flashes.config.notice.tagging_rules_not_imported';
151 $file = $taggingRulesImportform->get('file')->getData();
152
153 if (null !== $file && $file->isValid() && \in_array($file->getClientMimeType(), ['application/json', 'application/octet-stream'], true)) {
154 $content = json_decode(file_get_contents($file->getPathname()), true);
155
156 if (\is_array($content)) {
157 foreach ($content as $rule) {
158 $taggingRule = new TaggingRule();
159 $taggingRule->setRule($rule['rule']);
160 $taggingRule->setTags($rule['tags']);
161 $taggingRule->setConfig($config);
162 $em->persist($taggingRule);
163 }
164
165 $em->flush();
166
167 $message = 'flashes.config.notice.tagging_rules_imported';
168 }
169 }
170
171 $this->addFlash('notice', $message);
172
173 return $this->redirect($this->generateUrl('config') . '#set5');
174 }
175
176 return $this->render('WallabagCoreBundle:Config:index.html.twig', [
177 'form' => [
178 'config' => $configForm->createView(),
179 'feed' => $feedForm->createView(),
180 'pwd' => $pwdForm->createView(),
181 'user' => $userForm->createView(),
182 'new_tagging_rule' => $newTaggingRule->createView(),
183 'import_tagging_rule' => $taggingRulesImportform->createView(),
184 ],
185 'feed' => [
186 'username' => $user->getUsername(),
187 'token' => $config->getFeedToken(),
188 ],
189 'twofactor_auth' => $this->getParameter('twofactor_auth'),
190 'wallabag_url' => $this->getParameter('domain_name'),
191 'enabled_users' => $this->get('wallabag_user.user_repository')->getSumEnabledUsers(),
192 ]);
193 }
194
195 /**
196 * Enable 2FA using email.
197 *
198 * @Route("/config/otp/email", name="config_otp_email")
199 */
200 public function otpEmailAction()
201 {
202 if (!$this->getParameter('twofactor_auth')) {
203 return $this->createNotFoundException('two_factor not enabled');
204 }
205
206 $user = $this->getUser();
207
208 $user->setGoogleAuthenticatorSecret(null);
209 $user->setBackupCodes(null);
210 $user->setEmailTwoFactor(true);
211
212 $this->container->get('fos_user.user_manager')->updateUser($user, true);
213
214 $this->addFlash(
215 'notice',
216 'flashes.config.notice.otp_enabled'
217 );
218
219 return $this->redirect($this->generateUrl('config') . '#set3');
220 }
221
222 /**
223 * Enable 2FA using OTP app, user will need to confirm the generated code from the app.
224 *
225 * @Route("/config/otp/app", name="config_otp_app")
226 */
227 public function otpAppAction()
228 {
229 if (!$this->getParameter('twofactor_auth')) {
230 return $this->createNotFoundException('two_factor not enabled');
231 }
232
233 $user = $this->getUser();
234 $secret = $this->get('scheb_two_factor.security.google_authenticator')->generateSecret();
235
236 $user->setGoogleAuthenticatorSecret($secret);
237 $user->setEmailTwoFactor(false);
238
239 $backupCodes = (new BackupCodes())->toArray();
240 $backupCodesHashed = array_map(
241 function ($backupCode) {
242 return password_hash($backupCode, PASSWORD_DEFAULT);
243 },
244 $backupCodes
245 );
246
247 $user->setBackupCodes($backupCodesHashed);
248
249 $this->container->get('fos_user.user_manager')->updateUser($user, true);
250
251 return $this->render('WallabagCoreBundle:Config:otp_app.html.twig', [
252 'backupCodes' => $backupCodes,
253 'qr_code' => $this->get('scheb_two_factor.security.google_authenticator')->getQRContent($user),
254 ]);
255 }
256
257 /**
258 * Cancelling 2FA using OTP app.
259 *
260 * @Route("/config/otp/app/cancel", name="config_otp_app_cancel")
261 */
262 public function otpAppCancelAction()
263 {
264 if (!$this->getParameter('twofactor_auth')) {
265 return $this->createNotFoundException('two_factor not enabled');
266 }
267
268 $user = $this->getUser();
269 $user->setGoogleAuthenticatorSecret(null);
270 $user->setBackupCodes(null);
271
272 $this->container->get('fos_user.user_manager')->updateUser($user, true);
273
274 return $this->redirect($this->generateUrl('config') . '#set3');
275 }
276
277 /**
278 * Validate OTP code.
279 *
280 * @Route("/config/otp/app/check", name="config_otp_app_check")
281 */
282 public function otpAppCheckAction(Request $request)
283 {
284 $isValid = $this->get('scheb_two_factor.security.google_authenticator')->checkCode(
285 $this->getUser(),
286 $request->get('_auth_code')
287 );
288
289 if (true === $isValid) {
290 $this->addFlash(
291 'notice',
292 'flashes.config.notice.otp_enabled'
293 );
294
295 return $this->redirect($this->generateUrl('config') . '#set3');
296 }
297
298 $this->addFlash(
299 'two_factor',
300 'scheb_two_factor.code_invalid'
301 );
302
303 return $this->redirect($this->generateUrl('config_otp_app'));
304 }
305
306 /**
307 * @Route("/generate-token", name="generate_token")
308 *
309 * @return RedirectResponse|JsonResponse
310 */
311 public function generateTokenAction(Request $request)
312 {
313 $config = $this->getConfig();
314 $config->setFeedToken(Utils::generateToken());
315
316 $em = $this->getDoctrine()->getManager();
317 $em->persist($config);
318 $em->flush();
319
320 if ($request->isXmlHttpRequest()) {
321 return new JsonResponse(['token' => $config->getFeedToken()]);
322 }
323
324 $this->addFlash(
325 'notice',
326 'flashes.config.notice.feed_token_updated'
327 );
328
329 return $this->redirect($this->generateUrl('config') . '#set2');
330 }
331
332 /**
333 * @Route("/revoke-token", name="revoke_token")
334 *
335 * @return RedirectResponse|JsonResponse
336 */
337 public function revokeTokenAction(Request $request)
338 {
339 $config = $this->getConfig();
340 $config->setFeedToken(null);
341
342 $em = $this->getDoctrine()->getManager();
343 $em->persist($config);
344 $em->flush();
345
346 if ($request->isXmlHttpRequest()) {
347 return new JsonResponse();
348 }
349
350 $this->addFlash(
351 'notice',
352 'flashes.config.notice.feed_token_revoked'
353 );
354
355 return $this->redirect($this->generateUrl('config') . '#set2');
356 }
357
358 /**
359 * Deletes a tagging rule and redirect to the config homepage.
360 *
361 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
362 *
363 * @return RedirectResponse
364 */
365 public function deleteTaggingRuleAction(TaggingRule $rule)
366 {
367 $this->validateRuleAction($rule);
368
369 $em = $this->getDoctrine()->getManager();
370 $em->remove($rule);
371 $em->flush();
372
373 $this->addFlash(
374 'notice',
375 'flashes.config.notice.tagging_rules_deleted'
376 );
377
378 return $this->redirect($this->generateUrl('config') . '#set5');
379 }
380
381 /**
382 * Edit a tagging rule.
383 *
384 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
385 *
386 * @return RedirectResponse
387 */
388 public function editTaggingRuleAction(TaggingRule $rule)
389 {
390 $this->validateRuleAction($rule);
391
392 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
393 }
394
395 /**
396 * Remove all annotations OR tags OR entries for the current user.
397 *
398 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
399 *
400 * @return RedirectResponse
401 */
402 public function resetAction($type)
403 {
404 switch ($type) {
405 case 'annotations':
406 $this->getDoctrine()
407 ->getRepository('WallabagAnnotationBundle:Annotation')
408 ->removeAllByUserId($this->getUser()->getId());
409 break;
410 case 'tags':
411 $this->removeAllTagsByUserId($this->getUser()->getId());
412 break;
413 case 'entries':
414 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
415 // otherwise they won't be removed ...
416 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
417 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
418 }
419
420 // manually remove tags to avoid orphan tag
421 $this->removeAllTagsByUserId($this->getUser()->getId());
422
423 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
424 break;
425 case 'archived':
426 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
427 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
428 }
429
430 // manually remove tags to avoid orphan tag
431 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
432
433 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
434 break;
435 }
436
437 $this->addFlash(
438 'notice',
439 'flashes.config.notice.' . $type . '_reset'
440 );
441
442 return $this->redirect($this->generateUrl('config') . '#set3');
443 }
444
445 /**
446 * Delete account for current user.
447 *
448 * @Route("/account/delete", name="delete_account")
449 *
450 * @throws AccessDeniedHttpException
451 *
452 * @return \Symfony\Component\HttpFoundation\RedirectResponse
453 */
454 public function deleteAccountAction(Request $request)
455 {
456 $enabledUsers = $this->get('wallabag_user.user_repository')
457 ->getSumEnabledUsers();
458
459 if ($enabledUsers <= 1) {
460 throw new AccessDeniedHttpException();
461 }
462
463 $user = $this->getUser();
464
465 // logout current user
466 $this->get('security.token_storage')->setToken(null);
467 $request->getSession()->invalidate();
468
469 $em = $this->get('fos_user.user_manager');
470 $em->deleteUser($user);
471
472 return $this->redirect($this->generateUrl('fos_user_security_login'));
473 }
474
475 /**
476 * Switch view mode for current user.
477 *
478 * @Route("/config/view-mode", name="switch_view_mode")
479 *
480 * @return \Symfony\Component\HttpFoundation\RedirectResponse
481 */
482 public function changeViewModeAction(Request $request)
483 {
484 $user = $this->getUser();
485 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
486
487 $em = $this->getDoctrine()->getManager();
488 $em->persist($user);
489 $em->flush();
490
491 return $this->redirect($request->headers->get('referer'));
492 }
493
494 /**
495 * Change the locale for the current user.
496 *
497 * @param string $language
498 *
499 * @Route("/locale/{language}", name="changeLocale")
500 *
501 * @return \Symfony\Component\HttpFoundation\RedirectResponse
502 */
503 public function setLocaleAction(Request $request, $language = null)
504 {
505 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
506
507 if (0 === \count($errors)) {
508 $request->getSession()->set('_locale', $language);
509 }
510
511 return $this->redirect($request->headers->get('referer', $this->generateUrl('homepage')));
512 }
513
514 /**
515 * Export tagging rules for the logged in user.
516 *
517 * @Route("/tagging-rule/export", name="export_tagging_rule")
518 *
519 * @return Response
520 */
521 public function exportTaggingRulesAction()
522 {
523 $data = SerializerBuilder::create()->build()->serialize(
524 $this->getUser()->getConfig()->getTaggingRules(),
525 'json',
526 SerializationContext::create()->setGroups(['export_tagging_rule'])
527 );
528
529 return Response::create(
530 $data,
531 200,
532 [
533 'Content-type' => 'application/json',
534 'Content-Disposition' => 'attachment; filename="tagging_rules_' . $this->getUser()->getUsername() . '.json"',
535 'Content-Transfer-Encoding' => 'UTF-8',
536 ]
537 );
538 }
539
540 /**
541 * Remove all tags for given tags and a given user and cleanup orphan tags.
542 *
543 * @param array $tags
544 * @param int $userId
545 */
546 private function removeAllTagsByStatusAndUserId($tags, $userId)
547 {
548 if (empty($tags)) {
549 return;
550 }
551
552 $this->get('wallabag_core.entry_repository')
553 ->removeTags($userId, $tags);
554
555 // cleanup orphan tags
556 $em = $this->getDoctrine()->getManager();
557
558 foreach ($tags as $tag) {
559 if (0 === \count($tag->getEntries())) {
560 $em->remove($tag);
561 }
562 }
563
564 $em->flush();
565 }
566
567 /**
568 * Remove all tags for a given user and cleanup orphan tags.
569 *
570 * @param int $userId
571 */
572 private function removeAllTagsByUserId($userId)
573 {
574 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
575 $this->removeAllTagsByStatusAndUserId($tags, $userId);
576 }
577
578 /**
579 * Remove all tags for a given user and cleanup orphan tags.
580 *
581 * @param int $userId
582 */
583 private function removeTagsForArchivedByUserId($userId)
584 {
585 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
586 $this->removeAllTagsByStatusAndUserId($tags, $userId);
587 }
588
589 private function removeAnnotationsForArchivedByUserId($userId)
590 {
591 $em = $this->getDoctrine()->getManager();
592
593 $archivedEntriesAnnotations = $this->getDoctrine()
594 ->getRepository('WallabagAnnotationBundle:Annotation')
595 ->findAllArchivedEntriesByUser($userId);
596
597 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
598 $em->remove($archivedEntriesAnnotation);
599 }
600
601 $em->flush();
602 }
603
604 /**
605 * Validate that a rule can be edited/deleted by the current user.
606 */
607 private function validateRuleAction(TaggingRule $rule)
608 {
609 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
610 throw $this->createAccessDeniedException('You can not access this tagging rule.');
611 }
612 }
613
614 /**
615 * Retrieve config for the current user.
616 * If no config were found, create a new one.
617 *
618 * @return Config
619 */
620 private function getConfig()
621 {
622 $config = $this->getDoctrine()
623 ->getRepository('WallabagCoreBundle:Config')
624 ->findOneByUser($this->getUser());
625
626 // should NEVER HAPPEN ...
627 if (!$config) {
628 $config = new Config($this->getUser());
629 }
630
631 return $config;
632 }
633 }