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