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