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 // `googleTwoFactor` isn't a field within the User entity, we need to define it's value in a different way
85 if ($this->getParameter('twofactor_auth') && true === $user->isGoogleAuthenticatorEnabled() && false === $userForm->isSubmitted()) {
86 $userForm->get('googleTwoFactor')->setData(true);
89 if ($userForm->isSubmitted() && $userForm->isValid()) {
90 // handle creation / reset of the OTP secret if checkbox changed from the previous state
91 if ($this->getParameter('twofactor_auth')) {
92 if (true === $userForm->get('googleTwoFactor')->getData() && false === $user->isGoogleAuthenticatorEnabled()) {
93 $secret = $this->get('scheb_two_factor.security.google_authenticator')->generateSecret();
95 $user->setGoogleAuthenticatorSecret($secret);
96 $user->setEmailTwoFactor(false);
97 $user->setBackupCodes((new BackupCodes())->toArray());
99 $this->addFlash('OtpQrCode', $this->get('scheb_two_factor.security.google_authenticator')->getQRContent($user));
100 } elseif (false === $userForm->get('googleTwoFactor')->getData() && true === $user->isGoogleAuthenticatorEnabled()) {
101 $user->setGoogleAuthenticatorSecret(null);
102 $user->setBackupCodes(null);
106 $userManager->updateUser($user, true);
110 'flashes.config.notice.user_updated'
113 return $this->redirect($this->generateUrl('config') . '#set3');
116 // handle rss information
117 $rssForm = $this->createForm(RssType
::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
118 $rssForm->handleRequest($request);
120 if ($rssForm->isSubmitted() && $rssForm->isValid()) {
121 $em->persist($config);
126 'flashes.config.notice.rss_updated'
129 return $this->redirect($this->generateUrl('config') . '#set2');
132 // handle tagging rule
133 $taggingRule = new TaggingRule();
134 $action = $this->generateUrl('config') . '#set5';
136 if ($request->query
->has('tagging-rule')) {
137 $taggingRule = $this->getDoctrine()
138 ->getRepository('WallabagCoreBundle:TaggingRule')
139 ->find($request->query
->get('tagging-rule'));
141 if ($this->getUser()->getId() !== $taggingRule->getConfig()->getUser()->getId()) {
142 return $this->redirect($action);
145 $action = $this->generateUrl('config') . '?tagging-rule=' . $taggingRule->getId() . '#set5';
148 $newTaggingRule = $this->createForm(TaggingRuleType
::class, $taggingRule, ['action' => $action]);
149 $newTaggingRule->handleRequest($request);
151 if ($newTaggingRule->isSubmitted() && $newTaggingRule->isValid()) {
152 $taggingRule->setConfig($config);
153 $em->persist($taggingRule);
158 'flashes.config.notice.tagging_rules_updated'
161 return $this->redirect($this->generateUrl('config') . '#set5');
164 return $this->render('WallabagCoreBundle:Config:index.html.twig', [
166 'config' => $configForm->createView(),
167 'rss' => $rssForm->createView(),
168 'pwd' => $pwdForm->createView(),
169 'user' => $userForm->createView(),
170 'new_tagging_rule' => $newTaggingRule->createView(),
173 'username' => $user->getUsername(),
174 'token' => $config->getRssToken(),
176 'twofactor_auth' => $this->getParameter('twofactor_auth'),
177 'wallabag_url' => $this->getParameter('domain_name'),
178 'enabled_users' => $this->get('wallabag_user.user_repository')
179 ->getSumEnabledUsers(),
184 * @param Request $request
186 * @Route("/generate-token", name="generate_token")
188 * @return RedirectResponse|JsonResponse
190 public function generateTokenAction(Request
$request)
192 $config = $this->getConfig();
193 $config->setRssToken(Utils
::generateToken());
195 $em = $this->getDoctrine()->getManager();
196 $em->persist($config);
199 if ($request->isXmlHttpRequest()) {
200 return new JsonResponse(['token' => $config->getRssToken()]);
205 'flashes.config.notice.rss_token_updated'
208 return $this->redirect($this->generateUrl('config') . '#set2');
212 * Deletes a tagging rule and redirect to the config homepage.
214 * @param TaggingRule $rule
216 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
218 * @return RedirectResponse
220 public function deleteTaggingRuleAction(TaggingRule
$rule)
222 $this->validateRuleAction($rule);
224 $em = $this->getDoctrine()->getManager();
230 'flashes.config.notice.tagging_rules_deleted'
233 return $this->redirect($this->generateUrl('config') . '#set5');
237 * Edit a tagging rule.
239 * @param TaggingRule $rule
241 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
243 * @return RedirectResponse
245 public function editTaggingRuleAction(TaggingRule
$rule)
247 $this->validateRuleAction($rule);
249 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
253 * Remove all annotations OR tags OR entries for the current user.
255 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
257 * @return RedirectResponse
259 public function resetAction($type)
264 ->getRepository('WallabagAnnotationBundle:Annotation')
265 ->removeAllByUserId($this->getUser()->getId());
268 $this->removeAllTagsByUserId($this->getUser()->getId());
271 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
272 // otherwise they won't be removed ...
273 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform
) {
274 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
277 // manually remove tags to avoid orphan tag
278 $this->removeAllTagsByUserId($this->getUser()->getId());
280 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
283 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform
) {
284 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
287 // manually remove tags to avoid orphan tag
288 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
290 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
296 'flashes.config.notice.' . $type . '_reset'
299 return $this->redirect($this->generateUrl('config') . '#set3');
303 * Delete account for current user.
305 * @Route("/account/delete", name="delete_account")
307 * @param Request $request
309 * @throws AccessDeniedHttpException
311 * @return \Symfony\Component\HttpFoundation\RedirectResponse
313 public function deleteAccountAction(Request
$request)
315 $enabledUsers = $this->get('wallabag_user.user_repository')
316 ->getSumEnabledUsers();
318 if ($enabledUsers <= 1) {
319 throw new AccessDeniedHttpException();
322 $user = $this->getUser();
324 // logout current user
325 $this->get('security.token_storage')->setToken(null);
326 $request->getSession()->invalidate();
328 $em = $this->get('fos_user.user_manager');
329 $em->deleteUser($user);
331 return $this->redirect($this->generateUrl('fos_user_security_login'));
335 * Switch view mode for current user.
337 * @Route("/config/view-mode", name="switch_view_mode")
339 * @param Request $request
341 * @return \Symfony\Component\HttpFoundation\RedirectResponse
343 public function changeViewModeAction(Request
$request)
345 $user = $this->getUser();
346 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
348 $em = $this->getDoctrine()->getManager();
352 return $this->redirect($request->headers
->get('referer'));
356 * Change the locale for the current user.
358 * @param Request $request
359 * @param string $language
361 * @Route("/locale/{language}", name="changeLocale")
363 * @return \Symfony\Component\HttpFoundation\RedirectResponse
365 public function setLocaleAction(Request
$request, $language = null)
367 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
369 if (0 === \
count($errors)) {
370 $request->getSession()->set('_locale', $language);
373 return $this->redirect($request->headers
->get('referer', $this->generateUrl('homepage')));
377 * Remove all tags for given tags and a given user and cleanup orphan tags.
382 private function removeAllTagsByStatusAndUserId($tags, $userId)
388 $this->get('wallabag_core.entry_repository')
389 ->removeTags($userId, $tags);
391 // cleanup orphan tags
392 $em = $this->getDoctrine()->getManager();
394 foreach ($tags as $tag) {
395 if (0 === \
count($tag->getEntries())) {
404 * Remove all tags for a given user and cleanup orphan tags.
408 private function removeAllTagsByUserId($userId)
410 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
411 $this->removeAllTagsByStatusAndUserId($tags, $userId);
415 * Remove all tags for a given user and cleanup orphan tags.
419 private function removeTagsForArchivedByUserId($userId)
421 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
422 $this->removeAllTagsByStatusAndUserId($tags, $userId);
425 private function removeAnnotationsForArchivedByUserId($userId)
427 $em = $this->getDoctrine()->getManager();
429 $archivedEntriesAnnotations = $this->getDoctrine()
430 ->getRepository('WallabagAnnotationBundle:Annotation')
431 ->findAllArchivedEntriesByUser($userId);
433 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
434 $em->remove($archivedEntriesAnnotation);
441 * Validate that a rule can be edited/deleted by the current user.
443 * @param TaggingRule $rule
445 private function validateRuleAction(TaggingRule
$rule)
447 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
448 throw $this->createAccessDeniedException('You can not access this tagging rule.');
453 * Retrieve config for the current user.
454 * If no config were found, create a new one.
458 private function getConfig()
460 $config = $this->getDoctrine()
461 ->getRepository('WallabagCoreBundle:Config')
462 ->findOneByUser($this->getUser());
464 // should NEVER HAPPEN ...
466 $config = new Config($this->getUser());