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