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