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\Form\Type\EntryFilterType
;
13 use Wallabag\CoreBundle\Form\Type\EditEntryType
;
14 use Wallabag\CoreBundle\Form\Type\NewEntryType
;
15 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache
;
16 use Wallabag\CoreBundle\Event\EntrySavedEvent
;
17 use Wallabag\CoreBundle\Event\EntryDeletedEvent
;
18 use Wallabag\CoreBundle\Form\Type\SearchEntryType
;
20 class EntryController
extends Controller
23 * @param Request $request
26 * @Route("/search/{page}", name="search", defaults={"page" = 1})
28 * Default parameter for page is hardcoded (in duplication of the defaults from the Route)
29 * because this controller is also called inside the layout template without any page as argument
31 * @return \Symfony\Component\HttpFoundation\Response
33 public function searchFormAction(Request
$request, $page = 1, $currentRoute = null)
35 // fallback to retrieve currentRoute from query parameter instead of injected one (when using inside a template)
36 if (null === $currentRoute && $request->query
->has('currentRoute')) {
37 $currentRoute = $request->query
->get('currentRoute');
40 $form = $this->createForm(SearchEntryType
::class);
42 $form->handleRequest($request);
44 if ($form->isSubmitted() && $form->isValid()) {
45 return $this->showEntries('search', $request, $page);
48 return $this->render('WallabagCoreBundle:Entry:search_form.html.twig', [
49 'form' => $form->createView(),
50 'currentRoute' => $currentRoute,
55 * Fetch content and update entry.
56 * In case it fails, $entry->getContent will return an error message.
59 * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded
61 private function updateEntry(Entry
$entry, $prefixMessage = 'entry_saved')
63 $message = 'flashes.entry.notice.'.$prefixMessage;
66 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
67 } catch (\Exception
$e) {
68 $this->get('logger')->error('Error while saving an entry', [
73 $message = 'flashes.entry.notice.'.$prefixMessage.'_failed';
76 $this->get('session')->getFlashBag()->add('notice', $message);
80 * @param Request $request
82 * @Route("/new-entry", name="new_entry")
84 * @return \Symfony\Component\HttpFoundation\Response
86 public function addEntryFormAction(Request
$request)
88 $entry = new Entry($this->getUser());
90 $form = $this->createForm(NewEntryType
::class, $entry);
92 $form->handleRequest($request);
94 if ($form->isSubmitted() && $form->isValid()) {
95 $existingEntry = $this->checkIfEntryAlreadyExists($entry);
97 if (false !== $existingEntry) {
98 $this->get('session')->getFlashBag()->add(
100 $this->get('translator')->trans('flashes.entry.notice.entry_already_saved', ['%date%' => $existingEntry->getCreatedAt()->format('d-m-Y')])
103 return $this->redirect($this->generateUrl('view', ['id' => $existingEntry->getId()]));
106 $this->updateEntry($entry);
108 $em = $this->getDoctrine()->getManager();
109 $em->persist($entry);
112 // entry saved, dispatch event about it!
113 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
115 return $this->redirect($this->generateUrl('homepage'));
118 return $this->render('WallabagCoreBundle:Entry:new_form.html.twig', [
119 'form' => $form->createView(),
124 * @param Request $request
126 * @Route("/bookmarklet", name="bookmarklet")
128 * @return \Symfony\Component\HttpFoundation\Response
130 public function addEntryViaBookmarkletAction(Request
$request)
132 $entry = new Entry($this->getUser());
133 $entry->setUrl($request->get('url'));
135 if (false === $this->checkIfEntryAlreadyExists($entry)) {
136 $this->updateEntry($entry);
138 $em = $this->getDoctrine()->getManager();
139 $em->persist($entry);
142 // entry saved, dispatch event about it!
143 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
146 return $this->redirect($this->generateUrl('homepage'));
150 * @Route("/new", name="new")
152 * @return \Symfony\Component\HttpFoundation\Response
154 public function addEntryAction()
156 return $this->render('WallabagCoreBundle:Entry:new.html.twig');
160 * Edit an entry content.
162 * @param Request $request
163 * @param Entry $entry
165 * @Route("/edit/{id}", requirements={"id" = "\d+"}, name="edit")
167 * @return \Symfony\Component\HttpFoundation\Response
169 public function editEntryAction(Request
$request, Entry
$entry)
171 $this->checkUserAction($entry);
173 $form = $this->createForm(EditEntryType
::class, $entry);
175 $form->handleRequest($request);
177 if ($form->isSubmitted() && $form->isValid()) {
178 $em = $this->getDoctrine()->getManager();
179 $em->persist($entry);
182 $this->get('session')->getFlashBag()->add(
184 'flashes.entry.notice.entry_updated'
187 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
190 return $this->render('WallabagCoreBundle:Entry:edit.html.twig', [
191 'form' => $form->createView(),
196 * Shows all entries for current user.
198 * @param Request $request
201 * @Route("/all/list/{page}", name="all", defaults={"page" = "1"})
203 * @return \Symfony\Component\HttpFoundation\Response
205 public function showAllAction(Request
$request, $page)
207 return $this->showEntries('all', $request, $page);
211 * Shows unread entries for current user.
213 * @param Request $request
216 * @Route("/unread/list/{page}", name="unread", defaults={"page" = "1"})
218 * @return \Symfony\Component\HttpFoundation\Response
220 public function showUnreadAction(Request
$request, $page)
222 // load the quickstart if no entry in database
223 if ($page == 1 && $this->get('wallabag_core.entry_repository')->countAllEntriesByUser($this->getUser()->getId()) == 0) {
224 return $this->redirect($this->generateUrl('quickstart'));
227 return $this->showEntries('unread', $request, $page);
231 * Shows read entries for current user.
233 * @param Request $request
236 * @Route("/archive/list/{page}", name="archive", defaults={"page" = "1"})
238 * @return \Symfony\Component\HttpFoundation\Response
240 public function showArchiveAction(Request
$request, $page)
242 return $this->showEntries('archive', $request, $page);
246 * Shows starred entries for current user.
248 * @param Request $request
251 * @Route("/starred/list/{page}", name="starred", defaults={"page" = "1"})
253 * @return \Symfony\Component\HttpFoundation\Response
255 public function showStarredAction(Request
$request, $page)
257 return $this->showEntries('starred', $request, $page);
261 * Global method to retrieve entries depending on the given type
262 * It returns the response to be send.
264 * @param string $type Entries type: unread, starred or archive
265 * @param Request $request
268 * @return \Symfony\Component\HttpFoundation\Response
270 private function showEntries($type, Request
$request, $page)
272 $repository = $this->get('wallabag_core.entry_repository');
273 $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : '');
274 $currentRoute = (!is_null($request->query
->get('currentRoute')) ? $request->query
->get('currentRoute') : '');
278 $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute);
282 $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId());
286 $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId());
290 $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId());
294 $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId());
298 $qb = $repository->getBuilderForAllByUser($this->getUser()->getId());
302 throw new \
InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
305 $form = $this->createForm(EntryFilterType
::class);
307 if ($request->query
->has($form->getName())) {
308 // manually bind values from the request
309 $form->submit($request->query
->get($form->getName()));
311 // build the query from the given form object
312 $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb);
315 $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false);
317 $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter);
320 $entries->setCurrentPage($page);
321 } catch (OutOfRangeCurrentPageException
$e) {
323 return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302);
327 return $this->render(
328 'WallabagCoreBundle:Entry:entries.html.twig', [
329 'form' => $form->createView(),
330 'entries' => $entries,
331 'currentPage' => $page,
332 'searchTerm' => $searchTerm,
338 * Shows entry content.
340 * @param Entry $entry
342 * @Route("/view/{id}", requirements={"id" = "\d+"}, name="view")
344 * @return \Symfony\Component\HttpFoundation\Response
346 public function viewAction(Entry
$entry)
348 $this->checkUserAction($entry);
350 return $this->render(
351 'WallabagCoreBundle:Entry:entry.html.twig',
358 * Refetch content from the website and make it readable again.
360 * @param Entry $entry
362 * @Route("/reload/{id}", requirements={"id" = "\d+"}, name="reload_entry")
364 * @return \Symfony\Component\HttpFoundation\RedirectResponse
366 public function reloadAction(Entry
$entry)
368 $this->checkUserAction($entry);
370 $this->updateEntry($entry, 'entry_reloaded');
372 // if refreshing entry failed, don't save it
373 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
374 $bag = $this->get('session')->getFlashBag();
376 $bag->add('notice', 'flashes.entry.notice.entry_reloaded_failed');
378 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
381 $em = $this->getDoctrine()->getManager();
382 $em->persist($entry);
385 // entry saved, dispatch event about it!
386 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
388 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
392 * Changes read status for an entry.
394 * @param Request $request
395 * @param Entry $entry
397 * @Route("/archive/{id}", requirements={"id" = "\d+"}, name="archive_entry")
399 * @return \Symfony\Component\HttpFoundation\RedirectResponse
401 public function toggleArchiveAction(Request
$request, Entry
$entry)
403 $this->checkUserAction($entry);
405 $entry->toggleArchive();
406 $this->getDoctrine()->getManager()->flush();
408 $message = 'flashes.entry.notice.entry_unarchived';
409 if ($entry->isArchived()) {
410 $message = 'flashes.entry.notice.entry_archived';
413 $this->get('session')->getFlashBag()->add(
418 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
420 return $this->redirect($redirectUrl);
424 * Changes starred status for an entry.
426 * @param Request $request
427 * @param Entry $entry
429 * @Route("/star/{id}", requirements={"id" = "\d+"}, name="star_entry")
431 * @return \Symfony\Component\HttpFoundation\RedirectResponse
433 public function toggleStarAction(Request
$request, Entry
$entry)
435 $this->checkUserAction($entry);
437 $entry->toggleStar();
438 $this->getDoctrine()->getManager()->flush();
440 $message = 'flashes.entry.notice.entry_unstarred';
441 if ($entry->isStarred()) {
442 $message = 'flashes.entry.notice.entry_starred';
445 $this->get('session')->getFlashBag()->add(
450 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
452 return $this->redirect($redirectUrl);
456 * Deletes entry and redirect to the homepage or the last viewed page.
458 * @param Entry $entry
460 * @Route("/delete/{id}", requirements={"id" = "\d+"}, name="delete_entry")
462 * @return \Symfony\Component\HttpFoundation\RedirectResponse
464 public function deleteEntryAction(Request
$request, Entry
$entry)
466 $this->checkUserAction($entry);
468 // generates the view url for this entry to check for redirection later
469 // to avoid redirecting to the deleted entry. Ugh.
470 $url = $this->generateUrl(
472 ['id' => $entry->getId()],
473 UrlGeneratorInterface
::ABSOLUTE_PATH
476 // entry deleted, dispatch event about it!
477 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
479 $em = $this->getDoctrine()->getManager();
483 $this->get('session')->getFlashBag()->add(
485 'flashes.entry.notice.entry_deleted'
488 // don't redirect user to the deleted entry (check that the referer doesn't end with the same url)
489 $referer = $request->headers
->get('referer');
490 $to = (1 !== preg_match('#'.$url.'$#i', $referer) ? $referer : null);
492 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to);
494 return $this->redirect($redirectUrl);
498 * Check if the logged user can manage the given entry.
500 * @param Entry $entry
502 private function checkUserAction(Entry
$entry)
504 if (null === $this->getUser() || $this->getUser()->getId() != $entry->getUser()->getId()) {
505 throw $this->createAccessDeniedException('You can not access this entry.');
510 * Check for existing entry, if it exists, redirect to it with a message.
512 * @param Entry $entry
516 private function checkIfEntryAlreadyExists(Entry
$entry)
518 return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId());
522 * Get public URL for entry (and generate it if necessary).
524 * @param Entry $entry
526 * @Route("/share/{id}", requirements={"id" = "\d+"}, name="share")
528 * @return \Symfony\Component\HttpFoundation\Response
530 public function shareAction(Entry
$entry)
532 $this->checkUserAction($entry);
534 if (null === $entry->getUid()) {
535 $entry->generateUid();
537 $em = $this->getDoctrine()->getManager();
538 $em->persist($entry);
542 return $this->redirect($this->generateUrl('share_entry', [
543 'uid' => $entry->getUid(),
548 * Disable public sharing for an entry.
550 * @param Entry $entry
552 * @Route("/share/delete/{id}", requirements={"id" = "\d+"}, name="delete_share")
554 * @return \Symfony\Component\HttpFoundation\Response
556 public function deleteShareAction(Entry
$entry)
558 $this->checkUserAction($entry);
562 $em = $this->getDoctrine()->getManager();
563 $em->persist($entry);
566 return $this->redirect($this->generateUrl('view', [
567 'id' => $entry->getId(),
572 * Ability to view a content publicly.
574 * @param Entry $entry
576 * @Route("/share/{uid}", requirements={"uid" = ".+"}, name="share_entry")
577 * @Cache(maxage="25200", smaxage="25200", public=true)
579 * @return \Symfony\Component\HttpFoundation\Response
581 public function shareEntryAction(Entry
$entry)
583 if (!$this->get('craue_config')->get('share_public')) {
584 throw $this->createAccessDeniedException('Sharing an entry is disabled for this user.');
587 return $this->render(
588 '@WallabagCore/themes/common/Entry/share.html.twig',
594 * Shows untagged articles for current user.
596 * @param Request $request
599 * @Route("/untagged/list/{page}", name="untagged", defaults={"page" = "1"})
601 * @return \Symfony\Component\HttpFoundation\Response
603 public function showUntaggedEntriesAction(Request
$request, $page)
605 return $this->showEntries('untagged', $request, $page);