]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Controller/EntryController.php
dfb5eb5490c2ad502015238abaea05e6dd985a9e
[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 entry depending on the given type.
253 *
254 * @param string $type
255 *
256 * @Route("/{type}/random", name="random_entry", requirements={"_locale": "unread|starred|archive|untagged|all"})
257 *
258 * @return \Symfony\Component\HttpFoundation\RedirectResponse
259 */
260 public function redirectRandomEntryAction($type = 'all')
261 {
262 try {
263 $entry = $this->get('wallabag_core.entry_repository')
264 ->getRandomEntry($this->getUser()->getId(), $type);
265 } catch (NoResultException $e) {
266 $bag = $this->get('session')->getFlashBag();
267 $bag->clear();
268 $bag->add('notice', 'flashes.entry.notice.no_random_entry');
269
270 return $this->redirect($this->generateUrl($type));
271 }
272
273 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
274 }
275
276 /**
277 * Shows entry content.
278 *
279 * @param Entry $entry
280 *
281 * @Route("/view/{id}", requirements={"id" = "\d+"}, name="view")
282 *
283 * @return \Symfony\Component\HttpFoundation\Response
284 */
285 public function viewAction(Entry $entry)
286 {
287 $this->checkUserAction($entry);
288
289 return $this->render(
290 'WallabagCoreBundle:Entry:entry.html.twig',
291 ['entry' => $entry]
292 );
293 }
294
295 /**
296 * Reload an entry.
297 * Refetch content from the website and make it readable again.
298 *
299 * @param Entry $entry
300 *
301 * @Route("/reload/{id}", requirements={"id" = "\d+"}, name="reload_entry")
302 *
303 * @return \Symfony\Component\HttpFoundation\RedirectResponse
304 */
305 public function reloadAction(Entry $entry)
306 {
307 $this->checkUserAction($entry);
308
309 $this->updateEntry($entry, 'entry_reloaded');
310
311 // if refreshing entry failed, don't save it
312 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
313 $bag = $this->get('session')->getFlashBag();
314 $bag->clear();
315 $bag->add('notice', 'flashes.entry.notice.entry_reloaded_failed');
316
317 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
318 }
319
320 $em = $this->getDoctrine()->getManager();
321 $em->persist($entry);
322 $em->flush();
323
324 // entry saved, dispatch event about it!
325 $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
326
327 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
328 }
329
330 /**
331 * Changes read status for an entry.
332 *
333 * @param Request $request
334 * @param Entry $entry
335 *
336 * @Route("/archive/{id}", requirements={"id" = "\d+"}, name="archive_entry")
337 *
338 * @return \Symfony\Component\HttpFoundation\RedirectResponse
339 */
340 public function toggleArchiveAction(Request $request, Entry $entry)
341 {
342 $this->checkUserAction($entry);
343
344 $entry->toggleArchive();
345 $this->getDoctrine()->getManager()->flush();
346
347 $message = 'flashes.entry.notice.entry_unarchived';
348 if ($entry->isArchived()) {
349 $message = 'flashes.entry.notice.entry_archived';
350 }
351
352 $this->get('session')->getFlashBag()->add(
353 'notice',
354 $message
355 );
356
357 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers->get('referer'));
358
359 return $this->redirect($redirectUrl);
360 }
361
362 /**
363 * Changes starred status for an entry.
364 *
365 * @param Request $request
366 * @param Entry $entry
367 *
368 * @Route("/star/{id}", requirements={"id" = "\d+"}, name="star_entry")
369 *
370 * @return \Symfony\Component\HttpFoundation\RedirectResponse
371 */
372 public function toggleStarAction(Request $request, Entry $entry)
373 {
374 $this->checkUserAction($entry);
375
376 $entry->toggleStar();
377 $entry->updateStar($entry->isStarred());
378 $this->getDoctrine()->getManager()->flush();
379
380 $message = 'flashes.entry.notice.entry_unstarred';
381 if ($entry->isStarred()) {
382 $message = 'flashes.entry.notice.entry_starred';
383 }
384
385 $this->get('session')->getFlashBag()->add(
386 'notice',
387 $message
388 );
389
390 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers->get('referer'));
391
392 return $this->redirect($redirectUrl);
393 }
394
395 /**
396 * Deletes entry and redirect to the homepage or the last viewed page.
397 *
398 * @param Entry $entry
399 *
400 * @Route("/delete/{id}", requirements={"id" = "\d+"}, name="delete_entry")
401 *
402 * @return \Symfony\Component\HttpFoundation\RedirectResponse
403 */
404 public function deleteEntryAction(Request $request, Entry $entry)
405 {
406 $this->checkUserAction($entry);
407
408 // generates the view url for this entry to check for redirection later
409 // to avoid redirecting to the deleted entry. Ugh.
410 $url = $this->generateUrl(
411 'view',
412 ['id' => $entry->getId()],
413 UrlGeneratorInterface::ABSOLUTE_PATH
414 );
415
416 // entry deleted, dispatch event about it!
417 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry));
418
419 $em = $this->getDoctrine()->getManager();
420 $em->remove($entry);
421 $em->flush();
422
423 $this->get('session')->getFlashBag()->add(
424 'notice',
425 'flashes.entry.notice.entry_deleted'
426 );
427
428 // don't redirect user to the deleted entry (check that the referer doesn't end with the same url)
429 $referer = $request->headers->get('referer');
430 $to = (1 !== preg_match('#' . $url . '$#i', $referer) ? $referer : null);
431
432 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to);
433
434 return $this->redirect($redirectUrl);
435 }
436
437 /**
438 * Get public URL for entry (and generate it if necessary).
439 *
440 * @param Entry $entry
441 *
442 * @Route("/share/{id}", requirements={"id" = "\d+"}, name="share")
443 *
444 * @return \Symfony\Component\HttpFoundation\Response
445 */
446 public function shareAction(Entry $entry)
447 {
448 $this->checkUserAction($entry);
449
450 if (null === $entry->getUid()) {
451 $entry->generateUid();
452
453 $em = $this->getDoctrine()->getManager();
454 $em->persist($entry);
455 $em->flush();
456 }
457
458 return $this->redirect($this->generateUrl('share_entry', [
459 'uid' => $entry->getUid(),
460 ]));
461 }
462
463 /**
464 * Disable public sharing for an entry.
465 *
466 * @param Entry $entry
467 *
468 * @Route("/share/delete/{id}", requirements={"id" = "\d+"}, name="delete_share")
469 *
470 * @return \Symfony\Component\HttpFoundation\Response
471 */
472 public function deleteShareAction(Entry $entry)
473 {
474 $this->checkUserAction($entry);
475
476 $entry->cleanUid();
477
478 $em = $this->getDoctrine()->getManager();
479 $em->persist($entry);
480 $em->flush();
481
482 return $this->redirect($this->generateUrl('view', [
483 'id' => $entry->getId(),
484 ]));
485 }
486
487 /**
488 * Ability to view a content publicly.
489 *
490 * @param Entry $entry
491 *
492 * @Route("/share/{uid}", requirements={"uid" = ".+"}, name="share_entry")
493 * @Cache(maxage="25200", smaxage="25200", public=true)
494 *
495 * @return \Symfony\Component\HttpFoundation\Response
496 */
497 public function shareEntryAction(Entry $entry)
498 {
499 if (!$this->get('craue_config')->get('share_public')) {
500 throw $this->createAccessDeniedException('Sharing an entry is disabled for this user.');
501 }
502
503 return $this->render(
504 '@WallabagCore/themes/common/Entry/share.html.twig',
505 ['entry' => $entry]
506 );
507 }
508
509 /**
510 * Global method to retrieve entries depending on the given type
511 * It returns the response to be send.
512 *
513 * @param string $type Entries type: unread, starred or archive
514 * @param Request $request
515 * @param int $page
516 *
517 * @return \Symfony\Component\HttpFoundation\Response
518 */
519 private function showEntries($type, Request $request, $page)
520 {
521 $repository = $this->get('wallabag_core.entry_repository');
522 $searchTerm = (isset($request->get('search_entry')['term']) ? $request->get('search_entry')['term'] : '');
523 $currentRoute = (null !== $request->query->get('currentRoute') ? $request->query->get('currentRoute') : '');
524
525 switch ($type) {
526 case 'search':
527 $qb = $repository->getBuilderForSearchByUser($this->getUser()->getId(), $searchTerm, $currentRoute);
528 break;
529 case 'untagged':
530 $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId());
531 break;
532 case 'starred':
533 $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId());
534 break;
535 case 'archive':
536 $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId());
537 break;
538 case 'unread':
539 $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId());
540 break;
541 case 'all':
542 $qb = $repository->getBuilderForAllByUser($this->getUser()->getId());
543 break;
544 default:
545 throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
546 }
547
548 $form = $this->createForm(EntryFilterType::class);
549
550 if ($request->query->has($form->getName())) {
551 // manually bind values from the request
552 $form->submit($request->query->get($form->getName()));
553
554 // build the query from the given form object
555 $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb);
556 }
557
558 $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false);
559
560 $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter);
561
562 try {
563 $entries->setCurrentPage($page);
564 } catch (OutOfRangeCurrentPageException $e) {
565 if ($page > 1) {
566 return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302);
567 }
568 }
569
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(),
577 ]
578 );
579 }
580
581 /**
582 * Fetch content and update entry.
583 * In case it fails, $entry->getContent will return an error message.
584 *
585 * @param Entry $entry
586 * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded
587 */
588 private function updateEntry(Entry $entry, $prefixMessage = 'entry_saved')
589 {
590 $message = 'flashes.entry.notice.' . $prefixMessage;
591
592 try {
593 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
594 } catch (\Exception $e) {
595 $this->get('logger')->error('Error while saving an entry', [
596 'exception' => $e,
597 'entry' => $entry,
598 ]);
599
600 $message = 'flashes.entry.notice.' . $prefixMessage . '_failed';
601 }
602
603 if (empty($entry->getDomainName())) {
604 $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
605 }
606
607 if (empty($entry->getTitle())) {
608 $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
609 }
610
611 $this->get('session')->getFlashBag()->add('notice', $message);
612 }
613
614 /**
615 * Check if the logged user can manage the given entry.
616 *
617 * @param Entry $entry
618 */
619 private function checkUserAction(Entry $entry)
620 {
621 if (null === $this->getUser() || $this->getUser()->getId() !== $entry->getUser()->getId()) {
622 throw $this->createAccessDeniedException('You can not access this entry.');
623 }
624 }
625
626 /**
627 * Check for existing entry, if it exists, redirect to it with a message.
628 *
629 * @param Entry $entry
630 *
631 * @return Entry|bool
632 */
633 private function checkIfEntryAlreadyExists(Entry $entry)
634 {
635 return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId());
636 }
637 }