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