]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Controller/ConfigController.php
Show untagged entries count on tag list (#3993)
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Controller / ConfigController.php
CommitLineData
4d85d7e9
J
1<?php
2
3namespace Wallabag\CoreBundle\Controller;
4
dfd0a7bc 5use PragmaRX\Recovery\Recovery as BackupCodes;
4d85d7e9 6use Symfony\Bundle\FrameworkBundle\Controller\Controller;
0c83fd59 7use Symfony\Component\HttpFoundation\JsonResponse;
98568055 8use Symfony\Component\HttpFoundation\RedirectResponse;
619cc453 9use Symfony\Component\HttpFoundation\Request;
bb0c78f4 10use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
115de64e 11use Symfony\Component\Routing\Annotation\Route;
4d4147b2 12use Symfony\Component\Validator\Constraints\Locale as LocaleConstraint;
4d85d7e9 13use Wallabag\CoreBundle\Entity\Config;
f19f9f62 14use Wallabag\CoreBundle\Entity\TaggingRule;
d9085c63 15use Wallabag\CoreBundle\Form\Type\ChangePasswordType;
f808b016 16use Wallabag\CoreBundle\Form\Type\ConfigType;
531c8d0a 17use Wallabag\CoreBundle\Form\Type\FeedType;
619cc453
JB
18use Wallabag\CoreBundle\Form\Type\TaggingRuleType;
19use Wallabag\CoreBundle\Form\Type\UserInformationType;
0c83fd59 20use Wallabag\CoreBundle\Tools\Utils;
4d85d7e9
J
21
22class ConfigController extends Controller
23{
24 /**
25 * @param Request $request
26 *
27 * @Route("/config", name="config")
4d85d7e9
J
28 */
29 public function indexAction(Request $request)
30 {
d9085c63 31 $em = $this->getDoctrine()->getManager();
4d85d7e9 32 $config = $this->getConfig();
fcb1fba5 33 $userManager = $this->container->get('fos_user.user_manager');
c0d9eba0 34 $user = $this->getUser();
4d85d7e9 35
32da2a70 36 // handle basic config detail (this form is defined as a service)
4094ea47 37 $configForm = $this->createForm(ConfigType::class, $config, ['action' => $this->generateUrl('config')]);
d9085c63 38 $configForm->handleRequest($request);
4d85d7e9 39
21e7ccef 40 if ($configForm->isSubmitted() && $configForm->isValid()) {
4d85d7e9
J
41 $em->persist($config);
42 $em->flush();
43
ece4718f
NL
44 $request->getSession()->set('_locale', $config->getLanguage());
45
32da2a70
J
46 // switch active theme
47 $activeTheme = $this->get('liip_theme.active_theme');
48 $activeTheme->setName($config->getTheme());
49
a6b242a1 50 $this->addFlash(
4d85d7e9 51 'notice',
4204a06b 52 'flashes.config.notice.config_saved'
4d85d7e9
J
53 );
54
55 return $this->redirect($this->generateUrl('config'));
56 }
57
d9085c63 58 // handle changing password
f808b016 59 $pwdForm = $this->createForm(ChangePasswordType::class, null, ['action' => $this->generateUrl('config') . '#set4']);
d9085c63
J
60 $pwdForm->handleRequest($request);
61
21e7ccef 62 if ($pwdForm->isSubmitted() && $pwdForm->isValid()) {
a4f42c59 63 if ($this->get('craue_config')->get('demo_mode_enabled') && $this->get('craue_config')->get('demo_mode_username') === $user->getUsername()) {
4204a06b 64 $message = 'flashes.config.notice.password_not_updated_demo';
6c9f50a6 65 } else {
4204a06b 66 $message = 'flashes.config.notice.password_updated';
b6c00b0b 67
d8d56448
NL
68 $user->setPlainPassword($pwdForm->get('new_password')->getData());
69 $userManager->updateUser($user, true);
6c9f50a6 70 }
d9085c63 71
a6b242a1 72 $this->addFlash('notice', $message);
b6c00b0b 73
f808b016 74 return $this->redirect($this->generateUrl('config') . '#set4');
d9085c63
J
75 }
76
c0d9eba0 77 // handle changing user information
4094ea47
JB
78 $userForm = $this->createForm(UserInformationType::class, $user, [
79 'validation_groups' => ['Profile'],
f808b016 80 'action' => $this->generateUrl('config') . '#set3',
4094ea47 81 ]);
c0d9eba0
J
82 $userForm->handleRequest($request);
83
21e7ccef 84 if ($userForm->isSubmitted() && $userForm->isValid()) {
fcb1fba5 85 $userManager->updateUser($user, true);
c0d9eba0 86
a6b242a1 87 $this->addFlash(
c0d9eba0 88 'notice',
4204a06b 89 'flashes.config.notice.user_updated'
c0d9eba0
J
90 );
91
f808b016 92 return $this->redirect($this->generateUrl('config') . '#set3');
c0d9eba0
J
93 }
94
531c8d0a
TC
95 // handle feed information
96 $feedForm = $this->createForm(FeedType::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
97 $feedForm->handleRequest($request);
0c83fd59 98
531c8d0a 99 if ($feedForm->isSubmitted() && $feedForm->isValid()) {
0c83fd59
J
100 $em->persist($config);
101 $em->flush();
102
a6b242a1 103 $this->addFlash(
0c83fd59 104 'notice',
531c8d0a 105 'flashes.config.notice.feed_updated'
0c83fd59
J
106 );
107
f808b016 108 return $this->redirect($this->generateUrl('config') . '#set2');
0c83fd59
J
109 }
110
f19f9f62
KG
111 // handle tagging rule
112 $taggingRule = new TaggingRule();
f808b016 113 $action = $this->generateUrl('config') . '#set5';
bf3dc999
JB
114
115 if ($request->query->has('tagging-rule')) {
116 $taggingRule = $this->getDoctrine()
117 ->getRepository('WallabagCoreBundle:TaggingRule')
118 ->find($request->query->get('tagging-rule'));
119
120 if ($this->getUser()->getId() !== $taggingRule->getConfig()->getUser()->getId()) {
121 return $this->redirect($action);
122 }
123
f808b016 124 $action = $this->generateUrl('config') . '?tagging-rule=' . $taggingRule->getId() . '#set5';
bf3dc999
JB
125 }
126
127 $newTaggingRule = $this->createForm(TaggingRuleType::class, $taggingRule, ['action' => $action]);
f19f9f62
KG
128 $newTaggingRule->handleRequest($request);
129
21e7ccef 130 if ($newTaggingRule->isSubmitted() && $newTaggingRule->isValid()) {
f19f9f62
KG
131 $taggingRule->setConfig($config);
132 $em->persist($taggingRule);
133 $em->flush();
134
a6b242a1 135 $this->addFlash(
f19f9f62 136 'notice',
4204a06b 137 'flashes.config.notice.tagging_rules_updated'
f19f9f62
KG
138 );
139
f808b016 140 return $this->redirect($this->generateUrl('config') . '#set5');
f19f9f62
KG
141 }
142
4094ea47
JB
143 return $this->render('WallabagCoreBundle:Config:index.html.twig', [
144 'form' => [
0c83fd59 145 'config' => $configForm->createView(),
531c8d0a 146 'feed' => $feedForm->createView(),
0c83fd59
J
147 'pwd' => $pwdForm->createView(),
148 'user' => $userForm->createView(),
f19f9f62 149 'new_tagging_rule' => $newTaggingRule->createView(),
4094ea47 150 ],
531c8d0a 151 'feed' => [
0c83fd59 152 'username' => $user->getUsername(),
531c8d0a 153 'token' => $config->getFeedToken(),
4094ea47 154 ],
63e40f2d 155 'twofactor_auth' => $this->getParameter('twofactor_auth'),
be9d693e 156 'wallabag_url' => $this->getParameter('domain_name'),
a0c5eb00 157 'enabled_users' => $this->get('wallabag_user.user_repository')->getSumEnabledUsers(),
4094ea47 158 ]);
4d85d7e9
J
159 }
160
a0c5eb00
JB
161 /**
162 * Enable 2FA using email.
163 *
a0c5eb00
JB
164 * @Route("/config/otp/email", name="config_otp_email")
165 */
c416ed48 166 public function otpEmailAction()
a0c5eb00
JB
167 {
168 if (!$this->getParameter('twofactor_auth')) {
169 return $this->createNotFoundException('two_factor not enabled');
170 }
171
172 $user = $this->getUser();
173
174 $user->setGoogleAuthenticatorSecret(null);
175 $user->setBackupCodes(null);
176 $user->setEmailTwoFactor(true);
177
178 $this->container->get('fos_user.user_manager')->updateUser($user, true);
179
180 $this->addFlash(
181 'notice',
182 'flashes.config.notice.otp_enabled'
183 );
184
185 return $this->redirect($this->generateUrl('config') . '#set3');
186 }
187
188 /**
189 * Enable 2FA using OTP app, user will need to confirm the generated code from the app.
190 *
191 * @Route("/config/otp/app", name="config_otp_app")
192 */
193 public function otpAppAction()
194 {
195 if (!$this->getParameter('twofactor_auth')) {
196 return $this->createNotFoundException('two_factor not enabled');
197 }
198
199 $user = $this->getUser();
4654a83b 200 $secret = $this->get('scheb_two_factor.security.google_authenticator')->generateSecret();
a0c5eb00 201
4654a83b
JB
202 $user->setGoogleAuthenticatorSecret($secret);
203 $user->setEmailTwoFactor(false);
a0c5eb00 204
4654a83b
JB
205 $backupCodes = (new BackupCodes())->toArray();
206 $backupCodesHashed = array_map(
207 function ($backupCode) {
208 return password_hash($backupCode, PASSWORD_DEFAULT);
209 },
210 $backupCodes
211 );
a0c5eb00 212
4654a83b
JB
213 $user->setBackupCodes($backupCodesHashed);
214
215 $this->container->get('fos_user.user_manager')->updateUser($user, true);
a0c5eb00
JB
216
217 return $this->render('WallabagCoreBundle:Config:otp_app.html.twig', [
4654a83b 218 'backupCodes' => $backupCodes,
a0c5eb00
JB
219 'qr_code' => $this->get('scheb_two_factor.security.google_authenticator')->getQRContent($user),
220 ]);
221 }
222
223 /**
224 * Cancelling 2FA using OTP app.
225 *
226 * @Route("/config/otp/app/cancel", name="config_otp_app_cancel")
227 */
228 public function otpAppCancelAction()
229 {
230 if (!$this->getParameter('twofactor_auth')) {
231 return $this->createNotFoundException('two_factor not enabled');
232 }
233
234 $user = $this->getUser();
235 $user->setGoogleAuthenticatorSecret(null);
236 $user->setBackupCodes(null);
237
238 $this->container->get('fos_user.user_manager')->updateUser($user, true);
239
240 return $this->redirect($this->generateUrl('config') . '#set3');
241 }
242
243 /**
244 * Validate OTP code.
245 *
246 * @param Request $request
247 *
248 * @Route("/config/otp/app/check", name="config_otp_app_check")
249 */
250 public function otpAppCheckAction(Request $request)
251 {
252 $isValid = $this->get('scheb_two_factor.security.google_authenticator')->checkCode(
253 $this->getUser(),
254 $request->get('_auth_code')
255 );
256
257 if (true === $isValid) {
258 $this->addFlash(
259 'notice',
260 'flashes.config.notice.otp_enabled'
261 );
262
263 return $this->redirect($this->generateUrl('config') . '#set3');
264 }
265
266 $this->addFlash(
267 'two_factor',
268 'scheb_two_factor.code_invalid'
269 );
270
271 return $this->redirect($this->generateUrl('config_otp_app'));
272 }
273
0c83fd59
J
274 /**
275 * @param Request $request
276 *
277 * @Route("/generate-token", name="generate_token")
278 *
98568055 279 * @return RedirectResponse|JsonResponse
0c83fd59
J
280 */
281 public function generateTokenAction(Request $request)
282 {
283 $config = $this->getConfig();
531c8d0a 284 $config->setFeedToken(Utils::generateToken());
0c83fd59
J
285
286 $em = $this->getDoctrine()->getManager();
287 $em->persist($config);
288 $em->flush();
289
290 if ($request->isXmlHttpRequest()) {
531c8d0a 291 return new JsonResponse(['token' => $config->getFeedToken()]);
0c83fd59
J
292 }
293
a6b242a1 294 $this->addFlash(
c7a4f74f 295 'notice',
531c8d0a 296 'flashes.config.notice.feed_token_updated'
c7a4f74f
JB
297 );
298
f808b016 299 return $this->redirect($this->generateUrl('config') . '#set2');
0c83fd59
J
300 }
301
c4bf12aa
JB
302 /**
303 * @param Request $request
304 *
305 * @Route("/revoke-token", name="revoke_token")
306 *
307 * @return RedirectResponse|JsonResponse
308 */
309 public function revokeTokenAction(Request $request)
310 {
311 $config = $this->getConfig();
312 $config->setFeedToken(null);
313
314 $em = $this->getDoctrine()->getManager();
315 $em->persist($config);
316 $em->flush();
317
318 if ($request->isXmlHttpRequest()) {
319 return new JsonResponse();
320 }
321
322 $this->addFlash(
323 'notice',
324 'flashes.config.notice.feed_token_revoked'
325 );
326
327 return $this->redirect($this->generateUrl('config') . '#set2');
328 }
329
52e423f3
KG
330 /**
331 * Deletes a tagging rule and redirect to the config homepage.
332 *
333 * @param TaggingRule $rule
334 *
335 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
336 *
98568055 337 * @return RedirectResponse
52e423f3 338 */
5f8a7857 339 public function deleteTaggingRuleAction(TaggingRule $rule)
52e423f3 340 {
8799bde0 341 $this->validateRuleAction($rule);
52e423f3
KG
342
343 $em = $this->getDoctrine()->getManager();
344 $em->remove($rule);
345 $em->flush();
346
a6b242a1 347 $this->addFlash(
52e423f3 348 'notice',
4204a06b 349 'flashes.config.notice.tagging_rules_deleted'
52e423f3
KG
350 );
351
f808b016 352 return $this->redirect($this->generateUrl('config') . '#set5');
52e423f3
KG
353 }
354
bf3dc999
JB
355 /**
356 * Edit a tagging rule.
357 *
358 * @param TaggingRule $rule
359 *
360 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
361 *
362 * @return RedirectResponse
363 */
364 public function editTaggingRuleAction(TaggingRule $rule)
8799bde0
JB
365 {
366 $this->validateRuleAction($rule);
367
f808b016 368 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
8799bde0
JB
369 }
370
206bade5
JB
371 /**
372 * Remove all annotations OR tags OR entries for the current user.
373 *
374 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
375 *
376 * @return RedirectResponse
377 */
378 public function resetAction($type)
379 {
206bade5
JB
380 switch ($type) {
381 case 'annotations':
191564b7
JB
382 $this->getDoctrine()
383 ->getRepository('WallabagAnnotationBundle:Annotation')
384 ->removeAllByUserId($this->getUser()->getId());
206bade5 385 break;
206bade5 386 case 'tags':
191564b7
JB
387 $this->removeAllTagsByUserId($this->getUser()->getId());
388 break;
191564b7 389 case 'entries':
6da1aebc 390 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
191564b7 391 // otherwise they won't be removed ...
7ab5eb95 392 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
191564b7 393 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
206bade5
JB
394 }
395
8c61fd12 396 // manually remove tags to avoid orphan tag
f71e55ac
JB
397 $this->removeAllTagsByUserId($this->getUser()->getId());
398
25203e50 399 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
6da1aebc
TC
400 break;
401 case 'archived':
7ab5eb95 402 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
6da1aebc
TC
403 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
404 }
405
406 // manually remove tags to avoid orphan tag
407 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
408
25203e50 409 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
6da1aebc 410 break;
206bade5
JB
411 }
412
a6b242a1 413 $this->addFlash(
206bade5 414 'notice',
f808b016 415 'flashes.config.notice.' . $type . '_reset'
206bade5
JB
416 );
417
f808b016
JB
418 return $this->redirect($this->generateUrl('config') . '#set3');
419 }
420
421 /**
422 * Delete account for current user.
423 *
424 * @Route("/account/delete", name="delete_account")
425 *
426 * @param Request $request
427 *
428 * @throws AccessDeniedHttpException
429 *
430 * @return \Symfony\Component\HttpFoundation\RedirectResponse
431 */
432 public function deleteAccountAction(Request $request)
433 {
434 $enabledUsers = $this->get('wallabag_user.user_repository')
435 ->getSumEnabledUsers();
436
437 if ($enabledUsers <= 1) {
438 throw new AccessDeniedHttpException();
439 }
440
441 $user = $this->getUser();
442
443 // logout current user
444 $this->get('security.token_storage')->setToken(null);
445 $request->getSession()->invalidate();
446
447 $em = $this->get('fos_user.user_manager');
448 $em->deleteUser($user);
449
450 return $this->redirect($this->generateUrl('fos_user_security_login'));
451 }
452
453 /**
454 * Switch view mode for current user.
455 *
456 * @Route("/config/view-mode", name="switch_view_mode")
457 *
458 * @param Request $request
459 *
460 * @return \Symfony\Component\HttpFoundation\RedirectResponse
461 */
462 public function changeViewModeAction(Request $request)
463 {
464 $user = $this->getUser();
465 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
466
467 $em = $this->getDoctrine()->getManager();
468 $em->persist($user);
469 $em->flush();
470
471 return $this->redirect($request->headers->get('referer'));
206bade5
JB
472 }
473
be417ef2
NL
474 /**
475 * Change the locale for the current user.
476 *
477 * @param Request $request
478 * @param string $language
479 *
480 * @Route("/locale/{language}", name="changeLocale")
481 *
482 * @return \Symfony\Component\HttpFoundation\RedirectResponse
483 */
484 public function setLocaleAction(Request $request, $language = null)
485 {
4d4147b2
JB
486 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
487
488 if (0 === \count($errors)) {
489 $request->getSession()->set('_locale', $language);
be417ef2
NL
490 }
491
4d4147b2 492 return $this->redirect($request->headers->get('referer', $this->generateUrl('homepage')));
be417ef2
NL
493 }
494
191564b7 495 /**
e682a70f 496 * Remove all tags for given tags and a given user and cleanup orphan tags.
191564b7 497 *
e682a70f
NL
498 * @param array $tags
499 * @param int $userId
191564b7 500 */
e682a70f 501 private function removeAllTagsByStatusAndUserId($tags, $userId)
191564b7 502 {
191564b7
JB
503 if (empty($tags)) {
504 return;
505 }
506
25203e50 507 $this->get('wallabag_core.entry_repository')
191564b7 508 ->removeTags($userId, $tags);
f71e55ac 509
8c61fd12 510 // cleanup orphan tags
f71e55ac
JB
511 $em = $this->getDoctrine()->getManager();
512
513 foreach ($tags as $tag) {
2a1ceb67 514 if (0 === \count($tag->getEntries())) {
f71e55ac
JB
515 $em->remove($tag);
516 }
517 }
518
519 $em->flush();
191564b7
JB
520 }
521
e682a70f
NL
522 /**
523 * Remove all tags for a given user and cleanup orphan tags.
524 *
525 * @param int $userId
526 */
527 private function removeAllTagsByUserId($userId)
528 {
25203e50 529 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
e682a70f
NL
530 $this->removeAllTagsByStatusAndUserId($tags, $userId);
531 }
532
6da1aebc
TC
533 /**
534 * Remove all tags for a given user and cleanup orphan tags.
535 *
536 * @param int $userId
537 */
538 private function removeTagsForArchivedByUserId($userId)
539 {
25203e50 540 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
e682a70f 541 $this->removeAllTagsByStatusAndUserId($tags, $userId);
6da1aebc
TC
542 }
543
544 private function removeAnnotationsForArchivedByUserId($userId)
545 {
546 $em = $this->getDoctrine()->getManager();
547
548 $archivedEntriesAnnotations = $this->getDoctrine()
549 ->getRepository('WallabagAnnotationBundle:Annotation')
13a592a1 550 ->findAllArchivedEntriesByUser($userId);
6da1aebc
TC
551
552 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
553 $em->remove($archivedEntriesAnnotation);
554 }
555
556 $em->flush();
557 }
558
8799bde0 559 /**
2455472e 560 * Validate that a rule can be edited/deleted by the current user.
8799bde0 561 *
2455472e 562 * @param TaggingRule $rule
8799bde0
JB
563 */
564 private function validateRuleAction(TaggingRule $rule)
bf3dc999 565 {
f808b016 566 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
bf3dc999
JB
567 throw $this->createAccessDeniedException('You can not access this tagging rule.');
568 }
bf3dc999
JB
569 }
570
d9085c63
J
571 /**
572 * Retrieve config for the current user.
573 * If no config were found, create a new one.
574 *
4094ea47 575 * @return Config
d9085c63 576 */
4d85d7e9
J
577 private function getConfig()
578 {
579 $config = $this->getDoctrine()
580 ->getRepository('WallabagCoreBundle:Config')
581 ->findOneByUser($this->getUser());
582
ca17abce 583 // should NEVER HAPPEN ...
4d85d7e9
J
584 if (!$config) {
585 $config = new Config($this->getUser());
586 }
587
588 return $config;
589 }
590}