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