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