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