3 namespace Shaarli\Api\Controllers
;
5 use Shaarli\Api\ApiUtils
;
6 use Shaarli\Api\Exceptions\ApiBadParametersException
;
8 use Slim\Http\Response
;
13 * REST API Controller: all services related to links collection.
15 * @package Api\Controllers
16 * @see http://shaarli.github.io/api-documentation/#links-links-collection
18 class Links
extends ApiController
21 * @var int Number of links returned if no limit is provided.
23 public static $DEFAULT_LIMIT = 20;
26 * Retrieve a list of links, allowing different filters.
28 * @param Request $request Slim request.
29 * @param Response $response Slim response.
31 * @return Response response.
33 * @throws ApiBadParametersException Invalid parameters.
35 public function getLinks($request, $response)
37 $private = $request->getParam('private');
38 $links = $this->linkDb
->filterSearch(
40 'searchtags' => $request->getParam('searchtags', ''),
41 'searchterm' => $request->getParam('searchterm', ''),
44 $private === 'true' || $private === '1'
47 // Return links from the {offset}th link, starting from 0.
48 $offset = $request->getParam('offset');
49 if (! empty($offset) && ! ctype_digit($offset)) {
50 throw new ApiBadParametersException('Invalid offset');
52 $offset = ! empty($offset) ? intval($offset) : 0;
53 if ($offset > count($links)) {
54 return $response->withJson([], 200, $this->jsonStyle
);
57 // limit parameter is either a number of links or 'all' for everything.
58 $limit = $request->getParam('limit');
60 $limit = self
::$DEFAULT_LIMIT;
62 else if (ctype_digit($limit)) {
63 $limit = intval($limit);
64 } else if ($limit === 'all') {
65 $limit = count($links);
67 throw new ApiBadParametersException('Invalid limit');
70 // 'environment' is set by Slim and encapsulate $_SERVER.
71 $index = index_url($this->ci
['environment']);
75 foreach ($links as $link) {
76 if (count($out) >= $limit) {
79 if ($cpt++
>= $offset) {
80 $out[] = ApiUtils
::formatLink($link, $index);
84 return $response->withJson($out, 200, $this->jsonStyle
);