3 namespace Wallabag\CoreBundle\Controller
;
5 use Pagerfanta\Adapter\DoctrineORMAdapter
;
6 use Pagerfanta\Exception\OutOfRangeCurrentPageException
;
7 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route
;
8 use Symfony\Bundle\FrameworkBundle\Controller\Controller
;
9 use Symfony\Component\HttpFoundation\Request
;
10 use Symfony\Component\Routing\Generator\UrlGeneratorInterface
;
11 use Wallabag\CoreBundle\Entity\Entry
;
12 use Wallabag\CoreBundle\Event\EntryUpdatedEvent
;
13 use Wallabag\CoreBundle\Form\Type\EntryFilterType
;
14 use Wallabag\CoreBundle\Form\Type\EditEntryType
;
15 use Wallabag\CoreBundle\Form\Type\NewEntryType
;
16 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache
;
17 use Wallabag\CoreBundle\Event\EntrySavedEvent
;
18 use Wallabag\CoreBundle\Event\EntryDeletedEvent
;
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 * Fetch content and update entry.
57 * In case it fails, entry will return to avod loosing the data.
60 * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded
64 private function updateEntry(Entry
$entry, $prefixMessage = 'entry_saved')
66 // put default title in case of fetching content failed
67 $entry->setTitle('No title found');
69 $message = 'flashes.entry.notice.'.$prefixMessage;
72 $entry = $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
73 } catch (\Exception
$e) {
74 $this->get('logger')->error('Error while saving an entry', [
79 $message = 'flashes.entry.notice.'.$prefixMessage.'_failed';
82 $this->get('session')->getFlashBag()->add('notice', $message);
88 * @param Request $request
90 * @Route("/new-entry", name="new_entry")
92 * @return \Symfony\Component\HttpFoundation\Response
94 public function addEntryFormAction(Request
$request)
96 $entry = new Entry($this->getUser());
98 $form = $this->createForm(NewEntryType
::class, $entry);
100 $form->handleRequest($request);
102 if ($form->isSubmitted() && $form->isValid()) {
103 $existingEntry = $this->checkIfEntryAlreadyExists($entry);
105 if (false !== $existingEntry) {
106 $this->get('session')->getFlashBag()->add(
108 $this->get('translator')->trans('flashes.entry.notice.entry_already_saved', ['%date%' => $existingEntry->getCreatedAt()->format('d-m-Y')])
111 return $this->redirect($this->generateUrl('view', ['id' => $existingEntry->getId()]));
114 $this->updateEntry($entry);
116 $em = $this->getDoctrine()->getManager();
117 $em->persist($entry);
120 // entry saved, dispatch event about it!
121 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
123 return $this->redirect($this->generateUrl('homepage'));
126 return $this->render('WallabagCoreBundle:Entry:new_form.html.twig', [
127 'form' => $form->createView(),
132 * @param Request $request
134 * @Route("/bookmarklet", name="bookmarklet")
136 * @return \Symfony\Component\HttpFoundation\Response
138 public function addEntryViaBookmarkletAction(Request
$request)
140 $entry = new Entry($this->getUser());
141 $entry->setUrl($request->get('url'));
143 if (false === $this->checkIfEntryAlreadyExists($entry)) {
144 $this->updateEntry($entry);
146 $em = $this->getDoctrine()->getManager();
147 $em->persist($entry);
150 // entry saved, dispatch event about it!
151 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
154 return $this->redirect($this->generateUrl('homepage'));
158 * @Route("/new", name="new")
160 * @return \Symfony\Component\HttpFoundation\Response
162 public function addEntryAction()
164 return $this->render('WallabagCoreBundle:Entry:new.html.twig');
168 * Edit an entry content.
170 * @param Request $request
171 * @param Entry $entry
173 * @Route("/edit/{id}", requirements={"id" = "\d+"}, name="edit")
175 * @return \Symfony\Component\HttpFoundation\Response
177 public function editEntryAction(Request
$request, Entry
$entry)
179 $this->checkUserAction($entry);
181 $form = $this->createForm(EditEntryType
::class, $entry);
183 $form->handleRequest($request);
185 if ($form->isSubmitted() && $form->isValid()) {
186 $em = $this->getDoctrine()->getManager();
187 $em->persist($entry);
190 $this->get('session')->getFlashBag()->add(
192 'flashes.entry.notice.entry_updated'
195 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
198 return $this->render('WallabagCoreBundle:Entry:edit.html.twig', [
199 'form' => $form->createView(),
204 * Shows all entries for current user.
206 * @param Request $request
209 * @Route("/all/list/{page}", name="all", defaults={"page" = "1"})
211 * @return \Symfony\Component\HttpFoundation\Response
213 public function showAllAction(Request
$request, $page)
215 return $this->showEntries('all', $request, $page);
219 * Shows unread entries for current user.
221 * @param Request $request
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 ($page == 1 && $this->get('wallabag_core.entry_repository')->countAllEntriesByUser($this->getUser()->getId()) == 0) {
232 return $this->redirect($this->generateUrl('quickstart'));
235 return $this->showEntries('unread', $request, $page);
239 * Shows read entries for current user.
241 * @param Request $request
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.
256 * @param Request $request
259 * @Route("/starred/list/{page}", name="starred", defaults={"page" = "1"})
261 * @return \Symfony\Component\HttpFoundation\Response
263 public function showStarredAction(Request
$request, $page)
265 return $this->showEntries('starred', $request, $page);
269 * Global method to retrieve entries depending on the given type
270 * It returns the response to be send.
272 * @param string $type Entries type: unread, starred or archive
273 * @param Request $request
276 * @return \Symfony\Component\HttpFoundation\Response
278 private function showEntries($type, Request
$request, $page)
280 $repository = $this->get('wallabag_core.entry_repository');
281 $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : '');
282 $currentRoute = (!is_null($request->query
->get('currentRoute')) ? $request->query
->get('currentRoute') : '');
286 $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute);
290 $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId());
294 $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId());
298 $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId());
302 $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId());
306 $qb = $repository->getBuilderForAllByUser($this->getUser()->getId());
310 throw new \
InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
313 $form = $this->createForm(EntryFilterType
::class);
315 if ($request->query
->has($form->getName())) {
316 // manually bind values from the request
317 $form->submit($request->query
->get($form->getName()));
319 // build the query from the given form object
320 $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb);
323 $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false);
325 $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')
326 ->prepare($pagerAdapter, $page);
329 $entries->setCurrentPage($page);
330 } catch (OutOfRangeCurrentPageException
$e) {
332 return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302);
336 return $this->render(
337 'WallabagCoreBundle:Entry:entries.html.twig', [
338 'form' => $form->createView(),
339 'entries' => $entries,
340 'currentPage' => $page,
341 'searchTerm' => $searchTerm,
347 * Shows entry content.
349 * @param Entry $entry
351 * @Route("/view/{id}", requirements={"id" = "\d+"}, name="view")
353 * @return \Symfony\Component\HttpFoundation\Response
355 public function viewAction(Entry
$entry)
357 $this->checkUserAction($entry);
359 return $this->render(
360 'WallabagCoreBundle:Entry:entry.html.twig',
367 * Refetch content from the website and make it readable again.
369 * @param Entry $entry
371 * @Route("/reload/{id}", requirements={"id" = "\d+"}, name="reload_entry")
373 * @return \Symfony\Component\HttpFoundation\RedirectResponse
375 public function reloadAction(Entry
$entry)
377 $this->checkUserAction($entry);
379 $this->updateEntry($entry, 'entry_reloaded');
381 // if refreshing entry failed, don't save it
382 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
383 $bag = $this->get('session')->getFlashBag();
385 $bag->add('notice', 'flashes.entry.notice.entry_reloaded_failed');
387 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
390 $em = $this->getDoctrine()->getManager();
391 $em->persist($entry);
394 // entry saved, dispatch event about it!
395 $this->get('event_dispatcher')->dispatch(EntryUpdatedEvent
::NAME
, new EntryUpdatedEvent($entry));
396 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
398 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
402 * Changes read status for an entry.
404 * @param Request $request
405 * @param Entry $entry
407 * @Route("/archive/{id}", requirements={"id" = "\d+"}, name="archive_entry")
409 * @return \Symfony\Component\HttpFoundation\RedirectResponse
411 public function toggleArchiveAction(Request
$request, Entry
$entry)
413 $this->checkUserAction($entry);
415 $entry->toggleArchive();
416 $this->getDoctrine()->getManager()->flush();
418 $this->get('event_dispatcher')->dispatch(EntryUpdatedEvent
::NAME
, new EntryUpdatedEvent($entry));
420 $message = 'flashes.entry.notice.entry_unarchived';
421 if ($entry->isArchived()) {
422 $message = 'flashes.entry.notice.entry_archived';
425 $this->get('session')->getFlashBag()->add(
430 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
432 return $this->redirect($redirectUrl);
436 * Changes starred status for an entry.
438 * @param Request $request
439 * @param Entry $entry
441 * @Route("/star/{id}", requirements={"id" = "\d+"}, name="star_entry")
443 * @return \Symfony\Component\HttpFoundation\RedirectResponse
445 public function toggleStarAction(Request
$request, Entry
$entry)
447 $this->checkUserAction($entry);
449 $entry->toggleStar();
450 $this->getDoctrine()->getManager()->flush();
452 $this->get('event_dispatcher')->dispatch(EntryUpdatedEvent
::NAME
, new EntryUpdatedEvent($entry));
454 $message = 'flashes.entry.notice.entry_unstarred';
455 if ($entry->isStarred()) {
456 $message = 'flashes.entry.notice.entry_starred';
459 $this->get('session')->getFlashBag()->add(
464 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
466 return $this->redirect($redirectUrl);
470 * Deletes entry and redirect to the homepage or the last viewed page.
472 * @param Entry $entry
474 * @Route("/delete/{id}", requirements={"id" = "\d+"}, name="delete_entry")
476 * @return \Symfony\Component\HttpFoundation\RedirectResponse
478 public function deleteEntryAction(Request
$request, Entry
$entry)
480 $this->checkUserAction($entry);
482 // generates the view url for this entry to check for redirection later
483 // to avoid redirecting to the deleted entry. Ugh.
484 $url = $this->generateUrl(
486 ['id' => $entry->getId()],
487 UrlGeneratorInterface
::ABSOLUTE_PATH
490 // entry deleted, dispatch event about it!
491 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
493 $em = $this->getDoctrine()->getManager();
497 $this->get('session')->getFlashBag()->add(
499 'flashes.entry.notice.entry_deleted'
502 // don't redirect user to the deleted entry (check that the referer doesn't end with the same url)
503 $referer = $request->headers
->get('referer');
504 $to = (1 !== preg_match('#'.$url.'$#i', $referer) ? $referer : null);
506 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to);
508 return $this->redirect($redirectUrl);
512 * Check if the logged user can manage the given entry.
514 * @param Entry $entry
516 private function checkUserAction(Entry
$entry)
518 if (null === $this->getUser() || $this->getUser()->getId() != $entry->getUser()->getId()) {
519 throw $this->createAccessDeniedException('You can not access this entry.');
524 * Check for existing entry, if it exists, redirect to it with a message.
526 * @param Entry $entry
530 private function checkIfEntryAlreadyExists(Entry
$entry)
532 return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId());
536 * Get public URL for entry (and generate it if necessary).
538 * @param Entry $entry
540 * @Route("/share/{id}", requirements={"id" = "\d+"}, name="share")
542 * @return \Symfony\Component\HttpFoundation\Response
544 public function shareAction(Entry
$entry)
546 $this->checkUserAction($entry);
548 if (null === $entry->getUid()) {
549 $entry->generateUid();
551 $em = $this->getDoctrine()->getManager();
552 $em->persist($entry);
556 return $this->redirect($this->generateUrl('share_entry', [
557 'uid' => $entry->getUid(),
562 * Disable public sharing for an entry.
564 * @param Entry $entry
566 * @Route("/share/delete/{id}", requirements={"id" = "\d+"}, name="delete_share")
568 * @return \Symfony\Component\HttpFoundation\Response
570 public function deleteShareAction(Entry
$entry)
572 $this->checkUserAction($entry);
576 $em = $this->getDoctrine()->getManager();
577 $em->persist($entry);
580 return $this->redirect($this->generateUrl('view', [
581 'id' => $entry->getId(),
586 * Ability to view a content publicly.
588 * @param Entry $entry
590 * @Route("/share/{uid}", requirements={"uid" = ".+"}, name="share_entry")
591 * @Cache(maxage="25200", smaxage="25200", public=true)
593 * @return \Symfony\Component\HttpFoundation\Response
595 public function shareEntryAction(Entry
$entry)
597 if (!$this->get('craue_config')->get('share_public')) {
598 throw $this->createAccessDeniedException('Sharing an entry is disabled for this user.');
601 return $this->render(
602 '@WallabagCore/themes/common/Entry/share.html.twig',
608 * Shows untagged articles for current user.
610 * @param Request $request
613 * @Route("/untagged/list/{page}", name="untagged", defaults={"page" = "1"})
615 * @return \Symfony\Component\HttpFoundation\Response
617 public function showUntaggedEntriesAction(Request
$request, $page)
619 return $this->showEntries('untagged', $request, $page);