]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/ApiBundle/Controller/EntryRestController.php
Merge pull request #3627 from craig0990/feature/add-search-api-endpoint
[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"}
571 * }
572 * )
573 *
574 * @return JsonResponse
575 */
576 public function deleteEntriesAction(Entry $entry)
577 {
578 $this->validateAuthentication();
579 $this->validateUserAccess($entry->getUser()->getId());
580
f5ea67e4
KD
581 // We copy $entry to keep id in returned object
582 $e = $entry;
583
900c8448
NL
584 $em = $this->getDoctrine()->getManager();
585 $em->remove($entry);
586 $em->flush();
587
5a619812
JB
588 // entry deleted, dispatch event about it!
589 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry));
590
f5ea67e4 591 return $this->sendResponse($e);
900c8448
NL
592 }
593
594 /**
595 * Retrieve all tags for an entry.
596 *
597 * @ApiDoc(
598 * requirements={
599 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
600 * }
601 * )
602 *
603 * @return JsonResponse
604 */
605 public function getEntriesTagsAction(Entry $entry)
606 {
607 $this->validateAuthentication();
608 $this->validateUserAccess($entry->getUser()->getId());
609
72db15ca 610 return $this->sendResponse($entry->getTags());
900c8448
NL
611 }
612
613 /**
614 * Add one or more tags to an entry.
615 *
616 * @ApiDoc(
617 * requirements={
618 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
619 * },
620 * parameters={
621 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
622 * }
623 * )
624 *
625 * @return JsonResponse
626 */
627 public function postEntriesTagsAction(Request $request, Entry $entry)
628 {
629 $this->validateAuthentication();
630 $this->validateUserAccess($entry->getUser()->getId());
631
632 $tags = $request->request->get('tags', '');
633 if (!empty($tags)) {
6bc6fb1f 634 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
900c8448
NL
635 }
636
637 $em = $this->getDoctrine()->getManager();
638 $em->persist($entry);
639 $em->flush();
640
72db15ca 641 return $this->sendResponse($entry);
900c8448
NL
642 }
643
644 /**
645 * Permanently remove one tag for an entry.
646 *
647 * @ApiDoc(
648 * requirements={
649 * {"name"="tag", "dataType"="integer", "requirement"="\w+", "description"="The tag ID"},
650 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
651 * }
652 * )
653 *
654 * @return JsonResponse
655 */
656 public function deleteEntriesTagsAction(Entry $entry, Tag $tag)
657 {
658 $this->validateAuthentication();
659 $this->validateUserAccess($entry->getUser()->getId());
660
661 $entry->removeTag($tag);
662 $em = $this->getDoctrine()->getManager();
663 $em->persist($entry);
664 $em->flush();
665
72db15ca 666 return $this->sendResponse($entry);
900c8448 667 }
d1fc5902
NL
668
669 /**
80299ed2 670 * Handles an entries list delete tags from them.
d1fc5902
NL
671 *
672 * @ApiDoc(
673 * parameters={
80299ed2 674 * {"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
675 * }
676 * )
677 *
678 * @return JsonResponse
679 */
80299ed2 680 public function deleteEntriesTagsListAction(Request $request)
d1fc5902
NL
681 {
682 $this->validateAuthentication();
683
684 $list = json_decode($request->query->get('list', []));
72db15ca
JB
685
686 if (empty($list)) {
687 return $this->sendResponse([]);
688 }
d1fc5902
NL
689
690 // handle multiple urls
72db15ca 691 $results = [];
d1fc5902 692
72db15ca
JB
693 foreach ($list as $key => $element) {
694 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
695 $element->url,
696 $this->getUser()->getId()
697 );
d1fc5902 698
72db15ca
JB
699 $results[$key]['url'] = $element->url;
700 $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
d1fc5902 701
72db15ca 702 $tags = $element->tags;
80299ed2 703
72db15ca
JB
704 if (false !== $entry && !(empty($tags))) {
705 $tags = explode(',', $tags);
706 foreach ($tags as $label) {
707 $label = trim($label);
80299ed2 708
72db15ca
JB
709 $tag = $this->getDoctrine()
710 ->getRepository('WallabagCoreBundle:Tag')
711 ->findOneByLabel($label);
d1fc5902 712
72db15ca
JB
713 if (false !== $tag) {
714 $entry->removeTag($tag);
715 }
d1fc5902 716 }
72db15ca
JB
717
718 $em = $this->getDoctrine()->getManager();
719 $em->persist($entry);
720 $em->flush();
d1fc5902
NL
721 }
722 }
723
72db15ca 724 return $this->sendResponse($results);
d1fc5902 725 }
80299ed2
NL
726
727 /**
728 * Handles an entries list and add tags to them.
729 *
730 * @ApiDoc(
731 * parameters={
732 * {"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."}
733 * }
734 * )
735 *
736 * @return JsonResponse
737 */
738 public function postEntriesTagsListAction(Request $request)
739 {
740 $this->validateAuthentication();
741
742 $list = json_decode($request->query->get('list', []));
72db15ca
JB
743
744 if (empty($list)) {
745 return $this->sendResponse([]);
746 }
747
80299ed2
NL
748 $results = [];
749
750 // handle multiple urls
72db15ca
JB
751 foreach ($list as $key => $element) {
752 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
753 $element->url,
754 $this->getUser()->getId()
755 );
80299ed2 756
72db15ca
JB
757 $results[$key]['url'] = $element->url;
758 $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
80299ed2 759
72db15ca 760 $tags = $element->tags;
80299ed2 761
72db15ca 762 if (false !== $entry && !(empty($tags))) {
6bc6fb1f 763 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
80299ed2 764
72db15ca
JB
765 $em = $this->getDoctrine()->getManager();
766 $em->persist($entry);
767 $em->flush();
80299ed2
NL
768 }
769 }
770
72db15ca
JB
771 return $this->sendResponse($results);
772 }
773
db0c48af 774 /**
a05b6115
JB
775 * Retrieve value from the request.
776 * Used for POST & PATCH on a an entry.
db0c48af 777 *
db0c48af 778 * @param Request $request
a05b6115
JB
779 *
780 * @return array
db0c48af 781 */
a05b6115 782 private function retrieveValueFromRequest(Request $request)
db0c48af 783 {
a05b6115
JB
784 return [
785 'title' => $request->request->get('title'),
786 'tags' => $request->request->get('tags', []),
787 'isArchived' => $request->request->get('archive'),
788 'isStarred' => $request->request->get('starred'),
789 'isPublic' => $request->request->get('public'),
790 'content' => $request->request->get('content'),
791 'language' => $request->request->get('language'),
792 'picture' => $request->request->get('preview_picture'),
793 'publishedAt' => $request->request->get('published_at'),
794 'authors' => $request->request->get('authors', ''),
e0ef1a1c 795 'origin_url' => $request->request->get('origin_url', ''),
a05b6115 796 ];
db0c48af 797 }
39ffaba3
JB
798
799 /**
800 * Return information about the entry if it exist and depending on the id or not.
801 *
802 * @param Entry|null $entry
803 * @param bool $returnId
804 *
805 * @return bool|int
806 */
807 private function returnExistInformation($entry, $returnId)
808 {
809 if ($returnId) {
810 return $entry instanceof Entry ? $entry->getId() : null;
811 }
812
331e5b02 813 return $entry instanceof Entry;
39ffaba3 814 }
900c8448 815}