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