]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/api/ApiUtils.php
Add strict types for bookmarks management
[github/shaarli/Shaarli.git] / application / api / ApiUtils.php
CommitLineData
18e67967 1<?php
18e67967
A
2namespace Shaarli\Api;
3
4use Shaarli\Api\Exceptions\ApiAuthorizationException;
cf92b4dd 5use Shaarli\Bookmark\Bookmark;
dea72c71 6use Shaarli\Http\Base64Url;
18e67967
A
7
8/**
7a9daac5 9 * REST API utilities
18e67967
A
10 */
11class ApiUtils
12{
13 /**
14 * Validates a JWT token authenticity.
15 *
00af48d9 16 * @param string $token JWT token extracted from the headers.
18e67967
A
17 * @param string $secret API secret set in the settings.
18 *
def39d0d
A
19 * @return bool true on success
20 *
18e67967
A
21 * @throws ApiAuthorizationException the token is not valid.
22 */
23 public static function validateJwtToken($token, $secret)
24 {
25 $parts = explode('.', $token);
26 if (count($parts) != 3 || strlen($parts[0]) == 0 || strlen($parts[1]) == 0) {
27 throw new ApiAuthorizationException('Malformed JWT token');
28 }
29
7a9daac5 30 $genSign = Base64Url::encode(hash_hmac('sha512', $parts[0] .'.'. $parts[1], $secret, true));
18e67967
A
31 if ($parts[2] != $genSign) {
32 throw new ApiAuthorizationException('Invalid JWT signature');
33 }
34
7a9daac5 35 $header = json_decode(Base64Url::decode($parts[0]));
18e67967
A
36 if ($header === null) {
37 throw new ApiAuthorizationException('Invalid JWT header');
38 }
39
7a9daac5 40 $payload = json_decode(Base64Url::decode($parts[1]));
18e67967
A
41 if ($payload === null) {
42 throw new ApiAuthorizationException('Invalid JWT payload');
43 }
44
45 if (empty($payload->iat)
46 || $payload->iat > time()
47 || time() - $payload->iat > ApiMiddleware::$TOKEN_DURATION
48 ) {
49 throw new ApiAuthorizationException('Invalid JWT issued time');
50 }
def39d0d
A
51
52 return true;
18e67967 53 }
c3b00963
A
54
55 /**
56 * Format a Link for the REST API.
57 *
cf92b4dd
A
58 * @param Bookmark $bookmark Bookmark data read from the datastore.
59 * @param string $indexUrl Shaarli's index URL (used for relative URL).
c3b00963
A
60 *
61 * @return array Link data formatted for the REST API.
62 */
cf92b4dd 63 public static function formatLink($bookmark, $indexUrl)
c3b00963 64 {
cf92b4dd 65 $out['id'] = $bookmark->getId();
c3b00963 66 // Not an internal link
cf92b4dd
A
67 if (! $bookmark->isNote()) {
68 $out['url'] = $bookmark->getUrl();
c3b00963 69 } else {
301c7ab1 70 $out['url'] = rtrim($indexUrl, '/') . '/' . ltrim($bookmark->getUrl(), '/');
c3b00963 71 }
cf92b4dd
A
72 $out['shorturl'] = $bookmark->getShortUrl();
73 $out['title'] = $bookmark->getTitle();
74 $out['description'] = $bookmark->getDescription();
75 $out['tags'] = $bookmark->getTags();
76 $out['private'] = $bookmark->isPrivate();
77 $out['created'] = $bookmark->getCreated()->format(\DateTime::ATOM);
78 if (! empty($bookmark->getUpdated())) {
79 $out['updated'] = $bookmark->getUpdated()->format(\DateTime::ATOM);
c3b00963
A
80 } else {
81 $out['updated'] = '';
82 }
83 return $out;
84 }
68016e37
A
85
86 /**
cf92b4dd 87 * Convert a link given through a request, to a valid Bookmark for the datastore.
68016e37
A
88 *
89 * If no URL is provided, it will generate a local note URL.
90 * If no title is provided, it will use the URL as title.
91 *
efb7d21b
A
92 * @param array|null $input Request Link.
93 * @param bool $defaultPrivate Setting defined if a bookmark is private by default.
68016e37 94 *
cf92b4dd 95 * @return Bookmark instance.
68016e37 96 */
efb7d21b 97 public static function buildBookmarkFromRequest(?array $input, bool $defaultPrivate): Bookmark
68016e37 98 {
cf92b4dd
A
99 $bookmark = new Bookmark();
100 $url = ! empty($input['url']) ? cleanup_url($input['url']) : '';
68016e37
A
101 if (isset($input['private'])) {
102 $private = filter_var($input['private'], FILTER_VALIDATE_BOOLEAN);
103 } else {
104 $private = $defaultPrivate;
105 }
106
cf92b4dd
A
107 $bookmark->setTitle(! empty($input['title']) ? $input['title'] : '');
108 $bookmark->setUrl($url);
109 $bookmark->setDescription(! empty($input['description']) ? $input['description'] : '');
110 $bookmark->setTags(! empty($input['tags']) ? $input['tags'] : []);
111 $bookmark->setPrivate($private);
112
b06fc28a
A
113 $created = \DateTime::createFromFormat(\DateTime::ATOM, $input['created'] ?? '');
114 if ($created instanceof \DateTimeInterface) {
115 $bookmark->setCreated($created);
116 }
117 $updated = \DateTime::createFromFormat(\DateTime::ATOM, $input['updated'] ?? '');
118 if ($updated instanceof \DateTimeInterface) {
119 $bookmark->setUpdated($updated);
120 }
121
cf92b4dd 122 return $bookmark;
68016e37 123 }
cf9181dd
A
124
125 /**
126 * Update link fields using an updated link object.
127 *
cf92b4dd
A
128 * @param Bookmark $oldLink data
129 * @param Bookmark $newLink data
cf9181dd 130 *
cf92b4dd 131 * @return Bookmark $oldLink updated with $newLink values
cf9181dd
A
132 */
133 public static function updateLink($oldLink, $newLink)
134 {
cf92b4dd
A
135 $oldLink->setTitle($newLink->getTitle());
136 $oldLink->setUrl($newLink->getUrl());
137 $oldLink->setDescription($newLink->getDescription());
138 $oldLink->setTags($newLink->getTags());
139 $oldLink->setPrivate($newLink->isPrivate());
cf9181dd
A
140
141 return $oldLink;
142 }
d3f42ca4
A
143
144 /**
145 * Format a Tag for the REST API.
146 *
147 * @param string $tag Tag name
cf92b4dd 148 * @param int $occurrences Number of bookmarks using this tag
d3f42ca4
A
149 *
150 * @return array Link data formatted for the REST API.
151 */
152 public static function formatTag($tag, $occurences)
153 {
154 return [
155 'name' => $tag,
156 'occurrences' => $occurences,
157 ];
158 }
18e67967 159}