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 * @param Request $request
27 * @Route("/search/{page}", name="search", defaults={"page" = 1})
29 * Default parameter for page is hardcoded (in duplication of the defaults from the Route)
30 * because this controller is also called inside the layout template without any page as argument
32 * @return \Symfony\Component\HttpFoundation\Response
34 public function searchFormAction(Request
$request, $page = 1, $currentRoute = null)
36 // fallback to retrieve currentRoute from query parameter instead of injected one (when using inside a template)
37 if (null === $currentRoute && $request->query
->has('currentRoute')) {
38 $currentRoute = $request->query
->get('currentRoute');
41 $form = $this->createForm(SearchEntryType
::class);
43 $form->handleRequest($request);
45 if ($form->isSubmitted() && $form->isValid()) {
46 return $this->showEntries('search', $request, $page);
49 return $this->render('WallabagCoreBundle:Entry:search_form.html.twig', [
50 'form' => $form->createView(),
51 'currentRoute' => $currentRoute,
56 * @param Request $request
58 * @Route("/new-entry", name="new_entry")
60 * @return \Symfony\Component\HttpFoundation\Response
62 public function addEntryFormAction(Request
$request)
64 $entry = new Entry($this->getUser());
66 $form = $this->createForm(NewEntryType
::class, $entry);
68 $form->handleRequest($request);
70 if ($form->isSubmitted() && $form->isValid()) {
71 $existingEntry = $this->checkIfEntryAlreadyExists($entry);
73 if (false !== $existingEntry) {
74 $this->get('session')->getFlashBag()->add(
76 $this->get('translator')->trans('flashes.entry.notice.entry_already_saved', ['%date%' => $existingEntry->getCreatedAt()->format('d-m-Y')])
79 return $this->redirect($this->generateUrl('view', ['id' => $existingEntry->getId()]));
82 $this->updateEntry($entry);
84 $em = $this->getDoctrine()->getManager();
88 // entry saved, dispatch event about it!
89 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
91 return $this->redirect($this->generateUrl('homepage'));
94 return $this->render('WallabagCoreBundle:Entry:new_form.html.twig', [
95 'form' => $form->createView(),
100 * @param Request $request
102 * @Route("/bookmarklet", name="bookmarklet")
104 * @return \Symfony\Component\HttpFoundation\Response
106 public function addEntryViaBookmarkletAction(Request
$request)
108 $entry = new Entry($this->getUser());
109 $entry->setUrl($request->get('url'));
111 if (false === $this->checkIfEntryAlreadyExists($entry)) {
112 $this->updateEntry($entry);
114 $em = $this->getDoctrine()->getManager();
115 $em->persist($entry);
118 // entry saved, dispatch event about it!
119 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
122 return $this->redirect($this->generateUrl('homepage'));
126 * @Route("/new", name="new")
128 * @return \Symfony\Component\HttpFoundation\Response
130 public function addEntryAction()
132 return $this->render('WallabagCoreBundle:Entry:new.html.twig');
136 * Edit an entry content.
138 * @param Request $request
139 * @param Entry $entry
141 * @Route("/edit/{id}", requirements={"id" = "\d+"}, name="edit")
143 * @return \Symfony\Component\HttpFoundation\Response
145 public function editEntryAction(Request
$request, Entry
$entry)
147 $this->checkUserAction($entry);
149 $form = $this->createForm(EditEntryType
::class, $entry);
151 $form->handleRequest($request);
153 if ($form->isSubmitted() && $form->isValid()) {
154 $em = $this->getDoctrine()->getManager();
155 $em->persist($entry);
158 $this->get('session')->getFlashBag()->add(
160 'flashes.entry.notice.entry_updated'
163 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
166 return $this->render('WallabagCoreBundle:Entry:edit.html.twig', [
167 'form' => $form->createView(),
172 * Shows all entries for current user.
174 * @param Request $request
177 * @Route("/all/list/{page}", name="all", defaults={"page" = "1"})
179 * @return \Symfony\Component\HttpFoundation\Response
181 public function showAllAction(Request
$request, $page)
183 return $this->showEntries('all', $request, $page);
187 * Shows unread entries for current user.
189 * @param Request $request
192 * @Route("/unread/list/{page}", name="unread", defaults={"page" = "1"})
194 * @return \Symfony\Component\HttpFoundation\Response
196 public function showUnreadAction(Request
$request, $page)
198 // load the quickstart if no entry in database
199 if (1 === (int) $page && 0 === $this->get('wallabag_core.entry_repository')->countAllEntriesByUser($this->getUser()->getId())) {
200 return $this->redirect($this->generateUrl('quickstart'));
203 return $this->showEntries('unread', $request, $page);
207 * Shows read entries for current user.
209 * @param Request $request
212 * @Route("/archive/list/{page}", name="archive", defaults={"page" = "1"})
214 * @return \Symfony\Component\HttpFoundation\Response
216 public function showArchiveAction(Request
$request, $page)
218 return $this->showEntries('archive', $request, $page);
222 * Shows starred entries for current user.
224 * @param Request $request
227 * @Route("/starred/list/{page}", name="starred", defaults={"page" = "1"})
229 * @return \Symfony\Component\HttpFoundation\Response
231 public function showStarredAction(Request
$request, $page)
233 return $this->showEntries('starred', $request, $page);
237 * Shows untagged articles for current user.
239 * @param Request $request
242 * @Route("/untagged/list/{page}", name="untagged", defaults={"page" = "1"})
244 * @return \Symfony\Component\HttpFoundation\Response
246 public function showUntaggedEntriesAction(Request
$request, $page)
248 return $this->showEntries('untagged', $request, $page);
252 * Shows random unread entry.
254 * @param Entry $entry
256 * @Route("/unread/random", name="unread_random")
258 * @return \Symfony\Component\HttpFoundation\Response
260 public function showRandomUnreadEntryAction()
262 return $this->showRandomEntries('unread');
266 * Shows random favorite entry.
268 * @param Entry $entry
270 * @Route("/starred/random", name="starred_random")
272 * @return \Symfony\Component\HttpFoundation\Response
274 public function showRandomStarredEntryAction()
276 return $this->showRandomEntries('starred');
280 * Shows random archived entry.
282 * @param Entry $entry
284 * @Route("/archive/random", name="archive_random")
286 * @return \Symfony\Component\HttpFoundation\Response
288 public function showRandomArchiveEntryAction()
290 return $this->showRandomEntries('archive');
294 * Shows random all entry.
296 * @param Entry $entry
298 * @Route("/untagged/random", name="untagged_random")
300 * @return \Symfony\Component\HttpFoundation\Response
302 public function showRandomUntaggedEntryAction()
304 return $this->showRandomEntries('untagged');
308 * Shows random all entry.
310 * @param Entry $entry
312 * @Route("/all/random", name="all_random")
314 * @return \Symfony\Component\HttpFoundation\Response
316 public function showRandomAllEntryAction()
318 return $this->showRandomEntries();
322 * Shows entry content.
324 * @param Entry $entry
326 * @Route("/view/{id}", requirements={"id" = "\d+"}, name="view")
328 * @return \Symfony\Component\HttpFoundation\Response
330 public function viewAction(Entry
$entry)
332 $this->checkUserAction($entry);
334 return $this->render(
335 'WallabagCoreBundle:Entry:entry.html.twig',
342 * Refetch content from the website and make it readable again.
344 * @param Entry $entry
346 * @Route("/reload/{id}", requirements={"id" = "\d+"}, name="reload_entry")
348 * @return \Symfony\Component\HttpFoundation\RedirectResponse
350 public function reloadAction(Entry
$entry)
352 $this->checkUserAction($entry);
354 $this->updateEntry($entry, 'entry_reloaded');
356 // if refreshing entry failed, don't save it
357 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
358 $bag = $this->get('session')->getFlashBag();
360 $bag->add('notice', 'flashes.entry.notice.entry_reloaded_failed');
362 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
365 $em = $this->getDoctrine()->getManager();
366 $em->persist($entry);
369 // entry saved, dispatch event about it!
370 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
372 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
376 * Changes read status for an entry.
378 * @param Request $request
379 * @param Entry $entry
381 * @Route("/archive/{id}", requirements={"id" = "\d+"}, name="archive_entry")
383 * @return \Symfony\Component\HttpFoundation\RedirectResponse
385 public function toggleArchiveAction(Request
$request, Entry
$entry)
387 $this->checkUserAction($entry);
389 $entry->toggleArchive();
390 $this->getDoctrine()->getManager()->flush();
392 $message = 'flashes.entry.notice.entry_unarchived';
393 if ($entry->isArchived()) {
394 $message = 'flashes.entry.notice.entry_archived';
397 $this->get('session')->getFlashBag()->add(
402 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
404 return $this->redirect($redirectUrl);
408 * Changes starred status for an entry.
410 * @param Request $request
411 * @param Entry $entry
413 * @Route("/star/{id}", requirements={"id" = "\d+"}, name="star_entry")
415 * @return \Symfony\Component\HttpFoundation\RedirectResponse
417 public function toggleStarAction(Request
$request, Entry
$entry)
419 $this->checkUserAction($entry);
421 $entry->toggleStar();
422 $entry->updateStar($entry->isStarred());
423 $this->getDoctrine()->getManager()->flush();
425 $message = 'flashes.entry.notice.entry_unstarred';
426 if ($entry->isStarred()) {
427 $message = 'flashes.entry.notice.entry_starred';
430 $this->get('session')->getFlashBag()->add(
435 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
437 return $this->redirect($redirectUrl);
441 * Deletes entry and redirect to the homepage or the last viewed page.
443 * @param Entry $entry
445 * @Route("/delete/{id}", requirements={"id" = "\d+"}, name="delete_entry")
447 * @return \Symfony\Component\HttpFoundation\RedirectResponse
449 public function deleteEntryAction(Request
$request, Entry
$entry)
451 $this->checkUserAction($entry);
453 // generates the view url for this entry to check for redirection later
454 // to avoid redirecting to the deleted entry. Ugh.
455 $url = $this->generateUrl(
457 ['id' => $entry->getId()],
458 UrlGeneratorInterface
::ABSOLUTE_PATH
461 // entry deleted, dispatch event about it!
462 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
464 $em = $this->getDoctrine()->getManager();
468 $this->get('session')->getFlashBag()->add(
470 'flashes.entry.notice.entry_deleted'
473 // don't redirect user to the deleted entry (check that the referer doesn't end with the same url)
474 $referer = $request->headers
->get('referer');
475 $to = (1 !== preg_match('#' . $url . '$#i', $referer) ? $referer : null);
477 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to);
479 return $this->redirect($redirectUrl);
483 * Get public URL for entry (and generate it if necessary).
485 * @param Entry $entry
487 * @Route("/share/{id}", requirements={"id" = "\d+"}, name="share")
489 * @return \Symfony\Component\HttpFoundation\Response
491 public function shareAction(Entry
$entry)
493 $this->checkUserAction($entry);
495 if (null === $entry->getUid()) {
496 $entry->generateUid();
498 $em = $this->getDoctrine()->getManager();
499 $em->persist($entry);
503 return $this->redirect($this->generateUrl('share_entry', [
504 'uid' => $entry->getUid(),
509 * Disable public sharing for an entry.
511 * @param Entry $entry
513 * @Route("/share/delete/{id}", requirements={"id" = "\d+"}, name="delete_share")
515 * @return \Symfony\Component\HttpFoundation\Response
517 public function deleteShareAction(Entry
$entry)
519 $this->checkUserAction($entry);
523 $em = $this->getDoctrine()->getManager();
524 $em->persist($entry);
527 return $this->redirect($this->generateUrl('view', [
528 'id' => $entry->getId(),
533 * Ability to view a content publicly.
535 * @param Entry $entry
537 * @Route("/share/{uid}", requirements={"uid" = ".+"}, name="share_entry")
538 * @Cache(maxage="25200", smaxage="25200", public=true)
540 * @return \Symfony\Component\HttpFoundation\Response
542 public function shareEntryAction(Entry
$entry)
544 if (!$this->get('craue_config')->get('share_public')) {
545 throw $this->createAccessDeniedException('Sharing an entry is disabled for this user.');
548 return $this->render(
549 '@WallabagCore/themes/common/Entry/share.html.twig',
555 * Global method to retrieve entries depending on the given type
556 * It returns the response to be send.
558 * @param string $type Entries type: unread, starred or archive
559 * @param Request $request
562 * @return \Symfony\Component\HttpFoundation\Response
564 private function showEntries($type, Request
$request, $page)
566 $repository = $this->get('wallabag_core.entry_repository');
567 $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : '');
568 $currentRoute = (null !== $request->query
->get('currentRoute') ? $request->query
->get('currentRoute') : '');
572 $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute);
575 $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId());
578 $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId());
581 $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId());
584 $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId());
587 $qb = $repository->getBuilderForAllByUser($this->getUser()->getId());
590 throw new \
InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
593 $form = $this->createForm(EntryFilterType
::class);
595 if ($request->query
->has($form->getName())) {
596 // manually bind values from the request
597 $form->submit($request->query
->get($form->getName()));
599 // build the query from the given form object
600 $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb);
603 $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false);
605 $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter);
608 $entries->setCurrentPage($page);
609 } catch (OutOfRangeCurrentPageException
$e) {
611 return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302);
615 return $this->render(
616 'WallabagCoreBundle:Entry:entries.html.twig', [
617 'form' => $form->createView(),
618 'entries' => $entries,
619 'currentPage' => $page,
620 'searchTerm' => $searchTerm,
621 'isFiltered' => $form->isSubmitted(),
627 * Global method to retrieve random entries depending on the given type.
629 * @param string $type Entries type: unread, starred, archive or untagged
631 * @return \Symfony\Component\HttpFoundation\RedirectResponse
633 private function showRandomEntries($type)
635 $repository = $this->get('wallabag_core.entry_repository');
638 $entry = $repository->getRandomEntry($this->getUser()->getId(), $type);
639 } catch (NoResultException
$e) {
640 $bag = $this->get('session')->getFlashBag();
642 $bag->add('notice', 'flashes.entry.notice.no_random_entry');
644 return $this->redirect($this->generateUrl('homepage'));
647 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
651 * Fetch content and update entry.
652 * In case it fails, $entry->getContent will return an error message.
654 * @param Entry $entry
655 * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded
657 private function updateEntry(Entry
$entry, $prefixMessage = 'entry_saved')
659 $message = 'flashes.entry.notice.' . $prefixMessage;
662 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
663 } catch (\Exception
$e) {
664 $this->get('logger')->error('Error while saving an entry', [
669 $message = 'flashes.entry.notice.' . $prefixMessage . '_failed';
672 if (empty($entry->getDomainName())) {
673 $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
676 if (empty($entry->getTitle())) {
677 $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
680 $this->get('session')->getFlashBag()->add('notice', $message);
684 * Check if the logged user can manage the given entry.
686 * @param Entry $entry
688 private function checkUserAction(Entry
$entry)
690 if (null === $this->getUser() || $this->getUser()->getId() !== $entry->getUser()->getId()) {
691 throw $this->createAccessDeniedException('You can not access this entry.');
696 * Check for existing entry, if it exists, redirect to it with a message.
698 * @param Entry $entry
702 private function checkIfEntryAlreadyExists(Entry
$entry)
704 return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId());