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\RssType
;
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 rss information
96 $rssForm = $this->createForm(RssType
::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
97 $rssForm->handleRequest($request);
99 if ($rssForm->isSubmitted() && $rssForm->isValid()) {
100 $em->persist($config);
105 'flashes.config.notice.rss_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 'rss' => $rssForm->createView(),
147 'pwd' => $pwdForm->createView(),
148 'user' => $userForm->createView(),
149 'new_tagging_rule' => $newTaggingRule->createView(),
152 'username' => $user->getUsername(),
153 'token' => $config->getRssToken(),
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 * @param Request $request
166 * @Route("/config/otp/email", name="config_otp_email")
168 public function otpEmailAction(Request
$request)
170 if (!$this->getParameter('twofactor_auth')) {
171 return $this->createNotFoundException('two_factor not enabled');
174 $user = $this->getUser();
176 $user->setGoogleAuthenticatorSecret(null);
177 $user->setBackupCodes(null);
178 $user->setEmailTwoFactor(true);
180 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
184 'flashes.config.notice.otp_enabled'
187 return $this->redirect($this->generateUrl('config') . '#set3');
191 * Enable 2FA using OTP app, user will need to confirm the generated code from the app.
193 * @Route("/config/otp/app", name="config_otp_app")
195 public function otpAppAction()
197 if (!$this->getParameter('twofactor_auth')) {
198 return $this->createNotFoundException('two_factor not enabled');
201 $user = $this->getUser();
203 if (!$user->isGoogleTwoFactor()) {
204 $secret = $this->get('scheb_two_factor.security.google_authenticator')->generateSecret();
206 $user->setGoogleAuthenticatorSecret($secret);
207 $user->setEmailTwoFactor(false);
208 $user->setBackupCodes((new BackupCodes())->toArray());
210 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
213 return $this->render('WallabagCoreBundle:Config:otp_app.html.twig', [
214 'qr_code' => $this->get('scheb_two_factor.security.google_authenticator')->getQRContent($user),
219 * Cancelling 2FA using OTP app.
221 * @Route("/config/otp/app/cancel", name="config_otp_app_cancel")
223 public function otpAppCancelAction()
225 if (!$this->getParameter('twofactor_auth')) {
226 return $this->createNotFoundException('two_factor not enabled');
229 $user = $this->getUser();
230 $user->setGoogleAuthenticatorSecret(null);
231 $user->setBackupCodes(null);
233 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
235 return $this->redirect($this->generateUrl('config') . '#set3');
241 * @param Request $request
243 * @Route("/config/otp/app/check", name="config_otp_app_check")
245 public function otpAppCheckAction(Request
$request)
247 $isValid = $this->get('scheb_two_factor.security.google_authenticator')->checkCode(
249 $request->get('_auth_code')
252 if (true === $isValid) {
255 'flashes.config.notice.otp_enabled'
258 return $this->redirect($this->generateUrl('config') . '#set3');
263 'scheb_two_factor.code_invalid'
266 return $this->redirect($this->generateUrl('config_otp_app'));
270 * @param Request $request
272 * @Route("/generate-token", name="generate_token")
274 * @return RedirectResponse|JsonResponse
276 public function generateTokenAction(Request
$request)
278 $config = $this->getConfig();
279 $config->setRssToken(Utils
::generateToken());
281 $em = $this->getDoctrine()->getManager();
282 $em->persist($config);
285 if ($request->isXmlHttpRequest()) {
286 return new JsonResponse(['token' => $config->getRssToken()]);
291 'flashes.config.notice.rss_token_updated'
294 return $this->redirect($this->generateUrl('config') . '#set2');
298 * Deletes a tagging rule and redirect to the config homepage.
300 * @param TaggingRule $rule
302 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
304 * @return RedirectResponse
306 public function deleteTaggingRuleAction(TaggingRule
$rule)
308 $this->validateRuleAction($rule);
310 $em = $this->getDoctrine()->getManager();
316 'flashes.config.notice.tagging_rules_deleted'
319 return $this->redirect($this->generateUrl('config') . '#set5');
323 * Edit a tagging rule.
325 * @param TaggingRule $rule
327 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
329 * @return RedirectResponse
331 public function editTaggingRuleAction(TaggingRule
$rule)
333 $this->validateRuleAction($rule);
335 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
339 * Remove all annotations OR tags OR entries for the current user.
341 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
343 * @return RedirectResponse
345 public function resetAction($type)
350 ->getRepository('WallabagAnnotationBundle:Annotation')
351 ->removeAllByUserId($this->getUser()->getId());
354 $this->removeAllTagsByUserId($this->getUser()->getId());
357 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
358 // otherwise they won't be removed ...
359 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform
) {
360 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
363 // manually remove tags to avoid orphan tag
364 $this->removeAllTagsByUserId($this->getUser()->getId());
366 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
369 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform
) {
370 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
373 // manually remove tags to avoid orphan tag
374 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
376 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
382 'flashes.config.notice.' . $type . '_reset'
385 return $this->redirect($this->generateUrl('config') . '#set3');
389 * Delete account for current user.
391 * @Route("/account/delete", name="delete_account")
393 * @param Request $request
395 * @throws AccessDeniedHttpException
397 * @return \Symfony\Component\HttpFoundation\RedirectResponse
399 public function deleteAccountAction(Request
$request)
401 $enabledUsers = $this->get('wallabag_user.user_repository')
402 ->getSumEnabledUsers();
404 if ($enabledUsers <= 1) {
405 throw new AccessDeniedHttpException();
408 $user = $this->getUser();
410 // logout current user
411 $this->get('security.token_storage')->setToken(null);
412 $request->getSession()->invalidate();
414 $em = $this->get('fos_user.user_manager');
415 $em->deleteUser($user);
417 return $this->redirect($this->generateUrl('fos_user_security_login'));
421 * Switch view mode for current user.
423 * @Route("/config/view-mode", name="switch_view_mode")
425 * @param Request $request
427 * @return \Symfony\Component\HttpFoundation\RedirectResponse
429 public function changeViewModeAction(Request
$request)
431 $user = $this->getUser();
432 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
434 $em = $this->getDoctrine()->getManager();
438 return $this->redirect($request->headers
->get('referer'));
442 * Change the locale for the current user.
444 * @param Request $request
445 * @param string $language
447 * @Route("/locale/{language}", name="changeLocale")
449 * @return \Symfony\Component\HttpFoundation\RedirectResponse
451 public function setLocaleAction(Request
$request, $language = null)
453 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
455 if (0 === \
count($errors)) {
456 $request->getSession()->set('_locale', $language);
459 return $this->redirect($request->headers
->get('referer', $this->generateUrl('homepage')));
463 * Remove all tags for given tags and a given user and cleanup orphan tags.
468 private function removeAllTagsByStatusAndUserId($tags, $userId)
474 $this->get('wallabag_core.entry_repository')
475 ->removeTags($userId, $tags);
477 // cleanup orphan tags
478 $em = $this->getDoctrine()->getManager();
480 foreach ($tags as $tag) {
481 if (0 === \
count($tag->getEntries())) {
490 * Remove all tags for a given user and cleanup orphan tags.
494 private function removeAllTagsByUserId($userId)
496 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
497 $this->removeAllTagsByStatusAndUserId($tags, $userId);
501 * Remove all tags for a given user and cleanup orphan tags.
505 private function removeTagsForArchivedByUserId($userId)
507 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
508 $this->removeAllTagsByStatusAndUserId($tags, $userId);
511 private function removeAnnotationsForArchivedByUserId($userId)
513 $em = $this->getDoctrine()->getManager();
515 $archivedEntriesAnnotations = $this->getDoctrine()
516 ->getRepository('WallabagAnnotationBundle:Annotation')
517 ->findAllArchivedEntriesByUser($userId);
519 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
520 $em->remove($archivedEntriesAnnotation);
527 * Validate that a rule can be edited/deleted by the current user.
529 * @param TaggingRule $rule
531 private function validateRuleAction(TaggingRule
$rule)
533 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
534 throw $this->createAccessDeniedException('You can not access this tagging rule.');
539 * Retrieve config for the current user.
540 * If no config were found, create a new one.
544 private function getConfig()
546 $config = $this->getDoctrine()
547 ->getRepository('WallabagCoreBundle:Config')
548 ->findOneByUser($this->getUser());
550 // should NEVER HAPPEN ...
552 $config = new Config($this->getUser());