]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/ApiBundle/Controller/EntryRestController.php
Add client_credentials as grant_type
[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;
0f8268c9 8use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
72db15ca 9use Symfony\Component\HttpKernel\Exception\HttpException;
900c8448
NL
10use Symfony\Component\HttpFoundation\Request;
11use Symfony\Component\HttpFoundation\JsonResponse;
12use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
13use Wallabag\CoreBundle\Entity\Entry;
14use Wallabag\CoreBundle\Entity\Tag;
5a619812
JB
15use Wallabag\CoreBundle\Event\EntrySavedEvent;
16use Wallabag\CoreBundle\Event\EntryDeletedEvent;
900c8448
NL
17
18class EntryRestController extends WallabagRestController
19{
20 /**
21 * Check if an entry exist by url.
22 *
23 * @ApiDoc(
24 * parameters={
25 * {"name"="url", "dataType"="string", "required"=true, "format"="An url", "description"="Url to check if it exists"},
26 * {"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"}
27 * }
28 * )
0f8268c9 29 * @Security("has_role('ROLE_READ')")
900c8448
NL
30 * @return JsonResponse
31 */
32 public function getEntriesExistsAction(Request $request)
33 {
34 $this->validateAuthentication();
35
36 $urls = $request->query->get('urls', []);
37
38 // handle multiple urls first
39 if (!empty($urls)) {
40 $results = [];
41 foreach ($urls as $url) {
42 $res = $this->getDoctrine()
43 ->getRepository('WallabagCoreBundle:Entry')
44 ->findByUrlAndUserId($url, $this->getUser()->getId());
45
ca9a83ee 46 $results[$url] = $res instanceof Entry ? $res->getId() : false;
900c8448
NL
47 }
48
72db15ca 49 return $this->sendResponse($results);
900c8448
NL
50 }
51
52 // let's see if it is a simple url?
53 $url = $request->query->get('url', '');
54
55 if (empty($url)) {
56 throw $this->createAccessDeniedException('URL is empty?, logged user id: '.$this->getUser()->getId());
57 }
58
59 $res = $this->getDoctrine()
60 ->getRepository('WallabagCoreBundle:Entry')
61 ->findByUrlAndUserId($url, $this->getUser()->getId());
62
ca9a83ee 63 $exists = $res instanceof Entry ? $res->getId() : false;
900c8448 64
72db15ca 65 return $this->sendResponse(['exists' => $exists]);
900c8448
NL
66 }
67
68 /**
69 * Retrieve all entries. It could be filtered by many options.
70 *
71 * @ApiDoc(
72 * parameters={
73 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by archived status."},
74 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by starred status."},
75 * {"name"="sort", "dataType"="string", "required"=false, "format"="'created' or 'updated', default 'created'", "description"="sort entries by date."},
76 * {"name"="order", "dataType"="string", "required"=false, "format"="'asc' or 'desc', default 'desc'", "description"="order of sort."},
77 * {"name"="page", "dataType"="integer", "required"=false, "format"="default '1'", "description"="what page you want."},
78 * {"name"="perPage", "dataType"="integer", "required"=false, "format"="default'30'", "description"="results per page."},
79 * {"name"="tags", "dataType"="string", "required"=false, "format"="api,rest", "description"="a list of tags url encoded. Will returns entries that matches ALL tags."},
80 * {"name"="since", "dataType"="integer", "required"=false, "format"="default '0'", "description"="The timestamp since when you want entries updated."},
1112e547 81 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by entries with a public link"},
900c8448
NL
82 * }
83 * )
0f8268c9 84 * @Security("has_role('ROLE_READ')")
900c8448
NL
85 * @return JsonResponse
86 */
87 public function getEntriesAction(Request $request)
88 {
89 $this->validateAuthentication();
90
91 $isArchived = (null === $request->query->get('archive')) ? null : (bool) $request->query->get('archive');
92 $isStarred = (null === $request->query->get('starred')) ? null : (bool) $request->query->get('starred');
1112e547 93 $isPublic = (null === $request->query->get('public')) ? null : (bool) $request->query->get('public');
900c8448
NL
94 $sort = $request->query->get('sort', 'created');
95 $order = $request->query->get('order', 'desc');
96 $page = (int) $request->query->get('page', 1);
97 $perPage = (int) $request->query->get('perPage', 30);
98 $tags = $request->query->get('tags', '');
99 $since = $request->query->get('since', 0);
100
b60a666d 101 /** @var \Pagerfanta\Pagerfanta $pager */
1112e547
JB
102 $pager = $this->get('wallabag_core.entry_repository')->findEntries(
103 $this->getUser()->getId(),
104 $isArchived,
105 $isStarred,
106 $isPublic,
107 $sort,
108 $order,
109 $since,
110 $tags
111 );
900c8448 112
900c8448 113 $pager->setMaxPerPage($perPage);
b60a666d 114 $pager->setCurrentPage($page);
900c8448
NL
115
116 $pagerfantaFactory = new PagerfantaFactory('page', 'perPage');
117 $paginatedCollection = $pagerfantaFactory->createRepresentation(
118 $pager,
119 new Route(
120 'api_get_entries',
121 [
122 'archive' => $isArchived,
123 'starred' => $isStarred,
1112e547 124 'public' => $isPublic,
900c8448
NL
125 'sort' => $sort,
126 'order' => $order,
127 'page' => $page,
128 'perPage' => $perPage,
129 'tags' => $tags,
130 'since' => $since,
131 ],
132 UrlGeneratorInterface::ABSOLUTE_URL
133 )
134 );
135
72db15ca 136 return $this->sendResponse($paginatedCollection);
900c8448
NL
137 }
138
139 /**
140 * Retrieve a single entry.
141 *
142 * @ApiDoc(
143 * requirements={
144 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
145 * }
146 * )
0f8268c9 147 * @Security("has_role('ROLE_READ')")
900c8448
NL
148 * @return JsonResponse
149 */
150 public function getEntryAction(Entry $entry)
151 {
152 $this->validateAuthentication();
153 $this->validateUserAccess($entry->getUser()->getId());
154
72db15ca 155 return $this->sendResponse($entry);
900c8448
NL
156 }
157
864c1dd2
JB
158 /**
159 * Retrieve a single entry as a predefined format.
160 *
161 * @ApiDoc(
162 * requirements={
163 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
164 * }
165 * )
0f8268c9 166 * @Security("has_role('ROLE_READ')")
864c1dd2
JB
167 * @return Response
168 */
169 public function getEntryExportAction(Entry $entry, Request $request)
170 {
171 $this->validateAuthentication();
172 $this->validateUserAccess($entry->getUser()->getId());
173
174 return $this->get('wallabag_core.helper.entries_export')
175 ->setEntries($entry)
176 ->updateTitle('entry')
177 ->exportAs($request->attributes->get('_format'));
178 }
179
1eca7831 180 /**
a7abcc7b 181 * Handles an entries list and delete URL.
1eca7831
NL
182 *
183 * @ApiDoc(
184 * parameters={
a7abcc7b 185 * {"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
186 * }
187 * )
188 *
189 * @return JsonResponse
190 */
a7abcc7b 191 public function deleteEntriesListAction(Request $request)
1eca7831
NL
192 {
193 $this->validateAuthentication();
194
a7abcc7b 195 $urls = json_decode($request->query->get('urls', []));
72db15ca
JB
196
197 if (empty($urls)) {
198 return $this->sendResponse([]);
199 }
200
1eca7831
NL
201 $results = [];
202
203 // handle multiple urls
72db15ca
JB
204 foreach ($urls as $key => $url) {
205 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
206 $url,
207 $this->getUser()->getId()
208 );
a7abcc7b 209
72db15ca 210 $results[$key]['url'] = $url;
a7abcc7b 211
72db15ca
JB
212 if (false !== $entry) {
213 $em = $this->getDoctrine()->getManager();
214 $em->remove($entry);
215 $em->flush();
1eca7831 216
72db15ca
JB
217 // entry deleted, dispatch event about it!
218 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry));
a7abcc7b 219 }
1eca7831 220
72db15ca
JB
221 $results[$key]['entry'] = $entry instanceof Entry ? true : false;
222 }
1eca7831 223
72db15ca 224 return $this->sendResponse($results);
a7abcc7b 225 }
1eca7831 226
a7abcc7b
NL
227 /**
228 * Handles an entries list and create URL.
229 *
230 * @ApiDoc(
231 * parameters={
232 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to create."}
233 * }
234 * )
235 *
236 * @return JsonResponse
efd351c9 237 *
72db15ca 238 * @throws HttpException When limit is reached
a7abcc7b
NL
239 */
240 public function postEntriesListAction(Request $request)
241 {
242 $this->validateAuthentication();
1eca7831 243
a7abcc7b 244 $urls = json_decode($request->query->get('urls', []));
1eca7831 245
efd351c9
NL
246 $limit = $this->container->getParameter('wallabag_core.api_limit_mass_actions');
247
248 if (count($urls) > $limit) {
72db15ca 249 throw new HttpException(400, 'API limit reached');
efd351c9
NL
250 }
251
d5c2cc54
JB
252 $results = [];
253 if (empty($urls)) {
254 return $this->sendResponse($results);
255 }
256
a7abcc7b 257 // handle multiple urls
d5c2cc54
JB
258 foreach ($urls as $key => $url) {
259 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
260 $url,
261 $this->getUser()->getId()
262 );
1eca7831 263
d5c2cc54 264 $results[$key]['url'] = $url;
1eca7831 265
d5c2cc54
JB
266 if (false === $entry) {
267 $entry = new Entry($this->getUser());
a7abcc7b 268
d5c2cc54
JB
269 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $url);
270 }
a7abcc7b 271
d5c2cc54
JB
272 $em = $this->getDoctrine()->getManager();
273 $em->persist($entry);
274 $em->flush();
a7abcc7b 275
d5c2cc54
JB
276 $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
277
278 // entry saved, dispatch event about it!
279 $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
1eca7831
NL
280 }
281
72db15ca 282 return $this->sendResponse($results);
1eca7831
NL
283 }
284
900c8448
NL
285 /**
286 * Create an entry.
287 *
9e349f08
JB
288 * 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**.
289 * Otherwise, content will be fetched as normal from the url and values will be overwritten.
290 *
900c8448
NL
291 * @ApiDoc(
292 * parameters={
293 * {"name"="url", "dataType"="string", "required"=true, "format"="http://www.test.com/article.html", "description"="Url for the entry."},
294 * {"name"="title", "dataType"="string", "required"=false, "description"="Optional, we'll get the title from the page."},
295 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
296 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"},
297 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already archived"},
e668a812
JB
298 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
299 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
300 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
f0378b4d 301 * {"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 302 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
1112e547 303 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
900c8448
NL
304 * }
305 * )
0f8268c9 306 * @Security("has_role('ROLE_WRITE')")
900c8448
NL
307 * @return JsonResponse
308 */
309 public function postEntriesAction(Request $request)
310 {
311 $this->validateAuthentication();
312
313 $url = $request->request->get('url');
900c8448 314
db0c48af
JB
315 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
316 $url,
317 $this->getUser()->getId()
318 );
900c8448
NL
319
320 if (false === $entry) {
08f29ae7 321 $entry = new Entry($this->getUser());
e668a812 322 $entry->setUrl($url);
900c8448
NL
323 }
324
db0c48af 325 $this->upsertEntry($entry, $request);
5a619812 326
72db15ca 327 return $this->sendResponse($entry);
900c8448
NL
328 }
329
330 /**
331 * Change several properties of an entry.
332 *
333 * @ApiDoc(
334 * requirements={
335 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
336 * },
337 * parameters={
338 * {"name"="title", "dataType"="string", "required"=false},
339 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
340 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="archived the entry."},
341 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="starred the entry."},
645291e8
JB
342 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
343 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
344 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
345 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
346 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
1112e547 347 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
900c8448
NL
348 * }
349 * )
0f8268c9 350 * @Security("has_role('ROLE_WRITE')")
900c8448
NL
351 * @return JsonResponse
352 */
353 public function patchEntriesAction(Entry $entry, Request $request)
354 {
355 $this->validateAuthentication();
356 $this->validateUserAccess($entry->getUser()->getId());
357
db0c48af 358 $this->upsertEntry($entry, $request, true);
900c8448 359
72db15ca 360 return $this->sendResponse($entry);
900c8448
NL
361 }
362
0a6f4568
JB
363 /**
364 * Reload an entry.
5cd0857e 365 * 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
366 *
367 * @ApiDoc(
368 * requirements={
369 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
370 * }
371 * )
0f8268c9 372 * @Security("has_role('ROLE_WRITE')")
0a6f4568
JB
373 * @return JsonResponse
374 */
375 public function patchEntriesReloadAction(Entry $entry)
376 {
377 $this->validateAuthentication();
378 $this->validateUserAccess($entry->getUser()->getId());
379
0a6f4568 380 try {
7aba665e 381 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
0a6f4568
JB
382 } catch (\Exception $e) {
383 $this->get('logger')->error('Error while saving an entry', [
384 'exception' => $e,
385 'entry' => $entry,
386 ]);
387
5cd0857e 388 return new JsonResponse([], 304);
0a6f4568
JB
389 }
390
391 // if refreshing entry failed, don't save it
392 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
5cd0857e 393 return new JsonResponse([], 304);
0a6f4568
JB
394 }
395
396 $em = $this->getDoctrine()->getManager();
397 $em->persist($entry);
398 $em->flush();
399
400 // entry saved, dispatch event about it!
401 $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
402
72db15ca 403 return $this->sendResponse($entry);
0a6f4568
JB
404 }
405
900c8448
NL
406 /**
407 * Delete **permanently** an entry.
408 *
409 * @ApiDoc(
410 * requirements={
411 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
412 * }
413 * )
0f8268c9 414 * @Security("has_role('ROLE_WRITE')")
900c8448
NL
415 * @return JsonResponse
416 */
417 public function deleteEntriesAction(Entry $entry)
418 {
419 $this->validateAuthentication();
420 $this->validateUserAccess($entry->getUser()->getId());
421
422 $em = $this->getDoctrine()->getManager();
423 $em->remove($entry);
424 $em->flush();
425
5a619812
JB
426 // entry deleted, dispatch event about it!
427 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry));
428
72db15ca 429 return $this->sendResponse($entry);
900c8448
NL
430 }
431
432 /**
433 * Retrieve all tags for an entry.
434 *
435 * @ApiDoc(
436 * requirements={
437 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
438 * }
439 * )
0f8268c9 440 * @Security("has_role('ROLE_READ')")
900c8448
NL
441 * @return JsonResponse
442 */
443 public function getEntriesTagsAction(Entry $entry)
444 {
445 $this->validateAuthentication();
446 $this->validateUserAccess($entry->getUser()->getId());
447
72db15ca 448 return $this->sendResponse($entry->getTags());
900c8448
NL
449 }
450
451 /**
452 * Add one or more tags to an entry.
453 *
454 * @ApiDoc(
455 * requirements={
456 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
457 * },
458 * parameters={
459 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
460 * }
461 * )
0f8268c9 462 * @Security("has_role('ROLE_WRITE')")
900c8448
NL
463 * @return JsonResponse
464 */
465 public function postEntriesTagsAction(Request $request, Entry $entry)
466 {
467 $this->validateAuthentication();
468 $this->validateUserAccess($entry->getUser()->getId());
469
470 $tags = $request->request->get('tags', '');
471 if (!empty($tags)) {
6bc6fb1f 472 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
900c8448
NL
473 }
474
475 $em = $this->getDoctrine()->getManager();
476 $em->persist($entry);
477 $em->flush();
478
72db15ca 479 return $this->sendResponse($entry);
900c8448
NL
480 }
481
482 /**
483 * Permanently remove one tag for an entry.
484 *
485 * @ApiDoc(
486 * requirements={
487 * {"name"="tag", "dataType"="integer", "requirement"="\w+", "description"="The tag ID"},
488 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
489 * }
490 * )
0f8268c9 491 * @Security("has_role('ROLE_WRITE')")
900c8448
NL
492 * @return JsonResponse
493 */
494 public function deleteEntriesTagsAction(Entry $entry, Tag $tag)
495 {
496 $this->validateAuthentication();
497 $this->validateUserAccess($entry->getUser()->getId());
498
499 $entry->removeTag($tag);
500 $em = $this->getDoctrine()->getManager();
501 $em->persist($entry);
502 $em->flush();
503
72db15ca 504 return $this->sendResponse($entry);
900c8448 505 }
d1fc5902
NL
506
507 /**
80299ed2 508 * Handles an entries list delete tags from them.
d1fc5902
NL
509 *
510 * @ApiDoc(
511 * parameters={
80299ed2 512 * {"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
513 * }
514 * )
515 *
516 * @return JsonResponse
517 */
80299ed2 518 public function deleteEntriesTagsListAction(Request $request)
d1fc5902
NL
519 {
520 $this->validateAuthentication();
521
522 $list = json_decode($request->query->get('list', []));
72db15ca
JB
523
524 if (empty($list)) {
525 return $this->sendResponse([]);
526 }
d1fc5902
NL
527
528 // handle multiple urls
72db15ca 529 $results = [];
d1fc5902 530
72db15ca
JB
531 foreach ($list as $key => $element) {
532 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
533 $element->url,
534 $this->getUser()->getId()
535 );
d1fc5902 536
72db15ca
JB
537 $results[$key]['url'] = $element->url;
538 $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
d1fc5902 539
72db15ca 540 $tags = $element->tags;
80299ed2 541
72db15ca
JB
542 if (false !== $entry && !(empty($tags))) {
543 $tags = explode(',', $tags);
544 foreach ($tags as $label) {
545 $label = trim($label);
80299ed2 546
72db15ca
JB
547 $tag = $this->getDoctrine()
548 ->getRepository('WallabagCoreBundle:Tag')
549 ->findOneByLabel($label);
d1fc5902 550
72db15ca
JB
551 if (false !== $tag) {
552 $entry->removeTag($tag);
553 }
d1fc5902 554 }
72db15ca
JB
555
556 $em = $this->getDoctrine()->getManager();
557 $em->persist($entry);
558 $em->flush();
d1fc5902
NL
559 }
560 }
561
72db15ca 562 return $this->sendResponse($results);
d1fc5902 563 }
80299ed2
NL
564
565 /**
566 * Handles an entries list and add tags to them.
567 *
568 * @ApiDoc(
569 * parameters={
570 * {"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."}
571 * }
572 * )
573 *
574 * @return JsonResponse
575 */
576 public function postEntriesTagsListAction(Request $request)
577 {
578 $this->validateAuthentication();
579
580 $list = json_decode($request->query->get('list', []));
72db15ca
JB
581
582 if (empty($list)) {
583 return $this->sendResponse([]);
584 }
585
80299ed2
NL
586 $results = [];
587
588 // handle multiple urls
72db15ca
JB
589 foreach ($list as $key => $element) {
590 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
591 $element->url,
592 $this->getUser()->getId()
593 );
80299ed2 594
72db15ca
JB
595 $results[$key]['url'] = $element->url;
596 $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
80299ed2 597
72db15ca 598 $tags = $element->tags;
80299ed2 599
72db15ca 600 if (false !== $entry && !(empty($tags))) {
6bc6fb1f 601 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
80299ed2 602
72db15ca
JB
603 $em = $this->getDoctrine()->getManager();
604 $em->persist($entry);
605 $em->flush();
80299ed2
NL
606 }
607 }
608
72db15ca
JB
609 return $this->sendResponse($results);
610 }
611
612 /**
613 * Shortcut to send data serialized in json.
614 *
615 * @param mixed $data
616 *
617 * @return JsonResponse
618 */
619 private function sendResponse($data)
620 {
621 $json = $this->get('serializer')->serialize($data, 'json');
80299ed2
NL
622
623 return (new JsonResponse())->setJson($json);
624 }
db0c48af
JB
625
626 /**
627 * Update or Insert a new entry.
628 *
629 * @param Entry $entry
630 * @param Request $request
631 * @param bool $disableContentUpdate If we don't want the content to be update by fetching the url (used when patching instead of posting)
632 */
633 private function upsertEntry(Entry $entry, Request $request, $disableContentUpdate = false)
634 {
635 $title = $request->request->get('title');
636 $tags = $request->request->get('tags', []);
637 $isArchived = $request->request->get('archive');
638 $isStarred = $request->request->get('starred');
1112e547 639 $isPublic = $request->request->get('public');
db0c48af
JB
640 $content = $request->request->get('content');
641 $language = $request->request->get('language');
642 $picture = $request->request->get('preview_picture');
643 $publishedAt = $request->request->get('published_at');
644 $authors = $request->request->get('authors', '');
645
646 try {
647 $this->get('wallabag_core.content_proxy')->updateEntry(
648 $entry,
649 $entry->getUrl(),
650 [
651 'title' => !empty($title) ? $title : $entry->getTitle(),
652 'html' => !empty($content) ? $content : $entry->getContent(),
653 'url' => $entry->getUrl(),
654 'language' => !empty($language) ? $language : $entry->getLanguage(),
655 'date' => !empty($publishedAt) ? $publishedAt : $entry->getPublishedAt(),
656 // faking the open graph preview picture
657 'open_graph' => [
658 'og_image' => !empty($picture) ? $picture : $entry->getPreviewPicture(),
659 ],
660 'authors' => is_string($authors) ? explode(',', $authors) : $entry->getPublishedBy(),
661 ],
662 $disableContentUpdate
663 );
664 } catch (\Exception $e) {
665 $this->get('logger')->error('Error while saving an entry', [
666 'exception' => $e,
667 'entry' => $entry,
668 ]);
669 }
670
671 if (!is_null($isArchived)) {
672 $entry->setArchived((bool) $isArchived);
673 }
674
675 if (!is_null($isStarred)) {
676 $entry->setStarred((bool) $isStarred);
677 }
678
679 if (!empty($tags)) {
680 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
681 }
682
1112e547 683 if (!is_null($isPublic)) {
1112e547
JB
684 if (true === (bool) $isPublic && null === $entry->getUid()) {
685 $entry->generateUid();
d9da186f 686 } elseif (false === (bool) $isPublic) {
a9c6577f 687 $entry->cleanUid();
1112e547
JB
688 }
689 }
690
db0c48af
JB
691 $em = $this->getDoctrine()->getManager();
692 $em->persist($entry);
693 $em->flush();
694
695 // entry saved, dispatch event about it!
696 $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
697 }
900c8448 698}