3 namespace Wallabag\CoreBundle\Controller
;
5 use Doctrine\ORM\NoResultException
;
6 use Pagerfanta\Adapter\DoctrineORMAdapter
;
7 use Pagerfanta\Exception\OutOfRangeCurrentPageException
;
8 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache
;
9 use Symfony\Bundle\FrameworkBundle\Controller\Controller
;
10 use Symfony\Component\HttpFoundation\Request
;
11 use Symfony\Component\Routing\Annotation\Route
;
12 use Symfony\Component\Routing\Generator\UrlGeneratorInterface
;
13 use Wallabag\CoreBundle\Entity\Entry
;
14 use Wallabag\CoreBundle\Event\EntryDeletedEvent
;
15 use Wallabag\CoreBundle\Event\EntrySavedEvent
;
16 use Wallabag\CoreBundle\Form\Type\EditEntryType
;
17 use Wallabag\CoreBundle\Form\Type\EntryFilterType
;
18 use Wallabag\CoreBundle\Form\Type\EntrySortType
;
19 use Wallabag\CoreBundle\Form\Type\NewEntryType
;
20 use Wallabag\CoreBundle\Form\Type\SearchEntryType
;
22 class EntryController
extends Controller
25 * @Route("/mass", name="mass_action")
27 * @return \Symfony\Component\HttpFoundation\Response
29 public function massAction(Request
$request)
31 $em = $this->getDoctrine()->getManager();
32 $values = $request->request
->all();
34 $action = 'toggle-read';
35 if (isset($values['toggle-star'])) {
36 $action = 'toggle-star';
37 } elseif (isset($values['delete'])) {
41 if (isset($values['entry-checkbox'])) {
42 foreach ($values['entry-checkbox'] as $id) {
44 $entry = $this->get('wallabag_core.entry_repository')->findById((int) $id)[0];
46 $this->checkUserAction($entry);
48 if ('toggle-read' === $action) {
49 $entry->toggleArchive();
50 } elseif ('toggle-star' === $action) {
52 } elseif ('delete' === $action) {
53 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
61 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
63 return $this->redirect($redirectUrl);
69 * @Route("/search/{page}", name="search", defaults={"page" = 1})
71 * Default parameter for page is hardcoded (in duplication of the defaults from the Route)
72 * because this controller is also called inside the layout template without any page as argument
74 * @return \Symfony\Component\HttpFoundation\Response
76 public function searchFormAction(Request
$request, $page = 1, $currentRoute = null)
78 // fallback to retrieve currentRoute from query parameter instead of injected one (when using inside a template)
79 if (null === $currentRoute && $request->query
->has('currentRoute')) {
80 $currentRoute = $request->query
->get('currentRoute');
83 $form = $this->createForm(SearchEntryType
::class);
85 $form->handleRequest($request);
87 if ($form->isSubmitted() && $form->isValid()) {
88 return $this->showEntries('search', $request, $page);
91 return $this->render('WallabagCoreBundle:Entry:search_form.html.twig', [
92 'form' => $form->createView(),
93 'currentRoute' => $currentRoute,
98 * @Route("/new-entry", name="new_entry")
100 * @return \Symfony\Component\HttpFoundation\Response
102 public function addEntryFormAction(Request
$request)
104 $entry = new Entry($this->getUser());
106 $form = $this->createForm(NewEntryType
::class, $entry);
108 $form->handleRequest($request);
110 if ($form->isSubmitted() && $form->isValid()) {
111 $existingEntry = $this->checkIfEntryAlreadyExists($entry);
113 if (false !== $existingEntry) {
114 $this->get('session')->getFlashBag()->add(
116 $this->get('translator')->trans('flashes.entry.notice.entry_already_saved', ['%date%' => $existingEntry->getCreatedAt()->format('d-m-Y')])
119 return $this->redirect($this->generateUrl('view', ['id' => $existingEntry->getId()]));
122 $this->updateEntry($entry);
124 $em = $this->getDoctrine()->getManager();
125 $em->persist($entry);
128 // entry saved, dispatch event about it!
129 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
131 return $this->redirect($this->generateUrl('homepage'));
134 return $this->render('WallabagCoreBundle:Entry:new_form.html.twig', [
135 'form' => $form->createView(),
140 * @Route("/bookmarklet", name="bookmarklet")
142 * @return \Symfony\Component\HttpFoundation\Response
144 public function addEntryViaBookmarkletAction(Request
$request)
146 $entry = new Entry($this->getUser());
147 $entry->setUrl($request->get('url'));
149 if (false === $this->checkIfEntryAlreadyExists($entry)) {
150 $this->updateEntry($entry);
152 $em = $this->getDoctrine()->getManager();
153 $em->persist($entry);
156 // entry saved, dispatch event about it!
157 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
160 return $this->redirect($this->generateUrl('homepage'));
164 * @Route("/new", name="new")
166 * @return \Symfony\Component\HttpFoundation\Response
168 public function addEntryAction()
170 return $this->render('WallabagCoreBundle:Entry:new.html.twig');
174 * Edit an entry content.
176 * @Route("/edit/{id}", requirements={"id" = "\d+"}, name="edit")
178 * @return \Symfony\Component\HttpFoundation\Response
180 public function editEntryAction(Request
$request, Entry
$entry)
182 $this->checkUserAction($entry);
184 $form = $this->createForm(EditEntryType
::class, $entry);
186 $form->handleRequest($request);
188 if ($form->isSubmitted() && $form->isValid()) {
189 $em = $this->getDoctrine()->getManager();
190 $em->persist($entry);
193 $this->get('session')->getFlashBag()->add(
195 'flashes.entry.notice.entry_updated'
198 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
201 return $this->render('WallabagCoreBundle:Entry:edit.html.twig', [
202 'form' => $form->createView(),
207 * Shows all entries for current user.
211 * @Route("/all/list/{page}", name="all", defaults={"page" = "1"})
213 * @return \Symfony\Component\HttpFoundation\Response
215 public function showAllAction(Request
$request, $page)
217 return $this->showEntries('all', $request, $page);
221 * Shows unread entries for current user.
225 * @Route("/unread/list/{page}", name="unread", defaults={"page" = "1"})
227 * @return \Symfony\Component\HttpFoundation\Response
229 public function showUnreadAction(Request
$request, $page)
231 // load the quickstart if no entry in database
232 if (1 === (int) $page && 0 === $this->get('wallabag_core.entry_repository')->countAllEntriesByUser($this->getUser()->getId())) {
233 return $this->redirect($this->generateUrl('quickstart'));
236 return $this->showEntries('unread', $request, $page);
240 * Shows read entries for current user.
244 * @Route("/archive/list/{page}", name="archive", defaults={"page" = "1"})
246 * @return \Symfony\Component\HttpFoundation\Response
248 public function showArchiveAction(Request
$request, $page)
250 return $this->showEntries('archive', $request, $page);
254 * Shows starred entries for current user.
258 * @Route("/starred/list/{page}", name="starred", defaults={"page" = "1"})
260 * @return \Symfony\Component\HttpFoundation\Response
262 public function showStarredAction(Request
$request, $page)
264 return $this->showEntries('starred', $request, $page);
268 * Shows untagged articles for current user.
272 * @Route("/untagged/list/{page}", name="untagged", defaults={"page" = "1"})
274 * @return \Symfony\Component\HttpFoundation\Response
276 public function showUntaggedEntriesAction(Request
$request, $page)
278 return $this->showEntries('untagged', $request, $page);
282 * Shows random entry depending on the given type.
284 * @param string $type
286 * @Route("/{type}/random", name="random_entry", requirements={"type": "unread|starred|archive|untagged|all"})
288 * @return \Symfony\Component\HttpFoundation\RedirectResponse
290 public function redirectRandomEntryAction($type = 'all')
293 $entry = $this->get('wallabag_core.entry_repository')
294 ->getRandomEntry($this->getUser()->getId(), $type);
295 } catch (NoResultException
$e) {
296 $bag = $this->get('session')->getFlashBag();
298 $bag->add('notice', 'flashes.entry.notice.no_random_entry');
300 return $this->redirect($this->generateUrl($type));
303 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
307 * Shows entry content.
309 * @Route("/view/{id}", requirements={"id" = "\d+"}, name="view")
311 * @return \Symfony\Component\HttpFoundation\Response
313 public function viewAction(Entry
$entry)
315 $this->checkUserAction($entry);
317 return $this->render(
318 'WallabagCoreBundle:Entry:entry.html.twig',
325 * Refetch content from the website and make it readable again.
327 * @Route("/reload/{id}", requirements={"id" = "\d+"}, name="reload_entry")
329 * @return \Symfony\Component\HttpFoundation\RedirectResponse
331 public function reloadAction(Entry
$entry)
333 $this->checkUserAction($entry);
335 $this->updateEntry($entry, 'entry_reloaded');
337 // if refreshing entry failed, don't save it
338 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
339 $bag = $this->get('session')->getFlashBag();
341 $bag->add('notice', 'flashes.entry.notice.entry_reloaded_failed');
343 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
346 $em = $this->getDoctrine()->getManager();
347 $em->persist($entry);
350 // entry saved, dispatch event about it!
351 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
353 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
357 * Changes read status for an entry.
359 * @Route("/archive/{id}", requirements={"id" = "\d+"}, name="archive_entry")
361 * @return \Symfony\Component\HttpFoundation\RedirectResponse
363 public function toggleArchiveAction(Request
$request, Entry
$entry)
365 $this->checkUserAction($entry);
367 $entry->toggleArchive();
368 $this->getDoctrine()->getManager()->flush();
370 $message = 'flashes.entry.notice.entry_unarchived';
371 if ($entry->isArchived()) {
372 $message = 'flashes.entry.notice.entry_archived';
375 $this->get('session')->getFlashBag()->add(
380 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
382 return $this->redirect($redirectUrl);
386 * Changes starred status for an entry.
388 * @Route("/star/{id}", requirements={"id" = "\d+"}, name="star_entry")
390 * @return \Symfony\Component\HttpFoundation\RedirectResponse
392 public function toggleStarAction(Request
$request, Entry
$entry)
394 $this->checkUserAction($entry);
396 $entry->toggleStar();
397 $entry->updateStar($entry->isStarred());
398 $this->getDoctrine()->getManager()->flush();
400 $message = 'flashes.entry.notice.entry_unstarred';
401 if ($entry->isStarred()) {
402 $message = 'flashes.entry.notice.entry_starred';
405 $this->get('session')->getFlashBag()->add(
410 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
412 return $this->redirect($redirectUrl);
416 * Deletes entry and redirect to the homepage or the last viewed page.
418 * @Route("/delete/{id}", requirements={"id" = "\d+"}, name="delete_entry")
420 * @return \Symfony\Component\HttpFoundation\RedirectResponse
422 public function deleteEntryAction(Request
$request, Entry
$entry)
424 $this->checkUserAction($entry);
426 // generates the view url for this entry to check for redirection later
427 // to avoid redirecting to the deleted entry. Ugh.
428 $url = $this->generateUrl(
430 ['id' => $entry->getId()],
431 UrlGeneratorInterface
::ABSOLUTE_PATH
434 // entry deleted, dispatch event about it!
435 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
437 $em = $this->getDoctrine()->getManager();
441 $this->get('session')->getFlashBag()->add(
443 'flashes.entry.notice.entry_deleted'
446 // don't redirect user to the deleted entry (check that the referer doesn't end with the same url)
447 $referer = $request->headers
->get('referer');
448 $to = (1 !== preg_match('#' . $url . '$#i', $referer) ? $referer : null);
450 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to);
452 return $this->redirect($redirectUrl);
456 * Get public URL for entry (and generate it if necessary).
458 * @Route("/share/{id}", requirements={"id" = "\d+"}, name="share")
460 * @return \Symfony\Component\HttpFoundation\Response
462 public function shareAction(Entry
$entry)
464 $this->checkUserAction($entry);
466 if (null === $entry->getUid()) {
467 $entry->generateUid();
469 $em = $this->getDoctrine()->getManager();
470 $em->persist($entry);
474 return $this->redirect($this->generateUrl('share_entry', [
475 'uid' => $entry->getUid(),
480 * Disable public sharing for an entry.
482 * @Route("/share/delete/{id}", requirements={"id" = "\d+"}, name="delete_share")
484 * @return \Symfony\Component\HttpFoundation\Response
486 public function deleteShareAction(Entry
$entry)
488 $this->checkUserAction($entry);
492 $em = $this->getDoctrine()->getManager();
493 $em->persist($entry);
496 return $this->redirect($this->generateUrl('view', [
497 'id' => $entry->getId(),
502 * Ability to view a content publicly.
504 * @Route("/share/{uid}", requirements={"uid" = ".+"}, name="share_entry")
505 * @Cache(maxage="25200", smaxage="25200", public=true)
507 * @return \Symfony\Component\HttpFoundation\Response
509 public function shareEntryAction(Entry
$entry)
511 if (!$this->get('craue_config')->get('share_public')) {
512 throw $this->createAccessDeniedException('Sharing an entry is disabled for this user.');
515 return $this->render(
516 '@WallabagCore/themes/common/Entry/share.html.twig',
522 * Global method to retrieve entries depending on the given type
523 * It returns the response to be send.
525 * @param string $type Entries type: unread, starred or archive
528 * @return \Symfony\Component\HttpFoundation\Response
530 private function showEntries($type, Request
$request, $page)
532 $repository = $this->get('wallabag_core.entry_repository');
533 $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : '');
534 $currentRoute = (null !== $request->query
->get('currentRoute') ? $request->query
->get('currentRoute') : '');
535 $direction = (null !== $request->query
->get('entry_sort')['sortOrder'] ? $request->query
->get('entry_sort')['sortOrder'] : 'asc');
537 // defined as null by default because each repository method have the right field as default value too
538 // like `getBuilderForStarredByUser` will have `starredAt` sort by default
540 if (\
in_array($request->get('entry_sort')['sortType'], ['id', 'title', 'createdAt', 'updatedAt', 'starredAt', 'archivedAt'], true)) {
541 $sortBy = $request->get('entry_sort')['sortType'];
546 $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute);
549 $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId(), $sortBy, $direction);
552 $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId(), $sortBy, $direction);
555 $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId(), $sortBy, $direction);
558 $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId(), $sortBy, $direction);
561 $qb = $repository->getBuilderForAllByUser($this->getUser()->getId(), $sortBy, $direction);
564 throw new \
InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
567 $form = $this->createForm(EntryFilterType
::class);
568 $sortForm = $this->createForm(EntrySortType
::class);
570 if ($request->query
->has($form->getName())) {
571 // manually bind values from the request
572 $form->submit($request->query
->get($form->getName()));
574 // build the query from the given form object
575 $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb);
578 if ($request->query
->has($sortForm->getName())) {
579 // manually bind values from the request
580 $sortForm->submit($request->query
->get($sortForm->getName()));
583 $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false);
585 $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter);
588 $entries->setCurrentPage($page);
589 } catch (OutOfRangeCurrentPageException
$e) {
591 return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302);
595 $nbEntriesUntagged = $this->get('wallabag_core.entry_repository')
596 ->countUntaggedEntriesByUser($this->getUser()->getId());
598 return $this->render(
599 'WallabagCoreBundle:Entry:entries.html.twig', [
600 'form' => $form->createView(),
601 'sortForm' => $sortForm->createView(),
602 'entries' => $entries,
603 'currentPage' => $page,
604 'searchTerm' => $searchTerm,
605 'isFiltered' => $form->isSubmitted(),
606 'nbEntriesUntagged' => $nbEntriesUntagged,
612 * Fetch content and update entry.
613 * In case it fails, $entry->getContent will return an error message.
615 * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded
617 private function updateEntry(Entry
$entry, $prefixMessage = 'entry_saved')
619 $message = 'flashes.entry.notice.' . $prefixMessage;
622 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
623 } catch (\Exception
$e) {
624 $this->get('logger')->error('Error while saving an entry', [
629 $message = 'flashes.entry.notice.' . $prefixMessage . '_failed';
632 if (empty($entry->getDomainName())) {
633 $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
636 if (empty($entry->getTitle())) {
637 $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
640 $this->get('session')->getFlashBag()->add('notice', $message);
644 * Check if the logged user can manage the given entry.
646 private function checkUserAction(Entry
$entry)
648 if (null === $this->getUser() || $this->getUser()->getId() !== $entry->getUser()->getId()) {
649 throw $this->createAccessDeniedException('You can not access this entry.');
654 * Check for existing entry, if it exists, redirect to it with a message.
658 private function checkIfEntryAlreadyExists(Entry
$entry)
660 return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId());