3 namespace Wallabag\CoreBundle\Controller
;
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
;
26 class ConfigController
extends Controller
29 * @param Request $request
31 * @Route("/config", name="config")
33 public function indexAction(Request
$request)
35 $em = $this->getDoctrine()->getManager();
36 $config = $this->getConfig();
37 $userManager = $this->container
->get('fos_user.user_manager');
38 $user = $this->getUser();
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);
44 if ($configForm->isSubmitted() && $configForm->isValid()) {
45 $em->persist($config);
48 $request->getSession()->set('_locale', $config->getLanguage());
50 // switch active theme
51 $activeTheme = $this->get('liip_theme.active_theme');
52 $activeTheme->setName($config->getTheme());
56 'flashes.config.notice.config_saved'
59 return $this->redirect($this->generateUrl('config'));
62 // handle changing password
63 $pwdForm = $this->createForm(ChangePasswordType
::class, null, ['action' => $this->generateUrl('config') . '#set4']);
64 $pwdForm->handleRequest($request);
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';
70 $message = 'flashes.config.notice.password_updated';
72 $user->setPlainPassword($pwdForm->get('new_password')->getData());
73 $userManager->updateUser($user, true);
76 $this->addFlash('notice', $message);
78 return $this->redirect($this->generateUrl('config') . '#set4');
81 // handle changing user information
82 $userForm = $this->createForm(UserInformationType
::class, $user, [
83 'validation_groups' => ['Profile'],
84 'action' => $this->generateUrl('config') . '#set3',
86 $userForm->handleRequest($request);
88 if ($userForm->isSubmitted() && $userForm->isValid()) {
89 $userManager->updateUser($user, true);
93 'flashes.config.notice.user_updated'
96 return $this->redirect($this->generateUrl('config') . '#set3');
99 // handle feed information
100 $feedForm = $this->createForm(FeedType
::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
101 $feedForm->handleRequest($request);
103 if ($feedForm->isSubmitted() && $feedForm->isValid()) {
104 $em->persist($config);
109 'flashes.config.notice.feed_updated'
112 return $this->redirect($this->generateUrl('config') . '#set2');
115 // handle tagging rule
116 $taggingRule = new TaggingRule();
117 $action = $this->generateUrl('config') . '#set5';
119 if ($request->query
->has('tagging-rule')) {
120 $taggingRule = $this->getDoctrine()
121 ->getRepository('WallabagCoreBundle:TaggingRule')
122 ->find($request->query
->get('tagging-rule'));
124 if ($this->getUser()->getId() !== $taggingRule->getConfig()->getUser()->getId()) {
125 return $this->redirect($action);
128 $action = $this->generateUrl('config') . '?tagging-rule=' . $taggingRule->getId() . '#set5';
131 $newTaggingRule = $this->createForm(TaggingRuleType
::class, $taggingRule, ['action' => $action]);
132 $newTaggingRule->handleRequest($request);
134 if ($newTaggingRule->isSubmitted() && $newTaggingRule->isValid()) {
135 $taggingRule->setConfig($config);
136 $em->persist($taggingRule);
141 'flashes.config.notice.tagging_rules_updated'
144 return $this->redirect($this->generateUrl('config') . '#set5');
147 // handle tagging rules import
148 $taggingRulesImportform = $this->createForm(TaggingRuleImportType
::class);
149 $taggingRulesImportform->handleRequest($request);
151 if ($taggingRulesImportform->isSubmitted() && $taggingRulesImportform->isValid()) {
152 $message = 'flashes.config.notice.tagging_rules_not_imported';
153 $file = $taggingRulesImportform->get('file')->getData();
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);
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);
169 $message = 'flashes.config.notice.tagging_rules_imported';
173 $this->addFlash('notice', $message);
175 return $this->redirect($this->generateUrl('config') . '#set5');
178 return $this->render('WallabagCoreBundle:Config:index.html.twig', [
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(),
188 'username' => $user->getUsername(),
189 'token' => $config->getFeedToken(),
191 'twofactor_auth' => $this->getParameter('twofactor_auth'),
192 'wallabag_url' => $this->getParameter('domain_name'),
193 'enabled_users' => $this->get('wallabag_user.user_repository')->getSumEnabledUsers(),
198 * Enable 2FA using email.
200 * @Route("/config/otp/email", name="config_otp_email")
202 public function otpEmailAction()
204 if (!$this->getParameter('twofactor_auth')) {
205 return $this->createNotFoundException('two_factor not enabled');
208 $user = $this->getUser();
210 $user->setGoogleAuthenticatorSecret(null);
211 $user->setBackupCodes(null);
212 $user->setEmailTwoFactor(true);
214 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
218 'flashes.config.notice.otp_enabled'
221 return $this->redirect($this->generateUrl('config') . '#set3');
225 * Enable 2FA using OTP app, user will need to confirm the generated code from the app.
227 * @Route("/config/otp/app", name="config_otp_app")
229 public function otpAppAction()
231 if (!$this->getParameter('twofactor_auth')) {
232 return $this->createNotFoundException('two_factor not enabled');
235 $user = $this->getUser();
236 $secret = $this->get('scheb_two_factor.security.google_authenticator')->generateSecret();
238 $user->setGoogleAuthenticatorSecret($secret);
239 $user->setEmailTwoFactor(false);
241 $backupCodes = (new BackupCodes())->toArray();
242 $backupCodesHashed = array_map(
243 function ($backupCode) {
244 return password_hash($backupCode, PASSWORD_DEFAULT
);
249 $user->setBackupCodes($backupCodesHashed);
251 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
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),
260 * Cancelling 2FA using OTP app.
262 * @Route("/config/otp/app/cancel", name="config_otp_app_cancel")
264 public function otpAppCancelAction()
266 if (!$this->getParameter('twofactor_auth')) {
267 return $this->createNotFoundException('two_factor not enabled');
270 $user = $this->getUser();
271 $user->setGoogleAuthenticatorSecret(null);
272 $user->setBackupCodes(null);
274 $this->container
->get('fos_user.user_manager')->updateUser($user, true);
276 return $this->redirect($this->generateUrl('config') . '#set3');
282 * @param Request $request
284 * @Route("/config/otp/app/check", name="config_otp_app_check")
286 public function otpAppCheckAction(Request
$request)
288 $isValid = $this->get('scheb_two_factor.security.google_authenticator')->checkCode(
290 $request->get('_auth_code')
293 if (true === $isValid) {
296 'flashes.config.notice.otp_enabled'
299 return $this->redirect($this->generateUrl('config') . '#set3');
304 'scheb_two_factor.code_invalid'
307 return $this->redirect($this->generateUrl('config_otp_app'));
311 * @param Request $request
313 * @Route("/generate-token", name="generate_token")
315 * @return RedirectResponse|JsonResponse
317 public function generateTokenAction(Request
$request)
319 $config = $this->getConfig();
320 $config->setFeedToken(Utils
::generateToken());
322 $em = $this->getDoctrine()->getManager();
323 $em->persist($config);
326 if ($request->isXmlHttpRequest()) {
327 return new JsonResponse(['token' => $config->getFeedToken()]);
332 'flashes.config.notice.feed_token_updated'
335 return $this->redirect($this->generateUrl('config') . '#set2');
339 * @param Request $request
341 * @Route("/revoke-token", name="revoke_token")
343 * @return RedirectResponse|JsonResponse
345 public function revokeTokenAction(Request
$request)
347 $config = $this->getConfig();
348 $config->setFeedToken(null);
350 $em = $this->getDoctrine()->getManager();
351 $em->persist($config);
354 if ($request->isXmlHttpRequest()) {
355 return new JsonResponse();
360 'flashes.config.notice.feed_token_revoked'
363 return $this->redirect($this->generateUrl('config') . '#set2');
367 * Deletes a tagging rule and redirect to the config homepage.
369 * @param TaggingRule $rule
371 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
373 * @return RedirectResponse
375 public function deleteTaggingRuleAction(TaggingRule
$rule)
377 $this->validateRuleAction($rule);
379 $em = $this->getDoctrine()->getManager();
385 'flashes.config.notice.tagging_rules_deleted'
388 return $this->redirect($this->generateUrl('config') . '#set5');
392 * Edit a tagging rule.
394 * @param TaggingRule $rule
396 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
398 * @return RedirectResponse
400 public function editTaggingRuleAction(TaggingRule
$rule)
402 $this->validateRuleAction($rule);
404 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
408 * Remove all annotations OR tags OR entries for the current user.
410 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
412 * @return RedirectResponse
414 public function resetAction($type)
419 ->getRepository('WallabagAnnotationBundle:Annotation')
420 ->removeAllByUserId($this->getUser()->getId());
423 $this->removeAllTagsByUserId($this->getUser()->getId());
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());
432 // manually remove tags to avoid orphan tag
433 $this->removeAllTagsByUserId($this->getUser()->getId());
435 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
438 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform
) {
439 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
442 // manually remove tags to avoid orphan tag
443 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
445 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
451 'flashes.config.notice.' . $type . '_reset'
454 return $this->redirect($this->generateUrl('config') . '#set3');
458 * Delete account for current user.
460 * @Route("/account/delete", name="delete_account")
462 * @param Request $request
464 * @throws AccessDeniedHttpException
466 * @return \Symfony\Component\HttpFoundation\RedirectResponse
468 public function deleteAccountAction(Request
$request)
470 $enabledUsers = $this->get('wallabag_user.user_repository')
471 ->getSumEnabledUsers();
473 if ($enabledUsers <= 1) {
474 throw new AccessDeniedHttpException();
477 $user = $this->getUser();
479 // logout current user
480 $this->get('security.token_storage')->setToken(null);
481 $request->getSession()->invalidate();
483 $em = $this->get('fos_user.user_manager');
484 $em->deleteUser($user);
486 return $this->redirect($this->generateUrl('fos_user_security_login'));
490 * Switch view mode for current user.
492 * @Route("/config/view-mode", name="switch_view_mode")
494 * @param Request $request
496 * @return \Symfony\Component\HttpFoundation\RedirectResponse
498 public function changeViewModeAction(Request
$request)
500 $user = $this->getUser();
501 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
503 $em = $this->getDoctrine()->getManager();
507 return $this->redirect($request->headers
->get('referer'));
511 * Change the locale for the current user.
513 * @param Request $request
514 * @param string $language
516 * @Route("/locale/{language}", name="changeLocale")
518 * @return \Symfony\Component\HttpFoundation\RedirectResponse
520 public function setLocaleAction(Request
$request, $language = null)
522 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
524 if (0 === \
count($errors)) {
525 $request->getSession()->set('_locale', $language);
528 return $this->redirect($request->headers
->get('referer', $this->generateUrl('homepage')));
532 * Export tagging rules for the logged in user.
534 * @Route("/tagging-rule/export", name="export_tagging_rule")
538 public function exportTaggingRulesAction()
540 $data = SerializerBuilder
::create()->build()->serialize(
541 $this->getUser()->getConfig()->getTaggingRules(),
543 SerializationContext
::create()->setGroups(['export_tagging_rule'])
546 return Response
::create(
550 'Content-type' => 'application/json',
551 'Content-Disposition' => 'attachment; filename="tagging_rules_' . $this->getUser()->getUsername() . '.json"',
552 'Content-Transfer-Encoding' => 'UTF-8',
558 * Remove all tags for given tags and a given user and cleanup orphan tags.
563 private function removeAllTagsByStatusAndUserId($tags, $userId)
569 $this->get('wallabag_core.entry_repository')
570 ->removeTags($userId, $tags);
572 // cleanup orphan tags
573 $em = $this->getDoctrine()->getManager();
575 foreach ($tags as $tag) {
576 if (0 === \
count($tag->getEntries())) {
585 * Remove all tags for a given user and cleanup orphan tags.
589 private function removeAllTagsByUserId($userId)
591 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
592 $this->removeAllTagsByStatusAndUserId($tags, $userId);
596 * Remove all tags for a given user and cleanup orphan tags.
600 private function removeTagsForArchivedByUserId($userId)
602 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
603 $this->removeAllTagsByStatusAndUserId($tags, $userId);
606 private function removeAnnotationsForArchivedByUserId($userId)
608 $em = $this->getDoctrine()->getManager();
610 $archivedEntriesAnnotations = $this->getDoctrine()
611 ->getRepository('WallabagAnnotationBundle:Annotation')
612 ->findAllArchivedEntriesByUser($userId);
614 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
615 $em->remove($archivedEntriesAnnotation);
622 * Validate that a rule can be edited/deleted by the current user.
624 * @param TaggingRule $rule
626 private function validateRuleAction(TaggingRule
$rule)
628 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
629 throw $this->createAccessDeniedException('You can not access this tagging rule.');
634 * Retrieve config for the current user.
635 * If no config were found, create a new one.
639 private function getConfig()
641 $config = $this->getDoctrine()
642 ->getRepository('WallabagCoreBundle:Config')
643 ->findOneByUser($this->getUser());
645 // should NEVER HAPPEN ...
647 $config = new Config($this->getUser());