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