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\NewEntryType
;
19 use Wallabag\CoreBundle\Form\Type\SearchEntryType
;
21 class EntryController
extends Controller
24 * @Route("/mass", name="mass_action")
26 * @return \Symfony\Component\HttpFoundation\Response
28 public function massAction(Request
$request)
30 $em = $this->getDoctrine()->getManager();
31 $values = $request->request
->all();
33 $action = 'toggle-read';
34 if (isset($values['toggle-star'])) {
35 $action = 'toggle-star';
36 } elseif (isset($values['delete'])) {
40 if (isset($values['entry-checkbox'])) {
41 foreach ($values['entry-checkbox'] as $id) {
43 $entry = $this->get('wallabag_core.entry_repository')->findById((int) $id)[0];
45 $this->checkUserAction($entry);
47 if ('toggle-read' === $action) {
48 $entry->toggleArchive();
49 } elseif ('toggle-star' === $action) {
51 } elseif ('delete' === $action) {
52 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
60 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
62 return $this->redirect($redirectUrl);
68 * @Route("/search/{page}", name="search", defaults={"page" = 1})
70 * Default parameter for page is hardcoded (in duplication of the defaults from the Route)
71 * because this controller is also called inside the layout template without any page as argument
73 * @return \Symfony\Component\HttpFoundation\Response
75 public function searchFormAction(Request
$request, $page = 1, $currentRoute = null)
77 // fallback to retrieve currentRoute from query parameter instead of injected one (when using inside a template)
78 if (null === $currentRoute && $request->query
->has('currentRoute')) {
79 $currentRoute = $request->query
->get('currentRoute');
82 $form = $this->createForm(SearchEntryType
::class);
84 $form->handleRequest($request);
86 if ($form->isSubmitted() && $form->isValid()) {
87 return $this->showEntries('search', $request, $page);
90 return $this->render('WallabagCoreBundle:Entry:search_form.html.twig', [
91 'form' => $form->createView(),
92 'currentRoute' => $currentRoute,
97 * @Route("/new-entry", name="new_entry")
99 * @return \Symfony\Component\HttpFoundation\Response
101 public function addEntryFormAction(Request
$request)
103 $entry = new Entry($this->getUser());
105 $form = $this->createForm(NewEntryType
::class, $entry);
107 $form->handleRequest($request);
109 if ($form->isSubmitted() && $form->isValid()) {
110 $existingEntry = $this->checkIfEntryAlreadyExists($entry);
112 if (false !== $existingEntry) {
113 $this->get('session')->getFlashBag()->add(
115 $this->get('translator')->trans('flashes.entry.notice.entry_already_saved', ['%date%' => $existingEntry->getCreatedAt()->format('d-m-Y')])
118 return $this->redirect($this->generateUrl('view', ['id' => $existingEntry->getId()]));
121 $this->updateEntry($entry);
123 $em = $this->getDoctrine()->getManager();
124 $em->persist($entry);
127 // entry saved, dispatch event about it!
128 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
130 return $this->redirect($this->generateUrl('homepage'));
133 return $this->render('WallabagCoreBundle:Entry:new_form.html.twig', [
134 'form' => $form->createView(),
139 * @Route("/bookmarklet", name="bookmarklet")
141 * @return \Symfony\Component\HttpFoundation\Response
143 public function addEntryViaBookmarkletAction(Request
$request)
145 $entry = new Entry($this->getUser());
146 $entry->setUrl($request->get('url'));
148 if (false === $this->checkIfEntryAlreadyExists($entry)) {
149 $this->updateEntry($entry);
151 $em = $this->getDoctrine()->getManager();
152 $em->persist($entry);
155 // entry saved, dispatch event about it!
156 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
159 return $this->redirect($this->generateUrl('homepage'));
163 * @Route("/new", name="new")
165 * @return \Symfony\Component\HttpFoundation\Response
167 public function addEntryAction()
169 return $this->render('WallabagCoreBundle:Entry:new.html.twig');
173 * Edit an entry content.
175 * @Route("/edit/{id}", requirements={"id" = "\d+"}, name="edit")
177 * @return \Symfony\Component\HttpFoundation\Response
179 public function editEntryAction(Request
$request, Entry
$entry)
181 $this->checkUserAction($entry);
183 $form = $this->createForm(EditEntryType
::class, $entry);
185 $form->handleRequest($request);
187 if ($form->isSubmitted() && $form->isValid()) {
188 $em = $this->getDoctrine()->getManager();
189 $em->persist($entry);
192 $this->get('session')->getFlashBag()->add(
194 'flashes.entry.notice.entry_updated'
197 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
200 return $this->render('WallabagCoreBundle:Entry:edit.html.twig', [
201 'form' => $form->createView(),
206 * Shows all entries for current user.
210 * @Route("/all/list/{page}", name="all", defaults={"page" = "1"})
212 * @return \Symfony\Component\HttpFoundation\Response
214 public function showAllAction(Request
$request, $page)
216 return $this->showEntries('all', $request, $page);
220 * Shows unread entries for current user.
224 * @Route("/unread/list/{page}", name="unread", defaults={"page" = "1"})
226 * @return \Symfony\Component\HttpFoundation\Response
228 public function showUnreadAction(Request
$request, $page)
230 // load the quickstart if no entry in database
231 if (1 === (int) $page && 0 === $this->get('wallabag_core.entry_repository')->countAllEntriesByUser($this->getUser()->getId())) {
232 return $this->redirect($this->generateUrl('quickstart'));
235 return $this->showEntries('unread', $request, $page);
239 * Shows read entries for current user.
243 * @Route("/archive/list/{page}", name="archive", defaults={"page" = "1"})
245 * @return \Symfony\Component\HttpFoundation\Response
247 public function showArchiveAction(Request
$request, $page)
249 return $this->showEntries('archive', $request, $page);
253 * Shows starred entries for current user.
257 * @Route("/starred/list/{page}", name="starred", defaults={"page" = "1"})
259 * @return \Symfony\Component\HttpFoundation\Response
261 public function showStarredAction(Request
$request, $page)
263 return $this->showEntries('starred', $request, $page);
267 * Shows untagged articles for current user.
271 * @Route("/untagged/list/{page}", name="untagged", defaults={"page" = "1"})
273 * @return \Symfony\Component\HttpFoundation\Response
275 public function showUntaggedEntriesAction(Request
$request, $page)
277 return $this->showEntries('untagged', $request, $page);
281 * Shows random entry depending on the given type.
283 * @param string $type
285 * @Route("/{type}/random", name="random_entry", requirements={"type": "unread|starred|archive|untagged|all"})
287 * @return \Symfony\Component\HttpFoundation\RedirectResponse
289 public function redirectRandomEntryAction($type = 'all')
292 $entry = $this->get('wallabag_core.entry_repository')
293 ->getRandomEntry($this->getUser()->getId(), $type);
294 } catch (NoResultException
$e) {
295 $bag = $this->get('session')->getFlashBag();
297 $bag->add('notice', 'flashes.entry.notice.no_random_entry');
299 return $this->redirect($this->generateUrl($type));
302 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
306 * Shows entry content.
308 * @Route("/view/{id}", requirements={"id" = "\d+"}, name="view")
310 * @return \Symfony\Component\HttpFoundation\Response
312 public function viewAction(Entry
$entry)
314 $this->checkUserAction($entry);
316 return $this->render(
317 'WallabagCoreBundle:Entry:entry.html.twig',
324 * Refetch content from the website and make it readable again.
326 * @Route("/reload/{id}", requirements={"id" = "\d+"}, name="reload_entry")
328 * @return \Symfony\Component\HttpFoundation\RedirectResponse
330 public function reloadAction(Entry
$entry)
332 $this->checkUserAction($entry);
334 $this->updateEntry($entry, 'entry_reloaded');
336 // if refreshing entry failed, don't save it
337 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
338 $bag = $this->get('session')->getFlashBag();
340 $bag->add('notice', 'flashes.entry.notice.entry_reloaded_failed');
342 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
345 $em = $this->getDoctrine()->getManager();
346 $em->persist($entry);
349 // entry saved, dispatch event about it!
350 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
352 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
356 * Changes read status for an entry.
358 * @Route("/archive/{id}", requirements={"id" = "\d+"}, name="archive_entry")
360 * @return \Symfony\Component\HttpFoundation\RedirectResponse
362 public function toggleArchiveAction(Request
$request, Entry
$entry)
364 $this->checkUserAction($entry);
366 $entry->toggleArchive();
367 $this->getDoctrine()->getManager()->flush();
369 $message = 'flashes.entry.notice.entry_unarchived';
370 if ($entry->isArchived()) {
371 $message = 'flashes.entry.notice.entry_archived';
374 $this->get('session')->getFlashBag()->add(
379 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
381 return $this->redirect($redirectUrl);
385 * Changes starred status for an entry.
387 * @Route("/star/{id}", requirements={"id" = "\d+"}, name="star_entry")
389 * @return \Symfony\Component\HttpFoundation\RedirectResponse
391 public function toggleStarAction(Request
$request, Entry
$entry)
393 $this->checkUserAction($entry);
395 $entry->toggleStar();
396 $entry->updateStar($entry->isStarred());
397 $this->getDoctrine()->getManager()->flush();
399 $message = 'flashes.entry.notice.entry_unstarred';
400 if ($entry->isStarred()) {
401 $message = 'flashes.entry.notice.entry_starred';
404 $this->get('session')->getFlashBag()->add(
409 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
411 return $this->redirect($redirectUrl);
415 * Deletes entry and redirect to the homepage or the last viewed page.
417 * @Route("/delete/{id}", requirements={"id" = "\d+"}, name="delete_entry")
419 * @return \Symfony\Component\HttpFoundation\RedirectResponse
421 public function deleteEntryAction(Request
$request, Entry
$entry)
423 $this->checkUserAction($entry);
425 // generates the view url for this entry to check for redirection later
426 // to avoid redirecting to the deleted entry. Ugh.
427 $url = $this->generateUrl(
429 ['id' => $entry->getId()],
430 UrlGeneratorInterface
::ABSOLUTE_PATH
433 // entry deleted, dispatch event about it!
434 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
436 $em = $this->getDoctrine()->getManager();
440 $this->get('session')->getFlashBag()->add(
442 'flashes.entry.notice.entry_deleted'
445 // don't redirect user to the deleted entry (check that the referer doesn't end with the same url)
446 $referer = $request->headers
->get('referer');
447 $to = (1 !== preg_match('#' . $url . '$#i', $referer) ? $referer : null);
449 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to);
451 return $this->redirect($redirectUrl);
455 * Get public URL for entry (and generate it if necessary).
457 * @Route("/share/{id}", requirements={"id" = "\d+"}, name="share")
459 * @return \Symfony\Component\HttpFoundation\Response
461 public function shareAction(Entry
$entry)
463 $this->checkUserAction($entry);
465 if (null === $entry->getUid()) {
466 $entry->generateUid();
468 $em = $this->getDoctrine()->getManager();
469 $em->persist($entry);
473 return $this->redirect($this->generateUrl('share_entry', [
474 'uid' => $entry->getUid(),
479 * Disable public sharing for an entry.
481 * @Route("/share/delete/{id}", requirements={"id" = "\d+"}, name="delete_share")
483 * @return \Symfony\Component\HttpFoundation\Response
485 public function deleteShareAction(Entry
$entry)
487 $this->checkUserAction($entry);
491 $em = $this->getDoctrine()->getManager();
492 $em->persist($entry);
495 return $this->redirect($this->generateUrl('view', [
496 'id' => $entry->getId(),
501 * Ability to view a content publicly.
503 * @Route("/share/{uid}", requirements={"uid" = ".+"}, name="share_entry")
504 * @Cache(maxage="25200", smaxage="25200", public=true)
506 * @return \Symfony\Component\HttpFoundation\Response
508 public function shareEntryAction(Entry
$entry)
510 if (!$this->get('craue_config')->get('share_public')) {
511 throw $this->createAccessDeniedException('Sharing an entry is disabled for this user.');
514 return $this->render(
515 '@WallabagCore/themes/common/Entry/share.html.twig',
521 * Global method to retrieve entries depending on the given type
522 * It returns the response to be send.
524 * @param string $type Entries type: unread, starred or archive
527 * @return \Symfony\Component\HttpFoundation\Response
529 private function showEntries($type, Request
$request, $page)
531 $repository = $this->get('wallabag_core.entry_repository');
532 $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : '');
533 $currentRoute = (null !== $request->query
->get('currentRoute') ? $request->query
->get('currentRoute') : '');
535 // defined as null by default because each repository method have the right field as default value too
536 // like `getBuilderForStarredByUser` will have `starredAt` sort by default
538 if (\
in_array($request->get('sort', 'createdAt'), ['id', 'title', 'createdAt', 'updatedAt', 'starredAt', 'archivedAt'], true)) {
539 $sortBy = $request->get('sort', null);
542 $direction = 'DESC' === $request->get('direction') ? 'DESC' : 'ASC';
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);
569 if ($request->query
->has($form->getName())) {
570 // manually bind values from the request
571 $form->submit($request->query
->get($form->getName()));
573 // build the query from the given form object
574 $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb);
577 $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false);
579 $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter);
582 $entries->setCurrentPage($page);
583 } catch (OutOfRangeCurrentPageException
$e) {
585 return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302);
589 $nbEntriesUntagged = $this->get('wallabag_core.entry_repository')
590 ->countUntaggedEntriesByUser($this->getUser()->getId());
592 return $this->render(
593 'WallabagCoreBundle:Entry:entries.html.twig', [
594 'form' => $form->createView(),
595 'entries' => $entries,
596 'currentPage' => $page,
597 'searchTerm' => $searchTerm,
598 'isFiltered' => $form->isSubmitted(),
599 'nbEntriesUntagged' => $nbEntriesUntagged,
605 * Fetch content and update entry.
606 * In case it fails, $entry->getContent will return an error message.
608 * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded
610 private function updateEntry(Entry
$entry, $prefixMessage = 'entry_saved')
612 $message = 'flashes.entry.notice.' . $prefixMessage;
615 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
616 } catch (\Exception
$e) {
617 $this->get('logger')->error('Error while saving an entry', [
622 $message = 'flashes.entry.notice.' . $prefixMessage . '_failed';
625 if (empty($entry->getDomainName())) {
626 $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
629 if (empty($entry->getTitle())) {
630 $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
633 $this->get('session')->getFlashBag()->add('notice', $message);
637 * Check if the logged user can manage the given entry.
639 private function checkUserAction(Entry
$entry)
641 if (null === $this->getUser() || $this->getUser()->getId() !== $entry->getUser()->getId()) {
642 throw $this->createAccessDeniedException('You can not access this entry.');
647 * Check for existing entry, if it exists, redirect to it with a message.
651 private function checkIfEntryAlreadyExists(Entry
$entry)
653 return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId());