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