]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/ApiBundle/Controller/EntryRestController.php
Avoid error when a bad `order` parameter is given
[github/wallabag/wallabag.git] / src / Wallabag / ApiBundle / Controller / EntryRestController.php
1 <?php
2
3 namespace Wallabag\ApiBundle\Controller;
4
5 use Hateoas\Configuration\Route;
6 use Hateoas\Representation\Factory\PagerfantaFactory;
7 use JMS\Serializer\SerializationContext;
8 use Nelmio\ApiDocBundle\Annotation\ApiDoc;
9 use Symfony\Component\HttpFoundation\JsonResponse;
10 use Symfony\Component\HttpFoundation\Request;
11 use Symfony\Component\HttpFoundation\Response;
12 use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
13 use Symfony\Component\HttpKernel\Exception\HttpException;
14 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
15 use Wallabag\CoreBundle\Entity\Entry;
16 use Wallabag\CoreBundle\Entity\Tag;
17 use Wallabag\CoreBundle\Event\EntryDeletedEvent;
18 use Wallabag\CoreBundle\Event\EntrySavedEvent;
19
20 class EntryRestController extends WallabagRestController
21 {
22 /**
23 * Check if an entry exist by url.
24 * Return ID if entry(ies) exist (and if you give the return_id parameter).
25 * Otherwise it returns false.
26 *
27 * @todo Remove that `return_id` in the next major release
28 *
29 * @ApiDoc(
30 * parameters={
31 * {"name"="return_id", "dataType"="string", "required"=false, "format"="1 or 0", "description"="Set 1 if you want to retrieve ID in case entry(ies) exists, 0 by default"},
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 $returnId = (null === $request->query->get('return_id')) ? false : (bool) $request->query->get('return_id');
44 $urls = $request->query->get('urls', []);
45
46 // handle multiple urls first
47 if (!empty($urls)) {
48 $results = [];
49 foreach ($urls as $url) {
50 $res = $this->getDoctrine()
51 ->getRepository('WallabagCoreBundle:Entry')
52 ->findByUrlAndUserId($url, $this->getUser()->getId());
53
54 $results[$url] = $this->returnExistInformation($res, $returnId);
55 }
56
57 return $this->sendResponse($results);
58 }
59
60 // let's see if it is a simple url?
61 $url = $request->query->get('url', '');
62
63 if (empty($url)) {
64 throw $this->createAccessDeniedException('URL is empty?, logged user id: ' . $this->getUser()->getId());
65 }
66
67 $res = $this->getDoctrine()
68 ->getRepository('WallabagCoreBundle:Entry')
69 ->findByUrlAndUserId($url, $this->getUser()->getId());
70
71 $exists = $this->returnExistInformation($res, $returnId);
72
73 return $this->sendResponse(['exists' => $exists]);
74 }
75
76 /**
77 * Retrieve all entries. It could be filtered by many options.
78 *
79 * @ApiDoc(
80 * parameters={
81 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by archived status."},
82 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by starred status."},
83 * {"name"="sort", "dataType"="string", "required"=false, "format"="'created' or 'updated', default 'created'", "description"="sort entries by date."},
84 * {"name"="order", "dataType"="string", "required"=false, "format"="'asc' or 'desc', default 'desc'", "description"="order of sort."},
85 * {"name"="page", "dataType"="integer", "required"=false, "format"="default '1'", "description"="what page you want."},
86 * {"name"="perPage", "dataType"="integer", "required"=false, "format"="default'30'", "description"="results per page."},
87 * {"name"="tags", "dataType"="string", "required"=false, "format"="api,rest", "description"="a list of tags url encoded. Will returns entries that matches ALL tags."},
88 * {"name"="since", "dataType"="integer", "required"=false, "format"="default '0'", "description"="The timestamp since when you want entries updated."},
89 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by entries with a public link"},
90 * }
91 * )
92 *
93 * @return JsonResponse
94 */
95 public function getEntriesAction(Request $request)
96 {
97 $this->validateAuthentication();
98
99 $isArchived = (null === $request->query->get('archive')) ? null : (bool) $request->query->get('archive');
100 $isStarred = (null === $request->query->get('starred')) ? null : (bool) $request->query->get('starred');
101 $isPublic = (null === $request->query->get('public')) ? null : (bool) $request->query->get('public');
102 $sort = strtolower($request->query->get('sort', 'created'));
103 $order = strtolower($request->query->get('order', 'desc'));
104 $page = (int) $request->query->get('page', 1);
105 $perPage = (int) $request->query->get('perPage', 30);
106 $tags = \is_array($request->query->get('tags')) ? '' : (string) $request->query->get('tags', '');
107 $since = $request->query->get('since', 0);
108
109 try {
110 /** @var \Pagerfanta\Pagerfanta $pager */
111 $pager = $this->get('wallabag_core.entry_repository')->findEntries(
112 $this->getUser()->getId(),
113 $isArchived,
114 $isStarred,
115 $isPublic,
116 $sort,
117 $order,
118 $since,
119 $tags
120 );
121 } catch (\Exception $e) {
122 throw new BadRequestHttpException($e->getMessage());
123 }
124
125 $pager->setMaxPerPage($perPage);
126 $pager->setCurrentPage($page);
127
128 $pagerfantaFactory = new PagerfantaFactory('page', 'perPage');
129 $paginatedCollection = $pagerfantaFactory->createRepresentation(
130 $pager,
131 new Route(
132 'api_get_entries',
133 [
134 'archive' => $isArchived,
135 'starred' => $isStarred,
136 'public' => $isPublic,
137 'sort' => $sort,
138 'order' => $order,
139 'page' => $page,
140 'perPage' => $perPage,
141 'tags' => $tags,
142 'since' => $since,
143 ],
144 UrlGeneratorInterface::ABSOLUTE_URL
145 )
146 );
147
148 return $this->sendResponse($paginatedCollection);
149 }
150
151 /**
152 * Retrieve a single entry.
153 *
154 * @ApiDoc(
155 * requirements={
156 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
157 * }
158 * )
159 *
160 * @return JsonResponse
161 */
162 public function getEntryAction(Entry $entry)
163 {
164 $this->validateAuthentication();
165 $this->validateUserAccess($entry->getUser()->getId());
166
167 return $this->sendResponse($entry);
168 }
169
170 /**
171 * Retrieve a single entry as a predefined format.
172 *
173 * @ApiDoc(
174 * requirements={
175 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
176 * }
177 * )
178 *
179 * @return Response
180 */
181 public function getEntryExportAction(Entry $entry, Request $request)
182 {
183 $this->validateAuthentication();
184 $this->validateUserAccess($entry->getUser()->getId());
185
186 return $this->get('wallabag_core.helper.entries_export')
187 ->setEntries($entry)
188 ->updateTitle('entry')
189 ->updateAuthor('entry')
190 ->exportAs($request->attributes->get('_format'));
191 }
192
193 /**
194 * Handles an entries list and delete URL.
195 *
196 * @ApiDoc(
197 * parameters={
198 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to delete."}
199 * }
200 * )
201 *
202 * @return JsonResponse
203 */
204 public function deleteEntriesListAction(Request $request)
205 {
206 $this->validateAuthentication();
207
208 $urls = json_decode($request->query->get('urls', []));
209
210 if (empty($urls)) {
211 return $this->sendResponse([]);
212 }
213
214 $results = [];
215
216 // handle multiple urls
217 foreach ($urls as $key => $url) {
218 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
219 $url,
220 $this->getUser()->getId()
221 );
222
223 $results[$key]['url'] = $url;
224
225 if (false !== $entry) {
226 $em = $this->getDoctrine()->getManager();
227 $em->remove($entry);
228 $em->flush();
229
230 // entry deleted, dispatch event about it!
231 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry));
232 }
233
234 $results[$key]['entry'] = $entry instanceof Entry ? true : false;
235 }
236
237 return $this->sendResponse($results);
238 }
239
240 /**
241 * Handles an entries list and create URL.
242 *
243 * @ApiDoc(
244 * parameters={
245 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to create."}
246 * }
247 * )
248 *
249 * @throws HttpException When limit is reached
250 *
251 * @return JsonResponse
252 */
253 public function postEntriesListAction(Request $request)
254 {
255 $this->validateAuthentication();
256
257 $urls = json_decode($request->query->get('urls', []));
258
259 $limit = $this->container->getParameter('wallabag_core.api_limit_mass_actions');
260
261 if (\count($urls) > $limit) {
262 throw new HttpException(400, 'API limit reached');
263 }
264
265 $results = [];
266 if (empty($urls)) {
267 return $this->sendResponse($results);
268 }
269
270 // handle multiple urls
271 foreach ($urls as $key => $url) {
272 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
273 $url,
274 $this->getUser()->getId()
275 );
276
277 $results[$key]['url'] = $url;
278
279 if (false === $entry) {
280 $entry = new Entry($this->getUser());
281
282 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $url);
283 }
284
285 $em = $this->getDoctrine()->getManager();
286 $em->persist($entry);
287 $em->flush();
288
289 $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
290
291 // entry saved, dispatch event about it!
292 $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
293 }
294
295 return $this->sendResponse($results);
296 }
297
298 /**
299 * Create an entry.
300 *
301 * If you want to provide the HTML content (which means wallabag won't fetch it from the url), you must provide `content`, `title` & `url` fields **non-empty**.
302 * Otherwise, content will be fetched as normal from the url and values will be overwritten.
303 *
304 * @ApiDoc(
305 * parameters={
306 * {"name"="url", "dataType"="string", "required"=true, "format"="http://www.test.com/article.html", "description"="Url for the entry."},
307 * {"name"="title", "dataType"="string", "required"=false, "description"="Optional, we'll get the title from the page."},
308 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
309 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already archived"},
310 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"},
311 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
312 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
313 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
314 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
315 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
316 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
317 * {"name"="origin_url", "dataType"="string", "required"=false, "format"="http://www.test.com/article.html", "description"="Origin url for the entry (from where you found it)."},
318 * }
319 * )
320 *
321 * @return JsonResponse
322 */
323 public function postEntriesAction(Request $request)
324 {
325 $this->validateAuthentication();
326
327 $url = $request->request->get('url');
328
329 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
330 $url,
331 $this->getUser()->getId()
332 );
333
334 if (false === $entry) {
335 $entry = new Entry($this->getUser());
336 $entry->setUrl($url);
337 }
338
339 $data = $this->retrieveValueFromRequest($request);
340
341 try {
342 $this->get('wallabag_core.content_proxy')->updateEntry(
343 $entry,
344 $entry->getUrl(),
345 [
346 'title' => !empty($data['title']) ? $data['title'] : $entry->getTitle(),
347 'html' => !empty($data['content']) ? $data['content'] : $entry->getContent(),
348 'url' => $entry->getUrl(),
349 'language' => !empty($data['language']) ? $data['language'] : $entry->getLanguage(),
350 'date' => !empty($data['publishedAt']) ? $data['publishedAt'] : $entry->getPublishedAt(),
351 // faking the open graph preview picture
352 'open_graph' => [
353 'og_image' => !empty($data['picture']) ? $data['picture'] : $entry->getPreviewPicture(),
354 ],
355 'authors' => \is_string($data['authors']) ? explode(',', $data['authors']) : $entry->getPublishedBy(),
356 ]
357 );
358 } catch (\Exception $e) {
359 $this->get('logger')->error('Error while saving an entry', [
360 'exception' => $e,
361 'entry' => $entry,
362 ]);
363 }
364
365 if (null !== $data['isArchived']) {
366 $entry->setArchived((bool) $data['isArchived']);
367 }
368
369 if (null !== $data['isStarred']) {
370 $entry->updateStar((bool) $data['isStarred']);
371 }
372
373 if (!empty($data['tags'])) {
374 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']);
375 }
376
377 if (!empty($data['origin_url'])) {
378 $entry->setOriginUrl($data['origin_url']);
379 }
380
381 if (null !== $data['isPublic']) {
382 if (true === (bool) $data['isPublic'] && null === $entry->getUid()) {
383 $entry->generateUid();
384 } elseif (false === (bool) $data['isPublic']) {
385 $entry->cleanUid();
386 }
387 }
388
389 if (empty($entry->getDomainName())) {
390 $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
391 }
392
393 if (empty($entry->getTitle())) {
394 $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
395 }
396
397 $em = $this->getDoctrine()->getManager();
398 $em->persist($entry);
399 $em->flush();
400
401 // entry saved, dispatch event about it!
402 $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
403
404 return $this->sendResponse($entry);
405 }
406
407 /**
408 * Change several properties of an entry.
409 *
410 * @ApiDoc(
411 * requirements={
412 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
413 * },
414 * parameters={
415 * {"name"="title", "dataType"="string", "required"=false},
416 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
417 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="archived the entry."},
418 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="starred the entry."},
419 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
420 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
421 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
422 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
423 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
424 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
425 * {"name"="origin_url", "dataType"="string", "required"=false, "format"="http://www.test.com/article.html", "description"="Origin url for the entry (from where you found it)."},
426 * }
427 * )
428 *
429 * @return JsonResponse
430 */
431 public function patchEntriesAction(Entry $entry, Request $request)
432 {
433 $this->validateAuthentication();
434 $this->validateUserAccess($entry->getUser()->getId());
435
436 $contentProxy = $this->get('wallabag_core.content_proxy');
437
438 $data = $this->retrieveValueFromRequest($request);
439
440 // this is a special case where user want to manually update the entry content
441 // the ContentProxy will only cleanup the html
442 // and also we force to not re-fetch the content in case of error
443 if (!empty($data['content'])) {
444 try {
445 $contentProxy->updateEntry(
446 $entry,
447 $entry->getUrl(),
448 [
449 'html' => $data['content'],
450 ],
451 true
452 );
453 } catch (\Exception $e) {
454 $this->get('logger')->error('Error while saving an entry', [
455 'exception' => $e,
456 'entry' => $entry,
457 ]);
458 }
459 }
460
461 if (!empty($data['title'])) {
462 $entry->setTitle($data['title']);
463 }
464
465 if (!empty($data['language'])) {
466 $contentProxy->updateLanguage($entry, $data['language']);
467 }
468
469 if (!empty($data['authors']) && \is_string($data['authors'])) {
470 $entry->setPublishedBy(explode(',', $data['authors']));
471 }
472
473 if (!empty($data['picture'])) {
474 $contentProxy->updatePreviewPicture($entry, $data['picture']);
475 }
476
477 if (!empty($data['publishedAt'])) {
478 $contentProxy->updatePublishedAt($entry, $data['publishedAt']);
479 }
480
481 if (null !== $data['isArchived']) {
482 $entry->setArchived((bool) $data['isArchived']);
483 }
484
485 if (null !== $data['isStarred']) {
486 $entry->updateStar((bool) $data['isStarred']);
487 }
488
489 if (!empty($data['tags'])) {
490 $entry->removeAllTags();
491 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']);
492 }
493
494 if (null !== $data['isPublic']) {
495 if (true === (bool) $data['isPublic'] && null === $entry->getUid()) {
496 $entry->generateUid();
497 } elseif (false === (bool) $data['isPublic']) {
498 $entry->cleanUid();
499 }
500 }
501
502 if (!empty($data['origin_url'])) {
503 $entry->setOriginUrl($data['origin_url']);
504 }
505
506 if (empty($entry->getDomainName())) {
507 $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
508 }
509
510 if (empty($entry->getTitle())) {
511 $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
512 }
513
514 $em = $this->getDoctrine()->getManager();
515 $em->persist($entry);
516 $em->flush();
517
518 // entry saved, dispatch event about it!
519 $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
520
521 return $this->sendResponse($entry);
522 }
523
524 /**
525 * Reload an entry.
526 * An empty response with HTTP Status 304 will be send if we weren't able to update the content (because it hasn't changed or we got an error).
527 *
528 * @ApiDoc(
529 * requirements={
530 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
531 * }
532 * )
533 *
534 * @return JsonResponse
535 */
536 public function patchEntriesReloadAction(Entry $entry)
537 {
538 $this->validateAuthentication();
539 $this->validateUserAccess($entry->getUser()->getId());
540
541 try {
542 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
543 } catch (\Exception $e) {
544 $this->get('logger')->error('Error while saving an entry', [
545 'exception' => $e,
546 'entry' => $entry,
547 ]);
548
549 return new JsonResponse([], 304);
550 }
551
552 // if refreshing entry failed, don't save it
553 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
554 return new JsonResponse([], 304);
555 }
556
557 $em = $this->getDoctrine()->getManager();
558 $em->persist($entry);
559 $em->flush();
560
561 // entry saved, dispatch event about it!
562 $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
563
564 return $this->sendResponse($entry);
565 }
566
567 /**
568 * Delete **permanently** an entry.
569 *
570 * @ApiDoc(
571 * requirements={
572 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
573 * }
574 * )
575 *
576 * @return JsonResponse
577 */
578 public function deleteEntriesAction(Entry $entry)
579 {
580 $this->validateAuthentication();
581 $this->validateUserAccess($entry->getUser()->getId());
582
583 // We copy $entry to keep id in returned object
584 $e = $entry;
585
586 $em = $this->getDoctrine()->getManager();
587 $em->remove($entry);
588 $em->flush();
589
590 // entry deleted, dispatch event about it!
591 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry));
592
593 return $this->sendResponse($e);
594 }
595
596 /**
597 * Retrieve all tags for an entry.
598 *
599 * @ApiDoc(
600 * requirements={
601 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
602 * }
603 * )
604 *
605 * @return JsonResponse
606 */
607 public function getEntriesTagsAction(Entry $entry)
608 {
609 $this->validateAuthentication();
610 $this->validateUserAccess($entry->getUser()->getId());
611
612 return $this->sendResponse($entry->getTags());
613 }
614
615 /**
616 * Add one or more tags to an entry.
617 *
618 * @ApiDoc(
619 * requirements={
620 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
621 * },
622 * parameters={
623 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
624 * }
625 * )
626 *
627 * @return JsonResponse
628 */
629 public function postEntriesTagsAction(Request $request, Entry $entry)
630 {
631 $this->validateAuthentication();
632 $this->validateUserAccess($entry->getUser()->getId());
633
634 $tags = $request->request->get('tags', '');
635 if (!empty($tags)) {
636 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
637 }
638
639 $em = $this->getDoctrine()->getManager();
640 $em->persist($entry);
641 $em->flush();
642
643 return $this->sendResponse($entry);
644 }
645
646 /**
647 * Permanently remove one tag for an entry.
648 *
649 * @ApiDoc(
650 * requirements={
651 * {"name"="tag", "dataType"="integer", "requirement"="\w+", "description"="The tag ID"},
652 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
653 * }
654 * )
655 *
656 * @return JsonResponse
657 */
658 public function deleteEntriesTagsAction(Entry $entry, Tag $tag)
659 {
660 $this->validateAuthentication();
661 $this->validateUserAccess($entry->getUser()->getId());
662
663 $entry->removeTag($tag);
664 $em = $this->getDoctrine()->getManager();
665 $em->persist($entry);
666 $em->flush();
667
668 return $this->sendResponse($entry);
669 }
670
671 /**
672 * Handles an entries list delete tags from them.
673 *
674 * @ApiDoc(
675 * parameters={
676 * {"name"="list", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...','tags': 'tag1, tag2'}, {'url': 'http://...','tags': 'tag1, tag2'}]", "description"="Urls (as an array) to handle."}
677 * }
678 * )
679 *
680 * @return JsonResponse
681 */
682 public function deleteEntriesTagsListAction(Request $request)
683 {
684 $this->validateAuthentication();
685
686 $list = json_decode($request->query->get('list', []));
687
688 if (empty($list)) {
689 return $this->sendResponse([]);
690 }
691
692 // handle multiple urls
693 $results = [];
694
695 foreach ($list as $key => $element) {
696 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
697 $element->url,
698 $this->getUser()->getId()
699 );
700
701 $results[$key]['url'] = $element->url;
702 $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
703
704 $tags = $element->tags;
705
706 if (false !== $entry && !(empty($tags))) {
707 $tags = explode(',', $tags);
708 foreach ($tags as $label) {
709 $label = trim($label);
710
711 $tag = $this->getDoctrine()
712 ->getRepository('WallabagCoreBundle:Tag')
713 ->findOneByLabel($label);
714
715 if (false !== $tag) {
716 $entry->removeTag($tag);
717 }
718 }
719
720 $em = $this->getDoctrine()->getManager();
721 $em->persist($entry);
722 $em->flush();
723 }
724 }
725
726 return $this->sendResponse($results);
727 }
728
729 /**
730 * Handles an entries list and add tags to them.
731 *
732 * @ApiDoc(
733 * parameters={
734 * {"name"="list", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...','tags': 'tag1, tag2'}, {'url': 'http://...','tags': 'tag1, tag2'}]", "description"="Urls (as an array) to handle."}
735 * }
736 * )
737 *
738 * @return JsonResponse
739 */
740 public function postEntriesTagsListAction(Request $request)
741 {
742 $this->validateAuthentication();
743
744 $list = json_decode($request->query->get('list', []));
745
746 if (empty($list)) {
747 return $this->sendResponse([]);
748 }
749
750 $results = [];
751
752 // handle multiple urls
753 foreach ($list as $key => $element) {
754 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
755 $element->url,
756 $this->getUser()->getId()
757 );
758
759 $results[$key]['url'] = $element->url;
760 $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
761
762 $tags = $element->tags;
763
764 if (false !== $entry && !(empty($tags))) {
765 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
766
767 $em = $this->getDoctrine()->getManager();
768 $em->persist($entry);
769 $em->flush();
770 }
771 }
772
773 return $this->sendResponse($results);
774 }
775
776 /**
777 * Shortcut to send data serialized in json.
778 *
779 * @param mixed $data
780 *
781 * @return JsonResponse
782 */
783 private function sendResponse($data)
784 {
785 // https://github.com/schmittjoh/JMSSerializerBundle/issues/293
786 $context = new SerializationContext();
787 $context->setSerializeNull(true);
788
789 $json = $this->get('jms_serializer')->serialize($data, 'json', $context);
790
791 return (new JsonResponse())->setJson($json);
792 }
793
794 /**
795 * Retrieve value from the request.
796 * Used for POST & PATCH on a an entry.
797 *
798 * @param Request $request
799 *
800 * @return array
801 */
802 private function retrieveValueFromRequest(Request $request)
803 {
804 return [
805 'title' => $request->request->get('title'),
806 'tags' => $request->request->get('tags', []),
807 'isArchived' => $request->request->get('archive'),
808 'isStarred' => $request->request->get('starred'),
809 'isPublic' => $request->request->get('public'),
810 'content' => $request->request->get('content'),
811 'language' => $request->request->get('language'),
812 'picture' => $request->request->get('preview_picture'),
813 'publishedAt' => $request->request->get('published_at'),
814 'authors' => $request->request->get('authors', ''),
815 'origin_url' => $request->request->get('origin_url', ''),
816 ];
817 }
818
819 /**
820 * Return information about the entry if it exist and depending on the id or not.
821 *
822 * @param Entry|null $entry
823 * @param bool $returnId
824 *
825 * @return bool|int
826 */
827 private function returnExistInformation($entry, $returnId)
828 {
829 if ($returnId) {
830 return $entry instanceof Entry ? $entry->getId() : null;
831 }
832
833 return $entry instanceof Entry;
834 }
835 }