]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/ApiBundle/Controller/WallabagRestController.php
CS
[github/wallabag/wallabag.git] / src / Wallabag / ApiBundle / Controller / WallabagRestController.php
1 <?php
2
3 namespace Wallabag\ApiBundle\Controller;
4
5 use FOS\RestBundle\Controller\FOSRestController;
6 use Hateoas\Configuration\Route as HateoasRoute;
7 use Hateoas\Representation\Factory\PagerfantaFactory;
8 use Nelmio\ApiDocBundle\Annotation\ApiDoc;
9 use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
10 use Symfony\Component\HttpFoundation\Request;
11 use Symfony\Component\HttpFoundation\JsonResponse;
12 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
13 use Symfony\Component\Security\Core\Exception\AccessDeniedException;
14 use Wallabag\CoreBundle\Entity\Entry;
15 use Wallabag\CoreBundle\Entity\Tag;
16 use Wallabag\AnnotationBundle\Entity\Annotation;
17
18 class WallabagRestController extends FOSRestController
19 {
20 private function validateAuthentication()
21 {
22 if (false === $this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
23 throw new AccessDeniedException();
24 }
25 }
26
27 /**
28 * Check if an entry exist by url.
29 *
30 * @ApiDoc(
31 * parameters={
32 * {"name"="url", "dataType"="string", "required"=true, "format"="An url", "description"="Url to check if it exists"},
33 * {"name"="urls", "dataType"="string", "required"=false, "format"="An array of urls (?urls[]=http...&urls[]=http...)", "description"="Urls (as an array) to check if it exists"}
34 * }
35 * )
36 *
37 * @return JsonResponse
38 */
39 public function getEntriesExistsAction(Request $request)
40 {
41 $this->validateAuthentication();
42
43 $urls = $request->query->get('urls', []);
44
45 // handle multiple urls first
46 if (!empty($urls)) {
47 $results = [];
48 foreach ($urls as $url) {
49 $res = $this->getDoctrine()
50 ->getRepository('WallabagCoreBundle:Entry')
51 ->findByUrlAndUserId($url, $this->getUser()->getId());
52
53 $results[$url] = false === $res ? false : true;
54 }
55
56 $json = $this->get('serializer')->serialize($results, 'json');
57
58 return (new JsonResponse())->setJson($json);
59 }
60
61 // let's see if it is a simple url?
62 $url = $request->query->get('url', '');
63
64 if (empty($url)) {
65 throw $this->createAccessDeniedException('URL is empty?, logged user id: '.$this->getUser()->getId());
66 }
67
68 $res = $this->getDoctrine()
69 ->getRepository('WallabagCoreBundle:Entry')
70 ->findByUrlAndUserId($url, $this->getUser()->getId());
71
72 $exists = false === $res ? false : true;
73
74 $json = $this->get('serializer')->serialize(['exists' => $exists], 'json');
75
76 return (new JsonResponse())->setJson($json);
77 }
78
79 /**
80 * Retrieve all entries. It could be filtered by many options.
81 *
82 * @ApiDoc(
83 * parameters={
84 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by archived status."},
85 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by starred status."},
86 * {"name"="sort", "dataType"="string", "required"=false, "format"="'created' or 'updated', default 'created'", "description"="sort entries by date."},
87 * {"name"="order", "dataType"="string", "required"=false, "format"="'asc' or 'desc', default 'desc'", "description"="order of sort."},
88 * {"name"="page", "dataType"="integer", "required"=false, "format"="default '1'", "description"="what page you want."},
89 * {"name"="perPage", "dataType"="integer", "required"=false, "format"="default'30'", "description"="results per page."},
90 * {"name"="tags", "dataType"="string", "required"=false, "format"="api,rest", "description"="a list of tags url encoded. Will returns entries that matches ALL tags."},
91 * {"name"="since", "dataType"="integer", "required"=false, "format"="default '0'", "description"="The timestamp since when you want entries updated."},
92 * }
93 * )
94 *
95 * @return JsonResponse
96 */
97 public function getEntriesAction(Request $request)
98 {
99 $this->validateAuthentication();
100
101 $isArchived = (null === $request->query->get('archive')) ? null : (bool) $request->query->get('archive');
102 $isStarred = (null === $request->query->get('starred')) ? null : (bool) $request->query->get('starred');
103 $sort = $request->query->get('sort', 'created');
104 $order = $request->query->get('order', 'desc');
105 $page = (int) $request->query->get('page', 1);
106 $perPage = (int) $request->query->get('perPage', 30);
107 $tags = $request->query->get('tags', '');
108 $since = $request->query->get('since', 0);
109
110 $pager = $this->getDoctrine()
111 ->getRepository('WallabagCoreBundle:Entry')
112 ->findEntries($this->getUser()->getId(), $isArchived, $isStarred, $sort, $order, $since, $tags);
113
114 $pager->setCurrentPage($page);
115 $pager->setMaxPerPage($perPage);
116
117 $pagerfantaFactory = new PagerfantaFactory('page', 'perPage');
118 $paginatedCollection = $pagerfantaFactory->createRepresentation(
119 $pager,
120 new HateoasRoute(
121 'api_get_entries',
122 [
123 'archive' => $isArchived,
124 'starred' => $isStarred,
125 'sort' => $sort,
126 'order' => $order,
127 'page' => $page,
128 'perPage' => $perPage,
129 'tags' => $tags,
130 'since' => $since,
131 ],
132 UrlGeneratorInterface::ABSOLUTE_URL
133 )
134 );
135
136 $json = $this->get('serializer')->serialize($paginatedCollection, 'json');
137
138 return (new JsonResponse())->setJson($json);
139 }
140
141 /**
142 * Retrieve a single entry.
143 *
144 * @ApiDoc(
145 * requirements={
146 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
147 * }
148 * )
149 *
150 * @return JsonResponse
151 */
152 public function getEntryAction(Entry $entry)
153 {
154 $this->validateAuthentication();
155 $this->validateUserAccess($entry->getUser()->getId());
156
157 $json = $this->get('serializer')->serialize($entry, 'json');
158
159 return (new JsonResponse())->setJson($json);
160 }
161
162 /**
163 * Retrieve a single entry as a predefined format.
164 *
165 * @ApiDoc(
166 * requirements={
167 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
168 * }
169 * )
170 *
171 * @return Response
172 */
173 public function getEntryExportAction(Entry $entry, Request $request)
174 {
175 $this->validateAuthentication();
176 $this->validateUserAccess($entry->getUser()->getId());
177
178 return $this->get('wallabag_core.helper.entries_export')
179 ->setEntries($entry)
180 ->updateTitle('entry')
181 ->exportAs($request->attributes->get('_format'));
182 }
183
184 /**
185 * Create an entry.
186 *
187 * @ApiDoc(
188 * parameters={
189 * {"name"="url", "dataType"="string", "required"=true, "format"="http://www.test.com/article.html", "description"="Url for the entry."},
190 * {"name"="title", "dataType"="string", "required"=false, "description"="Optional, we'll get the title from the page."},
191 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
192 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"},
193 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already archived"},
194 * }
195 * )
196 *
197 * @return JsonResponse
198 */
199 public function postEntriesAction(Request $request)
200 {
201 $this->validateAuthentication();
202
203 $url = $request->request->get('url');
204 $title = $request->request->get('title');
205 $isArchived = $request->request->get('archive');
206 $isStarred = $request->request->get('starred');
207
208 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($url, $this->getUser()->getId());
209
210 if (false === $entry) {
211 $entry = $this->get('wallabag_core.content_proxy')->updateEntry(
212 new Entry($this->getUser()),
213 $url
214 );
215 }
216
217 if (!is_null($title)) {
218 $entry->setTitle($title);
219 }
220
221 $tags = $request->request->get('tags', '');
222 if (!empty($tags)) {
223 $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags);
224 }
225
226 if (!is_null($isStarred)) {
227 $entry->setStarred((bool) $isStarred);
228 }
229
230 if (!is_null($isArchived)) {
231 $entry->setArchived((bool) $isArchived);
232 }
233
234 $em = $this->getDoctrine()->getManager();
235 $em->persist($entry);
236
237 $em->flush();
238
239 $json = $this->get('serializer')->serialize($entry, 'json');
240
241 return (new JsonResponse())->setJson($json);
242 }
243
244 /**
245 * Change several properties of an entry.
246 *
247 * @ApiDoc(
248 * requirements={
249 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
250 * },
251 * parameters={
252 * {"name"="title", "dataType"="string", "required"=false},
253 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
254 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="archived the entry."},
255 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="starred the entry."},
256 * }
257 * )
258 *
259 * @return JsonResponse
260 */
261 public function patchEntriesAction(Entry $entry, Request $request)
262 {
263 $this->validateAuthentication();
264 $this->validateUserAccess($entry->getUser()->getId());
265
266 $title = $request->request->get('title');
267 $isArchived = $request->request->get('archive');
268 $isStarred = $request->request->get('starred');
269
270 if (!is_null($title)) {
271 $entry->setTitle($title);
272 }
273
274 if (!is_null($isArchived)) {
275 $entry->setArchived((bool) $isArchived);
276 }
277
278 if (!is_null($isStarred)) {
279 $entry->setStarred((bool) $isStarred);
280 }
281
282 $tags = $request->request->get('tags', '');
283 if (!empty($tags)) {
284 $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags);
285 }
286
287 $em = $this->getDoctrine()->getManager();
288 $em->flush();
289
290 $json = $this->get('serializer')->serialize($entry, 'json');
291
292 return (new JsonResponse())->setJson($json);
293 }
294
295 /**
296 * Delete **permanently** an entry.
297 *
298 * @ApiDoc(
299 * requirements={
300 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
301 * }
302 * )
303 *
304 * @return JsonResponse
305 */
306 public function deleteEntriesAction(Entry $entry)
307 {
308 $this->validateAuthentication();
309 $this->validateUserAccess($entry->getUser()->getId());
310
311 $em = $this->getDoctrine()->getManager();
312 $em->remove($entry);
313 $em->flush();
314
315 $json = $this->get('serializer')->serialize($entry, 'json');
316
317 return (new JsonResponse())->setJson($json);
318 }
319
320 /**
321 * Retrieve all tags for an entry.
322 *
323 * @ApiDoc(
324 * requirements={
325 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
326 * }
327 * )
328 *
329 * @return JsonResponse
330 */
331 public function getEntriesTagsAction(Entry $entry)
332 {
333 $this->validateAuthentication();
334 $this->validateUserAccess($entry->getUser()->getId());
335
336 $json = $this->get('serializer')->serialize($entry->getTags(), 'json');
337
338 return (new JsonResponse())->setJson($json);
339 }
340
341 /**
342 * Add one or more tags to an entry.
343 *
344 * @ApiDoc(
345 * requirements={
346 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
347 * },
348 * parameters={
349 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
350 * }
351 * )
352 *
353 * @return JsonResponse
354 */
355 public function postEntriesTagsAction(Request $request, Entry $entry)
356 {
357 $this->validateAuthentication();
358 $this->validateUserAccess($entry->getUser()->getId());
359
360 $tags = $request->request->get('tags', '');
361 if (!empty($tags)) {
362 $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags);
363 }
364
365 $em = $this->getDoctrine()->getManager();
366 $em->persist($entry);
367 $em->flush();
368
369 $json = $this->get('serializer')->serialize($entry, 'json');
370
371 return (new JsonResponse())->setJson($json);
372 }
373
374 /**
375 * Permanently remove one tag for an entry.
376 *
377 * @ApiDoc(
378 * requirements={
379 * {"name"="tag", "dataType"="integer", "requirement"="\w+", "description"="The tag ID"},
380 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
381 * }
382 * )
383 *
384 * @return JsonResponse
385 */
386 public function deleteEntriesTagsAction(Entry $entry, Tag $tag)
387 {
388 $this->validateAuthentication();
389 $this->validateUserAccess($entry->getUser()->getId());
390
391 $entry->removeTag($tag);
392 $em = $this->getDoctrine()->getManager();
393 $em->persist($entry);
394 $em->flush();
395
396 $json = $this->get('serializer')->serialize($entry, 'json');
397
398 return (new JsonResponse())->setJson($json);
399 }
400
401 /**
402 * Retrieve all tags.
403 *
404 * @ApiDoc()
405 *
406 * @return JsonResponse
407 */
408 public function getTagsAction()
409 {
410 $this->validateAuthentication();
411
412 $tags = $this->getDoctrine()
413 ->getRepository('WallabagCoreBundle:Tag')
414 ->findAllTags($this->getUser()->getId());
415
416 $json = $this->get('serializer')->serialize($tags, 'json');
417
418 return (new JsonResponse())->setJson($json);
419 }
420
421 /**
422 * Permanently remove one tag from **every** entry.
423 *
424 * @ApiDoc(
425 * requirements={
426 * {"name"="tag", "dataType"="string", "required"=true, "requirement"="\w+", "description"="Tag as a string"}
427 * }
428 * )
429 *
430 * @return JsonResponse
431 */
432 public function deleteTagLabelAction(Request $request)
433 {
434 $this->validateAuthentication();
435 $label = $request->request->get('tag', '');
436
437 $tag = $this->getDoctrine()->getRepository('WallabagCoreBundle:Tag')->findOneByLabel($label);
438
439 if (empty($tag)) {
440 throw $this->createNotFoundException('Tag not found');
441 }
442
443 $this->getDoctrine()
444 ->getRepository('WallabagCoreBundle:Entry')
445 ->removeTag($this->getUser()->getId(), $tag);
446
447 $this->cleanOrphanTag($tag);
448
449 $json = $this->get('serializer')->serialize($tag, 'json');
450
451 return (new JsonResponse())->setJson($json);
452 }
453
454 /**
455 * Permanently remove some tags from **every** entry.
456 *
457 * @ApiDoc(
458 * requirements={
459 * {"name"="tags", "dataType"="string", "required"=true, "format"="tag1,tag2", "description"="Tags as strings (comma splitted)"}
460 * }
461 * )
462 *
463 * @return JsonResponse
464 */
465 public function deleteTagsLabelAction(Request $request)
466 {
467 $this->validateAuthentication();
468
469 $tagsLabels = $request->request->get('tags', '');
470
471 $tags = [];
472
473 foreach (explode(',', $tagsLabels) as $tagLabel) {
474 $tagEntity = $this->getDoctrine()->getRepository('WallabagCoreBundle:Tag')->findOneByLabel($tagLabel);
475
476 if (!empty($tagEntity)) {
477 $tags[] = $tagEntity;
478 }
479 }
480
481 if (empty($tags)) {
482 throw $this->createNotFoundException('Tags not found');
483 }
484
485 $this->getDoctrine()
486 ->getRepository('WallabagCoreBundle:Entry')
487 ->removeTags($this->getUser()->getId(), $tags);
488
489 $this->cleanOrphanTag($tags);
490
491 $json = $this->get('serializer')->serialize($tags, 'json');
492
493 return (new JsonResponse())->setJson($json);
494 }
495
496 /**
497 * Permanently remove one tag from **every** entry.
498 *
499 * @ApiDoc(
500 * requirements={
501 * {"name"="tag", "dataType"="integer", "requirement"="\w+", "description"="The tag"}
502 * }
503 * )
504 *
505 * @return JsonResponse
506 */
507 public function deleteTagAction(Tag $tag)
508 {
509 $this->validateAuthentication();
510
511 $this->getDoctrine()
512 ->getRepository('WallabagCoreBundle:Entry')
513 ->removeTag($this->getUser()->getId(), $tag);
514
515 $this->cleanOrphanTag($tag);
516
517 $json = $this->get('serializer')->serialize($tag, 'json');
518
519 return (new JsonResponse())->setJson($json);
520 }
521
522 /**
523 * Retrieve annotations for an entry.
524 *
525 * @ApiDoc(
526 * requirements={
527 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
528 * }
529 * )
530 *
531 * @param Entry $entry
532 *
533 * @return JsonResponse
534 */
535 public function getAnnotationsAction(Entry $entry)
536 {
537 $this->validateAuthentication();
538
539 return $this->forward('WallabagApiBundle:WallabagRest:getAnnotations', [
540 'entry' => $entry,
541 ]);
542 }
543
544 /**
545 * Creates a new annotation.
546 *
547 * @param Request $request
548 * @param Entry $entry
549 *
550 * @return JsonResponse
551 * @ApiDoc(
552 * requirements={
553 * {"name"="ranges", "dataType"="array", "requirement"="\w+", "description"="The range array for the annotation"},
554 * {"name"="quote", "dataType"="string", "required"=false, "description"="Optional, quote for the annotation"},
555 * {"name"="text", "dataType"="string", "required"=true, "description"=""},
556 * }
557 * )
558 */
559 public function postAnnotationAction(Request $request, Entry $entry)
560 {
561 $this->validateAuthentication();
562
563 return $this->forward('WallabagApiBundle:WallabagRest:postAnnotation', [
564 'request' => $request,
565 'entry' => $entry,
566 ]);
567 }
568
569 /**
570 * Updates an annotation.
571 *
572 * @ApiDoc(
573 * requirements={
574 * {"name"="annotation", "dataType"="string", "requirement"="\w+", "description"="The annotation ID"}
575 * }
576 * )
577 *
578 * @ParamConverter("annotation", class="WallabagAnnotationBundle:Annotation")
579 *
580 * @param Annotation $annotation
581 * @param Request $request
582 *
583 * @return JsonResponse
584 */
585 public function putAnnotationAction(Annotation $annotation, Request $request)
586 {
587 $this->validateAuthentication();
588
589 return $this->forward('WallabagApiBundle:WallabagRest:putAnnotation', [
590 'annotation' => $annotation,
591 'request' => $request,
592 ]);
593 }
594
595 /**
596 * Removes an annotation.
597 *
598 * @ApiDoc(
599 * requirements={
600 * {"name"="annotation", "dataType"="string", "requirement"="\w+", "description"="The annotation ID"}
601 * }
602 * )
603 *
604 * @ParamConverter("annotation", class="WallabagAnnotationBundle:Annotation")
605 *
606 * @param Annotation $annotation
607 *
608 * @return JsonResponse
609 */
610 public function deleteAnnotationAction(Annotation $annotation)
611 {
612 $this->validateAuthentication();
613
614 return $this->forward('WallabagApiBundle:WallabagRest:deleteAnnotation', [
615 'annotation' => $annotation,
616 ]);
617 }
618
619 /**
620 * Retrieve version number.
621 *
622 * @ApiDoc()
623 *
624 * @return JsonResponse
625 */
626 public function getVersionAction()
627 {
628 $version = $this->container->getParameter('wallabag_core.version');
629
630 $json = $this->get('serializer')->serialize($version, 'json');
631
632 return (new JsonResponse())->setJson($json);
633 }
634
635 /**
636 * Remove orphan tag in case no entries are associated to it.
637 *
638 * @param Tag|array $tags
639 */
640 private function cleanOrphanTag($tags)
641 {
642 if (!is_array($tags)) {
643 $tags = [$tags];
644 }
645
646 $em = $this->getDoctrine()->getManager();
647
648 foreach ($tags as $tag) {
649 if (count($tag->getEntries()) === 0) {
650 $em->remove($tag);
651 }
652 }
653
654 $em->flush();
655 }
656
657 /**
658 * Validate that the first id is equal to the second one.
659 * If not, throw exception. It means a user try to access information from an other user.
660 *
661 * @param int $requestUserId User id from the requested source
662 */
663 private function validateUserAccess($requestUserId)
664 {
665 $user = $this->get('security.token_storage')->getToken()->getUser();
666 if ($requestUserId != $user->getId()) {
667 throw $this->createAccessDeniedException('Access forbidden. Entry user id: '.$requestUserId.', logged user id: '.$user->getId());
668 }
669 }
670 }