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