]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/api/controllers/Links.php
Merge pull request #768 from ArthurHoaro/feature/get-public-links
[github/shaarli/Shaarli.git] / application / api / controllers / Links.php
CommitLineData
c3b00963
A
1<?php
2
3namespace Shaarli\Api\Controllers;
4
5use Shaarli\Api\ApiUtils;
6use Shaarli\Api\Exceptions\ApiBadParametersException;
7use Slim\Http\Request;
8use Slim\Http\Response;
9
10/**
11 * Class Links
12 *
13 * REST API Controller: all services related to links collection.
14 *
15 * @package Api\Controllers
16 * @see http://shaarli.github.io/api-documentation/#links-links-collection
17 */
18class Links extends ApiController
19{
20 /**
21 * @var int Number of links returned if no limit is provided.
22 */
23 public static $DEFAULT_LIMIT = 20;
24
25 /**
26 * Retrieve a list of links, allowing different filters.
27 *
28 * @param Request $request Slim request.
29 * @param Response $response Slim response.
30 *
31 * @return Response response.
32 *
33 * @throws ApiBadParametersException Invalid parameters.
34 */
35 public function getLinks($request, $response)
36 {
37 $private = $request->getParam('private');
38 $links = $this->linkDb->filterSearch(
39 [
40 'searchtags' => $request->getParam('searchtags', ''),
41 'searchterm' => $request->getParam('searchterm', ''),
42 ],
43 false,
7f96d9ec
A
44 // to updated in another PR depending on the API doc
45 ($private === 'true' || $private === '1') ? 'private' : 'all'
c3b00963
A
46 );
47
48 // Return links from the {offset}th link, starting from 0.
49 $offset = $request->getParam('offset');
50 if (! empty($offset) && ! ctype_digit($offset)) {
51 throw new ApiBadParametersException('Invalid offset');
52 }
53 $offset = ! empty($offset) ? intval($offset) : 0;
54 if ($offset > count($links)) {
55 return $response->withJson([], 200, $this->jsonStyle);
56 }
57
58 // limit parameter is either a number of links or 'all' for everything.
59 $limit = $request->getParam('limit');
60 if (empty($limit)) {
61 $limit = self::$DEFAULT_LIMIT;
62 }
63 else if (ctype_digit($limit)) {
64 $limit = intval($limit);
65 } else if ($limit === 'all') {
66 $limit = count($links);
67 } else {
68 throw new ApiBadParametersException('Invalid limit');
69 }
70
71 // 'environment' is set by Slim and encapsulate $_SERVER.
72 $index = index_url($this->ci['environment']);
73
74 $out = [];
75 $cpt = 0;
76 foreach ($links as $link) {
77 if (count($out) >= $limit) {
78 break;
79 }
80 if ($cpt++ >= $offset) {
81 $out[] = ApiUtils::formatLink($link, $index);
82 }
83 }
84
85 return $response->withJson($out, 200, $this->jsonStyle);
86 }
87}