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