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