3 namespace Wallabag\CoreBundle\Controller
;
5 use Symfony\Bundle\FrameworkBundle\Controller\Controller
;
6 use Symfony\Component\HttpFoundation\JsonResponse
;
7 use Symfony\Component\HttpFoundation\RedirectResponse
;
8 use Symfony\Component\HttpFoundation\Request
;
9 use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
;
10 use Symfony\Component\Routing\Annotation\Route
;
11 use Symfony\Component\Validator\Constraints\Locale
as LocaleConstraint
;
12 use Wallabag\CoreBundle\Entity\Config
;
13 use Wallabag\CoreBundle\Entity\TaggingRule
;
14 use Wallabag\CoreBundle\Form\Type\ChangePasswordType
;
15 use Wallabag\CoreBundle\Form\Type\ConfigType
;
16 use Wallabag\CoreBundle\Form\Type\RssType
;
17 use Wallabag\CoreBundle\Form\Type\TaggingRuleType
;
18 use Wallabag\CoreBundle\Form\Type\UserInformationType
;
19 use Wallabag\CoreBundle\Tools\Utils
;
21 class ConfigController
extends Controller
24 * @param Request $request
26 * @Route("/config", name="config")
28 public function indexAction(Request
$request)
30 $em = $this->getDoctrine()->getManager();
31 $config = $this->getConfig();
32 $userManager = $this->container
->get('fos_user.user_manager');
33 $user = $this->getUser();
35 // handle basic config detail (this form is defined as a service)
36 $configForm = $this->createForm(ConfigType
::class, $config, ['action' => $this->generateUrl('config')]);
37 $configForm->handleRequest($request);
39 if ($configForm->isSubmitted() && $configForm->isValid()) {
40 $em->persist($config);
43 $request->getSession()->set('_locale', $config->getLanguage());
45 // switch active theme
46 $activeTheme = $this->get('liip_theme.active_theme');
47 $activeTheme->setName($config->getTheme());
51 'flashes.config.notice.config_saved'
54 return $this->redirect($this->generateUrl('config'));
57 // handle changing password
58 $pwdForm = $this->createForm(ChangePasswordType
::class, null, ['action' => $this->generateUrl('config') . '#set4']);
59 $pwdForm->handleRequest($request);
61 if ($pwdForm->isSubmitted() && $pwdForm->isValid()) {
62 if ($this->get('craue_config')->get('demo_mode_enabled') && $this->get('craue_config')->get('demo_mode_username') === $user->getUsername()) {
63 $message = 'flashes.config.notice.password_not_updated_demo';
65 $message = 'flashes.config.notice.password_updated';
67 $user->setPlainPassword($pwdForm->get('new_password')->getData());
68 $userManager->updateUser($user, true);
71 $this->addFlash('notice', $message);
73 return $this->redirect($this->generateUrl('config') . '#set4');
76 // handle changing user information
77 $userForm = $this->createForm(UserInformationType
::class, $user, [
78 'validation_groups' => ['Profile'],
79 'action' => $this->generateUrl('config') . '#set3',
81 $userForm->handleRequest($request);
83 // `googleTwoFactor` isn't a field within the User entity, we need to define it's value in a different way
84 if ($this->getParameter('twofactor_auth') && true === $user->isGoogleAuthenticatorEnabled() && false === $userForm->isSubmitted()) {
85 $userForm->get('googleTwoFactor')->setData(true);
88 if ($userForm->isSubmitted() && $userForm->isValid()) {
89 // handle creation / reset of the OTP secret if checkbox changed from the previous state
90 if ($this->getParameter('twofactor_auth')) {
91 if (true === $userForm->get('googleTwoFactor')->getData() && false === $user->isGoogleAuthenticatorEnabled()) {
92 $secret = $this->get('scheb_two_factor.security.google_authenticator')->generateSecret();
94 $user->setGoogleAuthenticatorSecret($secret);
95 $user->setEmailTwoFactor(false);
97 $this->addFlash('OtpQrCode', $this->get('scheb_two_factor.security.google_authenticator')->getQRContent($user));
98 } elseif (false === $userForm->get('googleTwoFactor')->getData() && true === $user->isGoogleAuthenticatorEnabled()) {
99 $user->setGoogleAuthenticatorSecret(null);
103 $userManager->updateUser($user, true);
107 'flashes.config.notice.user_updated'
110 return $this->redirect($this->generateUrl('config') . '#set3');
113 // handle rss information
114 $rssForm = $this->createForm(RssType
::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
115 $rssForm->handleRequest($request);
117 if ($rssForm->isSubmitted() && $rssForm->isValid()) {
118 $em->persist($config);
123 'flashes.config.notice.rss_updated'
126 return $this->redirect($this->generateUrl('config') . '#set2');
129 // handle tagging rule
130 $taggingRule = new TaggingRule();
131 $action = $this->generateUrl('config') . '#set5';
133 if ($request->query
->has('tagging-rule')) {
134 $taggingRule = $this->getDoctrine()
135 ->getRepository('WallabagCoreBundle:TaggingRule')
136 ->find($request->query
->get('tagging-rule'));
138 if ($this->getUser()->getId() !== $taggingRule->getConfig()->getUser()->getId()) {
139 return $this->redirect($action);
142 $action = $this->generateUrl('config') . '?tagging-rule=' . $taggingRule->getId() . '#set5';
145 $newTaggingRule = $this->createForm(TaggingRuleType
::class, $taggingRule, ['action' => $action]);
146 $newTaggingRule->handleRequest($request);
148 if ($newTaggingRule->isSubmitted() && $newTaggingRule->isValid()) {
149 $taggingRule->setConfig($config);
150 $em->persist($taggingRule);
155 'flashes.config.notice.tagging_rules_updated'
158 return $this->redirect($this->generateUrl('config') . '#set5');
161 return $this->render('WallabagCoreBundle:Config:index.html.twig', [
163 'config' => $configForm->createView(),
164 'rss' => $rssForm->createView(),
165 'pwd' => $pwdForm->createView(),
166 'user' => $userForm->createView(),
167 'new_tagging_rule' => $newTaggingRule->createView(),
170 'username' => $user->getUsername(),
171 'token' => $config->getRssToken(),
173 'twofactor_auth' => $this->getParameter('twofactor_auth'),
174 'wallabag_url' => $this->getParameter('domain_name'),
175 'enabled_users' => $this->get('wallabag_user.user_repository')
176 ->getSumEnabledUsers(),
181 * @param Request $request
183 * @Route("/generate-token", name="generate_token")
185 * @return RedirectResponse|JsonResponse
187 public function generateTokenAction(Request
$request)
189 $config = $this->getConfig();
190 $config->setRssToken(Utils
::generateToken());
192 $em = $this->getDoctrine()->getManager();
193 $em->persist($config);
196 if ($request->isXmlHttpRequest()) {
197 return new JsonResponse(['token' => $config->getRssToken()]);
202 'flashes.config.notice.rss_token_updated'
205 return $this->redirect($this->generateUrl('config') . '#set2');
209 * Deletes a tagging rule and redirect to the config homepage.
211 * @param TaggingRule $rule
213 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
215 * @return RedirectResponse
217 public function deleteTaggingRuleAction(TaggingRule
$rule)
219 $this->validateRuleAction($rule);
221 $em = $this->getDoctrine()->getManager();
227 'flashes.config.notice.tagging_rules_deleted'
230 return $this->redirect($this->generateUrl('config') . '#set5');
234 * Edit a tagging rule.
236 * @param TaggingRule $rule
238 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
240 * @return RedirectResponse
242 public function editTaggingRuleAction(TaggingRule
$rule)
244 $this->validateRuleAction($rule);
246 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
250 * Remove all annotations OR tags OR entries for the current user.
252 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
254 * @return RedirectResponse
256 public function resetAction($type)
261 ->getRepository('WallabagAnnotationBundle:Annotation')
262 ->removeAllByUserId($this->getUser()->getId());
265 $this->removeAllTagsByUserId($this->getUser()->getId());
268 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
269 // otherwise they won't be removed ...
270 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform
) {
271 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
274 // manually remove tags to avoid orphan tag
275 $this->removeAllTagsByUserId($this->getUser()->getId());
277 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
280 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform
) {
281 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
284 // manually remove tags to avoid orphan tag
285 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
287 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
293 'flashes.config.notice.' . $type . '_reset'
296 return $this->redirect($this->generateUrl('config') . '#set3');
300 * Delete account for current user.
302 * @Route("/account/delete", name="delete_account")
304 * @param Request $request
306 * @throws AccessDeniedHttpException
308 * @return \Symfony\Component\HttpFoundation\RedirectResponse
310 public function deleteAccountAction(Request
$request)
312 $enabledUsers = $this->get('wallabag_user.user_repository')
313 ->getSumEnabledUsers();
315 if ($enabledUsers <= 1) {
316 throw new AccessDeniedHttpException();
319 $user = $this->getUser();
321 // logout current user
322 $this->get('security.token_storage')->setToken(null);
323 $request->getSession()->invalidate();
325 $em = $this->get('fos_user.user_manager');
326 $em->deleteUser($user);
328 return $this->redirect($this->generateUrl('fos_user_security_login'));
332 * Switch view mode for current user.
334 * @Route("/config/view-mode", name="switch_view_mode")
336 * @param Request $request
338 * @return \Symfony\Component\HttpFoundation\RedirectResponse
340 public function changeViewModeAction(Request
$request)
342 $user = $this->getUser();
343 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
345 $em = $this->getDoctrine()->getManager();
349 return $this->redirect($request->headers
->get('referer'));
353 * Change the locale for the current user.
355 * @param Request $request
356 * @param string $language
358 * @Route("/locale/{language}", name="changeLocale")
360 * @return \Symfony\Component\HttpFoundation\RedirectResponse
362 public function setLocaleAction(Request
$request, $language = null)
364 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
366 if (0 === \
count($errors)) {
367 $request->getSession()->set('_locale', $language);
370 return $this->redirect($request->headers
->get('referer', $this->generateUrl('homepage')));
374 * Remove all tags for given tags and a given user and cleanup orphan tags.
379 private function removeAllTagsByStatusAndUserId($tags, $userId)
385 $this->get('wallabag_core.entry_repository')
386 ->removeTags($userId, $tags);
388 // cleanup orphan tags
389 $em = $this->getDoctrine()->getManager();
391 foreach ($tags as $tag) {
392 if (0 === \
count($tag->getEntries())) {
401 * Remove all tags for a given user and cleanup orphan tags.
405 private function removeAllTagsByUserId($userId)
407 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
408 $this->removeAllTagsByStatusAndUserId($tags, $userId);
412 * Remove all tags for a given user and cleanup orphan tags.
416 private function removeTagsForArchivedByUserId($userId)
418 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
419 $this->removeAllTagsByStatusAndUserId($tags, $userId);
422 private function removeAnnotationsForArchivedByUserId($userId)
424 $em = $this->getDoctrine()->getManager();
426 $archivedEntriesAnnotations = $this->getDoctrine()
427 ->getRepository('WallabagAnnotationBundle:Annotation')
428 ->findAllArchivedEntriesByUser($userId);
430 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
431 $em->remove($archivedEntriesAnnotation);
438 * Validate that a rule can be edited/deleted by the current user.
440 * @param TaggingRule $rule
442 private function validateRuleAction(TaggingRule
$rule)
444 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
445 throw $this->createAccessDeniedException('You can not access this tagging rule.');
450 * Retrieve config for the current user.
451 * If no config were found, create a new one.
455 private function getConfig()
457 $config = $this->getDoctrine()
458 ->getRepository('WallabagCoreBundle:Config')
459 ->findOneByUser($this->getUser());
461 // should NEVER HAPPEN ...
463 $config = new Config($this->getUser());