]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Controller/EntryController.php
Avoid losing entry when fetching fail
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Controller / EntryController.php
CommitLineData
9d50517c
NL
1<?php
2
ad4d1caa 3namespace Wallabag\CoreBundle\Controller;
9d50517c 4
619cc453 5use Pagerfanta\Adapter\DoctrineORMAdapter;
671a2b88 6use Pagerfanta\Exception\OutOfRangeCurrentPageException;
9d50517c
NL
7use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
8use Symfony\Bundle\FrameworkBundle\Controller\Controller;
163eae0b 9use Symfony\Component\HttpFoundation\Request;
2863bf2a 10use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
be463487 11use Wallabag\CoreBundle\Entity\Entry;
b0b893ea 12use Wallabag\CoreBundle\Form\Type\EntryFilterType;
619cc453
JB
13use Wallabag\CoreBundle\Form\Type\EditEntryType;
14use Wallabag\CoreBundle\Form\Type\NewEntryType;
222e09f1 15use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
9d50517c
NL
16
17class EntryController extends Controller
18{
880a0e1c 19 /**
59b97fae
JB
20 * Fetch content and update entry.
21 * In case it fails, entry will return to avod loosing the data.
22 *
23 * @param Entry $entry
24 * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded
25 *
26 * @return Entry
880a0e1c 27 */
59b97fae 28 private function updateEntry(Entry $entry, $prefixMessage = 'entry_saved')
880a0e1c 29 {
59b97fae
JB
30 // put default title in case of fetching content failed
31 $entry->setTitle('No title found');
32
33 $message = 'flashes.entry.notice.'.$prefixMessage;
34
880a0e1c
NL
35 try {
36 $entry = $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
880a0e1c 37 } catch (\Exception $e) {
39ba51ca
JB
38 $this->get('logger')->error('Error while saving an entry', [
39 'exception' => $e,
40 'entry' => $entry,
41 ]);
42
59b97fae 43 $message = 'flashes.entry.notice.'.$prefixMessage.'_failed';
880a0e1c
NL
44 }
45
59b97fae
JB
46 $this->get('session')->getFlashBag()->add('notice', $message);
47
48 return $entry;
880a0e1c
NL
49 }
50
b84a8055 51 /**
3d2b2d62
J
52 * @param Request $request
53 *
053b9568 54 * @Route("/new-entry", name="new_entry")
3d2b2d62 55 *
b84a8055
NL
56 * @return \Symfony\Component\HttpFoundation\Response
57 */
053b9568 58 public function addEntryFormAction(Request $request)
b84a8055 59 {
3b815d2d 60 $entry = new Entry($this->getUser());
b84a8055 61
5c895a7f 62 $form = $this->createForm(NewEntryType::class, $entry);
b84a8055
NL
63
64 $form->handleRequest($request);
65
66 if ($form->isValid()) {
b00a89e0 67 $existingEntry = $this->checkIfEntryAlreadyExists($entry);
dda57bb9 68
5a4bbcc9 69 if (false !== $existingEntry) {
dda57bb9
NL
70 $this->get('session')->getFlashBag()->add(
71 'notice',
4094ea47 72 $this->get('translator')->trans('flashes.entry.notice.entry_already_saved', ['%date%' => $existingEntry->getCreatedAt()->format('d-m-Y')])
dda57bb9
NL
73 );
74
4094ea47 75 return $this->redirect($this->generateUrl('view', ['id' => $existingEntry->getId()]));
dda57bb9
NL
76 }
77
59b97fae 78 $this->updateEntry($entry);
39ba51ca 79
59b97fae
JB
80 $em = $this->getDoctrine()->getManager();
81 $em->persist($entry);
82 $em->flush();
b84a8055
NL
83
84 return $this->redirect($this->generateUrl('homepage'));
85 }
86
4094ea47 87 return $this->render('WallabagCoreBundle:Entry:new_form.html.twig', [
b84a8055 88 'form' => $form->createView(),
4094ea47 89 ]);
b84a8055
NL
90 }
91
880a0e1c
NL
92 /**
93 * @param Request $request
94 *
95 * @Route("/bookmarklet", name="bookmarklet")
96 *
97 * @return \Symfony\Component\HttpFoundation\Response
98 */
5f8a7857 99 public function addEntryViaBookmarkletAction(Request $request)
880a0e1c
NL
100 {
101 $entry = new Entry($this->getUser());
102 $entry->setUrl($request->get('url'));
f652f41d 103
b00a89e0 104 if (false === $this->checkIfEntryAlreadyExists($entry)) {
f652f41d 105 $this->updateEntry($entry);
59b97fae
JB
106
107 $em = $this->getDoctrine()->getManager();
108 $em->persist($entry);
109 $em->flush();
f652f41d 110 }
880a0e1c
NL
111
112 return $this->redirect($this->generateUrl('homepage'));
113 }
114
053b9568 115 /**
053b9568
NL
116 * @Route("/new", name="new")
117 *
118 * @return \Symfony\Component\HttpFoundation\Response
119 */
4d0ec0e7 120 public function addEntryAction()
053b9568
NL
121 {
122 return $this->render('WallabagCoreBundle:Entry:new.html.twig');
123 }
124
82d6d9cb
JB
125 /**
126 * Edit an entry content.
127 *
128 * @param Request $request
129 * @param Entry $entry
130 *
131 * @Route("/edit/{id}", requirements={"id" = "\d+"}, name="edit")
132 *
133 * @return \Symfony\Component\HttpFoundation\Response
134 */
135 public function editEntryAction(Request $request, Entry $entry)
136 {
137 $this->checkUserAction($entry);
138
5c895a7f 139 $form = $this->createForm(EditEntryType::class, $entry);
82d6d9cb
JB
140
141 $form->handleRequest($request);
142
143 if ($form->isValid()) {
144 $em = $this->getDoctrine()->getManager();
145 $em->persist($entry);
146 $em->flush();
147
148 $this->get('session')->getFlashBag()->add(
149 'notice',
4204a06b 150 'flashes.entry.notice.entry_updated'
82d6d9cb
JB
151 );
152
4094ea47 153 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
82d6d9cb
JB
154 }
155
4094ea47 156 return $this->render('WallabagCoreBundle:Entry:edit.html.twig', [
82d6d9cb 157 'form' => $form->createView(),
4094ea47 158 ]);
82d6d9cb
JB
159 }
160
89659c9e
NL
161 /**
162 * Shows all entries for current user.
163 *
164 * @param Request $request
165 * @param int $page
166 *
167 * @Route("/all/list/{page}", name="all", defaults={"page" = "1"})
168 *
169 * @return \Symfony\Component\HttpFoundation\Response
170 */
171 public function showAllAction(Request $request, $page)
172 {
2b7a4889 173 return $this->showEntries('all', $request, $page);
89659c9e
NL
174 }
175
9d50517c 176 /**
4346a860 177 * Shows unread entries for current user.
163eae0b 178 *
26864574
NL
179 * @param Request $request
180 * @param int $page
181 *
9fb6ac83 182 * @Route("/unread/list/{page}", name="unread", defaults={"page" = "1"})
3d2b2d62 183 *
163eae0b 184 * @return \Symfony\Component\HttpFoundation\Response
9d50517c 185 */
26864574 186 public function showUnreadAction(Request $request, $page)
9d50517c 187 {
5c072d2b
NL
188 // load the quickstart if no entry in database
189 if ($page == 1 && $this->get('wallabag_core.entry_repository')->countAllEntriesByUsername($this->getUser()->getId()) == 0) {
190 return $this->redirect($this->generateUrl('quickstart'));
191 }
192
0ab7404f 193 return $this->showEntries('unread', $request, $page);
9d50517c 194 }
bd9f0815
NL
195
196 /**
4346a860 197 * Shows read entries for current user.
163eae0b 198 *
26864574
NL
199 * @param Request $request
200 * @param int $page
201 *
9fb6ac83 202 * @Route("/archive/list/{page}", name="archive", defaults={"page" = "1"})
3d2b2d62 203 *
163eae0b 204 * @return \Symfony\Component\HttpFoundation\Response
bd9f0815 205 */
26864574 206 public function showArchiveAction(Request $request, $page)
bd9f0815 207 {
0ab7404f
JB
208 return $this->showEntries('archive', $request, $page);
209 }
210
211 /**
212 * Shows starred entries for current user.
213 *
214 * @param Request $request
215 * @param int $page
216 *
217 * @Route("/starred/list/{page}", name="starred", defaults={"page" = "1"})
218 *
219 * @return \Symfony\Component\HttpFoundation\Response
220 */
221 public function showStarredAction(Request $request, $page)
222 {
223 return $this->showEntries('starred', $request, $page);
224 }
26864574 225
0ab7404f
JB
226 /**
227 * Global method to retrieve entries depending on the given type
228 * It returns the response to be send.
229 *
230 * @param string $type Entries type: unread, starred or archive
231 * @param Request $request
232 * @param int $page
233 *
234 * @return \Symfony\Component\HttpFoundation\Response
235 */
236 private function showEntries($type, Request $request, $page)
237 {
5c072d2b 238 $repository = $this->get('wallabag_core.entry_repository');
0ab7404f
JB
239
240 switch ($type) {
b6520f0b
NL
241 case 'untagged':
242 $qb = $repository->getBuilderForUntaggedByUser($this->getUser()->getId());
243
244 break;
0ab7404f
JB
245 case 'starred':
246 $qb = $repository->getBuilderForStarredByUser($this->getUser()->getId());
247 break;
248
249 case 'archive':
250 $qb = $repository->getBuilderForArchiveByUser($this->getUser()->getId());
251 break;
252
253 case 'unread':
254 $qb = $repository->getBuilderForUnreadByUser($this->getUser()->getId());
255 break;
256
2b7a4889
NL
257 case 'all':
258 $qb = $repository->getBuilderForAllByUser($this->getUser()->getId());
259 break;
260
0ab7404f
JB
261 default:
262 throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
263 }
264
1d76102a 265 $form = $this->createForm(EntryFilterType::class);
9fb6ac83 266
26864574
NL
267 if ($request->query->has($form->getName())) {
268 // manually bind values from the request
269 $form->submit($request->query->get($form->getName()));
270
271 // build the query from the given form object
0ab7404f 272 $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $qb);
26864574
NL
273 }
274
0ab7404f 275 $pagerAdapter = new DoctrineORMAdapter($qb->getQuery());
26864574 276
891456ba
NL
277 $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')
278 ->prepare($pagerAdapter, $page);
279
671a2b88
ML
280 try {
281 $entries->setCurrentPage($page);
282 } catch (OutOfRangeCurrentPageException $e) {
283 if ($page > 1) {
4094ea47 284 return $this->redirect($this->generateUrl($type, ['page' => $entries->getNbPages()]), 302);
671a2b88
ML
285 }
286 }
bd9f0815
NL
287
288 return $this->render(
ad4d1caa 289 'WallabagCoreBundle:Entry:entries.html.twig',
4094ea47 290 [
8ce32af6
JB
291 'form' => $form->createView(),
292 'entries' => $entries,
293 'currentPage' => $page,
4094ea47 294 ]
bd9f0815 295 );
bd9f0815
NL
296 }
297
298 /**
4346a860 299 * Shows entry content.
163eae0b 300 *
3d2b2d62
J
301 * @param Entry $entry
302 *
bd9f0815 303 * @Route("/view/{id}", requirements={"id" = "\d+"}, name="view")
3d2b2d62 304 *
163eae0b 305 * @return \Symfony\Component\HttpFoundation\Response
bd9f0815 306 */
be463487 307 public function viewAction(Entry $entry)
bd9f0815 308 {
3d2b2d62
J
309 $this->checkUserAction($entry);
310
bd9f0815 311 return $this->render(
ad4d1caa 312 'WallabagCoreBundle:Entry:entry.html.twig',
4094ea47 313 ['entry' => $entry]
bd9f0815 314 );
163eae0b
NL
315 }
316
831b02aa
JB
317 /**
318 * Reload an entry.
319 * Refetch content from the website and make it readable again.
320 *
321 * @param Entry $entry
322 *
323 * @Route("/reload/{id}", requirements={"id" = "\d+"}, name="reload_entry")
324 *
325 * @return \Symfony\Component\HttpFoundation\RedirectResponse
326 */
327 public function reloadAction(Entry $entry)
328 {
329 $this->checkUserAction($entry);
330
59b97fae 331 $this->updateEntry($entry, 'entry_reloaded');
831b02aa 332
59b97fae
JB
333 $em = $this->getDoctrine()->getManager();
334 $em->persist($entry);
335 $em->flush();
831b02aa 336
4094ea47 337 return $this->redirect($this->generateUrl('view', ['id' => $entry->getId()]));
831b02aa
JB
338 }
339
163eae0b 340 /**
4346a860 341 * Changes read status for an entry.
163eae0b 342 *
3d2b2d62
J
343 * @param Request $request
344 * @param Entry $entry
345 *
163eae0b 346 * @Route("/archive/{id}", requirements={"id" = "\d+"}, name="archive_entry")
3d2b2d62 347 *
163eae0b
NL
348 * @return \Symfony\Component\HttpFoundation\RedirectResponse
349 */
be463487 350 public function toggleArchiveAction(Request $request, Entry $entry)
163eae0b 351 {
3d2b2d62
J
352 $this->checkUserAction($entry);
353
163eae0b
NL
354 $entry->toggleArchive();
355 $this->getDoctrine()->getManager()->flush();
356
4204a06b
JB
357 $message = 'flashes.entry.notice.entry_unarchived';
358 if ($entry->isArchived()) {
359 $message = 'flashes.entry.notice.entry_archived';
360 }
361
163eae0b
NL
362 $this->get('session')->getFlashBag()->add(
363 'notice',
4204a06b 364 $message
163eae0b
NL
365 );
366
af497a64
NL
367 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers->get('referer'));
368
369 return $this->redirect($redirectUrl);
163eae0b
NL
370 }
371
372 /**
eecd7e40 373 * Changes starred status for an entry.
163eae0b 374 *
3d2b2d62
J
375 * @param Request $request
376 * @param Entry $entry
377 *
163eae0b 378 * @Route("/star/{id}", requirements={"id" = "\d+"}, name="star_entry")
3d2b2d62 379 *
163eae0b
NL
380 * @return \Symfony\Component\HttpFoundation\RedirectResponse
381 */
be463487 382 public function toggleStarAction(Request $request, Entry $entry)
163eae0b 383 {
3d2b2d62
J
384 $this->checkUserAction($entry);
385
163eae0b
NL
386 $entry->toggleStar();
387 $this->getDoctrine()->getManager()->flush();
388
4204a06b
JB
389 $message = 'flashes.entry.notice.entry_unstarred';
390 if ($entry->isStarred()) {
391 $message = 'flashes.entry.notice.entry_starred';
392 }
393
163eae0b
NL
394 $this->get('session')->getFlashBag()->add(
395 'notice',
4204a06b 396 $message
163eae0b
NL
397 );
398
af497a64
NL
399 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers->get('referer'));
400
401 return $this->redirect($redirectUrl);
163eae0b
NL
402 }
403
404 /**
2863bf2a 405 * Deletes entry and redirect to the homepage or the last viewed page.
163eae0b 406 *
16a3d04c 407 * @param Entry $entry
3d2b2d62 408 *
163eae0b 409 * @Route("/delete/{id}", requirements={"id" = "\d+"}, name="delete_entry")
3d2b2d62 410 *
163eae0b
NL
411 * @return \Symfony\Component\HttpFoundation\RedirectResponse
412 */
18d5f454 413 public function deleteEntryAction(Request $request, Entry $entry)
163eae0b 414 {
3d2b2d62
J
415 $this->checkUserAction($entry);
416
2863bf2a
JB
417 // generates the view url for this entry to check for redirection later
418 // to avoid redirecting to the deleted entry. Ugh.
419 $url = $this->generateUrl(
420 'view',
4094ea47 421 ['id' => $entry->getId()],
ce0e9ec3 422 UrlGeneratorInterface::ABSOLUTE_PATH
2863bf2a
JB
423 );
424
1d147791
NL
425 $em = $this->getDoctrine()->getManager();
426 $em->remove($entry);
427 $em->flush();
163eae0b
NL
428
429 $this->get('session')->getFlashBag()->add(
430 'notice',
4204a06b 431 'flashes.entry.notice.entry_deleted'
163eae0b 432 );
bd9f0815 433
ce0e9ec3
JB
434 // don't redirect user to the deleted entry (check that the referer doesn't end with the same url)
435 $referer = $request->headers->get('referer');
436 $to = (1 !== preg_match('#'.$url.'$#i', $referer) ? $referer : null);
af497a64
NL
437
438 $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($to);
439
440 return $this->redirect($redirectUrl);
bd9f0815 441 }
3d2b2d62
J
442
443 /**
4346a860 444 * Check if the logged user can manage the given entry.
3d2b2d62
J
445 *
446 * @param Entry $entry
447 */
448 private function checkUserAction(Entry $entry)
449 {
f1be7af4 450 if (null === $this->getUser() || $this->getUser()->getId() != $entry->getUser()->getId()) {
82d6d9cb 451 throw $this->createAccessDeniedException('You can not access this entry.');
3d2b2d62
J
452 }
453 }
b00a89e0
NL
454
455 /**
456 * Check for existing entry, if it exists, redirect to it with a message.
457 *
4094ea47 458 * @param Entry $entry
b00a89e0 459 *
4094ea47 460 * @return Entry|bool
b00a89e0 461 */
4094ea47 462 private function checkIfEntryAlreadyExists(Entry $entry)
b00a89e0
NL
463 {
464 return $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($entry->getUrl(), $this->getUser()->getId());
f3d0cb91
NL
465 }
466
f1be7af4
NL
467 /**
468 * Get public URL for entry (and generate it if necessary).
469 *
470 * @param Entry $entry
471 *
472 * @Route("/share/{id}", requirements={"id" = "\d+"}, name="share")
473 *
474 * @return \Symfony\Component\HttpFoundation\Response
475 */
476 public function shareAction(Entry $entry)
477 {
478 $this->checkUserAction($entry);
479
eddda878
JB
480 if (null === $entry->getUuid()) {
481 $entry->generateUuid();
482
483 $em = $this->getDoctrine()->getManager();
484 $em->persist($entry);
485 $em->flush();
f1be7af4
NL
486 }
487
488 return $this->redirect($this->generateUrl('share_entry', [
489 'uuid' => $entry->getUuid(),
490 ]));
491 }
492
493 /**
494 * Disable public sharing for an entry.
495 *
496 * @param Entry $entry
497 *
498 * @Route("/share/delete/{id}", requirements={"id" = "\d+"}, name="delete_share")
499 *
500 * @return \Symfony\Component\HttpFoundation\Response
501 */
502 public function deleteShareAction(Entry $entry)
503 {
504 $this->checkUserAction($entry);
505
506 $entry->cleanUuid();
eddda878 507
f1be7af4
NL
508 $em = $this->getDoctrine()->getManager();
509 $em->persist($entry);
510 $em->flush();
511
512 return $this->redirect($this->generateUrl('view', [
513 'id' => $entry->getId(),
514 ]));
515 }
516
d0545b6b 517 /**
eddda878 518 * Ability to view a content publicly.
f3d0cb91
NL
519 *
520 * @param Entry $entry
521 *
f1be7af4 522 * @Route("/share/{uuid}", requirements={"uuid" = ".+"}, name="share_entry")
eddda878 523 * @Cache(maxage="25200", smaxage="25200", public=true)
f3d0cb91
NL
524 *
525 * @return \Symfony\Component\HttpFoundation\Response
526 */
d0545b6b 527 public function shareEntryAction(Entry $entry)
f3d0cb91 528 {
eddda878
JB
529 if (!$this->get('craue_config')->get('share_public')) {
530 throw $this->createAccessDeniedException('Sharing an entry is disabled for this user.');
531 }
532
f3d0cb91
NL
533 return $this->render(
534 '@WallabagCore/themes/share.html.twig',
eddda878 535 ['entry' => $entry]
f3d0cb91
NL
536 );
537 }
b6520f0b
NL
538
539 /**
540 * Shows untagged articles for current user.
541 *
542 * @param Request $request
543 * @param int $page
544 *
545 * @Route("/untagged/list/{page}", name="untagged", defaults={"page" = "1"})
546 *
547 * @return \Symfony\Component\HttpFoundation\Response
548 */
549 public function showUntaggedEntriesAction(Request $request, $page)
550 {
551 return $this->showEntries('untagged', $request, $page);
552 }
9d50517c 553}