]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/api/controllers/History.php
API: Get History endpoint
[github/shaarli/Shaarli.git] / application / api / controllers / History.php
1 <?php
2
3
4 namespace Shaarli\Api\Controllers;
5
6 use Shaarli\Api\Exceptions\ApiBadParametersException;
7 use Slim\Http\Request;
8 use Slim\Http\Response;
9
10 /**
11 * Class History
12 *
13 * REST API Controller: /history
14 *
15 * @package Shaarli\Api\Controllers
16 */
17 class History extends ApiController
18 {
19 /**
20 * Service providing operation regarding Shaarli datastore and settings.
21 *
22 * @param Request $request Slim request.
23 * @param Response $response Slim response.
24 *
25 * @return Response response.
26 *
27 * @throws ApiBadParametersException Invalid parameters.
28 */
29 public function getHistory($request, $response)
30 {
31 $history = (new \History($this->conf->get('resource.history')))->getHistory();
32 $history = array_reverse($history);
33
34 // Return history operations from the {offset}th, starting from {since}.
35 $since = \DateTime::createFromFormat(\DateTime::ATOM, $request->getParam('since'));
36 $offset = $request->getParam('offset');
37 if (empty($offset)) {
38 $offset = 0;
39 }
40 else if (ctype_digit($offset)) {
41 $offset = (int) $offset;
42 } else {
43 throw new ApiBadParametersException('Invalid offset');
44 }
45
46 // limit parameter is either a number of links or 'all' for everything.
47 $limit = $request->getParam('limit');
48 if (empty($limit)) {
49 $limit = count($history);
50 } else if (ctype_digit($limit)) {
51 $limit = (int) $limit;
52 } else {
53 throw new ApiBadParametersException('Invalid limit');
54 }
55
56 $out = [];
57 $i = 0;
58 foreach ($history as $entry) {
59 if ((! empty($since) && $entry['datetime'] <= $since) || count($out) >= $limit) {
60 break;
61 }
62 if (++$i > $offset) {
63 $out[$i] = $entry;
64 $out[$i]['datetime'] = $out[$i]['datetime']->format(\DateTime::ATOM);
65 }
66 }
67 $out = array_values($out);
68
69 return $response->withJson($out, 200, $this->jsonStyle);
70 }
71 }