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\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
;
26 class ConfigController
extends Controller
29 * @Route("/config", name="config")
31 public function indexAction(Request
$request)
33 $em = $this->getDoctrine()->getManager();
34 $config = $this->getConfig();
35 $userManager = $this->container
->get('fos_user.user_manager');
36 $user = $this->getUser();
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);
42 if ($configForm->isSubmitted() && $configForm->isValid()) {
43 $em->persist($config);
46 $request->getSession()->set('_locale', $config->getLanguage());
48 // switch active theme
49 $activeTheme = $this->get('liip_theme.active_theme');
50 $activeTheme->setName($config->getTheme());
54 'flashes.config.notice.config_saved'
57 return $this->redirect($this->generateUrl('config'));
60 // handle changing password
61 $pwdForm = $this->createForm(ChangePasswordType
::class, null, ['action' => $this->generateUrl('config') . '#set4']);
62 $pwdForm->handleRequest($request);
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';
68 $message = 'flashes.config.notice.password_updated';
70 $user->setPlainPassword($pwdForm->get('new_password')->getData());
71 $userManager->updateUser($user, true);
74 $this->addFlash('notice', $message);
76 return $this->redirect($this->generateUrl('config') . '#set4');
79 // handle changing user information
80 $userForm = $this->createForm(UserInformationType
::class, $user, [
81 'validation_groups' => ['Profile'],
82 'action' => $this->generateUrl('config') . '#set3',
84 $userForm->handleRequest($request);
86 if ($userForm->isSubmitted() && $userForm->isValid()) {
87 $userManager->updateUser($user, true);
91 'flashes.config.notice.user_updated'
94 return $this->redirect($this->generateUrl('config') . '#set3');
97 // handle feed information
98 $feedForm = $this->createForm(FeedType
::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
99 $feedForm->handleRequest($request);
101 if ($feedForm->isSubmitted() && $feedForm->isValid()) {
102 $em->persist($config);
107 'flashes.config.notice.feed_updated'
110 return $this->redirect($this->generateUrl('config') . '#set2');
113 // handle tagging rule
114 $taggingRule = new TaggingRule();
115 $action = $this->generateUrl('config') . '#set5';
117 if ($request->query
->has('tagging-rule')) {
118 $taggingRule = $this->getDoctrine()
119 ->getRepository('WallabagCoreBundle:TaggingRule')
120 ->find($request->query
->get('tagging-rule'));
122 if ($this->getUser()->getId() !== $taggingRule->getConfig()->getUser()->getId()) {
123 return $this->redirect($action);
126 $action = $this->generateUrl('config') . '?tagging-rule=' . $taggingRule->getId() . '#set5';
129 $newTaggingRule = $this->createForm(TaggingRuleType
::class, $taggingRule, ['action' => $action]);
130 $newTaggingRule->handleRequest($request);
132 if ($newTaggingRule->isSubmitted() && $newTaggingRule->isValid()) {
133 $taggingRule->setConfig($config);
134 $em->persist($taggingRule);
139 'flashes.config.notice.tagging_rules_updated'
142 return $this->redirect($this->generateUrl('config') . '#set5');
145 // handle tagging rules import
146 $taggingRulesImportform = $this->createForm(TaggingRuleImportType
::class);
147 $taggingRulesImportform->handleRequest($request);
149 if ($taggingRulesImportform->isSubmitted() && $taggingRulesImportform->isValid()) {
150 $message = 'flashes.config.notice.tagging_rules_not_imported';
151 $file = $taggingRulesImportform->get('file')->getData();
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);
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);
167 $message = 'flashes.config.notice.tagging_rules_imported';
171 $this->addFlash('notice', $message);
173 return $this->redirect($this->generateUrl('config') . '#set5');
176 return $this->render('WallabagCoreBundle:Config:index.html.twig', [
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(),
186 'username' => $user->getUsername(),
187 'token' => $config->getFeedToken(),
189 'twofactor_auth' => $this->getParameter('twofactor_auth'),
190 'wallabag_url' => $this->getParameter('domain_name'),
191 'enabled_users' => $this->get('wallabag_user.user_repository')->getSumEnabledUsers(),
196 * Disable 2FA using email.
198 * @Route("/config/otp/email/disable", name="disable_otp_email")
200 public function disableOtpEmailAction()
202 if (!$this->getParameter('twofactor_auth')) {
203 return $this->createNotFoundException('two_factor not enabled');
206 $user = $this->getUser();
207 $user->setEmailTwoFactor(false);
209 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
213 'flashes.config.notice.otp_disabled'
216 return $this->redirect($this->generateUrl('config') . '#set3');
220 * Enable 2FA using email.
222 * @Route("/config/otp/email", name="config_otp_email")
224 public function otpEmailAction()
226 if (!$this->getParameter('twofactor_auth')) {
227 return $this->createNotFoundException('two_factor not enabled');
230 $user = $this->getUser();
232 $user->setGoogleAuthenticatorSecret(null);
233 $user->setBackupCodes(null);
234 $user->setEmailTwoFactor(true);
236 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
240 'flashes.config.notice.otp_enabled'
243 return $this->redirect($this->generateUrl('config') . '#set3');
247 * Disable 2FA using OTP app.
249 * @Route("/config/otp/app/disable", name="disable_otp_app")
251 public function disableOtpAppAction()
253 if (!$this->getParameter('twofactor_auth')) {
254 return $this->createNotFoundException('two_factor not enabled');
257 $user = $this->getUser();
259 $user->setGoogleAuthenticatorSecret('');
260 $user->setBackupCodes(null);
262 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
266 'flashes.config.notice.otp_disabled'
269 return $this->redirect($this->generateUrl('config') . '#set3');
273 * Enable 2FA using OTP app, user will need to confirm the generated code from the app.
275 * @Route("/config/otp/app", name="config_otp_app")
277 public function otpAppAction()
279 if (!$this->getParameter('twofactor_auth')) {
280 return $this->createNotFoundException('two_factor not enabled');
283 $user = $this->getUser();
284 $secret = $this->get('scheb_two_factor.security.google_authenticator')->generateSecret();
286 $user->setGoogleAuthenticatorSecret($secret);
287 $user->setEmailTwoFactor(false);
289 $backupCodes = (new BackupCodes())->toArray();
290 $backupCodesHashed = array_map(
291 function ($backupCode) {
292 return password_hash($backupCode, PASSWORD_DEFAULT
);
297 $user->setBackupCodes($backupCodesHashed);
299 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
303 'flashes.config.notice.otp_enabled'
306 return $this->render('WallabagCoreBundle:Config:otp_app.html.twig', [
307 'backupCodes' => $backupCodes,
308 'qr_code' => $this->get('scheb_two_factor.security.google_authenticator')->getQRContent($user),
313 * Cancelling 2FA using OTP app.
315 * @Route("/config/otp/app/cancel", name="config_otp_app_cancel")
317 public function otpAppCancelAction()
319 if (!$this->getParameter('twofactor_auth')) {
320 return $this->createNotFoundException('two_factor not enabled');
323 $user = $this->getUser();
324 $user->setGoogleAuthenticatorSecret(null);
325 $user->setBackupCodes(null);
327 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
329 return $this->redirect($this->generateUrl('config') . '#set3');
335 * @Route("/config/otp/app/check", name="config_otp_app_check")
337 public function otpAppCheckAction(Request
$request)
339 $isValid = $this->get('scheb_two_factor.security.google_authenticator')->checkCode(
341 $request->get('_auth_code')
344 if (true === $isValid) {
347 'flashes.config.notice.otp_enabled'
350 return $this->redirect($this->generateUrl('config') . '#set3');
355 'scheb_two_factor.code_invalid'
358 return $this->redirect($this->generateUrl('config_otp_app'));
362 * @Route("/generate-token", name="generate_token")
364 * @return RedirectResponse|JsonResponse
366 public function generateTokenAction(Request
$request)
368 $config = $this->getConfig();
369 $config->setFeedToken(Utils
::generateToken());
371 $em = $this->getDoctrine()->getManager();
372 $em->persist($config);
375 if ($request->isXmlHttpRequest()) {
376 return new JsonResponse(['token' => $config->getFeedToken()]);
381 'flashes.config.notice.feed_token_updated'
384 return $this->redirect($this->generateUrl('config') . '#set2');
388 * @Route("/revoke-token", name="revoke_token")
390 * @return RedirectResponse|JsonResponse
392 public function revokeTokenAction(Request
$request)
394 $config = $this->getConfig();
395 $config->setFeedToken(null);
397 $em = $this->getDoctrine()->getManager();
398 $em->persist($config);
401 if ($request->isXmlHttpRequest()) {
402 return new JsonResponse();
407 'flashes.config.notice.feed_token_revoked'
410 return $this->redirect($this->generateUrl('config') . '#set2');
414 * Deletes a tagging rule and redirect to the config homepage.
416 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
418 * @return RedirectResponse
420 public function deleteTaggingRuleAction(TaggingRule
$rule)
422 $this->validateRuleAction($rule);
424 $em = $this->getDoctrine()->getManager();
430 'flashes.config.notice.tagging_rules_deleted'
433 return $this->redirect($this->generateUrl('config') . '#set5');
437 * Edit a tagging rule.
439 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
441 * @return RedirectResponse
443 public function editTaggingRuleAction(TaggingRule
$rule)
445 $this->validateRuleAction($rule);
447 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
451 * Remove all annotations OR tags OR entries for the current user.
453 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
455 * @return RedirectResponse
457 public function resetAction($type)
462 ->getRepository('WallabagAnnotationBundle:Annotation')
463 ->removeAllByUserId($this->getUser()->getId());
466 $this->removeAllTagsByUserId($this->getUser()->getId());
469 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
470 // otherwise they won't be removed ...
471 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform
) {
472 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
475 // manually remove tags to avoid orphan tag
476 $this->removeAllTagsByUserId($this->getUser()->getId());
478 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
481 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform
) {
482 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
485 // manually remove tags to avoid orphan tag
486 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
488 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
494 'flashes.config.notice.' . $type . '_reset'
497 return $this->redirect($this->generateUrl('config') . '#set3');
501 * Delete account for current user.
503 * @Route("/account/delete", name="delete_account")
505 * @throws AccessDeniedHttpException
507 * @return \Symfony\Component\HttpFoundation\RedirectResponse
509 public function deleteAccountAction(Request
$request)
511 $enabledUsers = $this->get('wallabag_user.user_repository')
512 ->getSumEnabledUsers();
514 if ($enabledUsers <= 1) {
515 throw new AccessDeniedHttpException();
518 $user = $this->getUser();
520 // logout current user
521 $this->get('security.token_storage')->setToken(null);
522 $request->getSession()->invalidate();
524 $em = $this->get('fos_user.user_manager');
525 $em->deleteUser($user);
527 return $this->redirect($this->generateUrl('fos_user_security_login'));
531 * Switch view mode for current user.
533 * @Route("/config/view-mode", name="switch_view_mode")
535 * @return \Symfony\Component\HttpFoundation\RedirectResponse
537 public function changeViewModeAction(Request
$request)
539 $user = $this->getUser();
540 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
542 $em = $this->getDoctrine()->getManager();
546 return $this->redirect($request->headers
->get('referer'));
550 * Change the locale for the current user.
552 * @param string $language
554 * @Route("/locale/{language}", name="changeLocale")
556 * @return \Symfony\Component\HttpFoundation\RedirectResponse
558 public function setLocaleAction(Request
$request, $language = null)
560 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
562 if (0 === \
count($errors)) {
563 $request->getSession()->set('_locale', $language);
566 return $this->redirect($request->headers
->get('referer', $this->generateUrl('homepage')));
570 * Export tagging rules for the logged in user.
572 * @Route("/tagging-rule/export", name="export_tagging_rule")
576 public function exportTaggingRulesAction()
578 $data = SerializerBuilder
::create()->build()->serialize(
579 $this->getUser()->getConfig()->getTaggingRules(),
581 SerializationContext
::create()->setGroups(['export_tagging_rule'])
584 return Response
::create(
588 'Content-type' => 'application/json',
589 'Content-Disposition' => 'attachment; filename="tagging_rules_' . $this->getUser()->getUsername() . '.json"',
590 'Content-Transfer-Encoding' => 'UTF-8',
596 * Remove all tags for given tags and a given user and cleanup orphan tags.
601 private function removeAllTagsByStatusAndUserId($tags, $userId)
607 $this->get('wallabag_core.entry_repository')
608 ->removeTags($userId, $tags);
610 // cleanup orphan tags
611 $em = $this->getDoctrine()->getManager();
613 foreach ($tags as $tag) {
614 if (0 === \
count($tag->getEntries())) {
623 * Remove all tags for a given user and cleanup orphan tags.
627 private function removeAllTagsByUserId($userId)
629 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
630 $this->removeAllTagsByStatusAndUserId($tags, $userId);
634 * Remove all tags for a given user and cleanup orphan tags.
638 private function removeTagsForArchivedByUserId($userId)
640 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
641 $this->removeAllTagsByStatusAndUserId($tags, $userId);
644 private function removeAnnotationsForArchivedByUserId($userId)
646 $em = $this->getDoctrine()->getManager();
648 $archivedEntriesAnnotations = $this->getDoctrine()
649 ->getRepository('WallabagAnnotationBundle:Annotation')
650 ->findAllArchivedEntriesByUser($userId);
652 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
653 $em->remove($archivedEntriesAnnotation);
660 * Validate that a rule can be edited/deleted by the current user.
662 private function validateRuleAction(TaggingRule
$rule)
664 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
665 throw $this->createAccessDeniedException('You can not access this tagging rule.');
670 * Retrieve config for the current user.
671 * If no config were found, create a new one.
675 private function getConfig()
677 $config = $this->getDoctrine()
678 ->getRepository('WallabagCoreBundle:Config')
679 ->findOneByUser($this->getUser());
681 // should NEVER HAPPEN ...
683 $config = new Config($this->getUser());