Links.php 2.5 KB

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