3 namespace Wallabag\CoreBundle\Controller
;
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\Event\Activity\Actions\User\UserDeletedEvent
;
14 use Wallabag\CoreBundle\Event\Activity\Actions\User\UserEditedEvent
;
15 use Wallabag\CoreBundle\Form\Type\ConfigType
;
16 use Wallabag\CoreBundle\Form\Type\ChangePasswordType
;
17 use Wallabag\CoreBundle\Form\Type\RssType
;
18 use Wallabag\CoreBundle\Form\Type\TaggingRuleType
;
19 use Wallabag\CoreBundle\Form\Type\UserInformationType
;
20 use Wallabag\CoreBundle\Tools\Utils
;
21 use Wallabag\FederationBundle\Form\Type\AccountType
;
22 use Wallabag\UserBundle\Entity\User
;
24 class ConfigController
extends Controller
27 * @param Request $request
29 * @Route("/config", name="config")
31 public function indexAction(Request
$request)
33 $em = $this->getDoctrine()->getManager();
34 $config = $this->getConfig();
35 $userManager = $this->container
->get('fos_user.user_manager');
36 $user = $this->getUser();
38 // handle basic config detail (this form is defined as a service)
39 $configForm = $this->createForm(ConfigType
::class, $config, ['action' => $this->generateUrl('config')]);
40 $configForm->handleRequest($request);
42 if ($configForm->isSubmitted() && $configForm->isValid()) {
43 $em->persist($config);
46 $request->getSession()->set('_locale', $config->getLanguage());
48 // switch active theme
49 $activeTheme = $this->get('liip_theme.active_theme');
50 $activeTheme->setName($config->getTheme());
52 $this->get('session')->getFlashBag()->add(
54 'flashes.config.notice.config_saved'
57 return $this->redirect($this->generateUrl('config'));
60 // handle changing password
61 $pwdForm = $this->createForm(ChangePasswordType
::class, null, ['action' => $this->generateUrl('config').'#set4']);
62 $pwdForm->handleRequest($request);
64 if ($pwdForm->isSubmitted() && $pwdForm->isValid()) {
65 if ($this->get('craue_config')->get('demo_mode_enabled') && $this->get('craue_config')->get('demo_mode_username') === $user->getUsername()) {
66 $message = 'flashes.config.notice.password_not_updated_demo';
68 $message = 'flashes.config.notice.password_updated';
70 $user->setPlainPassword($pwdForm->get('new_password')->getData());
71 $userManager->updateUser($user, true);
74 $this->get('session')->getFlashBag()->add('notice', $message);
76 return $this->redirect($this->generateUrl('config').'#set4');
79 // handle changing user information
80 $userForm = $this->createForm(UserInformationType
::class, $user, [
81 'validation_groups' => ['Profile'],
82 'action' => $this->generateUrl('config').'#set3',
84 $userForm->handleRequest($request);
86 if ($userForm->isSubmitted() && $userForm->isValid()) {
87 $userManager->updateUser($user, true);
89 $this->get('event_dispatcher')->dispatch(UserEditedEvent
::NAME
, new UserEditedEvent($user->getAccount()));
91 $this->get('session')->getFlashBag()->add(
93 'flashes.config.notice.user_updated'
96 return $this->redirect($this->generateUrl('config').'#set3');
99 // handle account information
100 $account = $user->getAccount();
101 $accountForm = $this->createForm(AccountType
::class, $account, [
102 'action' => $this->generateUrl('config').'#set3',
104 $accountForm->handleRequest($request);
106 if ($accountForm->isSubmitted() && $accountForm->isValid()) {
108 $avatar = $account->getAvatar();
109 $banner = $account->getBanner();
111 if (null !== $avatar) {
112 $avatarFileName = md5(uniqid('', true)) . '.' . $avatar->guessExtension();
115 $this->getParameter('media_directory') . '/avatar',
118 $account->setAvatar($avatarFileName);
121 if (null != $banner) {
122 $bannerFileName = md5(uniqid('', true)) . '.' . $banner->guessExtension();
125 $this->get('media_directory') . '/banner',
128 $account->setBanner($bannerFileName);
131 $this->get('event_dispatcher')->dispatch(UserEditedEvent
::NAME
, new UserEditedEvent($user));
133 $this->get('session')->getFlashBag()->add(
135 'flashes.config.notice.user_updated'
138 return $this->redirect($this->generateUrl('config').'#set3');
141 // handle rss information
142 $rssForm = $this->createForm(RssType
::class, $config, ['action' => $this->generateUrl('config').'#set2']);
143 $rssForm->handleRequest($request);
145 if ($rssForm->isSubmitted() && $rssForm->isValid()) {
146 $em->persist($config);
149 $this->get('session')->getFlashBag()->add(
151 'flashes.config.notice.rss_updated'
154 return $this->redirect($this->generateUrl('config').'#set2');
157 // handle tagging rule
158 $taggingRule = new TaggingRule();
159 $action = $this->generateUrl('config').'#set5';
161 if ($request->query
->has('tagging-rule')) {
162 $taggingRule = $this->getDoctrine()
163 ->getRepository('WallabagCoreBundle:TaggingRule')
164 ->find($request->query
->get('tagging-rule'));
166 if ($this->getUser()->getId() !== $taggingRule->getConfig()->getUser()->getId()) {
167 return $this->redirect($action);
170 $action = $this->generateUrl('config').'?tagging-rule='.$taggingRule->getId().'#set5';
173 $newTaggingRule = $this->createForm(TaggingRuleType
::class, $taggingRule, ['action' => $action]);
174 $newTaggingRule->handleRequest($request);
176 if ($newTaggingRule->isSubmitted() && $newTaggingRule->isValid()) {
177 $taggingRule->setConfig($config);
178 $em->persist($taggingRule);
181 $this->get('session')->getFlashBag()->add(
183 'flashes.config.notice.tagging_rules_updated'
186 return $this->redirect($this->generateUrl('config').'#set5');
189 return $this->render('WallabagCoreBundle:Config:index.html.twig', [
191 'config' => $configForm->createView(),
192 'rss' => $rssForm->createView(),
193 'pwd' => $pwdForm->createView(),
194 'user' => $userForm->createView(),
195 'new_tagging_rule' => $newTaggingRule->createView(),
196 'account' => $accountForm->createView(),
199 'username' => $user->getUsername(),
200 'token' => $config->getRssToken(),
202 'twofactor_auth' => $this->getParameter('twofactor_auth'),
203 'wallabag_url' => $this->getParameter('domain_name'),
204 'enabled_users' => $this->get('wallabag_user.user_repository')
205 ->getSumEnabledUsers(),
210 * @param Request $request
212 * @Route("/generate-token", name="generate_token")
214 * @return RedirectResponse|JsonResponse
216 public function generateTokenAction(Request
$request)
218 $config = $this->getConfig();
219 $config->setRssToken(Utils
::generateToken());
221 $em = $this->getDoctrine()->getManager();
222 $em->persist($config);
225 if ($request->isXmlHttpRequest()) {
226 return new JsonResponse(['token' => $config->getRssToken()]);
229 $this->get('session')->getFlashBag()->add(
231 'flashes.config.notice.rss_token_updated'
234 return $this->redirect($this->generateUrl('config').'#set2');
238 * Deletes a tagging rule and redirect to the config homepage.
240 * @param TaggingRule $rule
242 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
244 * @return RedirectResponse
246 public function deleteTaggingRuleAction(TaggingRule
$rule)
248 $this->validateRuleAction($rule);
250 $em = $this->getDoctrine()->getManager();
254 $this->get('session')->getFlashBag()->add(
256 'flashes.config.notice.tagging_rules_deleted'
259 return $this->redirect($this->generateUrl('config').'#set5');
263 * Edit a tagging rule.
265 * @param TaggingRule $rule
267 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
269 * @return RedirectResponse
271 public function editTaggingRuleAction(TaggingRule
$rule)
273 $this->validateRuleAction($rule);
275 return $this->redirect($this->generateUrl('config').'?tagging-rule='.$rule->getId().'#set5');
279 * Remove all annotations OR tags OR entries for the current user.
281 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
283 * @return RedirectResponse
285 public function resetAction($type)
290 ->getRepository('WallabagAnnotationBundle:Annotation')
291 ->removeAllByUserId($this->getUser()->getId());
295 $this->removeAllTagsByUserId($this->getUser()->getId());
299 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
300 // otherwise they won't be removed ...
301 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform
) {
302 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
305 // manually remove tags to avoid orphan tag
306 $this->removeAllTagsByUserId($this->getUser()->getId());
308 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
311 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform
) {
312 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
315 // manually remove tags to avoid orphan tag
316 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
318 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
322 $this->get('session')->getFlashBag()->add(
324 'flashes.config.notice.'.$type.'_reset'
327 return $this->redirect($this->generateUrl('config').'#set3');
331 * Remove all tags for given tags and a given user and cleanup orphan tags.
336 private function removeAllTagsByStatusAndUserId($tags, $userId)
342 $this->get('wallabag_core.entry_repository')
343 ->removeTags($userId, $tags);
345 // cleanup orphan tags
346 $em = $this->getDoctrine()->getManager();
348 foreach ($tags as $tag) {
349 if (count($tag->getEntries()) === 0) {
358 * Remove all tags for a given user and cleanup orphan tags.
362 private function removeAllTagsByUserId($userId)
364 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
365 $this->removeAllTagsByStatusAndUserId($tags, $userId);
369 * Remove all tags for a given user and cleanup orphan tags.
373 private function removeTagsForArchivedByUserId($userId)
375 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
376 $this->removeAllTagsByStatusAndUserId($tags, $userId);
379 private function removeAnnotationsForArchivedByUserId($userId)
381 $em = $this->getDoctrine()->getManager();
383 $archivedEntriesAnnotations = $this->getDoctrine()
384 ->getRepository('WallabagAnnotationBundle:Annotation')
385 ->findAllArchivedEntriesByUser($userId);
387 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
388 $em->remove($archivedEntriesAnnotation);
395 * Validate that a rule can be edited/deleted by the current user.
397 * @param TaggingRule $rule
399 private function validateRuleAction(TaggingRule
$rule)
401 if ($this->getUser()->getId() != $rule->getConfig()->getUser()->getId()) {
402 throw $this->createAccessDeniedException('You can not access this tagging rule.');
407 * Retrieve config for the current user.
408 * If no config were found, create a new one.
412 private function getConfig()
414 $config = $this->getDoctrine()
415 ->getRepository('WallabagCoreBundle:Config')
416 ->findOneByUser($this->getUser());
418 // should NEVER HAPPEN ...
420 $config = new Config($this->getUser());
427 * Delete account for current user.
429 * @Route("/account/delete", name="delete_account")
431 * @param Request $request
433 * @throws AccessDeniedHttpException
435 * @return \Symfony\Component\HttpFoundation\RedirectResponse
437 public function deleteAccountAction(Request
$request)
439 $enabledUsers = $this->get('wallabag_user.user_repository')
440 ->getSumEnabledUsers();
442 if ($enabledUsers <= 1) {
443 throw new AccessDeniedHttpException();
446 $user = $this->getUser();
448 // logout current user
449 $this->get('security.token_storage')->setToken(null);
450 $request->getSession()->invalidate();
452 $account = $user->getAccount();
454 $em = $this->get('fos_user.user_manager');
455 $em->deleteUser($user);
457 $this->get('event_dispatcher')->dispatch(UserDeletedEvent
::NAME
, new UserDeletedEvent($account));
459 return $this->redirect($this->generateUrl('fos_user_security_login'));
463 * Switch view mode for current user.
465 * @Route("/config/view-mode", name="switch_view_mode")
467 * @param Request $request
469 * @return \Symfony\Component\HttpFoundation\RedirectResponse
471 public function changeViewModeAction(Request
$request)
473 $user = $this->getUser();
474 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
476 $em = $this->getDoctrine()->getManager();
480 return $this->redirect($request->headers
->get('referer'));