3 namespace Wallabag\CoreBundle\Controller
;
5 use PragmaRX\Recovery\Recovery
as BackupCodes
;
6 use Symfony\Bundle\FrameworkBundle\Controller\Controller
;
7 use Symfony\Component\HttpFoundation\JsonResponse
;
8 use Symfony\Component\HttpFoundation\RedirectResponse
;
9 use Symfony\Component\HttpFoundation\Request
;
10 use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
;
11 use Symfony\Component\Routing\Annotation\Route
;
12 use Symfony\Component\Validator\Constraints\Locale
as LocaleConstraint
;
13 use Wallabag\CoreBundle\Entity\Config
;
14 use Wallabag\CoreBundle\Entity\TaggingRule
;
15 use Wallabag\CoreBundle\Form\Type\ChangePasswordType
;
16 use Wallabag\CoreBundle\Form\Type\ConfigType
;
17 use Wallabag\CoreBundle\Form\Type\FeedType
;
18 use Wallabag\CoreBundle\Form\Type\TaggingRuleType
;
19 use Wallabag\CoreBundle\Form\Type\UserInformationType
;
20 use Wallabag\CoreBundle\Tools\Utils
;
22 class ConfigController
extends Controller
25 * @param Request $request
27 * @Route("/config", name="config")
29 public function indexAction(Request
$request)
31 $em = $this->getDoctrine()->getManager();
32 $config = $this->getConfig();
33 $userManager = $this->container
->get('fos_user.user_manager');
34 $user = $this->getUser();
36 // handle basic config detail (this form is defined as a service)
37 $configForm = $this->createForm(ConfigType
::class, $config, ['action' => $this->generateUrl('config')]);
38 $configForm->handleRequest($request);
40 if ($configForm->isSubmitted() && $configForm->isValid()) {
41 $em->persist($config);
44 $request->getSession()->set('_locale', $config->getLanguage());
46 // switch active theme
47 $activeTheme = $this->get('liip_theme.active_theme');
48 $activeTheme->setName($config->getTheme());
52 'flashes.config.notice.config_saved'
55 return $this->redirect($this->generateUrl('config'));
58 // handle changing password
59 $pwdForm = $this->createForm(ChangePasswordType
::class, null, ['action' => $this->generateUrl('config') . '#set4']);
60 $pwdForm->handleRequest($request);
62 if ($pwdForm->isSubmitted() && $pwdForm->isValid()) {
63 if ($this->get('craue_config')->get('demo_mode_enabled') && $this->get('craue_config')->get('demo_mode_username') === $user->getUsername()) {
64 $message = 'flashes.config.notice.password_not_updated_demo';
66 $message = 'flashes.config.notice.password_updated';
68 $user->setPlainPassword($pwdForm->get('new_password')->getData());
69 $userManager->updateUser($user, true);
72 $this->addFlash('notice', $message);
74 return $this->redirect($this->generateUrl('config') . '#set4');
77 // handle changing user information
78 $userForm = $this->createForm(UserInformationType
::class, $user, [
79 'validation_groups' => ['Profile'],
80 'action' => $this->generateUrl('config') . '#set3',
82 $userForm->handleRequest($request);
84 if ($userForm->isSubmitted() && $userForm->isValid()) {
85 $userManager->updateUser($user, true);
89 'flashes.config.notice.user_updated'
92 return $this->redirect($this->generateUrl('config') . '#set3');
95 // handle feed information
96 $feedForm = $this->createForm(FeedType
::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
97 $feedForm->handleRequest($request);
99 if ($feedForm->isSubmitted() && $feedForm->isValid()) {
100 $em->persist($config);
105 'flashes.config.notice.feed_updated'
108 return $this->redirect($this->generateUrl('config') . '#set2');
111 // handle tagging rule
112 $taggingRule = new TaggingRule();
113 $action = $this->generateUrl('config') . '#set5';
115 if ($request->query
->has('tagging-rule')) {
116 $taggingRule = $this->getDoctrine()
117 ->getRepository('WallabagCoreBundle:TaggingRule')
118 ->find($request->query
->get('tagging-rule'));
120 if ($this->getUser()->getId() !== $taggingRule->getConfig()->getUser()->getId()) {
121 return $this->redirect($action);
124 $action = $this->generateUrl('config') . '?tagging-rule=' . $taggingRule->getId() . '#set5';
127 $newTaggingRule = $this->createForm(TaggingRuleType
::class, $taggingRule, ['action' => $action]);
128 $newTaggingRule->handleRequest($request);
130 if ($newTaggingRule->isSubmitted() && $newTaggingRule->isValid()) {
131 $taggingRule->setConfig($config);
132 $em->persist($taggingRule);
137 'flashes.config.notice.tagging_rules_updated'
140 return $this->redirect($this->generateUrl('config') . '#set5');
143 return $this->render('WallabagCoreBundle:Config:index.html.twig', [
145 'config' => $configForm->createView(),
146 'feed' => $feedForm->createView(),
147 'pwd' => $pwdForm->createView(),
148 'user' => $userForm->createView(),
149 'new_tagging_rule' => $newTaggingRule->createView(),
152 'username' => $user->getUsername(),
153 'token' => $config->getFeedToken(),
155 'twofactor_auth' => $this->getParameter('twofactor_auth'),
156 'wallabag_url' => $this->getParameter('domain_name'),
157 'enabled_users' => $this->get('wallabag_user.user_repository')->getSumEnabledUsers(),
162 * Enable 2FA using email.
164 * @Route("/config/otp/email", name="config_otp_email")
166 public function otpEmailAction()
168 if (!$this->getParameter('twofactor_auth')) {
169 return $this->createNotFoundException('two_factor not enabled');
172 $user = $this->getUser();
174 $user->setGoogleAuthenticatorSecret(null);
175 $user->setBackupCodes(null);
176 $user->setEmailTwoFactor(true);
178 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
182 'flashes.config.notice.otp_enabled'
185 return $this->redirect($this->generateUrl('config') . '#set3');
189 * Enable 2FA using OTP app, user will need to confirm the generated code from the app.
191 * @Route("/config/otp/app", name="config_otp_app")
193 public function otpAppAction()
195 if (!$this->getParameter('twofactor_auth')) {
196 return $this->createNotFoundException('two_factor not enabled');
199 $user = $this->getUser();
200 $secret = $this->get('scheb_two_factor.security.google_authenticator')->generateSecret();
202 $user->setGoogleAuthenticatorSecret($secret);
203 $user->setEmailTwoFactor(false);
205 $backupCodes = (new BackupCodes())->toArray();
206 $backupCodesHashed = array_map(
207 function ($backupCode) {
208 return password_hash($backupCode, PASSWORD_DEFAULT
);
213 $user->setBackupCodes($backupCodesHashed);
215 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
217 return $this->render('WallabagCoreBundle:Config:otp_app.html.twig', [
218 'backupCodes' => $backupCodes,
219 'qr_code' => $this->get('scheb_two_factor.security.google_authenticator')->getQRContent($user),
224 * Cancelling 2FA using OTP app.
226 * @Route("/config/otp/app/cancel", name="config_otp_app_cancel")
228 public function otpAppCancelAction()
230 if (!$this->getParameter('twofactor_auth')) {
231 return $this->createNotFoundException('two_factor not enabled');
234 $user = $this->getUser();
235 $user->setGoogleAuthenticatorSecret(null);
236 $user->setBackupCodes(null);
238 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
240 return $this->redirect($this->generateUrl('config') . '#set3');
246 * @param Request $request
248 * @Route("/config/otp/app/check", name="config_otp_app_check")
250 public function otpAppCheckAction(Request
$request)
252 $isValid = $this->get('scheb_two_factor.security.google_authenticator')->checkCode(
254 $request->get('_auth_code')
257 if (true === $isValid) {
260 'flashes.config.notice.otp_enabled'
263 return $this->redirect($this->generateUrl('config') . '#set3');
268 'scheb_two_factor.code_invalid'
271 return $this->redirect($this->generateUrl('config_otp_app'));
275 * @param Request $request
277 * @Route("/generate-token", name="generate_token")
279 * @return RedirectResponse|JsonResponse
281 public function generateTokenAction(Request
$request)
283 $config = $this->getConfig();
284 $config->setFeedToken(Utils
::generateToken());
286 $em = $this->getDoctrine()->getManager();
287 $em->persist($config);
290 if ($request->isXmlHttpRequest()) {
291 return new JsonResponse(['token' => $config->getFeedToken()]);
296 'flashes.config.notice.feed_token_updated'
299 return $this->redirect($this->generateUrl('config') . '#set2');
303 * @param Request $request
305 * @Route("/revoke-token", name="revoke_token")
307 * @return RedirectResponse|JsonResponse
309 public function revokeTokenAction(Request
$request)
311 $config = $this->getConfig();
312 $config->setFeedToken(null);
314 $em = $this->getDoctrine()->getManager();
315 $em->persist($config);
318 if ($request->isXmlHttpRequest()) {
319 return new JsonResponse();
324 'flashes.config.notice.feed_token_revoked'
327 return $this->redirect($this->generateUrl('config') . '#set2');
331 * Deletes a tagging rule and redirect to the config homepage.
333 * @param TaggingRule $rule
335 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
337 * @return RedirectResponse
339 public function deleteTaggingRuleAction(TaggingRule
$rule)
341 $this->validateRuleAction($rule);
343 $em = $this->getDoctrine()->getManager();
349 'flashes.config.notice.tagging_rules_deleted'
352 return $this->redirect($this->generateUrl('config') . '#set5');
356 * Edit a tagging rule.
358 * @param TaggingRule $rule
360 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
362 * @return RedirectResponse
364 public function editTaggingRuleAction(TaggingRule
$rule)
366 $this->validateRuleAction($rule);
368 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
372 * Remove all annotations OR tags OR entries for the current user.
374 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
376 * @return RedirectResponse
378 public function resetAction($type)
383 ->getRepository('WallabagAnnotationBundle:Annotation')
384 ->removeAllByUserId($this->getUser()->getId());
387 $this->removeAllTagsByUserId($this->getUser()->getId());
390 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
391 // otherwise they won't be removed ...
392 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform
) {
393 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
396 // manually remove tags to avoid orphan tag
397 $this->removeAllTagsByUserId($this->getUser()->getId());
399 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
402 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform
) {
403 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
406 // manually remove tags to avoid orphan tag
407 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
409 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
415 'flashes.config.notice.' . $type . '_reset'
418 return $this->redirect($this->generateUrl('config') . '#set3');
422 * Delete account for current user.
424 * @Route("/account/delete", name="delete_account")
426 * @param Request $request
428 * @throws AccessDeniedHttpException
430 * @return \Symfony\Component\HttpFoundation\RedirectResponse
432 public function deleteAccountAction(Request
$request)
434 $enabledUsers = $this->get('wallabag_user.user_repository')
435 ->getSumEnabledUsers();
437 if ($enabledUsers <= 1) {
438 throw new AccessDeniedHttpException();
441 $user = $this->getUser();
443 // logout current user
444 $this->get('security.token_storage')->setToken(null);
445 $request->getSession()->invalidate();
447 $em = $this->get('fos_user.user_manager');
448 $em->deleteUser($user);
450 return $this->redirect($this->generateUrl('fos_user_security_login'));
454 * Switch view mode for current user.
456 * @Route("/config/view-mode", name="switch_view_mode")
458 * @param Request $request
460 * @return \Symfony\Component\HttpFoundation\RedirectResponse
462 public function changeViewModeAction(Request
$request)
464 $user = $this->getUser();
465 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
467 $em = $this->getDoctrine()->getManager();
471 return $this->redirect($request->headers
->get('referer'));
475 * Change the locale for the current user.
477 * @param Request $request
478 * @param string $language
480 * @Route("/locale/{language}", name="changeLocale")
482 * @return \Symfony\Component\HttpFoundation\RedirectResponse
484 public function setLocaleAction(Request
$request, $language = null)
486 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
488 if (0 === \
count($errors)) {
489 $request->getSession()->set('_locale', $language);
492 return $this->redirect($request->headers
->get('referer', $this->generateUrl('homepage')));
496 * Remove all tags for given tags and a given user and cleanup orphan tags.
501 private function removeAllTagsByStatusAndUserId($tags, $userId)
507 $this->get('wallabag_core.entry_repository')
508 ->removeTags($userId, $tags);
510 // cleanup orphan tags
511 $em = $this->getDoctrine()->getManager();
513 foreach ($tags as $tag) {
514 if (0 === \
count($tag->getEntries())) {
523 * Remove all tags for a given user and cleanup orphan tags.
527 private function removeAllTagsByUserId($userId)
529 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
530 $this->removeAllTagsByStatusAndUserId($tags, $userId);
534 * Remove all tags for a given user and cleanup orphan tags.
538 private function removeTagsForArchivedByUserId($userId)
540 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
541 $this->removeAllTagsByStatusAndUserId($tags, $userId);
544 private function removeAnnotationsForArchivedByUserId($userId)
546 $em = $this->getDoctrine()->getManager();
548 $archivedEntriesAnnotations = $this->getDoctrine()
549 ->getRepository('WallabagAnnotationBundle:Annotation')
550 ->findAllArchivedEntriesByUser($userId);
552 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
553 $em->remove($archivedEntriesAnnotation);
560 * Validate that a rule can be edited/deleted by the current user.
562 * @param TaggingRule $rule
564 private function validateRuleAction(TaggingRule
$rule)
566 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
567 throw $this->createAccessDeniedException('You can not access this tagging rule.');
572 * Retrieve config for the current user.
573 * If no config were found, create a new one.
577 private function getConfig()
579 $config = $this->getDoctrine()
580 ->getRepository('WallabagCoreBundle:Config')
581 ->findOneByUser($this->getUser());
583 // should NEVER HAPPEN ...
585 $config = new Config($this->getUser());