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