]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Controller/ConfigController.php
Merge pull request #3516 from wallabag/delete-id
[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;
d9085c63 13use Wallabag\CoreBundle\Form\Type\ChangePasswordType;
f808b016 14use Wallabag\CoreBundle\Form\Type\ConfigType;
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
f808b016 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
f808b016 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'],
f808b016 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
f808b016 90 return $this->redirect($this->generateUrl('config') . '#set3');
c0d9eba0
J
91 }
92
0c83fd59 93 // handle rss information
f808b016 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
f808b016 106 return $this->redirect($this->generateUrl('config') . '#set2');
0c83fd59
J
107 }
108
f19f9f62
KG
109 // handle tagging rule
110 $taggingRule = new TaggingRule();
f808b016 111 $action = $this->generateUrl('config') . '#set5';
bf3dc999
JB
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
f808b016 122 $action = $this->generateUrl('config') . '?tagging-rule=' . $taggingRule->getId() . '#set5';
bf3dc999
JB
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
f808b016 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
f808b016 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
f808b016 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
f808b016 226 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
8799bde0
JB
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 243 break;
206bade5 244 case 'tags':
191564b7
JB
245 $this->removeAllTagsByUserId($this->getUser()->getId());
246 break;
191564b7 247 case 'entries':
6da1aebc 248 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
191564b7 249 // otherwise they won't be removed ...
7ab5eb95 250 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
191564b7 251 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
206bade5
JB
252 }
253
8c61fd12 254 // manually remove tags to avoid orphan tag
f71e55ac
JB
255 $this->removeAllTagsByUserId($this->getUser()->getId());
256
25203e50 257 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
6da1aebc
TC
258 break;
259 case 'archived':
7ab5eb95 260 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
6da1aebc
TC
261 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
262 }
263
264 // manually remove tags to avoid orphan tag
265 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
266
25203e50 267 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
6da1aebc 268 break;
206bade5
JB
269 }
270
271 $this->get('session')->getFlashBag()->add(
272 'notice',
f808b016 273 'flashes.config.notice.' . $type . '_reset'
206bade5
JB
274 );
275
f808b016
JB
276 return $this->redirect($this->generateUrl('config') . '#set3');
277 }
278
279 /**
280 * Delete account for current user.
281 *
282 * @Route("/account/delete", name="delete_account")
283 *
284 * @param Request $request
285 *
286 * @throws AccessDeniedHttpException
287 *
288 * @return \Symfony\Component\HttpFoundation\RedirectResponse
289 */
290 public function deleteAccountAction(Request $request)
291 {
292 $enabledUsers = $this->get('wallabag_user.user_repository')
293 ->getSumEnabledUsers();
294
295 if ($enabledUsers <= 1) {
296 throw new AccessDeniedHttpException();
297 }
298
299 $user = $this->getUser();
300
301 // logout current user
302 $this->get('security.token_storage')->setToken(null);
303 $request->getSession()->invalidate();
304
305 $em = $this->get('fos_user.user_manager');
306 $em->deleteUser($user);
307
308 return $this->redirect($this->generateUrl('fos_user_security_login'));
309 }
310
311 /**
312 * Switch view mode for current user.
313 *
314 * @Route("/config/view-mode", name="switch_view_mode")
315 *
316 * @param Request $request
317 *
318 * @return \Symfony\Component\HttpFoundation\RedirectResponse
319 */
320 public function changeViewModeAction(Request $request)
321 {
322 $user = $this->getUser();
323 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
324
325 $em = $this->getDoctrine()->getManager();
326 $em->persist($user);
327 $em->flush();
328
329 return $this->redirect($request->headers->get('referer'));
206bade5
JB
330 }
331
191564b7 332 /**
e682a70f 333 * Remove all tags for given tags and a given user and cleanup orphan tags.
191564b7 334 *
e682a70f
NL
335 * @param array $tags
336 * @param int $userId
191564b7 337 */
e682a70f 338 private function removeAllTagsByStatusAndUserId($tags, $userId)
191564b7 339 {
191564b7
JB
340 if (empty($tags)) {
341 return;
342 }
343
25203e50 344 $this->get('wallabag_core.entry_repository')
191564b7 345 ->removeTags($userId, $tags);
f71e55ac 346
8c61fd12 347 // cleanup orphan tags
f71e55ac
JB
348 $em = $this->getDoctrine()->getManager();
349
350 foreach ($tags as $tag) {
3ef055ce 351 if (0 === count($tag->getEntries())) {
f71e55ac
JB
352 $em->remove($tag);
353 }
354 }
355
356 $em->flush();
191564b7
JB
357 }
358
e682a70f
NL
359 /**
360 * Remove all tags for a given user and cleanup orphan tags.
361 *
362 * @param int $userId
363 */
364 private function removeAllTagsByUserId($userId)
365 {
25203e50 366 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
e682a70f
NL
367 $this->removeAllTagsByStatusAndUserId($tags, $userId);
368 }
369
6da1aebc
TC
370 /**
371 * Remove all tags for a given user and cleanup orphan tags.
372 *
373 * @param int $userId
374 */
375 private function removeTagsForArchivedByUserId($userId)
376 {
25203e50 377 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
e682a70f 378 $this->removeAllTagsByStatusAndUserId($tags, $userId);
6da1aebc
TC
379 }
380
381 private function removeAnnotationsForArchivedByUserId($userId)
382 {
383 $em = $this->getDoctrine()->getManager();
384
385 $archivedEntriesAnnotations = $this->getDoctrine()
386 ->getRepository('WallabagAnnotationBundle:Annotation')
13a592a1 387 ->findAllArchivedEntriesByUser($userId);
6da1aebc
TC
388
389 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
390 $em->remove($archivedEntriesAnnotation);
391 }
392
393 $em->flush();
394 }
395
8799bde0 396 /**
2455472e 397 * Validate that a rule can be edited/deleted by the current user.
8799bde0 398 *
2455472e 399 * @param TaggingRule $rule
8799bde0
JB
400 */
401 private function validateRuleAction(TaggingRule $rule)
bf3dc999 402 {
f808b016 403 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
bf3dc999
JB
404 throw $this->createAccessDeniedException('You can not access this tagging rule.');
405 }
bf3dc999
JB
406 }
407
d9085c63
J
408 /**
409 * Retrieve config for the current user.
410 * If no config were found, create a new one.
411 *
4094ea47 412 * @return Config
d9085c63 413 */
4d85d7e9
J
414 private function getConfig()
415 {
416 $config = $this->getDoctrine()
417 ->getRepository('WallabagCoreBundle:Config')
418 ->findOneByUser($this->getUser());
419
ca17abce 420 // should NEVER HAPPEN ...
4d85d7e9
J
421 if (!$config) {
422 $config = new Config($this->getUser());
423 }
424
425 return $config;
426 }
427}