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