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