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