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