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 entry depending on the given type.
254 * @param string $type
256 * @Route("/{type}/random", name="random_entry", requirements={"type": "unread|starred|archive|untagged|all"})
258 * @return \Symfony\Component\HttpFoundation\RedirectResponse
260 public function redirectRandomEntryAction($type = 'all')
263 $entry = $this->get('wallabag_core.entry_repository')
264 ->getRandomEntry($this->getUser()->getId(), $type);
265 } catch (NoResultException
$e) {
266 $bag = $this->get('session')->getFlashBag();
268 $bag->add('notice', 'flashes.entry.notice.no_random_entry');
270 return $this->redirect($this->generateUrl($type));
273 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
277 * Shows entry content.
279 * @param Entry $entry
281 * @Route("/view/{id}", requirements={"id" = "\d+"}, name="view")
283 * @return \Symfony\Component\HttpFoundation\Response
285 public function viewAction(Entry
$entry)
287 $this->checkUserAction($entry);
289 return $this->render(
290 'WallabagCoreBundle:Entry:entry.html.twig',
297 * Refetch content from the website and make it readable again.
299 * @param Entry $entry
301 * @Route("/reload/{id}", requirements={"id" = "\d+"}, name="reload_entry")
303 * @return \Symfony\Component\HttpFoundation\RedirectResponse
305 public function reloadAction(Entry
$entry)
307 $this->checkUserAction($entry);
309 $this->updateEntry($entry, 'entry_reloaded');
311 // if refreshing entry failed, don't save it
312 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
313 $bag = $this->get('session')->getFlashBag();
315 $bag->add('notice', 'flashes.entry.notice.entry_reloaded_failed');
317 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
320 $em = $this->getDoctrine()->getManager();
321 $em->persist($entry);
324 // entry saved, dispatch event about it!
325 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
327 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
331 * Changes read status for an entry.
333 * @param Request $request
334 * @param Entry $entry
336 * @Route("/archive/{id}", requirements={"id" = "\d+"}, name="archive_entry")
338 * @return \Symfony\Component\HttpFoundation\RedirectResponse
340 public function toggleArchiveAction(Request
$request, Entry
$entry)
342 $this->checkUserAction($entry);
344 $entry->toggleArchive();
345 $this->getDoctrine()->getManager()->flush();
347 $message = 'flashes.entry.notice.entry_unarchived';
348 if ($entry->isArchived()) {
349 $message = 'flashes.entry.notice.entry_archived';
352 $this->get('session')->getFlashBag()->add(
357 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
359 return $this->redirect($redirectUrl);
363 * Changes starred status for an entry.
365 * @param Request $request
366 * @param Entry $entry
368 * @Route("/star/{id}", requirements={"id" = "\d+"}, name="star_entry")
370 * @return \Symfony\Component\HttpFoundation\RedirectResponse
372 public function toggleStarAction(Request
$request, Entry
$entry)
374 $this->checkUserAction($entry);
376 $entry->toggleStar();
377 $entry->updateStar($entry->isStarred());
378 $this->getDoctrine()->getManager()->flush();
380 $message = 'flashes.entry.notice.entry_unstarred';
381 if ($entry->isStarred()) {
382 $message = 'flashes.entry.notice.entry_starred';
385 $this->get('session')->getFlashBag()->add(
390 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
392 return $this->redirect($redirectUrl);
396 * Deletes entry and redirect to the homepage or the last viewed page.
398 * @param Entry $entry
400 * @Route("/delete/{id}", requirements={"id" = "\d+"}, name="delete_entry")
402 * @return \Symfony\Component\HttpFoundation\RedirectResponse
404 public function deleteEntryAction(Request
$request, Entry
$entry)
406 $this->checkUserAction($entry);
408 // generates the view url for this entry to check for redirection later
409 // to avoid redirecting to the deleted entry. Ugh.
410 $url = $this->generateUrl(
412 ['id' => $entry->getId()],
413 UrlGeneratorInterface
::ABSOLUTE_PATH
416 // entry deleted, dispatch event about it!
417 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
419 $em = $this->getDoctrine()->getManager();
423 $this->get('session')->getFlashBag()->add(
425 'flashes.entry.notice.entry_deleted'
428 // don't redirect user to the deleted entry (check that the referer doesn't end with the same url)
429 $referer = $request->headers
->get('referer');
430 $to = (1 !== preg_match('#' . $url . '$#i', $referer) ? $referer : null);
432 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to);
434 return $this->redirect($redirectUrl);
438 * Get public URL for entry (and generate it if necessary).
440 * @param Entry $entry
442 * @Route("/share/{id}", requirements={"id" = "\d+"}, name="share")
444 * @return \Symfony\Component\HttpFoundation\Response
446 public function shareAction(Entry
$entry)
448 $this->checkUserAction($entry);
450 if (null === $entry->getUid()) {
451 $entry->generateUid();
453 $em = $this->getDoctrine()->getManager();
454 $em->persist($entry);
458 return $this->redirect($this->generateUrl('share_entry', [
459 'uid' => $entry->getUid(),
464 * Disable public sharing for an entry.
466 * @param Entry $entry
468 * @Route("/share/delete/{id}", requirements={"id" = "\d+"}, name="delete_share")
470 * @return \Symfony\Component\HttpFoundation\Response
472 public function deleteShareAction(Entry
$entry)
474 $this->checkUserAction($entry);
478 $em = $this->getDoctrine()->getManager();
479 $em->persist($entry);
482 return $this->redirect($this->generateUrl('view', [
483 'id' => $entry->getId(),
488 * Ability to view a content publicly.
490 * @param Entry $entry
492 * @Route("/share/{uid}", requirements={"uid" = ".+"}, name="share_entry")
493 * @Cache(maxage="25200", smaxage="25200", public=true)
495 * @return \Symfony\Component\HttpFoundation\Response
497 public function shareEntryAction(Entry
$entry)
499 if (!$this->get('craue_config')->get('share_public')) {
500 throw $this->createAccessDeniedException('Sharing an entry is disabled for this user.');
503 return $this->render(
504 '@WallabagCore/themes/common/Entry/share.html.twig',
510 * Global method to retrieve entries depending on the given type
511 * It returns the response to be send.
513 * @param string $type Entries type: unread, starred or archive
514 * @param Request $request
517 * @return \Symfony\Component\HttpFoundation\Response
519 private function showEntries($type, Request
$request, $page)
521 $repository = $this->get('wallabag_core.entry_repository');
522 $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : '');
523 $currentRoute = (null !== $request->query
->get('currentRoute') ? $request->query
->get('currentRoute') : '');
527 $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute);
530 $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId());
533 $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId());
536 $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId());
539 $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId());
542 $qb = $repository->getBuilderForAllByUser($this->getUser()->getId());
545 throw new \
InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
548 $form = $this->createForm(EntryFilterType
::class);
550 if ($request->query
->has($form->getName())) {
551 // manually bind values from the request
552 $form->submit($request->query
->get($form->getName()));
554 // build the query from the given form object
555 $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb);
558 $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false);
560 $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter);
563 $entries->setCurrentPage($page);
564 } catch (OutOfRangeCurrentPageException
$e) {
566 return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302);
570 return $this->render(
571 'WallabagCoreBundle:Entry:entries.html.twig', [
572 'form' => $form->createView(),
573 'entries' => $entries,
574 'currentPage' => $page,
575 'searchTerm' => $searchTerm,
576 'isFiltered' => $form->isSubmitted(),
582 * Fetch content and update entry.
583 * In case it fails, $entry->getContent will return an error message.
585 * @param Entry $entry
586 * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded
588 private function updateEntry(Entry
$entry, $prefixMessage = 'entry_saved')
590 $message = 'flashes.entry.notice.' . $prefixMessage;
593 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
594 } catch (\Exception
$e) {
595 $this->get('logger')->error('Error while saving an entry', [
600 $message = 'flashes.entry.notice.' . $prefixMessage . '_failed';
603 if (empty($entry->getDomainName())) {
604 $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
607 if (empty($entry->getTitle())) {
608 $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
611 $this->get('session')->getFlashBag()->add('notice', $message);
615 * Check if the logged user can manage the given entry.
617 * @param Entry $entry
619 private function checkUserAction(Entry
$entry)
621 if (null === $this->getUser() || $this->getUser()->getId() !== $entry->getUser()->getId()) {
622 throw $this->createAccessDeniedException('You can not access this entry.');
627 * Check for existing entry, if it exists, redirect to it with a message.
629 * @param Entry $entry
633 private function checkIfEntryAlreadyExists(Entry
$entry)
635 return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId());