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 will return to avod loosing the data.
59 * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded
63 private function updateEntry(Entry
$entry, $prefixMessage = 'entry_saved')
65 // put default title in case of fetching content failed
66 $entry->setTitle('No title found');
68 $message = 'flashes.entry.notice.'.$prefixMessage;
71 $entry = $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
72 } catch (\Exception
$e) {
73 $this->get('logger')->error('Error while saving an entry', [
78 $message = 'flashes.entry.notice.'.$prefixMessage.'_failed';
81 $this->get('session')->getFlashBag()->add('notice', $message);
87 * @param Request $request
89 * @Route("/new-entry", name="new_entry")
91 * @return \Symfony\Component\HttpFoundation\Response
93 public function addEntryFormAction(Request
$request)
95 $entry = new Entry($this->getUser());
97 $form = $this->createForm(NewEntryType
::class, $entry);
99 $form->handleRequest($request);
101 if ($form->isSubmitted() && $form->isValid()) {
102 $existingEntry = $this->checkIfEntryAlreadyExists($entry);
104 if (false !== $existingEntry) {
105 $this->get('session')->getFlashBag()->add(
107 $this->get('translator')->trans('flashes.entry.notice.entry_already_saved', ['%date%' => $existingEntry->getCreatedAt()->format('d-m-Y')])
110 return $this->redirect($this->generateUrl('view', ['id' => $existingEntry->getId()]));
113 $this->updateEntry($entry);
115 $em = $this->getDoctrine()->getManager();
116 $em->persist($entry);
119 // entry saved, dispatch event about it!
120 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
122 return $this->redirect($this->generateUrl('homepage'));
125 return $this->render('WallabagCoreBundle:Entry:new_form.html.twig', [
126 'form' => $form->createView(),
131 * @param Request $request
133 * @Route("/bookmarklet", name="bookmarklet")
135 * @return \Symfony\Component\HttpFoundation\Response
137 public function addEntryViaBookmarkletAction(Request
$request)
139 $entry = new Entry($this->getUser());
140 $entry->setUrl($request->get('url'));
142 if (false === $this->checkIfEntryAlreadyExists($entry)) {
143 $this->updateEntry($entry);
145 $em = $this->getDoctrine()->getManager();
146 $em->persist($entry);
149 // entry saved, dispatch event about it!
150 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
153 return $this->redirect($this->generateUrl('homepage'));
157 * @Route("/new", name="new")
159 * @return \Symfony\Component\HttpFoundation\Response
161 public function addEntryAction()
163 return $this->render('WallabagCoreBundle:Entry:new.html.twig');
167 * Edit an entry content.
169 * @param Request $request
170 * @param Entry $entry
172 * @Route("/edit/{id}", requirements={"id" = "\d+"}, name="edit")
174 * @return \Symfony\Component\HttpFoundation\Response
176 public function editEntryAction(Request
$request, Entry
$entry)
178 $this->checkUserAction($entry);
180 $form = $this->createForm(EditEntryType
::class, $entry);
182 $form->handleRequest($request);
184 if ($form->isSubmitted() && $form->isValid()) {
185 $em = $this->getDoctrine()->getManager();
186 $em->persist($entry);
189 $this->get('session')->getFlashBag()->add(
191 'flashes.entry.notice.entry_updated'
194 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
197 return $this->render('WallabagCoreBundle:Entry:edit.html.twig', [
198 'form' => $form->createView(),
203 * Shows all entries for current user.
205 * @param Request $request
208 * @Route("/all/list/{page}", name="all", defaults={"page" = "1"})
210 * @return \Symfony\Component\HttpFoundation\Response
212 public function showAllAction(Request
$request, $page)
214 return $this->showEntries('all', $request, $page);
218 * Shows unread entries for current user.
220 * @param Request $request
223 * @Route("/unread/list/{page}", name="unread", defaults={"page" = "1"})
225 * @return \Symfony\Component\HttpFoundation\Response
227 public function showUnreadAction(Request
$request, $page)
229 // load the quickstart if no entry in database
230 if ($page == 1 && $this->get('wallabag_core.entry_repository')->countAllEntriesByUsername($this->getUser()->getId()) == 0) {
231 return $this->redirect($this->generateUrl('quickstart'));
234 return $this->showEntries('unread', $request, $page);
238 * Shows read entries for current user.
240 * @param Request $request
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.
255 * @param Request $request
258 * @Route("/starred/list/{page}", name="starred", defaults={"page" = "1"})
260 * @return \Symfony\Component\HttpFoundation\Response
262 public function showStarredAction(Request
$request, $page)
264 return $this->showEntries('starred', $request, $page);
268 * Global method to retrieve entries depending on the given type
269 * It returns the response to be send.
271 * @param string $type Entries type: unread, starred or archive
272 * @param Request $request
275 * @return \Symfony\Component\HttpFoundation\Response
277 private function showEntries($type, Request
$request, $page)
279 $repository = $this->get('wallabag_core.entry_repository');
280 $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : '');
281 $currentRoute = (!is_null($request->query
->get('currentRoute')) ? $request->query
->get('currentRoute') : '');
285 $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute);
289 $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId());
293 $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId());
297 $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId());
301 $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId());
305 $qb = $repository->getBuilderForAllByUser($this->getUser()->getId());
309 throw new \
InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
312 $form = $this->createForm(EntryFilterType
::class);
314 if ($request->query
->has($form->getName())) {
315 // manually bind values from the request
316 $form->submit($request->query
->get($form->getName()));
318 // build the query from the given form object
319 $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb);
322 $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false);
324 $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')
325 ->prepare($pagerAdapter, $page);
328 $entries->setCurrentPage($page);
329 } catch (OutOfRangeCurrentPageException
$e) {
331 return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302);
335 return $this->render(
336 'WallabagCoreBundle:Entry:entries.html.twig', [
337 'form' => $form->createView(),
338 'entries' => $entries,
339 'currentPage' => $page,
340 'searchTerm' => $searchTerm,
346 * Shows entry content.
348 * @param Entry $entry
350 * @Route("/view/{id}", requirements={"id" = "\d+"}, name="view")
352 * @return \Symfony\Component\HttpFoundation\Response
354 public function viewAction(Entry
$entry)
356 $this->checkUserAction($entry);
358 return $this->render(
359 'WallabagCoreBundle:Entry:entry.html.twig',
366 * Refetch content from the website and make it readable again.
368 * @param Entry $entry
370 * @Route("/reload/{id}", requirements={"id" = "\d+"}, name="reload_entry")
372 * @return \Symfony\Component\HttpFoundation\RedirectResponse
374 public function reloadAction(Entry
$entry)
376 $this->checkUserAction($entry);
378 $this->updateEntry($entry, 'entry_reloaded');
380 // if refreshing entry failed, don't save it
381 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
382 $bag = $this->get('session')->getFlashBag();
384 $bag->add('notice', 'flashes.entry.notice.entry_reloaded_failed');
386 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
389 $em = $this->getDoctrine()->getManager();
390 $em->persist($entry);
393 // entry saved, dispatch event about it!
394 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
396 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
400 * Changes read status for an entry.
402 * @param Request $request
403 * @param Entry $entry
405 * @Route("/archive/{id}", requirements={"id" = "\d+"}, name="archive_entry")
407 * @return \Symfony\Component\HttpFoundation\RedirectResponse
409 public function toggleArchiveAction(Request
$request, Entry
$entry)
411 $this->checkUserAction($entry);
413 $entry->toggleArchive();
414 $this->getDoctrine()->getManager()->flush();
416 $message = 'flashes.entry.notice.entry_unarchived';
417 if ($entry->isArchived()) {
418 $message = 'flashes.entry.notice.entry_archived';
421 $this->get('session')->getFlashBag()->add(
426 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
428 return $this->redirect($redirectUrl);
432 * Changes starred status for an entry.
434 * @param Request $request
435 * @param Entry $entry
437 * @Route("/star/{id}", requirements={"id" = "\d+"}, name="star_entry")
439 * @return \Symfony\Component\HttpFoundation\RedirectResponse
441 public function toggleStarAction(Request
$request, Entry
$entry)
443 $this->checkUserAction($entry);
445 $entry->toggleStar();
446 $this->getDoctrine()->getManager()->flush();
448 $message = 'flashes.entry.notice.entry_unstarred';
449 if ($entry->isStarred()) {
450 $message = 'flashes.entry.notice.entry_starred';
453 $this->get('session')->getFlashBag()->add(
458 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
460 return $this->redirect($redirectUrl);
464 * Deletes entry and redirect to the homepage or the last viewed page.
466 * @param Entry $entry
468 * @Route("/delete/{id}", requirements={"id" = "\d+"}, name="delete_entry")
470 * @return \Symfony\Component\HttpFoundation\RedirectResponse
472 public function deleteEntryAction(Request
$request, Entry
$entry)
474 $this->checkUserAction($entry);
476 // generates the view url for this entry to check for redirection later
477 // to avoid redirecting to the deleted entry. Ugh.
478 $url = $this->generateUrl(
480 ['id' => $entry->getId()],
481 UrlGeneratorInterface
::ABSOLUTE_PATH
484 // entry deleted, dispatch event about it!
485 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
487 $em = $this->getDoctrine()->getManager();
491 $this->get('session')->getFlashBag()->add(
493 'flashes.entry.notice.entry_deleted'
496 // don't redirect user to the deleted entry (check that the referer doesn't end with the same url)
497 $referer = $request->headers
->get('referer');
498 $to = (1 !== preg_match('#'.$url.'$#i', $referer) ? $referer : null);
500 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to);
502 return $this->redirect($redirectUrl);
506 * Check if the logged user can manage the given entry.
508 * @param Entry $entry
510 private function checkUserAction(Entry
$entry)
512 if (null === $this->getUser() || $this->getUser()->getId() != $entry->getUser()->getId()) {
513 throw $this->createAccessDeniedException('You can not access this entry.');
518 * Check for existing entry, if it exists, redirect to it with a message.
520 * @param Entry $entry
524 private function checkIfEntryAlreadyExists(Entry
$entry)
526 return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId());
530 * Get public URL for entry (and generate it if necessary).
532 * @param Entry $entry
534 * @Route("/share/{id}", requirements={"id" = "\d+"}, name="share")
536 * @return \Symfony\Component\HttpFoundation\Response
538 public function shareAction(Entry
$entry)
540 $this->checkUserAction($entry);
542 if (null === $entry->getUuid()) {
543 $entry->generateUuid();
545 $em = $this->getDoctrine()->getManager();
546 $em->persist($entry);
550 return $this->redirect($this->generateUrl('share_entry', [
551 'uuid' => $entry->getUuid(),
556 * Disable public sharing for an entry.
558 * @param Entry $entry
560 * @Route("/share/delete/{id}", requirements={"id" = "\d+"}, name="delete_share")
562 * @return \Symfony\Component\HttpFoundation\Response
564 public function deleteShareAction(Entry
$entry)
566 $this->checkUserAction($entry);
570 $em = $this->getDoctrine()->getManager();
571 $em->persist($entry);
574 return $this->redirect($this->generateUrl('view', [
575 'id' => $entry->getId(),
580 * Ability to view a content publicly.
582 * @param Entry $entry
584 * @Route("/share/{uuid}", requirements={"uuid" = ".+"}, name="share_entry")
585 * @Cache(maxage="25200", smaxage="25200", public=true)
587 * @return \Symfony\Component\HttpFoundation\Response
589 public function shareEntryAction(Entry
$entry)
591 if (!$this->get('craue_config')->get('share_public')) {
592 throw $this->createAccessDeniedException('Sharing an entry is disabled for this user.');
595 return $this->render(
596 '@WallabagCore/themes/common/Entry/share.html.twig',
602 * Shows untagged articles for current user.
604 * @param Request $request
607 * @Route("/untagged/list/{page}", name="untagged", defaults={"page" = "1"})
609 * @return \Symfony\Component\HttpFoundation\Response
611 public function showUntaggedEntriesAction(Request
$request, $page)
613 return $this->showEntries('untagged', $request, $page);