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