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