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 // put default title in case of fetching content failed
64 $entry->setTitle('No title found');
66 $message = 'flashes.entry.notice.'.$prefixMessage;
69 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
70 } catch (\Exception
$e) {
71 $this->get('logger')->error('Error while saving an entry', [
76 $message = 'flashes.entry.notice.'.$prefixMessage.'_failed';
79 $this->get('session')->getFlashBag()->add('notice', $message);
83 * @param Request $request
85 * @Route("/new-entry", name="new_entry")
87 * @return \Symfony\Component\HttpFoundation\Response
89 public function addEntryFormAction(Request
$request)
91 $entry = new Entry($this->getUser());
93 $form = $this->createForm(NewEntryType
::class, $entry);
95 $form->handleRequest($request);
97 if ($form->isSubmitted() && $form->isValid()) {
98 $existingEntry = $this->checkIfEntryAlreadyExists($entry);
100 if (false !== $existingEntry) {
101 $this->get('session')->getFlashBag()->add(
103 $this->get('translator')->trans('flashes.entry.notice.entry_already_saved', ['%date%' => $existingEntry->getCreatedAt()->format('d-m-Y')])
106 return $this->redirect($this->generateUrl('view', ['id' => $existingEntry->getId()]));
109 $this->updateEntry($entry);
111 $em = $this->getDoctrine()->getManager();
112 $em->persist($entry);
115 // entry saved, dispatch event about it!
116 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
118 return $this->redirect($this->generateUrl('homepage'));
121 return $this->render('WallabagCoreBundle:Entry:new_form.html.twig', [
122 'form' => $form->createView(),
127 * @param Request $request
129 * @Route("/bookmarklet", name="bookmarklet")
131 * @return \Symfony\Component\HttpFoundation\Response
133 public function addEntryViaBookmarkletAction(Request
$request)
135 $entry = new Entry($this->getUser());
136 $entry->setUrl($request->get('url'));
138 if (false === $this->checkIfEntryAlreadyExists($entry)) {
139 $this->updateEntry($entry);
141 $em = $this->getDoctrine()->getManager();
142 $em->persist($entry);
145 // entry saved, dispatch event about it!
146 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
149 return $this->redirect($this->generateUrl('homepage'));
153 * @Route("/new", name="new")
155 * @return \Symfony\Component\HttpFoundation\Response
157 public function addEntryAction()
159 return $this->render('WallabagCoreBundle:Entry:new.html.twig');
163 * Edit an entry content.
165 * @param Request $request
166 * @param Entry $entry
168 * @Route("/edit/{id}", requirements={"id" = "\d+"}, name="edit")
170 * @return \Symfony\Component\HttpFoundation\Response
172 public function editEntryAction(Request
$request, Entry
$entry)
174 $this->checkUserAction($entry);
176 $form = $this->createForm(EditEntryType
::class, $entry);
178 $form->handleRequest($request);
180 if ($form->isSubmitted() && $form->isValid()) {
181 $em = $this->getDoctrine()->getManager();
182 $em->persist($entry);
185 $this->get('session')->getFlashBag()->add(
187 'flashes.entry.notice.entry_updated'
190 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
193 return $this->render('WallabagCoreBundle:Entry:edit.html.twig', [
194 'form' => $form->createView(),
199 * Shows all entries for current user.
201 * @param Request $request
204 * @Route("/all/list/{page}", name="all", defaults={"page" = "1"})
206 * @return \Symfony\Component\HttpFoundation\Response
208 public function showAllAction(Request
$request, $page)
210 return $this->showEntries('all', $request, $page);
214 * Shows unread entries for current user.
216 * @param Request $request
219 * @Route("/unread/list/{page}", name="unread", defaults={"page" = "1"})
221 * @return \Symfony\Component\HttpFoundation\Response
223 public function showUnreadAction(Request
$request, $page)
225 // load the quickstart if no entry in database
226 if ($page == 1 && $this->get('wallabag_core.entry_repository')->countAllEntriesByUser($this->getUser()->getId()) == 0) {
227 return $this->redirect($this->generateUrl('quickstart'));
230 return $this->showEntries('unread', $request, $page);
234 * Shows read entries for current user.
236 * @param Request $request
239 * @Route("/archive/list/{page}", name="archive", defaults={"page" = "1"})
241 * @return \Symfony\Component\HttpFoundation\Response
243 public function showArchiveAction(Request
$request, $page)
245 return $this->showEntries('archive', $request, $page);
249 * Shows starred entries for current user.
251 * @param Request $request
254 * @Route("/starred/list/{page}", name="starred", defaults={"page" = "1"})
256 * @return \Symfony\Component\HttpFoundation\Response
258 public function showStarredAction(Request
$request, $page)
260 return $this->showEntries('starred', $request, $page);
264 * Global method to retrieve entries depending on the given type
265 * It returns the response to be send.
267 * @param string $type Entries type: unread, starred or archive
268 * @param Request $request
271 * @return \Symfony\Component\HttpFoundation\Response
273 private function showEntries($type, Request
$request, $page)
275 $repository = $this->get('wallabag_core.entry_repository');
276 $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : '');
277 $currentRoute = (!is_null($request->query
->get('currentRoute')) ? $request->query
->get('currentRoute') : '');
281 $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute);
285 $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId());
289 $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId());
293 $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId());
297 $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId());
301 $qb = $repository->getBuilderForAllByUser($this->getUser()->getId());
305 throw new \
InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
308 $form = $this->createForm(EntryFilterType
::class);
310 if ($request->query
->has($form->getName())) {
311 // manually bind values from the request
312 $form->submit($request->query
->get($form->getName()));
314 // build the query from the given form object
315 $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb);
318 $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false);
320 $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')
321 ->prepare($pagerAdapter, $page);
324 $entries->setCurrentPage($page);
325 } catch (OutOfRangeCurrentPageException
$e) {
327 return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302);
331 return $this->render(
332 'WallabagCoreBundle:Entry:entries.html.twig', [
333 'form' => $form->createView(),
334 'entries' => $entries,
335 'currentPage' => $page,
336 'searchTerm' => $searchTerm,
342 * Shows entry content.
344 * @param Entry $entry
346 * @Route("/view/{id}", requirements={"id" = "\d+"}, name="view")
348 * @return \Symfony\Component\HttpFoundation\Response
350 public function viewAction(Entry
$entry)
352 $this->checkUserAction($entry);
354 return $this->render(
355 'WallabagCoreBundle:Entry:entry.html.twig',
362 * Refetch content from the website and make it readable again.
364 * @param Entry $entry
366 * @Route("/reload/{id}", requirements={"id" = "\d+"}, name="reload_entry")
368 * @return \Symfony\Component\HttpFoundation\RedirectResponse
370 public function reloadAction(Entry
$entry)
372 $this->checkUserAction($entry);
374 $this->updateEntry($entry, 'entry_reloaded');
376 // if refreshing entry failed, don't save it
377 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
378 $bag = $this->get('session')->getFlashBag();
380 $bag->add('notice', 'flashes.entry.notice.entry_reloaded_failed');
382 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
385 $em = $this->getDoctrine()->getManager();
386 $em->persist($entry);
389 // entry saved, dispatch event about it!
390 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
392 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
396 * Changes read status for an entry.
398 * @param Request $request
399 * @param Entry $entry
401 * @Route("/archive/{id}", requirements={"id" = "\d+"}, name="archive_entry")
403 * @return \Symfony\Component\HttpFoundation\RedirectResponse
405 public function toggleArchiveAction(Request
$request, Entry
$entry)
407 $this->checkUserAction($entry);
409 $entry->toggleArchive();
410 $this->getDoctrine()->getManager()->flush();
412 $message = 'flashes.entry.notice.entry_unarchived';
413 if ($entry->isArchived()) {
414 $message = 'flashes.entry.notice.entry_archived';
417 $this->get('session')->getFlashBag()->add(
422 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
424 return $this->redirect($redirectUrl);
428 * Changes starred status for an entry.
430 * @param Request $request
431 * @param Entry $entry
433 * @Route("/star/{id}", requirements={"id" = "\d+"}, name="star_entry")
435 * @return \Symfony\Component\HttpFoundation\RedirectResponse
437 public function toggleStarAction(Request
$request, Entry
$entry)
439 $this->checkUserAction($entry);
441 $entry->toggleStar();
442 $this->getDoctrine()->getManager()->flush();
444 $message = 'flashes.entry.notice.entry_unstarred';
445 if ($entry->isStarred()) {
446 $message = 'flashes.entry.notice.entry_starred';
449 $this->get('session')->getFlashBag()->add(
454 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
456 return $this->redirect($redirectUrl);
460 * Deletes entry and redirect to the homepage or the last viewed page.
462 * @param Entry $entry
464 * @Route("/delete/{id}", requirements={"id" = "\d+"}, name="delete_entry")
466 * @return \Symfony\Component\HttpFoundation\RedirectResponse
468 public function deleteEntryAction(Request
$request, Entry
$entry)
470 $this->checkUserAction($entry);
472 // generates the view url for this entry to check for redirection later
473 // to avoid redirecting to the deleted entry. Ugh.
474 $url = $this->generateUrl(
476 ['id' => $entry->getId()],
477 UrlGeneratorInterface
::ABSOLUTE_PATH
480 // entry deleted, dispatch event about it!
481 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
483 $em = $this->getDoctrine()->getManager();
487 $this->get('session')->getFlashBag()->add(
489 'flashes.entry.notice.entry_deleted'
492 // don't redirect user to the deleted entry (check that the referer doesn't end with the same url)
493 $referer = $request->headers
->get('referer');
494 $to = (1 !== preg_match('#'.$url.'$#i', $referer) ? $referer : null);
496 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to);
498 return $this->redirect($redirectUrl);
502 * Check if the logged user can manage the given entry.
504 * @param Entry $entry
506 private function checkUserAction(Entry
$entry)
508 if (null === $this->getUser() || $this->getUser()->getId() != $entry->getUser()->getId()) {
509 throw $this->createAccessDeniedException('You can not access this entry.');
514 * Check for existing entry, if it exists, redirect to it with a message.
516 * @param Entry $entry
520 private function checkIfEntryAlreadyExists(Entry
$entry)
522 return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId());
526 * Get public URL for entry (and generate it if necessary).
528 * @param Entry $entry
530 * @Route("/share/{id}", requirements={"id" = "\d+"}, name="share")
532 * @return \Symfony\Component\HttpFoundation\Response
534 public function shareAction(Entry
$entry)
536 $this->checkUserAction($entry);
538 if (null === $entry->getUid()) {
539 $entry->generateUid();
541 $em = $this->getDoctrine()->getManager();
542 $em->persist($entry);
546 return $this->redirect($this->generateUrl('share_entry', [
547 'uid' => $entry->getUid(),
552 * Disable public sharing for an entry.
554 * @param Entry $entry
556 * @Route("/share/delete/{id}", requirements={"id" = "\d+"}, name="delete_share")
558 * @return \Symfony\Component\HttpFoundation\Response
560 public function deleteShareAction(Entry
$entry)
562 $this->checkUserAction($entry);
566 $em = $this->getDoctrine()->getManager();
567 $em->persist($entry);
570 return $this->redirect($this->generateUrl('view', [
571 'id' => $entry->getId(),
576 * Ability to view a content publicly.
578 * @param Entry $entry
580 * @Route("/share/{uid}", requirements={"uid" = ".+"}, name="share_entry")
581 * @Cache(maxage="25200", smaxage="25200", public=true)
583 * @return \Symfony\Component\HttpFoundation\Response
585 public function shareEntryAction(Entry
$entry)
587 if (!$this->get('craue_config')->get('share_public')) {
588 throw $this->createAccessDeniedException('Sharing an entry is disabled for this user.');
591 return $this->render(
592 '@WallabagCore/themes/common/Entry/share.html.twig',
598 * Shows untagged articles for current user.
600 * @param Request $request
603 * @Route("/untagged/list/{page}", name="untagged", defaults={"page" = "1"})
605 * @return \Symfony\Component\HttpFoundation\Response
607 public function showUntaggedEntriesAction(Request
$request, $page)
609 return $this->showEntries('untagged', $request, $page);