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 $this->updateEntry($entry);
83 $em = $this->getDoctrine()->getManager();
87 // entry saved, dispatch event about it!
88 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
90 return $this->redirect($this->generateUrl('homepage'));
93 return $this->render('WallabagCoreBundle:Entry:new_form.html.twig', [
94 'form' => $form->createView(),
99 * @param Request $request
101 * @Route("/bookmarklet", name="bookmarklet")
103 * @return \Symfony\Component\HttpFoundation\Response
105 public function addEntryViaBookmarkletAction(Request
$request)
107 $entry = new Entry($this->getUser());
108 $entry->setUrl($request->get('url'));
110 if (false === $this->checkIfEntryAlreadyExists($entry)) {
111 $this->updateEntry($entry);
113 $em = $this->getDoctrine()->getManager();
114 $em->persist($entry);
117 // entry saved, dispatch event about it!
118 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
121 return $this->redirect($this->generateUrl('homepage'));
125 * @Route("/new", name="new")
127 * @return \Symfony\Component\HttpFoundation\Response
129 public function addEntryAction()
131 return $this->render('WallabagCoreBundle:Entry:new.html.twig');
135 * Edit an entry content.
137 * @param Request $request
138 * @param Entry $entry
140 * @Route("/edit/{id}", requirements={"id" = "\d+"}, name="edit")
142 * @return \Symfony\Component\HttpFoundation\Response
144 public function editEntryAction(Request
$request, Entry
$entry)
146 $this->checkUserAction($entry);
148 $form = $this->createForm(EditEntryType
::class, $entry);
150 $form->handleRequest($request);
152 if ($form->isSubmitted() && $form->isValid()) {
153 $em = $this->getDoctrine()->getManager();
154 $em->persist($entry);
157 $this->get('session')->getFlashBag()->add(
159 'flashes.entry.notice.entry_updated'
162 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
165 return $this->render('WallabagCoreBundle:Entry:edit.html.twig', [
166 'form' => $form->createView(),
171 * Shows all entries for current user.
173 * @param Request $request
176 * @Route("/all/list/{page}", name="all", defaults={"page" = "1"})
178 * @return \Symfony\Component\HttpFoundation\Response
180 public function showAllAction(Request
$request, $page)
182 return $this->showEntries('all', $request, $page);
186 * Shows unread entries for current user.
188 * @param Request $request
191 * @Route("/unread/list/{page}", name="unread", defaults={"page" = "1"})
193 * @return \Symfony\Component\HttpFoundation\Response
195 public function showUnreadAction(Request
$request, $page)
197 // load the quickstart if no entry in database
198 if ((int) $page === 1 && $this->get('wallabag_core.entry_repository')->countAllEntriesByUser($this->getUser()->getId()) === 0) {
199 return $this->redirect($this->generateUrl('quickstart'));
202 return $this->showEntries('unread', $request, $page);
206 * Shows read entries for current user.
208 * @param Request $request
211 * @Route("/archive/list/{page}", name="archive", defaults={"page" = "1"})
213 * @return \Symfony\Component\HttpFoundation\Response
215 public function showArchiveAction(Request
$request, $page)
217 return $this->showEntries('archive', $request, $page);
221 * Shows starred entries for current user.
223 * @param Request $request
226 * @Route("/starred/list/{page}", name="starred", defaults={"page" = "1"})
228 * @return \Symfony\Component\HttpFoundation\Response
230 public function showStarredAction(Request
$request, $page)
232 return $this->showEntries('starred', $request, $page);
236 * Shows entry content.
238 * @param Entry $entry
240 * @Route("/view/{id}", requirements={"id" = "\d+"}, name="view")
242 * @return \Symfony\Component\HttpFoundation\Response
244 public function viewAction(Entry
$entry)
246 $this->checkUserAction($entry);
248 return $this->render(
249 'WallabagCoreBundle:Entry:entry.html.twig',
256 * Refetch content from the website and make it readable again.
258 * @param Entry $entry
260 * @Route("/reload/{id}", requirements={"id" = "\d+"}, name="reload_entry")
262 * @return \Symfony\Component\HttpFoundation\RedirectResponse
264 public function reloadAction(Entry
$entry)
266 $this->checkUserAction($entry);
268 $this->updateEntry($entry, 'entry_reloaded');
270 // if refreshing entry failed, don't save it
271 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
272 $bag = $this->get('session')->getFlashBag();
274 $bag->add('notice', 'flashes.entry.notice.entry_reloaded_failed');
276 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
279 $em = $this->getDoctrine()->getManager();
280 $em->persist($entry);
283 // entry saved, dispatch event about it!
284 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
286 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
290 * Changes read status for an entry.
292 * @param Request $request
293 * @param Entry $entry
295 * @Route("/archive/{id}", requirements={"id" = "\d+"}, name="archive_entry")
297 * @return \Symfony\Component\HttpFoundation\RedirectResponse
299 public function toggleArchiveAction(Request
$request, Entry
$entry)
301 $this->checkUserAction($entry);
303 $entry->toggleArchive();
304 $this->getDoctrine()->getManager()->flush();
306 $message = 'flashes.entry.notice.entry_unarchived';
307 if ($entry->isArchived()) {
308 $message = 'flashes.entry.notice.entry_archived';
311 $this->get('session')->getFlashBag()->add(
316 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
318 return $this->redirect($redirectUrl);
322 * Changes starred status for an entry.
324 * @param Request $request
325 * @param Entry $entry
327 * @Route("/star/{id}", requirements={"id" = "\d+"}, name="star_entry")
329 * @return \Symfony\Component\HttpFoundation\RedirectResponse
331 public function toggleStarAction(Request
$request, Entry
$entry)
333 $this->checkUserAction($entry);
335 $entry->toggleStar();
336 $this->getDoctrine()->getManager()->flush();
338 $message = 'flashes.entry.notice.entry_unstarred';
339 if ($entry->isStarred()) {
340 $message = 'flashes.entry.notice.entry_starred';
343 $this->get('session')->getFlashBag()->add(
348 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
350 return $this->redirect($redirectUrl);
354 * Deletes entry and redirect to the homepage or the last viewed page.
356 * @param Entry $entry
358 * @Route("/delete/{id}", requirements={"id" = "\d+"}, name="delete_entry")
360 * @return \Symfony\Component\HttpFoundation\RedirectResponse
362 public function deleteEntryAction(Request
$request, Entry
$entry)
364 $this->checkUserAction($entry);
366 // generates the view url for this entry to check for redirection later
367 // to avoid redirecting to the deleted entry. Ugh.
368 $url = $this->generateUrl(
370 ['id' => $entry->getId()],
371 UrlGeneratorInterface
::ABSOLUTE_PATH
374 // entry deleted, dispatch event about it!
375 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
377 $em = $this->getDoctrine()->getManager();
381 $this->get('session')->getFlashBag()->add(
383 'flashes.entry.notice.entry_deleted'
386 // don't redirect user to the deleted entry (check that the referer doesn't end with the same url)
387 $referer = $request->headers
->get('referer');
388 $to = (1 !== preg_match('#' . $url . '$#i', $referer) ? $referer : null);
390 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to);
392 return $this->redirect($redirectUrl);
396 * Get public URL for entry (and generate it if necessary).
398 * @param Entry $entry
400 * @Route("/share/{id}", requirements={"id" = "\d+"}, name="share")
402 * @return \Symfony\Component\HttpFoundation\Response
404 public function shareAction(Entry
$entry)
406 $this->checkUserAction($entry);
408 if (null === $entry->getUid()) {
409 $entry->generateUid();
411 $em = $this->getDoctrine()->getManager();
412 $em->persist($entry);
416 return $this->redirect($this->generateUrl('share_entry', [
417 'uid' => $entry->getUid(),
422 * Disable public sharing for an entry.
424 * @param Entry $entry
426 * @Route("/share/delete/{id}", requirements={"id" = "\d+"}, name="delete_share")
428 * @return \Symfony\Component\HttpFoundation\Response
430 public function deleteShareAction(Entry
$entry)
432 $this->checkUserAction($entry);
436 $em = $this->getDoctrine()->getManager();
437 $em->persist($entry);
440 return $this->redirect($this->generateUrl('view', [
441 'id' => $entry->getId(),
446 * Ability to view a content publicly.
448 * @param Entry $entry
450 * @Route("/share/{uid}", requirements={"uid" = ".+"}, name="share_entry")
451 * @Cache(maxage="25200", smaxage="25200", public=true)
453 * @return \Symfony\Component\HttpFoundation\Response
455 public function shareEntryAction(Entry
$entry)
457 if (!$this->get('craue_config')->get('share_public')) {
458 throw $this->createAccessDeniedException('Sharing an entry is disabled for this user.');
461 return $this->render(
462 '@WallabagCore/themes/common/Entry/share.html.twig',
468 * Shows untagged articles for current user.
470 * @param Request $request
473 * @Route("/untagged/list/{page}", name="untagged", defaults={"page" = "1"})
475 * @return \Symfony\Component\HttpFoundation\Response
477 public function showUntaggedEntriesAction(Request
$request, $page)
479 return $this->showEntries('untagged', $request, $page);
483 * Fetch content and update entry.
484 * In case it fails, $entry->getContent will return an error message.
486 * @param Entry $entry
487 * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded
489 private function updateEntry(Entry
$entry, $prefixMessage = 'entry_saved')
491 $message = 'flashes.entry.notice.' . $prefixMessage;
494 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
495 } catch (\Exception
$e) {
496 $this->get('logger')->error('Error while saving an entry', [
501 $message = 'flashes.entry.notice.' . $prefixMessage . '_failed';
504 $this->get('session')->getFlashBag()->add('notice', $message);
508 * Global method to retrieve entries depending on the given type
509 * It returns the response to be send.
511 * @param string $type Entries type: unread, starred or archive
512 * @param Request $request
515 * @return \Symfony\Component\HttpFoundation\Response
517 private function showEntries($type, Request
$request, $page)
519 $repository = $this->get('wallabag_core.entry_repository');
520 $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : '');
521 $currentRoute = (null !== $request->query
->get('currentRoute') ? $request->query
->get('currentRoute') : '');
525 $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute);
529 $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 * Check if the logged user can manage the given entry.
584 * @param Entry $entry
586 private function checkUserAction(Entry
$entry)
588 if (null === $this->getUser() || $this->getUser()->getId() !== $entry->getUser()->getId()) {
589 throw $this->createAccessDeniedException('You can not access this entry.');
594 * Check for existing entry, if it exists, redirect to it with a message.
596 * @param Entry $entry
600 private function checkIfEntryAlreadyExists(Entry
$entry)
602 return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId());