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