]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Controller/ConfigController.php
Merge remote-tracking branch 'origin/master' into 2.2
[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\ConfigType;
14 use Wallabag\CoreBundle\Form\Type\ChangePasswordType;
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->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->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->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->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->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->get('craue_config')->get('wallabag_url'),
155 'enabled_users' => $this->getDoctrine()
156 ->getRepository('WallabagUserBundle:User')
157 ->getSumEnabledUsers(),
158 ]);
159 }
160
161 /**
162 * @param Request $request
163 *
164 * @Route("/generate-token", name="generate_token")
165 *
166 * @return RedirectResponse|JsonResponse
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()) {
178 return new JsonResponse(['token' => $config->getRssToken()]);
179 }
180
181 $this->get('session')->getFlashBag()->add(
182 'notice',
183 'flashes.config.notice.rss_token_updated'
184 );
185
186 return $this->redirect($this->generateUrl('config').'#set2');
187 }
188
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 *
196 * @return RedirectResponse
197 */
198 public function deleteTaggingRuleAction(TaggingRule $rule)
199 {
200 $this->validateRuleAction($rule);
201
202 $em = $this->getDoctrine()->getManager();
203 $em->remove($rule);
204 $em->flush();
205
206 $this->get('session')->getFlashBag()->add(
207 'notice',
208 'flashes.config.notice.tagging_rules_deleted'
209 );
210
211 return $this->redirect($this->generateUrl('config').'#set5');
212 }
213
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)
224 {
225 $this->validateRuleAction($rule);
226
227 return $this->redirect($this->generateUrl('config').'?tagging-rule='.$rule->getId().'#set5');
228 }
229
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 {
239 switch ($type) {
240 case 'annotations':
241 $this->getDoctrine()
242 ->getRepository('WallabagAnnotationBundle:Annotation')
243 ->removeAllByUserId($this->getUser()->getId());
244 break;
245
246 case 'tags':
247 $this->removeAllTagsByUserId($this->getUser()->getId());
248 break;
249
250 case 'entries':
251 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuf
252 // otherwise they won't be removed ...
253 if ($this->get('doctrine')->getConnection()->getDriver() instanceof \Doctrine\DBAL\Driver\PDOSqlite\Driver) {
254 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
255 }
256
257 // manually remove tags to avoid orphan tag
258 $this->removeAllTagsByUserId($this->getUser()->getId());
259
260 $this->getDoctrine()
261 ->getRepository('WallabagCoreBundle:Entry')
262 ->removeAllByUserId($this->getUser()->getId());
263 }
264
265 $this->get('session')->getFlashBag()->add(
266 'notice',
267 'flashes.config.notice.'.$type.'_reset'
268 );
269
270 return $this->redirect($this->generateUrl('config').'#set3');
271 }
272
273 /**
274 * Remove all tags for a given user and cleanup orphan tags.
275 *
276 * @param int $userId
277 */
278 private function removeAllTagsByUserId($userId)
279 {
280 $tags = $this->getDoctrine()->getRepository('WallabagCoreBundle:Tag')->findAllTags($userId);
281
282 if (empty($tags)) {
283 return;
284 }
285
286 $this->getDoctrine()
287 ->getRepository('WallabagCoreBundle:Entry')
288 ->removeTags($userId, $tags);
289
290 // cleanup orphan tags
291 $em = $this->getDoctrine()->getManager();
292
293 foreach ($tags as $tag) {
294 if (count($tag->getEntries()) === 0) {
295 $em->remove($tag);
296 }
297 }
298
299 $em->flush();
300 }
301
302 /**
303 * Validate that a rule can be edited/deleted by the current user.
304 *
305 * @param TaggingRule $rule
306 */
307 private function validateRuleAction(TaggingRule $rule)
308 {
309 if ($this->getUser()->getId() != $rule->getConfig()->getUser()->getId()) {
310 throw $this->createAccessDeniedException('You can not access this tagging rule.');
311 }
312 }
313
314 /**
315 * Retrieve config for the current user.
316 * If no config were found, create a new one.
317 *
318 * @return Config
319 */
320 private function getConfig()
321 {
322 $config = $this->getDoctrine()
323 ->getRepository('WallabagCoreBundle:Config')
324 ->findOneByUser($this->getUser());
325
326 // should NEVER HAPPEN ...
327 if (!$config) {
328 $config = new Config($this->getUser());
329 }
330
331 return $config;
332 }
333
334 /**
335 * Delete account for current user.
336 *
337 * @Route("/account/delete", name="delete_account")
338 *
339 * @param Request $request
340 *
341 * @throws AccessDeniedHttpException
342 *
343 * @return \Symfony\Component\HttpFoundation\RedirectResponse
344 */
345 public function deleteAccountAction(Request $request)
346 {
347 $enabledUsers = $this->getDoctrine()
348 ->getRepository('WallabagUserBundle:User')
349 ->getSumEnabledUsers();
350
351 if ($enabledUsers <= 1) {
352 throw new AccessDeniedHttpException();
353 }
354
355 $user = $this->getUser();
356
357 // logout current user
358 $this->get('security.token_storage')->setToken(null);
359 $request->getSession()->invalidate();
360
361 $em = $this->get('fos_user.user_manager');
362 $em->deleteUser($user);
363
364 return $this->redirect($this->generateUrl('fos_user_security_login'));
365 }
366 }