]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Controller/EntryController.php
669e15d7ca95262cd5fe49882ecbe2bd3c108c24
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Controller / EntryController.php
1 <?php
2
3 namespace Wallabag\CoreBundle\Controller;
4
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;
20
21 class EntryController extends Controller
22 {
23 /**
24 * @param Request $request
25 * @param int $page
26 *
27 * @Route("/search/{page}", name="search", defaults={"page" = 1})
28 *
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
31 *
32 * @return \Symfony\Component\HttpFoundation\Response
33 */
34 public function searchFormAction(Request $request, $page = 1, $currentRoute = null)
35 {
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');
39 }
40
41 $form = $this->createForm(SearchEntryType::class);
42
43 $form->handleRequest($request);
44
45 if ($form->isSubmitted() && $form->isValid()) {
46 return $this->showEntries('search', $request, $page);
47 }
48
49 return $this->render('WallabagCoreBundle:Entry:search_form.html.twig', [
50 'form' => $form->createView(),
51 'currentRoute' => $currentRoute,
52 ]);
53 }
54
55 /**
56 * @param Request $request
57 *
58 * @Route("/new-entry", name="new_entry")
59 *
60 * @return \Symfony\Component\HttpFoundation\Response
61 */
62 public function addEntryFormAction(Request $request)
63 {
64 $entry = new Entry($this->getUser());
65
66 $form = $this->createForm(NewEntryType::class, $entry);
67
68 $form->handleRequest($request);
69
70 if ($form->isSubmitted() && $form->isValid()) {
71 $existingEntry = $this->checkIfEntryAlreadyExists($entry);
72
73 if (false !== $existingEntry) {
74 $this->get('session')->getFlashBag()->add(
75 'notice',
76 $this->get('translator')->trans('flashes.entry.notice.entry_already_saved', ['%date%' => $existingEntry->getCreatedAt()->format('d-m-Y')])
77 );
78
79 return $this->redirect($this->generateUrl('view', ['id' => $existingEntry->getId()]));
80 }
81
82 $this->updateEntry($entry);
83
84 $em = $this->getDoctrine()->getManager();
85 $em->persist($entry);
86 $em->flush();
87
88 // entry saved, dispatch event about it!
89 $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
90
91 return $this->redirect($this->generateUrl('homepage'));
92 }
93
94 return $this->render('WallabagCoreBundle:Entry:new_form.html.twig', [
95 'form' => $form->createView(),
96 ]);
97 }
98
99 /**
100 * @param Request $request
101 *
102 * @Route("/bookmarklet", name="bookmarklet")
103 *
104 * @return \Symfony\Component\HttpFoundation\Response
105 */
106 public function addEntryViaBookmarkletAction(Request $request)
107 {
108 $entry = new Entry($this->getUser());
109 $entry->setUrl($request->get('url'));
110
111 if (false === $this->checkIfEntryAlreadyExists($entry)) {
112 $this->updateEntry($entry);
113
114 $em = $this->getDoctrine()->getManager();
115 $em->persist($entry);
116 $em->flush();
117
118 // entry saved, dispatch event about it!
119 $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
120 }
121
122 return $this->redirect($this->generateUrl('homepage'));
123 }
124
125 /**
126 * @Route("/new", name="new")
127 *
128 * @return \Symfony\Component\HttpFoundation\Response
129 */
130 public function addEntryAction()
131 {
132 return $this->render('WallabagCoreBundle:Entry:new.html.twig');
133 }
134
135 /**
136 * Edit an entry content.
137 *
138 * @param Request $request
139 * @param Entry $entry
140 *
141 * @Route("/edit/{id}", requirements={"id" = "\d+"}, name="edit")
142 *
143 * @return \Symfony\Component\HttpFoundation\Response
144 */
145 public function editEntryAction(Request $request, Entry $entry)
146 {
147 $this->checkUserAction($entry);
148
149 $form = $this->createForm(EditEntryType::class, $entry);
150
151 $form->handleRequest($request);
152
153 if ($form->isSubmitted() && $form->isValid()) {
154 $em = $this->getDoctrine()->getManager();
155 $em->persist($entry);
156 $em->flush();
157
158 $this->get('session')->getFlashBag()->add(
159 'notice',
160 'flashes.entry.notice.entry_updated'
161 );
162
163 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
164 }
165
166 return $this->render('WallabagCoreBundle:Entry:edit.html.twig', [
167 'form' => $form->createView(),
168 ]);
169 }
170
171 /**
172 * Shows all entries for current user.
173 *
174 * @param Request $request
175 * @param int $page
176 *
177 * @Route("/all/list/{page}", name="all", defaults={"page" = "1"})
178 *
179 * @return \Symfony\Component\HttpFoundation\Response
180 */
181 public function showAllAction(Request $request, $page)
182 {
183 return $this->showEntries('all', $request, $page);
184 }
185
186 /**
187 * Shows unread entries for current user.
188 *
189 * @param Request $request
190 * @param int $page
191 *
192 * @Route("/unread/list/{page}", name="unread", defaults={"page" = "1"})
193 *
194 * @return \Symfony\Component\HttpFoundation\Response
195 */
196 public function showUnreadAction(Request $request, $page)
197 {
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'));
201 }
202
203 return $this->showEntries('unread', $request, $page);
204 }
205
206 /**
207 * Shows read entries for current user.
208 *
209 * @param Request $request
210 * @param int $page
211 *
212 * @Route("/archive/list/{page}", name="archive", defaults={"page" = "1"})
213 *
214 * @return \Symfony\Component\HttpFoundation\Response
215 */
216 public function showArchiveAction(Request $request, $page)
217 {
218 return $this->showEntries('archive', $request, $page);
219 }
220
221 /**
222 * Shows starred entries for current user.
223 *
224 * @param Request $request
225 * @param int $page
226 *
227 * @Route("/starred/list/{page}", name="starred", defaults={"page" = "1"})
228 *
229 * @return \Symfony\Component\HttpFoundation\Response
230 */
231 public function showStarredAction(Request $request, $page)
232 {
233 return $this->showEntries('starred', $request, $page);
234 }
235
236 /**
237 * Shows untagged articles for current user.
238 *
239 * @param Request $request
240 * @param int $page
241 *
242 * @Route("/untagged/list/{page}", name="untagged", defaults={"page" = "1"})
243 *
244 * @return \Symfony\Component\HttpFoundation\Response
245 */
246 public function showUntaggedEntriesAction(Request $request, $page)
247 {
248 return $this->showEntries('untagged', $request, $page);
249 }
250
251 /**
252 * Shows random unread entry.
253 *
254 * @param Entry $entry
255 *
256 * @Route("/unread/random", name="unread_random")
257 *
258 * @return \Symfony\Component\HttpFoundation\Response
259 */
260 public function showRandomUnreadEntryAction()
261 {
262 return $this->showRandomEntries('unread');
263 }
264
265 /**
266 * Shows random favorite entry.
267 *
268 * @param Entry $entry
269 *
270 * @Route("/starred/random", name="starred_random")
271 *
272 * @return \Symfony\Component\HttpFoundation\Response
273 */
274 public function showRandomStarredEntryAction()
275 {
276 return $this->showRandomEntries('starred');
277 }
278
279 /**
280 * Shows random archived entry.
281 *
282 * @param Entry $entry
283 *
284 * @Route("/archive/random", name="archive_random")
285 *
286 * @return \Symfony\Component\HttpFoundation\Response
287 */
288 public function showRandomArchiveEntryAction()
289 {
290 return $this->showRandomEntries('archive');
291 }
292
293 /**
294 * Shows random all entry.
295 *
296 * @param Entry $entry
297 *
298 * @Route("/untagged/random", name="untagged_random")
299 *
300 * @return \Symfony\Component\HttpFoundation\Response
301 */
302 public function showRandomUntaggedEntryAction()
303 {
304 return $this->showRandomEntries('untagged');
305 }
306
307 /**
308 * Shows random all entry.
309 *
310 * @param Entry $entry
311 *
312 * @Route("/all/random", name="all_random")
313 *
314 * @return \Symfony\Component\HttpFoundation\Response
315 */
316 public function showRandomAllEntryAction()
317 {
318 return $this->showRandomEntries();
319 }
320
321 /**
322 * Shows entry content.
323 *
324 * @param Entry $entry
325 *
326 * @Route("/view/{id}", requirements={"id" = "\d+"}, name="view")
327 *
328 * @return \Symfony\Component\HttpFoundation\Response
329 */
330 public function viewAction(Entry $entry)
331 {
332 $this->checkUserAction($entry);
333
334 return $this->render(
335 'WallabagCoreBundle:Entry:entry.html.twig',
336 ['entry' => $entry]
337 );
338 }
339
340 /**
341 * Reload an entry.
342 * Refetch content from the website and make it readable again.
343 *
344 * @param Entry $entry
345 *
346 * @Route("/reload/{id}", requirements={"id" = "\d+"}, name="reload_entry")
347 *
348 * @return \Symfony\Component\HttpFoundation\RedirectResponse
349 */
350 public function reloadAction(Entry $entry)
351 {
352 $this->checkUserAction($entry);
353
354 $this->updateEntry($entry, 'entry_reloaded');
355
356 // if refreshing entry failed, don't save it
357 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
358 $bag = $this->get('session')->getFlashBag();
359 $bag->clear();
360 $bag->add('notice', 'flashes.entry.notice.entry_reloaded_failed');
361
362 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
363 }
364
365 $em = $this->getDoctrine()->getManager();
366 $em->persist($entry);
367 $em->flush();
368
369 // entry saved, dispatch event about it!
370 $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
371
372 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
373 }
374
375 /**
376 * Changes read status for an entry.
377 *
378 * @param Request $request
379 * @param Entry $entry
380 *
381 * @Route("/archive/{id}", requirements={"id" = "\d+"}, name="archive_entry")
382 *
383 * @return \Symfony\Component\HttpFoundation\RedirectResponse
384 */
385 public function toggleArchiveAction(Request $request, Entry $entry)
386 {
387 $this->checkUserAction($entry);
388
389 $entry->toggleArchive();
390 $this->getDoctrine()->getManager()->flush();
391
392 $message = 'flashes.entry.notice.entry_unarchived';
393 if ($entry->isArchived()) {
394 $message = 'flashes.entry.notice.entry_archived';
395 }
396
397 $this->get('session')->getFlashBag()->add(
398 'notice',
399 $message
400 );
401
402 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers->get('referer'));
403
404 return $this->redirect($redirectUrl);
405 }
406
407 /**
408 * Changes starred status for an entry.
409 *
410 * @param Request $request
411 * @param Entry $entry
412 *
413 * @Route("/star/{id}", requirements={"id" = "\d+"}, name="star_entry")
414 *
415 * @return \Symfony\Component\HttpFoundation\RedirectResponse
416 */
417 public function toggleStarAction(Request $request, Entry $entry)
418 {
419 $this->checkUserAction($entry);
420
421 $entry->toggleStar();
422 $entry->updateStar($entry->isStarred());
423 $this->getDoctrine()->getManager()->flush();
424
425 $message = 'flashes.entry.notice.entry_unstarred';
426 if ($entry->isStarred()) {
427 $message = 'flashes.entry.notice.entry_starred';
428 }
429
430 $this->get('session')->getFlashBag()->add(
431 'notice',
432 $message
433 );
434
435 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers->get('referer'));
436
437 return $this->redirect($redirectUrl);
438 }
439
440 /**
441 * Deletes entry and redirect to the homepage or the last viewed page.
442 *
443 * @param Entry $entry
444 *
445 * @Route("/delete/{id}", requirements={"id" = "\d+"}, name="delete_entry")
446 *
447 * @return \Symfony\Component\HttpFoundation\RedirectResponse
448 */
449 public function deleteEntryAction(Request $request, Entry $entry)
450 {
451 $this->checkUserAction($entry);
452
453 // generates the view url for this entry to check for redirection later
454 // to avoid redirecting to the deleted entry. Ugh.
455 $url = $this->generateUrl(
456 'view',
457 ['id' => $entry->getId()],
458 UrlGeneratorInterface::ABSOLUTE_PATH
459 );
460
461 // entry deleted, dispatch event about it!
462 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry));
463
464 $em = $this->getDoctrine()->getManager();
465 $em->remove($entry);
466 $em->flush();
467
468 $this->get('session')->getFlashBag()->add(
469 'notice',
470 'flashes.entry.notice.entry_deleted'
471 );
472
473 // don't redirect user to the deleted entry (check that the referer doesn't end with the same url)
474 $referer = $request->headers->get('referer');
475 $to = (1 !== preg_match('#' . $url . '$#i', $referer) ? $referer : null);
476
477 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to);
478
479 return $this->redirect($redirectUrl);
480 }
481
482 /**
483 * Get public URL for entry (and generate it if necessary).
484 *
485 * @param Entry $entry
486 *
487 * @Route("/share/{id}", requirements={"id" = "\d+"}, name="share")
488 *
489 * @return \Symfony\Component\HttpFoundation\Response
490 */
491 public function shareAction(Entry $entry)
492 {
493 $this->checkUserAction($entry);
494
495 if (null === $entry->getUid()) {
496 $entry->generateUid();
497
498 $em = $this->getDoctrine()->getManager();
499 $em->persist($entry);
500 $em->flush();
501 }
502
503 return $this->redirect($this->generateUrl('share_entry', [
504 'uid' => $entry->getUid(),
505 ]));
506 }
507
508 /**
509 * Disable public sharing for an entry.
510 *
511 * @param Entry $entry
512 *
513 * @Route("/share/delete/{id}", requirements={"id" = "\d+"}, name="delete_share")
514 *
515 * @return \Symfony\Component\HttpFoundation\Response
516 */
517 public function deleteShareAction(Entry $entry)
518 {
519 $this->checkUserAction($entry);
520
521 $entry->cleanUid();
522
523 $em = $this->getDoctrine()->getManager();
524 $em->persist($entry);
525 $em->flush();
526
527 return $this->redirect($this->generateUrl('view', [
528 'id' => $entry->getId(),
529 ]));
530 }
531
532 /**
533 * Ability to view a content publicly.
534 *
535 * @param Entry $entry
536 *
537 * @Route("/share/{uid}", requirements={"uid" = ".+"}, name="share_entry")
538 * @Cache(maxage="25200", smaxage="25200", public=true)
539 *
540 * @return \Symfony\Component\HttpFoundation\Response
541 */
542 public function shareEntryAction(Entry $entry)
543 {
544 if (!$this->get('craue_config')->get('share_public')) {
545 throw $this->createAccessDeniedException('Sharing an entry is disabled for this user.');
546 }
547
548 return $this->render(
549 '@WallabagCore/themes/common/Entry/share.html.twig',
550 ['entry' => $entry]
551 );
552 }
553
554 /**
555 * Global method to retrieve entries depending on the given type
556 * It returns the response to be send.
557 *
558 * @param string $type Entries type: unread, starred or archive
559 * @param Request $request
560 * @param int $page
561 *
562 * @return \Symfony\Component\HttpFoundation\Response
563 */
564 private function showEntries($type, Request $request, $page)
565 {
566 $repository = $this->get('wallabag_core.entry_repository');
567 $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : '');
568 $currentRoute = (null !== $request->query->get('currentRoute') ? $request->query->get('currentRoute') : '');
569
570 switch ($type) {
571 case 'search':
572 $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute);
573 break;
574 case 'untagged':
575 $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId());
576 break;
577 case 'starred':
578 $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId());
579 break;
580 case 'archive':
581 $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId());
582 break;
583 case 'unread':
584 $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId());
585 break;
586 case 'all':
587 $qb = $repository->getBuilderForAllByUser($this->getUser()->getId());
588 break;
589 default:
590 throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
591 }
592
593 $form = $this->createForm(EntryFilterType::class);
594
595 if ($request->query->has($form->getName())) {
596 // manually bind values from the request
597 $form->submit($request->query->get($form->getName()));
598
599 // build the query from the given form object
600 $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb);
601 }
602
603 $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false);
604
605 $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter);
606
607 try {
608 $entries->setCurrentPage($page);
609 } catch (OutOfRangeCurrentPageException $e) {
610 if ($page > 1) {
611 return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302);
612 }
613 }
614
615 return $this->render(
616 'WallabagCoreBundle:Entry:entries.html.twig', [
617 'form' => $form->createView(),
618 'entries' => $entries,
619 'currentPage' => $page,
620 'searchTerm' => $searchTerm,
621 'isFiltered' => $form->isSubmitted(),
622 ]
623 );
624 }
625
626 /**
627 * Global method to retrieve random entries depending on the given type.
628 *
629 * @param string $type Entries type: unread, starred, archive or untagged
630 *
631 * @return \Symfony\Component\HttpFoundation\RedirectResponse
632 */
633 private function showRandomEntries($type)
634 {
635 $repository = $this->get('wallabag_core.entry_repository');
636
637 try {
638 $entry = $repository->getRandomEntry($this->getUser()->getId(), $type);
639 } catch (NoResultException $e) {
640 $bag = $this->get('session')->getFlashBag();
641 $bag->clear();
642 $bag->add('notice', 'flashes.entry.notice.no_random_entry');
643
644 return $this->redirect($this->generateUrl('homepage'));
645 }
646
647 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
648 }
649
650 /**
651 * Fetch content and update entry.
652 * In case it fails, $entry->getContent will return an error message.
653 *
654 * @param Entry $entry
655 * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded
656 */
657 private function updateEntry(Entry $entry, $prefixMessage = 'entry_saved')
658 {
659 $message = 'flashes.entry.notice.' . $prefixMessage;
660
661 try {
662 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
663 } catch (\Exception $e) {
664 $this->get('logger')->error('Error while saving an entry', [
665 'exception' => $e,
666 'entry' => $entry,
667 ]);
668
669 $message = 'flashes.entry.notice.' . $prefixMessage . '_failed';
670 }
671
672 if (empty($entry->getDomainName())) {
673 $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
674 }
675
676 if (empty($entry->getTitle())) {
677 $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
678 }
679
680 $this->get('session')->getFlashBag()->add('notice', $message);
681 }
682
683 /**
684 * Check if the logged user can manage the given entry.
685 *
686 * @param Entry $entry
687 */
688 private function checkUserAction(Entry $entry)
689 {
690 if (null === $this->getUser() || $this->getUser()->getId() !== $entry->getUser()->getId()) {
691 throw $this->createAccessDeniedException('You can not access this entry.');
692 }
693 }
694
695 /**
696 * Check for existing entry, if it exists, redirect to it with a message.
697 *
698 * @param Entry $entry
699 *
700 * @return Entry|bool
701 */
702 private function checkIfEntryAlreadyExists(Entry $entry)
703 {
704 return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId());
705 }
706 }