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