3 namespace Wallabag\CoreBundle\Controller
;
5 use Pagerfanta\Adapter\DoctrineORMAdapter
;
6 use Pagerfanta\Exception\OutOfRangeCurrentPageException
;
7 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache
;
8 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route
;
9 use Symfony\Bundle\FrameworkBundle\Controller\Controller
;
10 use Symfony\Component\HttpFoundation\Request
;
11 use Symfony\Component\Routing\Generator\UrlGeneratorInterface
;
12 use Wallabag\CoreBundle\Entity\Entry
;
13 use Wallabag\CoreBundle\Event\EntryDeletedEvent
;
14 use Wallabag\CoreBundle\Event\EntrySavedEvent
;
15 use Wallabag\CoreBundle\Form\Type\EditEntryType
;
16 use Wallabag\CoreBundle\Form\Type\EntryFilterType
;
17 use Wallabag\CoreBundle\Form\Type\NewEntryType
;
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 * @param Request $request
57 * @Route("/new-entry", name="new_entry")
59 * @return \Symfony\Component\HttpFoundation\Response
61 public function addEntryFormAction(Request
$request)
63 $entry = new Entry($this->getUser());
65 $form = $this->createForm(NewEntryType
::class, $entry);
67 $form->handleRequest($request);
69 if ($form->isSubmitted() && $form->isValid()) {
70 $existingEntry = $this->checkIfEntryAlreadyExists($entry);
72 if (false !== $existingEntry) {
73 $this->get('session')->getFlashBag()->add(
75 $this->get('translator')->trans('flashes.entry.notice.entry_already_saved', ['%date%' => $existingEntry->getCreatedAt()->format('d-m-Y')])
78 return $this->redirect($this->generateUrl('view', ['id' => $existingEntry->getId()]));
81 $entry->setGivenUrl($entry->getUrl());
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 entry content.
239 * @param Entry $entry
241 * @Route("/view/{id}", requirements={"id" = "\d+"}, name="view")
243 * @return \Symfony\Component\HttpFoundation\Response
245 public function viewAction(Entry
$entry)
247 $this->checkUserAction($entry);
249 return $this->render(
250 'WallabagCoreBundle:Entry:entry.html.twig',
257 * Refetch content from the website and make it readable again.
259 * @param Entry $entry
261 * @Route("/reload/{id}", requirements={"id" = "\d+"}, name="reload_entry")
263 * @return \Symfony\Component\HttpFoundation\RedirectResponse
265 public function reloadAction(Entry
$entry)
267 $this->checkUserAction($entry);
269 $this->updateEntry($entry, 'entry_reloaded');
271 // if refreshing entry failed, don't save it
272 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
273 $bag = $this->get('session')->getFlashBag();
275 $bag->add('notice', 'flashes.entry.notice.entry_reloaded_failed');
277 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
280 $em = $this->getDoctrine()->getManager();
281 $em->persist($entry);
284 // entry saved, dispatch event about it!
285 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
287 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
291 * Changes read status for an entry.
293 * @param Request $request
294 * @param Entry $entry
296 * @Route("/archive/{id}", requirements={"id" = "\d+"}, name="archive_entry")
298 * @return \Symfony\Component\HttpFoundation\RedirectResponse
300 public function toggleArchiveAction(Request
$request, Entry
$entry)
302 $this->checkUserAction($entry);
304 $entry->toggleArchive();
305 $this->getDoctrine()->getManager()->flush();
307 $message = 'flashes.entry.notice.entry_unarchived';
308 if ($entry->isArchived()) {
309 $message = 'flashes.entry.notice.entry_archived';
312 $this->get('session')->getFlashBag()->add(
317 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
319 return $this->redirect($redirectUrl);
323 * Changes starred status for an entry.
325 * @param Request $request
326 * @param Entry $entry
328 * @Route("/star/{id}", requirements={"id" = "\d+"}, name="star_entry")
330 * @return \Symfony\Component\HttpFoundation\RedirectResponse
332 public function toggleStarAction(Request
$request, Entry
$entry)
334 $this->checkUserAction($entry);
336 $entry->toggleStar();
337 $entry->updateStar($entry->isStarred());
338 $this->getDoctrine()->getManager()->flush();
340 $message = 'flashes.entry.notice.entry_unstarred';
341 if ($entry->isStarred()) {
342 $message = 'flashes.entry.notice.entry_starred';
345 $this->get('session')->getFlashBag()->add(
350 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
352 return $this->redirect($redirectUrl);
356 * Deletes entry and redirect to the homepage or the last viewed page.
358 * @param Entry $entry
360 * @Route("/delete/{id}", requirements={"id" = "\d+"}, name="delete_entry")
362 * @return \Symfony\Component\HttpFoundation\RedirectResponse
364 public function deleteEntryAction(Request
$request, Entry
$entry)
366 $this->checkUserAction($entry);
368 // generates the view url for this entry to check for redirection later
369 // to avoid redirecting to the deleted entry. Ugh.
370 $url = $this->generateUrl(
372 ['id' => $entry->getId()],
373 UrlGeneratorInterface
::ABSOLUTE_PATH
376 // entry deleted, dispatch event about it!
377 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
379 $em = $this->getDoctrine()->getManager();
383 $this->get('session')->getFlashBag()->add(
385 'flashes.entry.notice.entry_deleted'
388 // don't redirect user to the deleted entry (check that the referer doesn't end with the same url)
389 $referer = $request->headers
->get('referer');
390 $to = (1 !== preg_match('#' . $url . '$#i', $referer) ? $referer : null);
392 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to);
394 return $this->redirect($redirectUrl);
398 * Get public URL for entry (and generate it if necessary).
400 * @param Entry $entry
402 * @Route("/share/{id}", requirements={"id" = "\d+"}, name="share")
404 * @return \Symfony\Component\HttpFoundation\Response
406 public function shareAction(Entry
$entry)
408 $this->checkUserAction($entry);
410 if (null === $entry->getUid()) {
411 $entry->generateUid();
413 $em = $this->getDoctrine()->getManager();
414 $em->persist($entry);
418 return $this->redirect($this->generateUrl('share_entry', [
419 'uid' => $entry->getUid(),
424 * Disable public sharing for an entry.
426 * @param Entry $entry
428 * @Route("/share/delete/{id}", requirements={"id" = "\d+"}, name="delete_share")
430 * @return \Symfony\Component\HttpFoundation\Response
432 public function deleteShareAction(Entry
$entry)
434 $this->checkUserAction($entry);
438 $em = $this->getDoctrine()->getManager();
439 $em->persist($entry);
442 return $this->redirect($this->generateUrl('view', [
443 'id' => $entry->getId(),
448 * Ability to view a content publicly.
450 * @param Entry $entry
452 * @Route("/share/{uid}", requirements={"uid" = ".+"}, name="share_entry")
453 * @Cache(maxage="25200", smaxage="25200", public=true)
455 * @return \Symfony\Component\HttpFoundation\Response
457 public function shareEntryAction(Entry
$entry)
459 if (!$this->get('craue_config')->get('share_public')) {
460 throw $this->createAccessDeniedException('Sharing an entry is disabled for this user.');
463 return $this->render(
464 '@WallabagCore/themes/common/Entry/share.html.twig',
470 * Shows untagged articles for current user.
472 * @param Request $request
475 * @Route("/untagged/list/{page}", name="untagged", defaults={"page" = "1"})
477 * @return \Symfony\Component\HttpFoundation\Response
479 public function showUntaggedEntriesAction(Request
$request, $page)
481 return $this->showEntries('untagged', $request, $page);
485 * Fetch content and update entry.
486 * In case it fails, $entry->getContent will return an error message.
488 * @param Entry $entry
489 * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded
491 private function updateEntry(Entry
$entry, $prefixMessage = 'entry_saved')
493 $message = 'flashes.entry.notice.' . $prefixMessage;
496 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
497 } catch (\Exception
$e) {
498 $this->get('logger')->error('Error while saving an entry', [
503 $message = 'flashes.entry.notice.' . $prefixMessage . '_failed';
506 if (empty($entry->getDomainName())) {
507 $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
510 if (empty($entry->getTitle())) {
511 $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
514 $this->get('session')->getFlashBag()->add('notice', $message);
518 * Global method to retrieve entries depending on the given type
519 * It returns the response to be send.
521 * @param string $type Entries type: unread, starred or archive
522 * @param Request $request
525 * @return \Symfony\Component\HttpFoundation\Response
527 private function showEntries($type, Request
$request, $page)
529 $repository = $this->get('wallabag_core.entry_repository');
530 $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : '');
531 $currentRoute = (null !== $request->query
->get('currentRoute') ? $request->query
->get('currentRoute') : '');
535 $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute);
539 $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId());
543 $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId());
546 $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId());
549 $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId());
552 $qb = $repository->getBuilderForAllByUser($this->getUser()->getId());
555 throw new \
InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
558 $form = $this->createForm(EntryFilterType
::class);
560 if ($request->query
->has($form->getName())) {
561 // manually bind values from the request
562 $form->submit($request->query
->get($form->getName()));
564 // build the query from the given form object
565 $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb);
568 $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false);
570 $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter);
573 $entries->setCurrentPage($page);
574 } catch (OutOfRangeCurrentPageException
$e) {
576 return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302);
580 return $this->render(
581 'WallabagCoreBundle:Entry:entries.html.twig', [
582 'form' => $form->createView(),
583 'entries' => $entries,
584 'currentPage' => $page,
585 'searchTerm' => $searchTerm,
586 'isFiltered' => $form->isSubmitted(),
592 * Check if the logged user can manage the given entry.
594 * @param Entry $entry
596 private function checkUserAction(Entry
$entry)
598 if (null === $this->getUser() || $this->getUser()->getId() !== $entry->getUser()->getId()) {
599 throw $this->createAccessDeniedException('You can not access this entry.');
604 * Check for existing entry, if it exists, redirect to it with a message.
606 * @param Entry $entry
610 private function checkIfEntryAlreadyExists(Entry
$entry)
612 return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId());