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