]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Controller/ConfigController.php
Ensure language is valid
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Controller / ConfigController.php
CommitLineData
4d85d7e9
J
1<?php
2
3namespace Wallabag\CoreBundle\Controller;
4
4d85d7e9 5use Symfony\Bundle\FrameworkBundle\Controller\Controller;
0c83fd59 6use Symfony\Component\HttpFoundation\JsonResponse;
98568055 7use Symfony\Component\HttpFoundation\RedirectResponse;
619cc453 8use Symfony\Component\HttpFoundation\Request;
bb0c78f4 9use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
115de64e 10use Symfony\Component\Routing\Annotation\Route;
4d4147b2 11use Symfony\Component\Validator\Constraints\Locale as LocaleConstraint;
4d85d7e9 12use Wallabag\CoreBundle\Entity\Config;
f19f9f62 13use Wallabag\CoreBundle\Entity\TaggingRule;
d9085c63 14use Wallabag\CoreBundle\Form\Type\ChangePasswordType;
f808b016 15use Wallabag\CoreBundle\Form\Type\ConfigType;
0c83fd59 16use Wallabag\CoreBundle\Form\Type\RssType;
619cc453
JB
17use Wallabag\CoreBundle\Form\Type\TaggingRuleType;
18use Wallabag\CoreBundle\Form\Type\UserInformationType;
0c83fd59 19use Wallabag\CoreBundle\Tools\Utils;
4d85d7e9
J
20
21class ConfigController extends Controller
22{
23 /**
24 * @param Request $request
25 *
26 * @Route("/config", name="config")
4d85d7e9
J
27 */
28 public function indexAction(Request $request)
29 {
d9085c63 30 $em = $this->getDoctrine()->getManager();
4d85d7e9 31 $config = $this->getConfig();
fcb1fba5 32 $userManager = $this->container->get('fos_user.user_manager');
c0d9eba0 33 $user = $this->getUser();
4d85d7e9 34
32da2a70 35 // handle basic config detail (this form is defined as a service)
4094ea47 36 $configForm = $this->createForm(ConfigType::class, $config, ['action' => $this->generateUrl('config')]);
d9085c63 37 $configForm->handleRequest($request);
4d85d7e9 38
21e7ccef 39 if ($configForm->isSubmitted() && $configForm->isValid()) {
4d85d7e9
J
40 $em->persist($config);
41 $em->flush();
42
ece4718f
NL
43 $request->getSession()->set('_locale', $config->getLanguage());
44
32da2a70
J
45 // switch active theme
46 $activeTheme = $this->get('liip_theme.active_theme');
47 $activeTheme->setName($config->getTheme());
48
4d85d7e9
J
49 $this->get('session')->getFlashBag()->add(
50 'notice',
4204a06b 51 'flashes.config.notice.config_saved'
4d85d7e9
J
52 );
53
54 return $this->redirect($this->generateUrl('config'));
55 }
56
d9085c63 57 // handle changing password
f808b016 58 $pwdForm = $this->createForm(ChangePasswordType::class, null, ['action' => $this->generateUrl('config') . '#set4']);
d9085c63
J
59 $pwdForm->handleRequest($request);
60
21e7ccef 61 if ($pwdForm->isSubmitted() && $pwdForm->isValid()) {
a4f42c59 62 if ($this->get('craue_config')->get('demo_mode_enabled') && $this->get('craue_config')->get('demo_mode_username') === $user->getUsername()) {
4204a06b 63 $message = 'flashes.config.notice.password_not_updated_demo';
6c9f50a6 64 } else {
4204a06b 65 $message = 'flashes.config.notice.password_updated';
b6c00b0b 66
d8d56448
NL
67 $user->setPlainPassword($pwdForm->get('new_password')->getData());
68 $userManager->updateUser($user, true);
6c9f50a6 69 }
d9085c63 70
b6c00b0b
JB
71 $this->get('session')->getFlashBag()->add('notice', $message);
72
f808b016 73 return $this->redirect($this->generateUrl('config') . '#set4');
d9085c63
J
74 }
75
c0d9eba0 76 // handle changing user information
4094ea47
JB
77 $userForm = $this->createForm(UserInformationType::class, $user, [
78 'validation_groups' => ['Profile'],
f808b016 79 'action' => $this->generateUrl('config') . '#set3',
4094ea47 80 ]);
c0d9eba0
J
81 $userForm->handleRequest($request);
82
21e7ccef 83 if ($userForm->isSubmitted() && $userForm->isValid()) {
fcb1fba5 84 $userManager->updateUser($user, true);
c0d9eba0
J
85
86 $this->get('session')->getFlashBag()->add(
87 'notice',
4204a06b 88 'flashes.config.notice.user_updated'
c0d9eba0
J
89 );
90
f808b016 91 return $this->redirect($this->generateUrl('config') . '#set3');
c0d9eba0
J
92 }
93
0c83fd59 94 // handle rss information
f808b016 95 $rssForm = $this->createForm(RssType::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
0c83fd59
J
96 $rssForm->handleRequest($request);
97
21e7ccef 98 if ($rssForm->isSubmitted() && $rssForm->isValid()) {
0c83fd59
J
99 $em->persist($config);
100 $em->flush();
101
102 $this->get('session')->getFlashBag()->add(
103 'notice',
4204a06b 104 'flashes.config.notice.rss_updated'
0c83fd59
J
105 );
106
f808b016 107 return $this->redirect($this->generateUrl('config') . '#set2');
0c83fd59
J
108 }
109
f19f9f62
KG
110 // handle tagging rule
111 $taggingRule = new TaggingRule();
f808b016 112 $action = $this->generateUrl('config') . '#set5';
bf3dc999
JB
113
114 if ($request->query->has('tagging-rule')) {
115 $taggingRule = $this->getDoctrine()
116 ->getRepository('WallabagCoreBundle:TaggingRule')
117 ->find($request->query->get('tagging-rule'));
118
119 if ($this->getUser()->getId() !== $taggingRule->getConfig()->getUser()->getId()) {
120 return $this->redirect($action);
121 }
122
f808b016 123 $action = $this->generateUrl('config') . '?tagging-rule=' . $taggingRule->getId() . '#set5';
bf3dc999
JB
124 }
125
126 $newTaggingRule = $this->createForm(TaggingRuleType::class, $taggingRule, ['action' => $action]);
f19f9f62
KG
127 $newTaggingRule->handleRequest($request);
128
21e7ccef 129 if ($newTaggingRule->isSubmitted() && $newTaggingRule->isValid()) {
f19f9f62
KG
130 $taggingRule->setConfig($config);
131 $em->persist($taggingRule);
132 $em->flush();
133
134 $this->get('session')->getFlashBag()->add(
135 'notice',
4204a06b 136 'flashes.config.notice.tagging_rules_updated'
f19f9f62
KG
137 );
138
f808b016 139 return $this->redirect($this->generateUrl('config') . '#set5');
f19f9f62
KG
140 }
141
4094ea47
JB
142 return $this->render('WallabagCoreBundle:Config:index.html.twig', [
143 'form' => [
0c83fd59
J
144 'config' => $configForm->createView(),
145 'rss' => $rssForm->createView(),
146 'pwd' => $pwdForm->createView(),
147 'user' => $userForm->createView(),
f19f9f62 148 'new_tagging_rule' => $newTaggingRule->createView(),
4094ea47
JB
149 ],
150 'rss' => [
0c83fd59
J
151 'username' => $user->getUsername(),
152 'token' => $config->getRssToken(),
4094ea47 153 ],
63e40f2d 154 'twofactor_auth' => $this->getParameter('twofactor_auth'),
be9d693e 155 'wallabag_url' => $this->getParameter('domain_name'),
25203e50 156 'enabled_users' => $this->get('wallabag_user.user_repository')
bb0c78f4 157 ->getSumEnabledUsers(),
4094ea47 158 ]);
4d85d7e9
J
159 }
160
0c83fd59
J
161 /**
162 * @param Request $request
163 *
164 * @Route("/generate-token", name="generate_token")
165 *
98568055 166 * @return RedirectResponse|JsonResponse
0c83fd59
J
167 */
168 public function generateTokenAction(Request $request)
169 {
170 $config = $this->getConfig();
171 $config->setRssToken(Utils::generateToken());
172
173 $em = $this->getDoctrine()->getManager();
174 $em->persist($config);
175 $em->flush();
176
177 if ($request->isXmlHttpRequest()) {
4094ea47 178 return new JsonResponse(['token' => $config->getRssToken()]);
0c83fd59
J
179 }
180
c7a4f74f
JB
181 $this->get('session')->getFlashBag()->add(
182 'notice',
4204a06b 183 'flashes.config.notice.rss_token_updated'
c7a4f74f
JB
184 );
185
f808b016 186 return $this->redirect($this->generateUrl('config') . '#set2');
0c83fd59
J
187 }
188
52e423f3
KG
189 /**
190 * Deletes a tagging rule and redirect to the config homepage.
191 *
192 * @param TaggingRule $rule
193 *
194 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
195 *
98568055 196 * @return RedirectResponse
52e423f3 197 */
5f8a7857 198 public function deleteTaggingRuleAction(TaggingRule $rule)
52e423f3 199 {
8799bde0 200 $this->validateRuleAction($rule);
52e423f3
KG
201
202 $em = $this->getDoctrine()->getManager();
203 $em->remove($rule);
204 $em->flush();
205
206 $this->get('session')->getFlashBag()->add(
207 'notice',
4204a06b 208 'flashes.config.notice.tagging_rules_deleted'
52e423f3
KG
209 );
210
f808b016 211 return $this->redirect($this->generateUrl('config') . '#set5');
52e423f3
KG
212 }
213
bf3dc999
JB
214 /**
215 * Edit a tagging rule.
216 *
217 * @param TaggingRule $rule
218 *
219 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
220 *
221 * @return RedirectResponse
222 */
223 public function editTaggingRuleAction(TaggingRule $rule)
8799bde0
JB
224 {
225 $this->validateRuleAction($rule);
226
f808b016 227 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
8799bde0
JB
228 }
229
206bade5
JB
230 /**
231 * Remove all annotations OR tags OR entries for the current user.
232 *
233 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
234 *
235 * @return RedirectResponse
236 */
237 public function resetAction($type)
238 {
206bade5
JB
239 switch ($type) {
240 case 'annotations':
191564b7
JB
241 $this->getDoctrine()
242 ->getRepository('WallabagAnnotationBundle:Annotation')
243 ->removeAllByUserId($this->getUser()->getId());
206bade5 244 break;
206bade5 245 case 'tags':
191564b7
JB
246 $this->removeAllTagsByUserId($this->getUser()->getId());
247 break;
191564b7 248 case 'entries':
6da1aebc 249 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
191564b7 250 // otherwise they won't be removed ...
7ab5eb95 251 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
191564b7 252 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
206bade5
JB
253 }
254
8c61fd12 255 // manually remove tags to avoid orphan tag
f71e55ac
JB
256 $this->removeAllTagsByUserId($this->getUser()->getId());
257
25203e50 258 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
6da1aebc
TC
259 break;
260 case 'archived':
7ab5eb95 261 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
6da1aebc
TC
262 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
263 }
264
265 // manually remove tags to avoid orphan tag
266 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
267
25203e50 268 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
6da1aebc 269 break;
206bade5
JB
270 }
271
272 $this->get('session')->getFlashBag()->add(
273 'notice',
f808b016 274 'flashes.config.notice.' . $type . '_reset'
206bade5
JB
275 );
276
f808b016
JB
277 return $this->redirect($this->generateUrl('config') . '#set3');
278 }
279
280 /**
281 * Delete account for current user.
282 *
283 * @Route("/account/delete", name="delete_account")
284 *
285 * @param Request $request
286 *
287 * @throws AccessDeniedHttpException
288 *
289 * @return \Symfony\Component\HttpFoundation\RedirectResponse
290 */
291 public function deleteAccountAction(Request $request)
292 {
293 $enabledUsers = $this->get('wallabag_user.user_repository')
294 ->getSumEnabledUsers();
295
296 if ($enabledUsers <= 1) {
297 throw new AccessDeniedHttpException();
298 }
299
300 $user = $this->getUser();
301
302 // logout current user
303 $this->get('security.token_storage')->setToken(null);
304 $request->getSession()->invalidate();
305
306 $em = $this->get('fos_user.user_manager');
307 $em->deleteUser($user);
308
309 return $this->redirect($this->generateUrl('fos_user_security_login'));
310 }
311
312 /**
313 * Switch view mode for current user.
314 *
315 * @Route("/config/view-mode", name="switch_view_mode")
316 *
317 * @param Request $request
318 *
319 * @return \Symfony\Component\HttpFoundation\RedirectResponse
320 */
321 public function changeViewModeAction(Request $request)
322 {
323 $user = $this->getUser();
324 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
325
326 $em = $this->getDoctrine()->getManager();
327 $em->persist($user);
328 $em->flush();
329
330 return $this->redirect($request->headers->get('referer'));
206bade5
JB
331 }
332
be417ef2
NL
333 /**
334 * Change the locale for the current user.
335 *
336 * @param Request $request
337 * @param string $language
338 *
339 * @Route("/locale/{language}", name="changeLocale")
340 *
341 * @return \Symfony\Component\HttpFoundation\RedirectResponse
342 */
343 public function setLocaleAction(Request $request, $language = null)
344 {
4d4147b2
JB
345 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
346
347 if (0 === \count($errors)) {
348 $request->getSession()->set('_locale', $language);
be417ef2
NL
349 }
350
4d4147b2 351 return $this->redirect($request->headers->get('referer', $this->generateUrl('homepage')));
be417ef2
NL
352 }
353
191564b7 354 /**
e682a70f 355 * Remove all tags for given tags and a given user and cleanup orphan tags.
191564b7 356 *
e682a70f
NL
357 * @param array $tags
358 * @param int $userId
191564b7 359 */
e682a70f 360 private function removeAllTagsByStatusAndUserId($tags, $userId)
191564b7 361 {
191564b7
JB
362 if (empty($tags)) {
363 return;
364 }
365
25203e50 366 $this->get('wallabag_core.entry_repository')
191564b7 367 ->removeTags($userId, $tags);
f71e55ac 368
8c61fd12 369 // cleanup orphan tags
f71e55ac
JB
370 $em = $this->getDoctrine()->getManager();
371
372 foreach ($tags as $tag) {
2a1ceb67 373 if (0 === \count($tag->getEntries())) {
f71e55ac
JB
374 $em->remove($tag);
375 }
376 }
377
378 $em->flush();
191564b7
JB
379 }
380
e682a70f
NL
381 /**
382 * Remove all tags for a given user and cleanup orphan tags.
383 *
384 * @param int $userId
385 */
386 private function removeAllTagsByUserId($userId)
387 {
25203e50 388 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
e682a70f
NL
389 $this->removeAllTagsByStatusAndUserId($tags, $userId);
390 }
391
6da1aebc
TC
392 /**
393 * Remove all tags for a given user and cleanup orphan tags.
394 *
395 * @param int $userId
396 */
397 private function removeTagsForArchivedByUserId($userId)
398 {
25203e50 399 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
e682a70f 400 $this->removeAllTagsByStatusAndUserId($tags, $userId);
6da1aebc
TC
401 }
402
403 private function removeAnnotationsForArchivedByUserId($userId)
404 {
405 $em = $this->getDoctrine()->getManager();
406
407 $archivedEntriesAnnotations = $this->getDoctrine()
408 ->getRepository('WallabagAnnotationBundle:Annotation')
13a592a1 409 ->findAllArchivedEntriesByUser($userId);
6da1aebc
TC
410
411 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
412 $em->remove($archivedEntriesAnnotation);
413 }
414
415 $em->flush();
416 }
417
8799bde0 418 /**
2455472e 419 * Validate that a rule can be edited/deleted by the current user.
8799bde0 420 *
2455472e 421 * @param TaggingRule $rule
8799bde0
JB
422 */
423 private function validateRuleAction(TaggingRule $rule)
bf3dc999 424 {
f808b016 425 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
bf3dc999
JB
426 throw $this->createAccessDeniedException('You can not access this tagging rule.');
427 }
bf3dc999
JB
428 }
429
d9085c63
J
430 /**
431 * Retrieve config for the current user.
432 * If no config were found, create a new one.
433 *
4094ea47 434 * @return Config
d9085c63 435 */
4d85d7e9
J
436 private function getConfig()
437 {
438 $config = $this->getDoctrine()
439 ->getRepository('WallabagCoreBundle:Config')
440 ->findOneByUser($this->getUser());
441
ca17abce 442 // should NEVER HAPPEN ...
4d85d7e9
J
443 if (!$config) {
444 $config = new Config($this->getUser());
445 }
446
447 return $config;
448 }
449}