]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Controller/ConfigController.php
Add a real configuration for CS-Fixer
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Controller / ConfigController.php
1 <?php
2
3 namespace Wallabag\CoreBundle\Controller;
4
5 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
6 use Symfony\Bundle\FrameworkBundle\Controller\Controller;
7 use Symfony\Component\HttpFoundation\JsonResponse;
8 use Symfony\Component\HttpFoundation\RedirectResponse;
9 use Symfony\Component\HttpFoundation\Request;
10 use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
11 use Wallabag\CoreBundle\Entity\Config;
12 use Wallabag\CoreBundle\Entity\TaggingRule;
13 use Wallabag\CoreBundle\Form\Type\ChangePasswordType;
14 use Wallabag\CoreBundle\Form\Type\ConfigType;
15 use Wallabag\CoreBundle\Form\Type\RssType;
16 use Wallabag\CoreBundle\Form\Type\TaggingRuleType;
17 use Wallabag\CoreBundle\Form\Type\UserInformationType;
18 use Wallabag\CoreBundle\Tools\Utils;
19
20 class ConfigController extends Controller
21 {
22 /**
23 * @param Request $request
24 *
25 * @Route("/config", name="config")
26 */
27 public function indexAction(Request $request)
28 {
29 $em = $this->getDoctrine()->getManager();
30 $config = $this->getConfig();
31 $userManager = $this->container->get('fos_user.user_manager');
32 $user = $this->getUser();
33
34 // handle basic config detail (this form is defined as a service)
35 $configForm = $this->createForm(ConfigType::class, $config, ['action' => $this->generateUrl('config')]);
36 $configForm->handleRequest($request);
37
38 if ($configForm->isSubmitted() && $configForm->isValid()) {
39 $em->persist($config);
40 $em->flush();
41
42 $request->getSession()->set('_locale', $config->getLanguage());
43
44 // switch active theme
45 $activeTheme = $this->get('liip_theme.active_theme');
46 $activeTheme->setName($config->getTheme());
47
48 $this->get('session')->getFlashBag()->add(
49 'notice',
50 'flashes.config.notice.config_saved'
51 );
52
53 return $this->redirect($this->generateUrl('config'));
54 }
55
56 // handle changing password
57 $pwdForm = $this->createForm(ChangePasswordType::class, null, ['action' => $this->generateUrl('config') . '#set4']);
58 $pwdForm->handleRequest($request);
59
60 if ($pwdForm->isSubmitted() && $pwdForm->isValid()) {
61 if ($this->get('craue_config')->get('demo_mode_enabled') && $this->get('craue_config')->get('demo_mode_username') === $user->getUsername()) {
62 $message = 'flashes.config.notice.password_not_updated_demo';
63 } else {
64 $message = 'flashes.config.notice.password_updated';
65
66 $user->setPlainPassword($pwdForm->get('new_password')->getData());
67 $userManager->updateUser($user, true);
68 }
69
70 $this->get('session')->getFlashBag()->add('notice', $message);
71
72 return $this->redirect($this->generateUrl('config') . '#set4');
73 }
74
75 // handle changing user information
76 $userForm = $this->createForm(UserInformationType::class, $user, [
77 'validation_groups' => ['Profile'],
78 'action' => $this->generateUrl('config') . '#set3',
79 ]);
80 $userForm->handleRequest($request);
81
82 if ($userForm->isSubmitted() && $userForm->isValid()) {
83 $userManager->updateUser($user, true);
84
85 $this->get('session')->getFlashBag()->add(
86 'notice',
87 'flashes.config.notice.user_updated'
88 );
89
90 return $this->redirect($this->generateUrl('config') . '#set3');
91 }
92
93 // handle rss information
94 $rssForm = $this->createForm(RssType::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
95 $rssForm->handleRequest($request);
96
97 if ($rssForm->isSubmitted() && $rssForm->isValid()) {
98 $em->persist($config);
99 $em->flush();
100
101 $this->get('session')->getFlashBag()->add(
102 'notice',
103 'flashes.config.notice.rss_updated'
104 );
105
106 return $this->redirect($this->generateUrl('config') . '#set2');
107 }
108
109 // handle tagging rule
110 $taggingRule = new TaggingRule();
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]);
126 $newTaggingRule->handleRequest($request);
127
128 if ($newTaggingRule->isSubmitted() && $newTaggingRule->isValid()) {
129 $taggingRule->setConfig($config);
130 $em->persist($taggingRule);
131 $em->flush();
132
133 $this->get('session')->getFlashBag()->add(
134 'notice',
135 'flashes.config.notice.tagging_rules_updated'
136 );
137
138 return $this->redirect($this->generateUrl('config') . '#set5');
139 }
140
141 return $this->render('WallabagCoreBundle:Config:index.html.twig', [
142 'form' => [
143 'config' => $configForm->createView(),
144 'rss' => $rssForm->createView(),
145 'pwd' => $pwdForm->createView(),
146 'user' => $userForm->createView(),
147 'new_tagging_rule' => $newTaggingRule->createView(),
148 ],
149 'rss' => [
150 'username' => $user->getUsername(),
151 'token' => $config->getRssToken(),
152 ],
153 'twofactor_auth' => $this->getParameter('twofactor_auth'),
154 'wallabag_url' => $this->getParameter('domain_name'),
155 'enabled_users' => $this->get('wallabag_user.user_repository')
156 ->getSumEnabledUsers(),
157 ]);
158 }
159
160 /**
161 * @param Request $request
162 *
163 * @Route("/generate-token", name="generate_token")
164 *
165 * @return RedirectResponse|JsonResponse
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()) {
177 return new JsonResponse(['token' => $config->getRssToken()]);
178 }
179
180 $this->get('session')->getFlashBag()->add(
181 'notice',
182 'flashes.config.notice.rss_token_updated'
183 );
184
185 return $this->redirect($this->generateUrl('config') . '#set2');
186 }
187
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 *
195 * @return RedirectResponse
196 */
197 public function deleteTaggingRuleAction(TaggingRule $rule)
198 {
199 $this->validateRuleAction($rule);
200
201 $em = $this->getDoctrine()->getManager();
202 $em->remove($rule);
203 $em->flush();
204
205 $this->get('session')->getFlashBag()->add(
206 'notice',
207 'flashes.config.notice.tagging_rules_deleted'
208 );
209
210 return $this->redirect($this->generateUrl('config') . '#set5');
211 }
212
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)
223 {
224 $this->validateRuleAction($rule);
225
226 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
227 }
228
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 {
238 switch ($type) {
239 case 'annotations':
240 $this->getDoctrine()
241 ->getRepository('WallabagAnnotationBundle:Annotation')
242 ->removeAllByUserId($this->getUser()->getId());
243 break;
244 case 'tags':
245 $this->removeAllTagsByUserId($this->getUser()->getId());
246 break;
247 case 'entries':
248 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
249 // otherwise they won't be removed ...
250 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
251 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
252 }
253
254 // manually remove tags to avoid orphan tag
255 $this->removeAllTagsByUserId($this->getUser()->getId());
256
257 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
258 break;
259 case 'archived':
260 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
261 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
262 }
263
264 // manually remove tags to avoid orphan tag
265 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
266
267 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
268 break;
269 }
270
271 $this->get('session')->getFlashBag()->add(
272 'notice',
273 'flashes.config.notice.' . $type . '_reset'
274 );
275
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'));
330 }
331
332 /**
333 * Remove all tags for given tags and a given user and cleanup orphan tags.
334 *
335 * @param array $tags
336 * @param int $userId
337 */
338 private function removeAllTagsByStatusAndUserId($tags, $userId)
339 {
340 if (empty($tags)) {
341 return;
342 }
343
344 $this->get('wallabag_core.entry_repository')
345 ->removeTags($userId, $tags);
346
347 // cleanup orphan tags
348 $em = $this->getDoctrine()->getManager();
349
350 foreach ($tags as $tag) {
351 if (count($tag->getEntries()) === 0) {
352 $em->remove($tag);
353 }
354 }
355
356 $em->flush();
357 }
358
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 {
366 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
367 $this->removeAllTagsByStatusAndUserId($tags, $userId);
368 }
369
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 {
377 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
378 $this->removeAllTagsByStatusAndUserId($tags, $userId);
379 }
380
381 private function removeAnnotationsForArchivedByUserId($userId)
382 {
383 $em = $this->getDoctrine()->getManager();
384
385 $archivedEntriesAnnotations = $this->getDoctrine()
386 ->getRepository('WallabagAnnotationBundle:Annotation')
387 ->findAllArchivedEntriesByUser($userId);
388
389 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
390 $em->remove($archivedEntriesAnnotation);
391 }
392
393 $em->flush();
394 }
395
396 /**
397 * Validate that a rule can be edited/deleted by the current user.
398 *
399 * @param TaggingRule $rule
400 */
401 private function validateRuleAction(TaggingRule $rule)
402 {
403 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
404 throw $this->createAccessDeniedException('You can not access this tagging rule.');
405 }
406 }
407
408 /**
409 * Retrieve config for the current user.
410 * If no config were found, create a new one.
411 *
412 * @return Config
413 */
414 private function getConfig()
415 {
416 $config = $this->getDoctrine()
417 ->getRepository('WallabagCoreBundle:Config')
418 ->findOneByUser($this->getUser());
419
420 // should NEVER HAPPEN ...
421 if (!$config) {
422 $config = new Config($this->getUser());
423 }
424
425 return $config;
426 }
427 }