]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Controller/EntryController.php
Page parameter was never used in the function
[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')->countAllEntriesByUser($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->query->get('currentRoute')) ? $request->query->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(), true, false);
323
324 $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter);
325
326 try {
327 $entries->setCurrentPage($page);
328 } catch (OutOfRangeCurrentPageException $e) {
329 if ($page > 1) {
330 return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302);
331 }
332 }
333
334 return $this->render(
335 'WallabagCoreBundle:Entry:entries.html.twig', [
336 'form' => $form->createView(),
337 'entries' => $entries,
338 'currentPage' => $page,
339 'searchTerm' => $searchTerm,
340 ]
341 );
342 }
343
344 /**
345 * Shows entry content.
346 *
347 * @param Entry $entry
348 *
349 * @Route("/view/{id}", requirements={"id" = "\d+"}, name="view")
350 *
351 * @return \Symfony\Component\HttpFoundation\Response
352 */
353 public function viewAction(Entry $entry)
354 {
355 $this->checkUserAction($entry);
356
357 return $this->render(
358 'WallabagCoreBundle:Entry:entry.html.twig',
359 ['entry' => $entry]
360 );
361 }
362
363 /**
364 * Reload an entry.
365 * Refetch content from the website and make it readable again.
366 *
367 * @param Entry $entry
368 *
369 * @Route("/reload/{id}", requirements={"id" = "\d+"}, name="reload_entry")
370 *
371 * @return \Symfony\Component\HttpFoundation\RedirectResponse
372 */
373 public function reloadAction(Entry $entry)
374 {
375 $this->checkUserAction($entry);
376
377 $this->updateEntry($entry, 'entry_reloaded');
378
379 // if refreshing entry failed, don't save it
380 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
381 $bag = $this->get('session')->getFlashBag();
382 $bag->clear();
383 $bag->add('notice', 'flashes.entry.notice.entry_reloaded_failed');
384
385 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
386 }
387
388 $em = $this->getDoctrine()->getManager();
389 $em->persist($entry);
390 $em->flush();
391
392 // entry saved, dispatch event about it!
393 $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
394
395 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
396 }
397
398 /**
399 * Changes read status for an entry.
400 *
401 * @param Request $request
402 * @param Entry $entry
403 *
404 * @Route("/archive/{id}", requirements={"id" = "\d+"}, name="archive_entry")
405 *
406 * @return \Symfony\Component\HttpFoundation\RedirectResponse
407 */
408 public function toggleArchiveAction(Request $request, Entry $entry)
409 {
410 $this->checkUserAction($entry);
411
412 $entry->toggleArchive();
413 $this->getDoctrine()->getManager()->flush();
414
415 $message = 'flashes.entry.notice.entry_unarchived';
416 if ($entry->isArchived()) {
417 $message = 'flashes.entry.notice.entry_archived';
418 }
419
420 $this->get('session')->getFlashBag()->add(
421 'notice',
422 $message
423 );
424
425 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers->get('referer'));
426
427 return $this->redirect($redirectUrl);
428 }
429
430 /**
431 * Changes starred status for an entry.
432 *
433 * @param Request $request
434 * @param Entry $entry
435 *
436 * @Route("/star/{id}", requirements={"id" = "\d+"}, name="star_entry")
437 *
438 * @return \Symfony\Component\HttpFoundation\RedirectResponse
439 */
440 public function toggleStarAction(Request $request, Entry $entry)
441 {
442 $this->checkUserAction($entry);
443
444 $entry->toggleStar();
445 $this->getDoctrine()->getManager()->flush();
446
447 $message = 'flashes.entry.notice.entry_unstarred';
448 if ($entry->isStarred()) {
449 $message = 'flashes.entry.notice.entry_starred';
450 }
451
452 $this->get('session')->getFlashBag()->add(
453 'notice',
454 $message
455 );
456
457 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers->get('referer'));
458
459 return $this->redirect($redirectUrl);
460 }
461
462 /**
463 * Deletes entry and redirect to the homepage or the last viewed page.
464 *
465 * @param Entry $entry
466 *
467 * @Route("/delete/{id}", requirements={"id" = "\d+"}, name="delete_entry")
468 *
469 * @return \Symfony\Component\HttpFoundation\RedirectResponse
470 */
471 public function deleteEntryAction(Request $request, Entry $entry)
472 {
473 $this->checkUserAction($entry);
474
475 // generates the view url for this entry to check for redirection later
476 // to avoid redirecting to the deleted entry. Ugh.
477 $url = $this->generateUrl(
478 'view',
479 ['id' => $entry->getId()],
480 UrlGeneratorInterface::ABSOLUTE_PATH
481 );
482
483 // entry deleted, dispatch event about it!
484 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry));
485
486 $em = $this->getDoctrine()->getManager();
487 $em->remove($entry);
488 $em->flush();
489
490 $this->get('session')->getFlashBag()->add(
491 'notice',
492 'flashes.entry.notice.entry_deleted'
493 );
494
495 // don't redirect user to the deleted entry (check that the referer doesn't end with the same url)
496 $referer = $request->headers->get('referer');
497 $to = (1 !== preg_match('#'.$url.'$#i', $referer) ? $referer : null);
498
499 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to);
500
501 return $this->redirect($redirectUrl);
502 }
503
504 /**
505 * Check if the logged user can manage the given entry.
506 *
507 * @param Entry $entry
508 */
509 private function checkUserAction(Entry $entry)
510 {
511 if (null === $this->getUser() || $this->getUser()->getId() != $entry->getUser()->getId()) {
512 throw $this->createAccessDeniedException('You can not access this entry.');
513 }
514 }
515
516 /**
517 * Check for existing entry, if it exists, redirect to it with a message.
518 *
519 * @param Entry $entry
520 *
521 * @return Entry|bool
522 */
523 private function checkIfEntryAlreadyExists(Entry $entry)
524 {
525 return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId());
526 }
527
528 /**
529 * Get public URL for entry (and generate it if necessary).
530 *
531 * @param Entry $entry
532 *
533 * @Route("/share/{id}", requirements={"id" = "\d+"}, name="share")
534 *
535 * @return \Symfony\Component\HttpFoundation\Response
536 */
537 public function shareAction(Entry $entry)
538 {
539 $this->checkUserAction($entry);
540
541 if (null === $entry->getUid()) {
542 $entry->generateUid();
543
544 $em = $this->getDoctrine()->getManager();
545 $em->persist($entry);
546 $em->flush();
547 }
548
549 return $this->redirect($this->generateUrl('share_entry', [
550 'uid' => $entry->getUid(),
551 ]));
552 }
553
554 /**
555 * Disable public sharing for an entry.
556 *
557 * @param Entry $entry
558 *
559 * @Route("/share/delete/{id}", requirements={"id" = "\d+"}, name="delete_share")
560 *
561 * @return \Symfony\Component\HttpFoundation\Response
562 */
563 public function deleteShareAction(Entry $entry)
564 {
565 $this->checkUserAction($entry);
566
567 $entry->cleanUid();
568
569 $em = $this->getDoctrine()->getManager();
570 $em->persist($entry);
571 $em->flush();
572
573 return $this->redirect($this->generateUrl('view', [
574 'id' => $entry->getId(),
575 ]));
576 }
577
578 /**
579 * Ability to view a content publicly.
580 *
581 * @param Entry $entry
582 *
583 * @Route("/share/{uid}", requirements={"uid" = ".+"}, name="share_entry")
584 * @Cache(maxage="25200", smaxage="25200", public=true)
585 *
586 * @return \Symfony\Component\HttpFoundation\Response
587 */
588 public function shareEntryAction(Entry $entry)
589 {
590 if (!$this->get('craue_config')->get('share_public')) {
591 throw $this->createAccessDeniedException('Sharing an entry is disabled for this user.');
592 }
593
594 return $this->render(
595 '@WallabagCore/themes/common/Entry/share.html.twig',
596 ['entry' => $entry]
597 );
598 }
599
600 /**
601 * Shows untagged articles for current user.
602 *
603 * @param Request $request
604 * @param int $page
605 *
606 * @Route("/untagged/list/{page}", name="untagged", defaults={"page" = "1"})
607 *
608 * @return \Symfony\Component\HttpFoundation\Response
609 */
610 public function showUntaggedEntriesAction(Request $request, $page)
611 {
612 return $this->showEntries('untagged', $request, $page);
613 }
614 }