3 namespace Wallabag\CoreBundle\Controller
;
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\IgnoreOriginUserRule
;
18 use Wallabag\CoreBundle\Entity\RuleInterface
;
19 use Wallabag\CoreBundle\Entity\TaggingRule
;
20 use Wallabag\CoreBundle\Form\Type\ChangePasswordType
;
21 use Wallabag\CoreBundle\Form\Type\ConfigType
;
22 use Wallabag\CoreBundle\Form\Type\FeedType
;
23 use Wallabag\CoreBundle\Form\Type\IgnoreOriginUserRuleType
;
24 use Wallabag\CoreBundle\Form\Type\TaggingRuleImportType
;
25 use Wallabag\CoreBundle\Form\Type\TaggingRuleType
;
26 use Wallabag\CoreBundle\Form\Type\UserInformationType
;
27 use Wallabag\CoreBundle\Tools\Utils
;
29 class ConfigController
extends Controller
32 * @Route("/config", name="config")
34 public function indexAction(Request
$request)
36 $em = $this->getDoctrine()->getManager();
37 $config = $this->getConfig();
38 $userManager = $this->container
->get('fos_user.user_manager');
39 $user = $this->getUser();
41 // handle basic config detail (this form is defined as a service)
42 $configForm = $this->createForm(ConfigType
::class, $config, ['action' => $this->generateUrl('config')]);
43 $configForm->handleRequest($request);
45 if ($configForm->isSubmitted() && $configForm->isValid()) {
46 $em->persist($config);
49 $request->getSession()->set('_locale', $config->getLanguage());
51 // switch active theme
52 $activeTheme = $this->get('liip_theme.active_theme');
53 $activeTheme->setName($config->getTheme());
57 'flashes.config.notice.config_saved'
60 return $this->redirect($this->generateUrl('config'));
63 // handle changing password
64 $pwdForm = $this->createForm(ChangePasswordType
::class, null, ['action' => $this->generateUrl('config') . '#set4']);
65 $pwdForm->handleRequest($request);
67 if ($pwdForm->isSubmitted() && $pwdForm->isValid()) {
68 if ($this->get('craue_config')->get('demo_mode_enabled') && $this->get('craue_config')->get('demo_mode_username') === $user->getUsername()) {
69 $message = 'flashes.config.notice.password_not_updated_demo';
71 $message = 'flashes.config.notice.password_updated';
73 $user->setPlainPassword($pwdForm->get('new_password')->getData());
74 $userManager->updateUser($user, true);
77 $this->addFlash('notice', $message);
79 return $this->redirect($this->generateUrl('config') . '#set4');
82 // handle changing user information
83 $userForm = $this->createForm(UserInformationType
::class, $user, [
84 'validation_groups' => ['Profile'],
85 'action' => $this->generateUrl('config') . '#set3',
87 $userForm->handleRequest($request);
89 if ($userForm->isSubmitted() && $userForm->isValid()) {
90 $userManager->updateUser($user, true);
94 'flashes.config.notice.user_updated'
97 return $this->redirect($this->generateUrl('config') . '#set3');
100 // handle feed information
101 $feedForm = $this->createForm(FeedType
::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
102 $feedForm->handleRequest($request);
104 if ($feedForm->isSubmitted() && $feedForm->isValid()) {
105 $em->persist($config);
110 'flashes.config.notice.feed_updated'
113 return $this->redirect($this->generateUrl('config') . '#set2');
116 // handle tagging rule
117 $taggingRule = new TaggingRule();
118 $action = $this->generateUrl('config') . '#set5';
120 if ($request->query
->has('tagging-rule')) {
121 $taggingRule = $this->getDoctrine()
122 ->getRepository('WallabagCoreBundle:TaggingRule')
123 ->find($request->query
->get('tagging-rule'));
125 if ($this->getUser()->getId() !== $taggingRule->getConfig()->getUser()->getId()) {
126 return $this->redirect($action);
129 $action = $this->generateUrl('config') . '?tagging-rule=' . $taggingRule->getId() . '#set5';
132 $newTaggingRule = $this->createForm(TaggingRuleType
::class, $taggingRule, ['action' => $action]);
133 $newTaggingRule->handleRequest($request);
135 if ($newTaggingRule->isSubmitted() && $newTaggingRule->isValid()) {
136 $taggingRule->setConfig($config);
137 $em->persist($taggingRule);
142 'flashes.config.notice.tagging_rules_updated'
145 return $this->redirect($this->generateUrl('config') . '#set5');
148 // handle tagging rules import
149 $taggingRulesImportform = $this->createForm(TaggingRuleImportType
::class);
150 $taggingRulesImportform->handleRequest($request);
152 if ($taggingRulesImportform->isSubmitted() && $taggingRulesImportform->isValid()) {
153 $message = 'flashes.config.notice.tagging_rules_not_imported';
154 $file = $taggingRulesImportform->get('file')->getData();
156 if (null !== $file && $file->isValid() && \
in_array($file->getClientMimeType(), ['application/json', 'application/octet-stream'], true)) {
157 $content = json_decode(file_get_contents($file->getPathname()), true);
159 if (\
is_array($content)) {
160 foreach ($content as $rule) {
161 $taggingRule = new TaggingRule();
162 $taggingRule->setRule($rule['rule']);
163 $taggingRule->setTags($rule['tags']);
164 $taggingRule->setConfig($config);
165 $em->persist($taggingRule);
170 $message = 'flashes.config.notice.tagging_rules_imported';
174 $this->addFlash('notice', $message);
176 return $this->redirect($this->generateUrl('config') . '#set5');
179 // handle ignore origin rules
180 $ignoreOriginUserRule = new IgnoreOriginUserRule();
181 $action = $this->generateUrl('config') . '#set6';
183 if ($request->query
->has('ignore-origin-user-rule')) {
184 $ignoreOriginUserRule = $this->getDoctrine()
185 ->getRepository('WallabagCoreBundle:IgnoreOriginUserRule')
186 ->find($request->query
->get('ignore-origin-user-rule'));
188 if ($this->getUser()->getId() !== $ignoreOriginUserRule->getConfig()->getUser()->getId()) {
189 return $this->redirect($action);
192 $action = $this->generateUrl('config', [
193 'ignore-origin-user-rule' => $ignoreOriginUserRule->getId(),
197 $newIgnoreOriginUserRule = $this->createForm(IgnoreOriginUserRuleType
::class, $ignoreOriginUserRule, ['action' => $action]);
198 $newIgnoreOriginUserRule->handleRequest($request);
200 if ($newIgnoreOriginUserRule->isSubmitted() && $newIgnoreOriginUserRule->isValid()) {
201 $ignoreOriginUserRule->setConfig($config);
202 $em->persist($ignoreOriginUserRule);
207 'flashes.config.notice.ignore_origin_rules_updated'
210 return $this->redirect($this->generateUrl('config') . '#set6');
213 return $this->render('WallabagCoreBundle:Config:index.html.twig', [
215 'config' => $configForm->createView(),
216 'feed' => $feedForm->createView(),
217 'pwd' => $pwdForm->createView(),
218 'user' => $userForm->createView(),
219 'new_tagging_rule' => $newTaggingRule->createView(),
220 'import_tagging_rule' => $taggingRulesImportform->createView(),
221 'new_ignore_origin_user_rule' => $newIgnoreOriginUserRule->createView(),
224 'username' => $user->getUsername(),
225 'token' => $config->getFeedToken(),
227 'twofactor_auth' => $this->getParameter('twofactor_auth'),
228 'wallabag_url' => $this->getParameter('domain_name'),
229 'enabled_users' => $this->get('wallabag_user.user_repository')->getSumEnabledUsers(),
234 * Disable 2FA using email.
236 * @Route("/config/otp/email/disable", name="disable_otp_email")
238 public function disableOtpEmailAction()
240 if (!$this->getParameter('twofactor_auth')) {
241 return $this->createNotFoundException('two_factor not enabled');
244 $user = $this->getUser();
245 $user->setEmailTwoFactor(false);
247 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
251 'flashes.config.notice.otp_disabled'
254 return $this->redirect($this->generateUrl('config') . '#set3');
258 * Enable 2FA using email.
260 * @Route("/config/otp/email", name="config_otp_email")
262 public function otpEmailAction()
264 if (!$this->getParameter('twofactor_auth')) {
265 return $this->createNotFoundException('two_factor not enabled');
268 $user = $this->getUser();
270 $user->setGoogleAuthenticatorSecret(null);
271 $user->setBackupCodes(null);
272 $user->setEmailTwoFactor(true);
274 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
278 'flashes.config.notice.otp_enabled'
281 return $this->redirect($this->generateUrl('config') . '#set3');
285 * Disable 2FA using OTP app.
287 * @Route("/config/otp/app/disable", name="disable_otp_app")
289 public function disableOtpAppAction()
291 if (!$this->getParameter('twofactor_auth')) {
292 return $this->createNotFoundException('two_factor not enabled');
295 $user = $this->getUser();
297 $user->setGoogleAuthenticatorSecret('');
298 $user->setBackupCodes(null);
300 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
304 'flashes.config.notice.otp_disabled'
307 return $this->redirect($this->generateUrl('config') . '#set3');
311 * Enable 2FA using OTP app, user will need to confirm the generated code from the app.
313 * @Route("/config/otp/app", name="config_otp_app")
315 public function otpAppAction()
317 if (!$this->getParameter('twofactor_auth')) {
318 return $this->createNotFoundException('two_factor not enabled');
321 $user = $this->getUser();
322 $secret = $this->get('scheb_two_factor.security.google_authenticator')->generateSecret();
324 $user->setGoogleAuthenticatorSecret($secret);
325 $user->setEmailTwoFactor(false);
327 $backupCodes = (new BackupCodes())->toArray();
328 $backupCodesHashed = array_map(
329 function ($backupCode) {
330 return password_hash($backupCode, PASSWORD_DEFAULT
);
335 $user->setBackupCodes($backupCodesHashed);
337 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
341 'flashes.config.notice.otp_enabled'
344 return $this->render('WallabagCoreBundle:Config:otp_app.html.twig', [
345 'backupCodes' => $backupCodes,
346 'qr_code' => $this->get('scheb_two_factor.security.google_authenticator')->getQRContent($user),
351 * Cancelling 2FA using OTP app.
353 * @Route("/config/otp/app/cancel", name="config_otp_app_cancel")
355 public function otpAppCancelAction()
357 if (!$this->getParameter('twofactor_auth')) {
358 return $this->createNotFoundException('two_factor not enabled');
361 $user = $this->getUser();
362 $user->setGoogleAuthenticatorSecret(null);
363 $user->setBackupCodes(null);
365 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
367 return $this->redirect($this->generateUrl('config') . '#set3');
373 * @Route("/config/otp/app/check", name="config_otp_app_check")
375 public function otpAppCheckAction(Request
$request)
377 $isValid = $this->get('scheb_two_factor.security.google_authenticator')->checkCode(
379 $request->get('_auth_code')
382 if (true === $isValid) {
385 'flashes.config.notice.otp_enabled'
388 return $this->redirect($this->generateUrl('config') . '#set3');
393 'scheb_two_factor.code_invalid'
396 return $this->redirect($this->generateUrl('config_otp_app'));
400 * @Route("/generate-token", name="generate_token")
402 * @return RedirectResponse|JsonResponse
404 public function generateTokenAction(Request
$request)
406 $config = $this->getConfig();
407 $config->setFeedToken(Utils
::generateToken());
409 $em = $this->getDoctrine()->getManager();
410 $em->persist($config);
413 if ($request->isXmlHttpRequest()) {
414 return new JsonResponse(['token' => $config->getFeedToken()]);
419 'flashes.config.notice.feed_token_updated'
422 return $this->redirect($this->generateUrl('config') . '#set2');
426 * @Route("/revoke-token", name="revoke_token")
428 * @return RedirectResponse|JsonResponse
430 public function revokeTokenAction(Request
$request)
432 $config = $this->getConfig();
433 $config->setFeedToken(null);
435 $em = $this->getDoctrine()->getManager();
436 $em->persist($config);
439 if ($request->isXmlHttpRequest()) {
440 return new JsonResponse();
445 'flashes.config.notice.feed_token_revoked'
448 return $this->redirect($this->generateUrl('config') . '#set2');
452 * Deletes a tagging rule and redirect to the config homepage.
454 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
456 * @return RedirectResponse
458 public function deleteTaggingRuleAction(TaggingRule
$rule)
460 $this->validateRuleAction($rule);
462 $em = $this->getDoctrine()->getManager();
468 'flashes.config.notice.tagging_rules_deleted'
471 return $this->redirect($this->generateUrl('config') . '#set5');
475 * Edit a tagging rule.
477 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
479 * @return RedirectResponse
481 public function editTaggingRuleAction(TaggingRule
$rule)
483 $this->validateRuleAction($rule);
485 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
489 * Deletes an ignore origin rule and redirect to the config homepage.
491 * @Route("/ignore-origin-user-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_ignore_origin_rule")
493 * @return RedirectResponse
495 public function deleteIgnoreOriginRuleAction(IgnoreOriginUserRule
$rule)
497 $this->validateRuleAction($rule);
499 $em = $this->getDoctrine()->getManager();
505 'flashes.config.notice.ignore_origin_rules_deleted'
508 return $this->redirect($this->generateUrl('config') . '#set6');
512 * Edit an ignore origin rule.
514 * @Route("/ignore-origin-user-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_ignore_origin_rule")
516 * @return RedirectResponse
518 public function editIgnoreOriginRuleAction(IgnoreOriginUserRule
$rule)
520 $this->validateRuleAction($rule);
522 return $this->redirect($this->generateUrl('config') . '?ignore-origin-user-rule=' . $rule->getId() . '#set6');
526 * Remove all annotations OR tags OR entries for the current user.
528 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
530 * @return RedirectResponse
532 public function resetAction($type)
537 ->getRepository('WallabagAnnotationBundle:Annotation')
538 ->removeAllByUserId($this->getUser()->getId());
541 $this->removeAllTagsByUserId($this->getUser()->getId());
544 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
545 // otherwise they won't be removed ...
546 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform
) {
547 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
550 // manually remove tags to avoid orphan tag
551 $this->removeAllTagsByUserId($this->getUser()->getId());
553 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
556 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform
) {
557 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
560 // manually remove tags to avoid orphan tag
561 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
563 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
569 'flashes.config.notice.' . $type . '_reset'
572 return $this->redirect($this->generateUrl('config') . '#set3');
576 * Delete account for current user.
578 * @Route("/account/delete", name="delete_account")
580 * @throws AccessDeniedHttpException
582 * @return \Symfony\Component\HttpFoundation\RedirectResponse
584 public function deleteAccountAction(Request
$request)
586 $enabledUsers = $this->get('wallabag_user.user_repository')
587 ->getSumEnabledUsers();
589 if ($enabledUsers <= 1) {
590 throw new AccessDeniedHttpException();
593 $user = $this->getUser();
595 // logout current user
596 $this->get('security.token_storage')->setToken(null);
597 $request->getSession()->invalidate();
599 $em = $this->get('fos_user.user_manager');
600 $em->deleteUser($user);
602 return $this->redirect($this->generateUrl('fos_user_security_login'));
606 * Switch view mode for current user.
608 * @Route("/config/view-mode", name="switch_view_mode")
610 * @return \Symfony\Component\HttpFoundation\RedirectResponse
612 public function changeViewModeAction(Request
$request)
614 $user = $this->getUser();
615 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
617 $em = $this->getDoctrine()->getManager();
621 return $this->redirect($request->headers
->get('referer'));
625 * Change the locale for the current user.
627 * @param string $language
629 * @Route("/locale/{language}", name="changeLocale")
631 * @return \Symfony\Component\HttpFoundation\RedirectResponse
633 public function setLocaleAction(Request
$request, $language = null)
635 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
637 if (0 === \
count($errors)) {
638 $request->getSession()->set('_locale', $language);
641 return $this->redirect($request->headers
->get('referer', $this->generateUrl('homepage')));
645 * Export tagging rules for the logged in user.
647 * @Route("/tagging-rule/export", name="export_tagging_rule")
651 public function exportTaggingRulesAction()
653 $data = SerializerBuilder
::create()->build()->serialize(
654 $this->getUser()->getConfig()->getTaggingRules(),
656 SerializationContext
::create()->setGroups(['export_tagging_rule'])
659 return Response
::create(
663 'Content-type' => 'application/json',
664 'Content-Disposition' => 'attachment; filename="tagging_rules_' . $this->getUser()->getUsername() . '.json"',
665 'Content-Transfer-Encoding' => 'UTF-8',
671 * Remove all tags for given tags and a given user and cleanup orphan tags.
676 private function removeAllTagsByStatusAndUserId($tags, $userId)
682 $this->get('wallabag_core.entry_repository')
683 ->removeTags($userId, $tags);
685 // cleanup orphan tags
686 $em = $this->getDoctrine()->getManager();
688 foreach ($tags as $tag) {
689 if (0 === \
count($tag->getEntries())) {
698 * Remove all tags for a given user and cleanup orphan tags.
702 private function removeAllTagsByUserId($userId)
704 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
705 $this->removeAllTagsByStatusAndUserId($tags, $userId);
709 * Remove all tags for a given user and cleanup orphan tags.
713 private function removeTagsForArchivedByUserId($userId)
715 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
716 $this->removeAllTagsByStatusAndUserId($tags, $userId);
719 private function removeAnnotationsForArchivedByUserId($userId)
721 $em = $this->getDoctrine()->getManager();
723 $archivedEntriesAnnotations = $this->getDoctrine()
724 ->getRepository('WallabagAnnotationBundle:Annotation')
725 ->findAllArchivedEntriesByUser($userId);
727 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
728 $em->remove($archivedEntriesAnnotation);
735 * Validate that a rule can be edited/deleted by the current user.
737 private function validateRuleAction(RuleInterface
$rule)
739 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
740 throw $this->createAccessDeniedException('You can not access this rule.');
745 * Retrieve config for the current user.
746 * If no config were found, create a new one.
750 private function getConfig()
752 $config = $this->getDoctrine()
753 ->getRepository('WallabagCoreBundle:Config')
754 ->findOneByUser($this->getUser());
756 // should NEVER HAPPEN ...
758 $config = new Config($this->getUser());