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
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 * @Route("/new-entry", name="new_entry")
57 * @return \Symfony\Component\HttpFoundation\Response
59 public function addEntryFormAction(Request
$request)
61 $entry = new Entry($this->getUser());
63 $form = $this->createForm(NewEntryType
::class, $entry);
65 $form->handleRequest($request);
67 if ($form->isSubmitted() && $form->isValid()) {
68 $existingEntry = $this->checkIfEntryAlreadyExists($entry);
70 if (false !== $existingEntry) {
71 $this->get('session')->getFlashBag()->add(
73 $this->get('translator')->trans('flashes.entry.notice.entry_already_saved', ['%date%' => $existingEntry->getCreatedAt()->format('d-m-Y')])
76 return $this->redirect($this->generateUrl('view', ['id' => $existingEntry->getId()]));
79 $this->updateEntry($entry);
81 $em = $this->getDoctrine()->getManager();
85 // entry saved, dispatch event about it!
86 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
88 return $this->redirect($this->generateUrl('homepage'));
91 return $this->render('WallabagCoreBundle:Entry:new_form.html.twig', [
92 'form' => $form->createView(),
97 * @Route("/bookmarklet", name="bookmarklet")
99 * @return \Symfony\Component\HttpFoundation\Response
101 public function addEntryViaBookmarkletAction(Request
$request)
103 $entry = new Entry($this->getUser());
104 $entry->setUrl($request->get('url'));
106 if (false === $this->checkIfEntryAlreadyExists($entry)) {
107 $this->updateEntry($entry);
109 $em = $this->getDoctrine()->getManager();
110 $em->persist($entry);
113 // entry saved, dispatch event about it!
114 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
117 return $this->redirect($this->generateUrl('homepage'));
121 * @Route("/new", name="new")
123 * @return \Symfony\Component\HttpFoundation\Response
125 public function addEntryAction()
127 return $this->render('WallabagCoreBundle:Entry:new.html.twig');
131 * Edit an entry content.
133 * @Route("/edit/{id}", requirements={"id" = "\d+"}, name="edit")
135 * @return \Symfony\Component\HttpFoundation\Response
137 public function editEntryAction(Request
$request, Entry
$entry)
139 $this->checkUserAction($entry);
141 $form = $this->createForm(EditEntryType
::class, $entry);
143 $form->handleRequest($request);
145 if ($form->isSubmitted() && $form->isValid()) {
146 $em = $this->getDoctrine()->getManager();
147 $em->persist($entry);
150 $this->get('session')->getFlashBag()->add(
152 'flashes.entry.notice.entry_updated'
155 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
158 return $this->render('WallabagCoreBundle:Entry:edit.html.twig', [
159 'form' => $form->createView(),
164 * Shows all entries for current user.
168 * @Route("/all/list/{page}", name="all", defaults={"page" = "1"})
170 * @return \Symfony\Component\HttpFoundation\Response
172 public function showAllAction(Request
$request, $page)
174 return $this->showEntries('all', $request, $page);
178 * Shows unread entries for current user.
182 * @Route("/unread/list/{page}", name="unread", defaults={"page" = "1"})
184 * @return \Symfony\Component\HttpFoundation\Response
186 public function showUnreadAction(Request
$request, $page)
188 // load the quickstart if no entry in database
189 if (1 === (int) $page && 0 === $this->get('wallabag_core.entry_repository')->countAllEntriesByUser($this->getUser()->getId())) {
190 return $this->redirect($this->generateUrl('quickstart'));
193 return $this->showEntries('unread', $request, $page);
197 * Shows read entries for current user.
201 * @Route("/archive/list/{page}", name="archive", defaults={"page" = "1"})
203 * @return \Symfony\Component\HttpFoundation\Response
205 public function showArchiveAction(Request
$request, $page)
207 return $this->showEntries('archive', $request, $page);
211 * Shows starred entries for current user.
215 * @Route("/starred/list/{page}", name="starred", defaults={"page" = "1"})
217 * @return \Symfony\Component\HttpFoundation\Response
219 public function showStarredAction(Request
$request, $page)
221 return $this->showEntries('starred', $request, $page);
225 * Shows untagged articles for current user.
229 * @Route("/untagged/list/{page}", name="untagged", defaults={"page" = "1"})
231 * @return \Symfony\Component\HttpFoundation\Response
233 public function showUntaggedEntriesAction(Request
$request, $page)
235 return $this->showEntries('untagged', $request, $page);
239 * Shows random entry depending on the given type.
241 * @param string $type
243 * @Route("/{type}/random", name="random_entry", requirements={"type": "unread|starred|archive|untagged|all"})
245 * @return \Symfony\Component\HttpFoundation\RedirectResponse
247 public function redirectRandomEntryAction($type = 'all')
250 $entry = $this->get('wallabag_core.entry_repository')
251 ->getRandomEntry($this->getUser()->getId(), $type);
252 } catch (NoResultException
$e) {
253 $bag = $this->get('session')->getFlashBag();
255 $bag->add('notice', 'flashes.entry.notice.no_random_entry');
257 return $this->redirect($this->generateUrl($type));
260 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
264 * Shows entry content.
266 * @Route("/view/{id}", requirements={"id" = "\d+"}, name="view")
268 * @return \Symfony\Component\HttpFoundation\Response
270 public function viewAction(Entry
$entry)
272 $this->checkUserAction($entry);
274 return $this->render(
275 'WallabagCoreBundle:Entry:entry.html.twig',
282 * Refetch content from the website and make it readable again.
284 * @Route("/reload/{id}", requirements={"id" = "\d+"}, name="reload_entry")
286 * @return \Symfony\Component\HttpFoundation\RedirectResponse
288 public function reloadAction(Entry
$entry)
290 $this->checkUserAction($entry);
292 $this->updateEntry($entry, 'entry_reloaded');
294 // if refreshing entry failed, don't save it
295 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
296 $bag = $this->get('session')->getFlashBag();
298 $bag->add('notice', 'flashes.entry.notice.entry_reloaded_failed');
300 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
303 $em = $this->getDoctrine()->getManager();
304 $em->persist($entry);
307 // entry saved, dispatch event about it!
308 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
310 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
314 * Changes read status for an entry.
316 * @Route("/archive/{id}", requirements={"id" = "\d+"}, name="archive_entry")
318 * @return \Symfony\Component\HttpFoundation\RedirectResponse
320 public function toggleArchiveAction(Request
$request, Entry
$entry)
322 $this->checkUserAction($entry);
324 $entry->toggleArchive();
325 $this->getDoctrine()->getManager()->flush();
327 $message = 'flashes.entry.notice.entry_unarchived';
328 if ($entry->isArchived()) {
329 $message = 'flashes.entry.notice.entry_archived';
332 $this->get('session')->getFlashBag()->add(
337 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
339 return $this->redirect($redirectUrl);
343 * Changes starred status for an entry.
345 * @Route("/star/{id}", requirements={"id" = "\d+"}, name="star_entry")
347 * @return \Symfony\Component\HttpFoundation\RedirectResponse
349 public function toggleStarAction(Request
$request, Entry
$entry)
351 $this->checkUserAction($entry);
353 $entry->toggleStar();
354 $entry->updateStar($entry->isStarred());
355 $this->getDoctrine()->getManager()->flush();
357 $message = 'flashes.entry.notice.entry_unstarred';
358 if ($entry->isStarred()) {
359 $message = 'flashes.entry.notice.entry_starred';
362 $this->get('session')->getFlashBag()->add(
367 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers
->get('referer'));
369 return $this->redirect($redirectUrl);
373 * Deletes entry and redirect to the homepage or the last viewed page.
375 * @Route("/delete/{id}", requirements={"id" = "\d+"}, name="delete_entry")
377 * @return \Symfony\Component\HttpFoundation\RedirectResponse
379 public function deleteEntryAction(Request
$request, Entry
$entry)
381 $this->checkUserAction($entry);
383 // generates the view url for this entry to check for redirection later
384 // to avoid redirecting to the deleted entry. Ugh.
385 $url = $this->generateUrl(
387 ['id' => $entry->getId()],
388 UrlGeneratorInterface
::ABSOLUTE_PATH
391 // entry deleted, dispatch event about it!
392 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
394 $em = $this->getDoctrine()->getManager();
398 $this->get('session')->getFlashBag()->add(
400 'flashes.entry.notice.entry_deleted'
403 // don't redirect user to the deleted entry (check that the referer doesn't end with the same url)
404 $referer = $request->headers
->get('referer');
405 $to = (1 !== preg_match('#' . $url . '$#i', $referer) ? $referer : null);
407 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to);
409 return $this->redirect($redirectUrl);
413 * Get public URL for entry (and generate it if necessary).
415 * @Route("/share/{id}", requirements={"id" = "\d+"}, name="share")
417 * @return \Symfony\Component\HttpFoundation\Response
419 public function shareAction(Entry
$entry)
421 $this->checkUserAction($entry);
423 if (null === $entry->getUid()) {
424 $entry->generateUid();
426 $em = $this->getDoctrine()->getManager();
427 $em->persist($entry);
431 return $this->redirect($this->generateUrl('share_entry', [
432 'uid' => $entry->getUid(),
437 * Disable public sharing for an entry.
439 * @Route("/share/delete/{id}", requirements={"id" = "\d+"}, name="delete_share")
441 * @return \Symfony\Component\HttpFoundation\Response
443 public function deleteShareAction(Entry
$entry)
445 $this->checkUserAction($entry);
449 $em = $this->getDoctrine()->getManager();
450 $em->persist($entry);
453 return $this->redirect($this->generateUrl('view', [
454 'id' => $entry->getId(),
459 * Ability to view a content publicly.
461 * @Route("/share/{uid}", requirements={"uid" = ".+"}, name="share_entry")
462 * @Cache(maxage="25200", smaxage="25200", public=true)
464 * @return \Symfony\Component\HttpFoundation\Response
466 public function shareEntryAction(Entry
$entry)
468 if (!$this->get('craue_config')->get('share_public')) {
469 throw $this->createAccessDeniedException('Sharing an entry is disabled for this user.');
472 return $this->render(
473 '@WallabagCore/themes/common/Entry/share.html.twig',
479 * Global method to retrieve entries depending on the given type
480 * It returns the response to be send.
482 * @param string $type Entries type: unread, starred or archive
485 * @return \Symfony\Component\HttpFoundation\Response
487 private function showEntries($type, Request
$request, $page)
489 $repository = $this->get('wallabag_core.entry_repository');
490 $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : '');
491 $currentRoute = (null !== $request->query
->get('currentRoute') ? $request->query
->get('currentRoute') : '');
495 $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute);
498 $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId());
501 $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId());
504 $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId());
507 $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId());
510 $qb = $repository->getBuilderForAllByUser($this->getUser()->getId());
513 throw new \
InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
516 $form = $this->createForm(EntryFilterType
::class);
518 if ($request->query
->has($form->getName())) {
519 // manually bind values from the request
520 $form->submit($request->query
->get($form->getName()));
522 // build the query from the given form object
523 $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb);
526 $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false);
528 $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter);
531 $entries->setCurrentPage($page);
532 } catch (OutOfRangeCurrentPageException
$e) {
534 return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302);
538 $nbEntriesUntagged = $this->get('wallabag_core.entry_repository')
539 ->countUntaggedEntriesByUser($this->getUser()->getId());
541 return $this->render(
542 'WallabagCoreBundle:Entry:entries.html.twig', [
543 'form' => $form->createView(),
544 'entries' => $entries,
545 'currentPage' => $page,
546 'searchTerm' => $searchTerm,
547 'isFiltered' => $form->isSubmitted(),
548 'nbEntriesUntagged' => $nbEntriesUntagged,
554 * Fetch content and update entry.
555 * In case it fails, $entry->getContent will return an error message.
557 * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded
559 private function updateEntry(Entry
$entry, $prefixMessage = 'entry_saved')
561 $message = 'flashes.entry.notice.' . $prefixMessage;
564 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
565 } catch (\Exception
$e) {
566 $this->get('logger')->error('Error while saving an entry', [
571 $message = 'flashes.entry.notice.' . $prefixMessage . '_failed';
574 if (empty($entry->getDomainName())) {
575 $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
578 if (empty($entry->getTitle())) {
579 $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
582 $this->get('session')->getFlashBag()->add('notice', $message);
586 * Check if the logged user can manage the given entry.
588 private function checkUserAction(Entry
$entry)
590 if (null === $this->getUser() || $this->getUser()->getId() !== $entry->getUser()->getId()) {
591 throw $this->createAccessDeniedException('You can not access this entry.');
596 * Check for existing entry, if it exists, redirect to it with a message.
600 private function checkIfEntryAlreadyExists(Entry
$entry)
602 return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId());