]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Controller/ConfigController.php
Merge remote-tracking branch 'origin/master' into 2.4
[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
52e423f3
KG
302 /**
303 * Deletes a tagging rule and redirect to the config homepage.
304 *
305 * @param TaggingRule $rule
306 *
307 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
308 *
98568055 309 * @return RedirectResponse
52e423f3 310 */
5f8a7857 311 public function deleteTaggingRuleAction(TaggingRule $rule)
52e423f3 312 {
8799bde0 313 $this->validateRuleAction($rule);
52e423f3
KG
314
315 $em = $this->getDoctrine()->getManager();
316 $em->remove($rule);
317 $em->flush();
318
a6b242a1 319 $this->addFlash(
52e423f3 320 'notice',
4204a06b 321 'flashes.config.notice.tagging_rules_deleted'
52e423f3
KG
322 );
323
f808b016 324 return $this->redirect($this->generateUrl('config') . '#set5');
52e423f3
KG
325 }
326
bf3dc999
JB
327 /**
328 * Edit a tagging rule.
329 *
330 * @param TaggingRule $rule
331 *
332 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
333 *
334 * @return RedirectResponse
335 */
336 public function editTaggingRuleAction(TaggingRule $rule)
8799bde0
JB
337 {
338 $this->validateRuleAction($rule);
339
f808b016 340 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
8799bde0
JB
341 }
342
206bade5
JB
343 /**
344 * Remove all annotations OR tags OR entries for the current user.
345 *
346 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
347 *
348 * @return RedirectResponse
349 */
350 public function resetAction($type)
351 {
206bade5
JB
352 switch ($type) {
353 case 'annotations':
191564b7
JB
354 $this->getDoctrine()
355 ->getRepository('WallabagAnnotationBundle:Annotation')
356 ->removeAllByUserId($this->getUser()->getId());
206bade5 357 break;
206bade5 358 case 'tags':
191564b7
JB
359 $this->removeAllTagsByUserId($this->getUser()->getId());
360 break;
191564b7 361 case 'entries':
6da1aebc 362 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
191564b7 363 // otherwise they won't be removed ...
7ab5eb95 364 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
191564b7 365 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
206bade5
JB
366 }
367
8c61fd12 368 // manually remove tags to avoid orphan tag
f71e55ac
JB
369 $this->removeAllTagsByUserId($this->getUser()->getId());
370
25203e50 371 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
6da1aebc
TC
372 break;
373 case 'archived':
7ab5eb95 374 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
6da1aebc
TC
375 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
376 }
377
378 // manually remove tags to avoid orphan tag
379 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
380
25203e50 381 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
6da1aebc 382 break;
206bade5
JB
383 }
384
a6b242a1 385 $this->addFlash(
206bade5 386 'notice',
f808b016 387 'flashes.config.notice.' . $type . '_reset'
206bade5
JB
388 );
389
f808b016
JB
390 return $this->redirect($this->generateUrl('config') . '#set3');
391 }
392
393 /**
394 * Delete account for current user.
395 *
396 * @Route("/account/delete", name="delete_account")
397 *
398 * @param Request $request
399 *
400 * @throws AccessDeniedHttpException
401 *
402 * @return \Symfony\Component\HttpFoundation\RedirectResponse
403 */
404 public function deleteAccountAction(Request $request)
405 {
406 $enabledUsers = $this->get('wallabag_user.user_repository')
407 ->getSumEnabledUsers();
408
409 if ($enabledUsers <= 1) {
410 throw new AccessDeniedHttpException();
411 }
412
413 $user = $this->getUser();
414
415 // logout current user
416 $this->get('security.token_storage')->setToken(null);
417 $request->getSession()->invalidate();
418
419 $em = $this->get('fos_user.user_manager');
420 $em->deleteUser($user);
421
422 return $this->redirect($this->generateUrl('fos_user_security_login'));
423 }
424
425 /**
426 * Switch view mode for current user.
427 *
428 * @Route("/config/view-mode", name="switch_view_mode")
429 *
430 * @param Request $request
431 *
432 * @return \Symfony\Component\HttpFoundation\RedirectResponse
433 */
434 public function changeViewModeAction(Request $request)
435 {
436 $user = $this->getUser();
437 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
438
439 $em = $this->getDoctrine()->getManager();
440 $em->persist($user);
441 $em->flush();
442
443 return $this->redirect($request->headers->get('referer'));
206bade5
JB
444 }
445
be417ef2
NL
446 /**
447 * Change the locale for the current user.
448 *
449 * @param Request $request
450 * @param string $language
451 *
452 * @Route("/locale/{language}", name="changeLocale")
453 *
454 * @return \Symfony\Component\HttpFoundation\RedirectResponse
455 */
456 public function setLocaleAction(Request $request, $language = null)
457 {
4d4147b2
JB
458 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
459
460 if (0 === \count($errors)) {
461 $request->getSession()->set('_locale', $language);
be417ef2
NL
462 }
463
4d4147b2 464 return $this->redirect($request->headers->get('referer', $this->generateUrl('homepage')));
be417ef2
NL
465 }
466
191564b7 467 /**
e682a70f 468 * Remove all tags for given tags and a given user and cleanup orphan tags.
191564b7 469 *
e682a70f
NL
470 * @param array $tags
471 * @param int $userId
191564b7 472 */
e682a70f 473 private function removeAllTagsByStatusAndUserId($tags, $userId)
191564b7 474 {
191564b7
JB
475 if (empty($tags)) {
476 return;
477 }
478
25203e50 479 $this->get('wallabag_core.entry_repository')
191564b7 480 ->removeTags($userId, $tags);
f71e55ac 481
8c61fd12 482 // cleanup orphan tags
f71e55ac
JB
483 $em = $this->getDoctrine()->getManager();
484
485 foreach ($tags as $tag) {
2a1ceb67 486 if (0 === \count($tag->getEntries())) {
f71e55ac
JB
487 $em->remove($tag);
488 }
489 }
490
491 $em->flush();
191564b7
JB
492 }
493
e682a70f
NL
494 /**
495 * Remove all tags for a given user and cleanup orphan tags.
496 *
497 * @param int $userId
498 */
499 private function removeAllTagsByUserId($userId)
500 {
25203e50 501 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
e682a70f
NL
502 $this->removeAllTagsByStatusAndUserId($tags, $userId);
503 }
504
6da1aebc
TC
505 /**
506 * Remove all tags for a given user and cleanup orphan tags.
507 *
508 * @param int $userId
509 */
510 private function removeTagsForArchivedByUserId($userId)
511 {
25203e50 512 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
e682a70f 513 $this->removeAllTagsByStatusAndUserId($tags, $userId);
6da1aebc
TC
514 }
515
516 private function removeAnnotationsForArchivedByUserId($userId)
517 {
518 $em = $this->getDoctrine()->getManager();
519
520 $archivedEntriesAnnotations = $this->getDoctrine()
521 ->getRepository('WallabagAnnotationBundle:Annotation')
13a592a1 522 ->findAllArchivedEntriesByUser($userId);
6da1aebc
TC
523
524 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
525 $em->remove($archivedEntriesAnnotation);
526 }
527
528 $em->flush();
529 }
530
8799bde0 531 /**
2455472e 532 * Validate that a rule can be edited/deleted by the current user.
8799bde0 533 *
2455472e 534 * @param TaggingRule $rule
8799bde0
JB
535 */
536 private function validateRuleAction(TaggingRule $rule)
bf3dc999 537 {
f808b016 538 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
bf3dc999
JB
539 throw $this->createAccessDeniedException('You can not access this tagging rule.');
540 }
bf3dc999
JB
541 }
542
d9085c63
J
543 /**
544 * Retrieve config for the current user.
545 * If no config were found, create a new one.
546 *
4094ea47 547 * @return Config
d9085c63 548 */
4d85d7e9
J
549 private function getConfig()
550 {
551 $config = $this->getDoctrine()
552 ->getRepository('WallabagCoreBundle:Config')
553 ->findOneByUser($this->getUser());
554
ca17abce 555 // should NEVER HAPPEN ...
4d85d7e9
J
556 if (!$config) {
557 $config = new Config($this->getUser());
558 }
559
560 return $config;
561 }
562}