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