]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Controller/ConfigController.php
CS
[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;
0c83fd59 17use Wallabag\CoreBundle\Form\Type\RssType;
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
0c83fd59 95 // handle rss information
f808b016 96 $rssForm = $this->createForm(RssType::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
0c83fd59
J
97 $rssForm->handleRequest($request);
98
21e7ccef 99 if ($rssForm->isSubmitted() && $rssForm->isValid()) {
0c83fd59
J
100 $em->persist($config);
101 $em->flush();
102
a6b242a1 103 $this->addFlash(
0c83fd59 104 'notice',
4204a06b 105 'flashes.config.notice.rss_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
J
145 'config' => $configForm->createView(),
146 'rss' => $rssForm->createView(),
147 'pwd' => $pwdForm->createView(),
148 'user' => $userForm->createView(),
f19f9f62 149 'new_tagging_rule' => $newTaggingRule->createView(),
4094ea47
JB
150 ],
151 'rss' => [
0c83fd59
J
152 'username' => $user->getUsername(),
153 'token' => $config->getRssToken(),
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();
200
201 if (!$user->isGoogleTwoFactor()) {
202 $secret = $this->get('scheb_two_factor.security.google_authenticator')->generateSecret();
203
204 $user->setGoogleAuthenticatorSecret($secret);
205 $user->setEmailTwoFactor(false);
206 $user->setBackupCodes((new BackupCodes())->toArray());
207
208 $this->container->get('fos_user.user_manager')->updateUser($user, true);
209 }
210
211 return $this->render('WallabagCoreBundle:Config:otp_app.html.twig', [
212 'qr_code' => $this->get('scheb_two_factor.security.google_authenticator')->getQRContent($user),
213 ]);
214 }
215
216 /**
217 * Cancelling 2FA using OTP app.
218 *
219 * @Route("/config/otp/app/cancel", name="config_otp_app_cancel")
220 */
221 public function otpAppCancelAction()
222 {
223 if (!$this->getParameter('twofactor_auth')) {
224 return $this->createNotFoundException('two_factor not enabled');
225 }
226
227 $user = $this->getUser();
228 $user->setGoogleAuthenticatorSecret(null);
229 $user->setBackupCodes(null);
230
231 $this->container->get('fos_user.user_manager')->updateUser($user, true);
232
233 return $this->redirect($this->generateUrl('config') . '#set3');
234 }
235
236 /**
237 * Validate OTP code.
238 *
239 * @param Request $request
240 *
241 * @Route("/config/otp/app/check", name="config_otp_app_check")
242 */
243 public function otpAppCheckAction(Request $request)
244 {
245 $isValid = $this->get('scheb_two_factor.security.google_authenticator')->checkCode(
246 $this->getUser(),
247 $request->get('_auth_code')
248 );
249
250 if (true === $isValid) {
251 $this->addFlash(
252 'notice',
253 'flashes.config.notice.otp_enabled'
254 );
255
256 return $this->redirect($this->generateUrl('config') . '#set3');
257 }
258
259 $this->addFlash(
260 'two_factor',
261 'scheb_two_factor.code_invalid'
262 );
263
264 return $this->redirect($this->generateUrl('config_otp_app'));
265 }
266
0c83fd59
J
267 /**
268 * @param Request $request
269 *
270 * @Route("/generate-token", name="generate_token")
271 *
98568055 272 * @return RedirectResponse|JsonResponse
0c83fd59
J
273 */
274 public function generateTokenAction(Request $request)
275 {
276 $config = $this->getConfig();
277 $config->setRssToken(Utils::generateToken());
278
279 $em = $this->getDoctrine()->getManager();
280 $em->persist($config);
281 $em->flush();
282
283 if ($request->isXmlHttpRequest()) {
4094ea47 284 return new JsonResponse(['token' => $config->getRssToken()]);
0c83fd59
J
285 }
286
a6b242a1 287 $this->addFlash(
c7a4f74f 288 'notice',
4204a06b 289 'flashes.config.notice.rss_token_updated'
c7a4f74f
JB
290 );
291
f808b016 292 return $this->redirect($this->generateUrl('config') . '#set2');
0c83fd59
J
293 }
294
52e423f3
KG
295 /**
296 * Deletes a tagging rule and redirect to the config homepage.
297 *
298 * @param TaggingRule $rule
299 *
300 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
301 *
98568055 302 * @return RedirectResponse
52e423f3 303 */
5f8a7857 304 public function deleteTaggingRuleAction(TaggingRule $rule)
52e423f3 305 {
8799bde0 306 $this->validateRuleAction($rule);
52e423f3
KG
307
308 $em = $this->getDoctrine()->getManager();
309 $em->remove($rule);
310 $em->flush();
311
a6b242a1 312 $this->addFlash(
52e423f3 313 'notice',
4204a06b 314 'flashes.config.notice.tagging_rules_deleted'
52e423f3
KG
315 );
316
f808b016 317 return $this->redirect($this->generateUrl('config') . '#set5');
52e423f3
KG
318 }
319
bf3dc999
JB
320 /**
321 * Edit a tagging rule.
322 *
323 * @param TaggingRule $rule
324 *
325 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
326 *
327 * @return RedirectResponse
328 */
329 public function editTaggingRuleAction(TaggingRule $rule)
8799bde0
JB
330 {
331 $this->validateRuleAction($rule);
332
f808b016 333 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
8799bde0
JB
334 }
335
206bade5
JB
336 /**
337 * Remove all annotations OR tags OR entries for the current user.
338 *
339 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
340 *
341 * @return RedirectResponse
342 */
343 public function resetAction($type)
344 {
206bade5
JB
345 switch ($type) {
346 case 'annotations':
191564b7
JB
347 $this->getDoctrine()
348 ->getRepository('WallabagAnnotationBundle:Annotation')
349 ->removeAllByUserId($this->getUser()->getId());
206bade5 350 break;
206bade5 351 case 'tags':
191564b7
JB
352 $this->removeAllTagsByUserId($this->getUser()->getId());
353 break;
191564b7 354 case 'entries':
6da1aebc 355 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
191564b7 356 // otherwise they won't be removed ...
7ab5eb95 357 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
191564b7 358 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
206bade5
JB
359 }
360
8c61fd12 361 // manually remove tags to avoid orphan tag
f71e55ac
JB
362 $this->removeAllTagsByUserId($this->getUser()->getId());
363
25203e50 364 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
6da1aebc
TC
365 break;
366 case 'archived':
7ab5eb95 367 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
6da1aebc
TC
368 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
369 }
370
371 // manually remove tags to avoid orphan tag
372 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
373
25203e50 374 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
6da1aebc 375 break;
206bade5
JB
376 }
377
a6b242a1 378 $this->addFlash(
206bade5 379 'notice',
f808b016 380 'flashes.config.notice.' . $type . '_reset'
206bade5
JB
381 );
382
f808b016
JB
383 return $this->redirect($this->generateUrl('config') . '#set3');
384 }
385
386 /**
387 * Delete account for current user.
388 *
389 * @Route("/account/delete", name="delete_account")
390 *
391 * @param Request $request
392 *
393 * @throws AccessDeniedHttpException
394 *
395 * @return \Symfony\Component\HttpFoundation\RedirectResponse
396 */
397 public function deleteAccountAction(Request $request)
398 {
399 $enabledUsers = $this->get('wallabag_user.user_repository')
400 ->getSumEnabledUsers();
401
402 if ($enabledUsers <= 1) {
403 throw new AccessDeniedHttpException();
404 }
405
406 $user = $this->getUser();
407
408 // logout current user
409 $this->get('security.token_storage')->setToken(null);
410 $request->getSession()->invalidate();
411
412 $em = $this->get('fos_user.user_manager');
413 $em->deleteUser($user);
414
415 return $this->redirect($this->generateUrl('fos_user_security_login'));
416 }
417
418 /**
419 * Switch view mode for current user.
420 *
421 * @Route("/config/view-mode", name="switch_view_mode")
422 *
423 * @param Request $request
424 *
425 * @return \Symfony\Component\HttpFoundation\RedirectResponse
426 */
427 public function changeViewModeAction(Request $request)
428 {
429 $user = $this->getUser();
430 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
431
432 $em = $this->getDoctrine()->getManager();
433 $em->persist($user);
434 $em->flush();
435
436 return $this->redirect($request->headers->get('referer'));
206bade5
JB
437 }
438
be417ef2
NL
439 /**
440 * Change the locale for the current user.
441 *
442 * @param Request $request
443 * @param string $language
444 *
445 * @Route("/locale/{language}", name="changeLocale")
446 *
447 * @return \Symfony\Component\HttpFoundation\RedirectResponse
448 */
449 public function setLocaleAction(Request $request, $language = null)
450 {
4d4147b2
JB
451 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
452
453 if (0 === \count($errors)) {
454 $request->getSession()->set('_locale', $language);
be417ef2
NL
455 }
456
4d4147b2 457 return $this->redirect($request->headers->get('referer', $this->generateUrl('homepage')));
be417ef2
NL
458 }
459
191564b7 460 /**
e682a70f 461 * Remove all tags for given tags and a given user and cleanup orphan tags.
191564b7 462 *
e682a70f
NL
463 * @param array $tags
464 * @param int $userId
191564b7 465 */
e682a70f 466 private function removeAllTagsByStatusAndUserId($tags, $userId)
191564b7 467 {
191564b7
JB
468 if (empty($tags)) {
469 return;
470 }
471
25203e50 472 $this->get('wallabag_core.entry_repository')
191564b7 473 ->removeTags($userId, $tags);
f71e55ac 474
8c61fd12 475 // cleanup orphan tags
f71e55ac
JB
476 $em = $this->getDoctrine()->getManager();
477
478 foreach ($tags as $tag) {
2a1ceb67 479 if (0 === \count($tag->getEntries())) {
f71e55ac
JB
480 $em->remove($tag);
481 }
482 }
483
484 $em->flush();
191564b7
JB
485 }
486
e682a70f
NL
487 /**
488 * Remove all tags for a given user and cleanup orphan tags.
489 *
490 * @param int $userId
491 */
492 private function removeAllTagsByUserId($userId)
493 {
25203e50 494 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
e682a70f
NL
495 $this->removeAllTagsByStatusAndUserId($tags, $userId);
496 }
497
6da1aebc
TC
498 /**
499 * Remove all tags for a given user and cleanup orphan tags.
500 *
501 * @param int $userId
502 */
503 private function removeTagsForArchivedByUserId($userId)
504 {
25203e50 505 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
e682a70f 506 $this->removeAllTagsByStatusAndUserId($tags, $userId);
6da1aebc
TC
507 }
508
509 private function removeAnnotationsForArchivedByUserId($userId)
510 {
511 $em = $this->getDoctrine()->getManager();
512
513 $archivedEntriesAnnotations = $this->getDoctrine()
514 ->getRepository('WallabagAnnotationBundle:Annotation')
13a592a1 515 ->findAllArchivedEntriesByUser($userId);
6da1aebc
TC
516
517 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
518 $em->remove($archivedEntriesAnnotation);
519 }
520
521 $em->flush();
522 }
523
8799bde0 524 /**
2455472e 525 * Validate that a rule can be edited/deleted by the current user.
8799bde0 526 *
2455472e 527 * @param TaggingRule $rule
8799bde0
JB
528 */
529 private function validateRuleAction(TaggingRule $rule)
bf3dc999 530 {
f808b016 531 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
bf3dc999
JB
532 throw $this->createAccessDeniedException('You can not access this tagging rule.');
533 }
bf3dc999
JB
534 }
535
d9085c63
J
536 /**
537 * Retrieve config for the current user.
538 * If no config were found, create a new one.
539 *
4094ea47 540 * @return Config
d9085c63 541 */
4d85d7e9
J
542 private function getConfig()
543 {
544 $config = $this->getDoctrine()
545 ->getRepository('WallabagCoreBundle:Config')
546 ->findOneByUser($this->getUser());
547
ca17abce 548 // should NEVER HAPPEN ...
4d85d7e9
J
549 if (!$config) {
550 $config = new Config($this->getUser());
551 }
552
553 return $config;
554 }
555}