diff options
Diffstat (limited to 'application/helper')
-rw-r--r-- | application/helper/ApplicationUtils.php | 319 | ||||
-rw-r--r-- | application/helper/DailyPageHelper.php | 208 | ||||
-rw-r--r-- | application/helper/FileUtils.php | 140 |
3 files changed, 667 insertions, 0 deletions
diff --git a/application/helper/ApplicationUtils.php b/application/helper/ApplicationUtils.php new file mode 100644 index 00000000..212dd8e2 --- /dev/null +++ b/application/helper/ApplicationUtils.php | |||
@@ -0,0 +1,319 @@ | |||
1 | <?php | ||
2 | |||
3 | namespace Shaarli\Helper; | ||
4 | |||
5 | use Exception; | ||
6 | use Shaarli\Config\ConfigManager; | ||
7 | |||
8 | /** | ||
9 | * Shaarli (application) utilities | ||
10 | */ | ||
11 | class ApplicationUtils | ||
12 | { | ||
13 | /** | ||
14 | * @var string File containing the current version | ||
15 | */ | ||
16 | public static $VERSION_FILE = 'shaarli_version.php'; | ||
17 | |||
18 | public static $GITHUB_URL = 'https://github.com/shaarli/Shaarli'; | ||
19 | public static $GIT_RAW_URL = 'https://raw.githubusercontent.com/shaarli/Shaarli'; | ||
20 | public static $GIT_BRANCHES = ['latest', 'stable']; | ||
21 | private static $VERSION_START_TAG = '<?php /* '; | ||
22 | private static $VERSION_END_TAG = ' */ ?>'; | ||
23 | |||
24 | /** | ||
25 | * Gets the latest version code from the Git repository | ||
26 | * | ||
27 | * The code is read from the raw content of the version file on the Git server. | ||
28 | * | ||
29 | * @param string $url URL to reach to get the latest version. | ||
30 | * @param int $timeout Timeout to check the URL (in seconds). | ||
31 | * | ||
32 | * @return mixed the version code from the repository if available, else 'false' | ||
33 | */ | ||
34 | public static function getLatestGitVersionCode($url, $timeout = 2) | ||
35 | { | ||
36 | list($headers, $data) = get_http_response($url, $timeout); | ||
37 | |||
38 | if (strpos($headers[0], '200 OK') === false) { | ||
39 | error_log('Failed to retrieve ' . $url); | ||
40 | return false; | ||
41 | } | ||
42 | |||
43 | return $data; | ||
44 | } | ||
45 | |||
46 | /** | ||
47 | * Retrieve the version from a remote URL or a file. | ||
48 | * | ||
49 | * @param string $remote URL or file to fetch. | ||
50 | * @param int $timeout For URLs fetching. | ||
51 | * | ||
52 | * @return bool|string The version or false if it couldn't be retrieved. | ||
53 | */ | ||
54 | public static function getVersion($remote, $timeout = 2) | ||
55 | { | ||
56 | if (startsWith($remote, 'http')) { | ||
57 | if (($data = static::getLatestGitVersionCode($remote, $timeout)) === false) { | ||
58 | return false; | ||
59 | } | ||
60 | } else { | ||
61 | if (!is_file($remote)) { | ||
62 | return false; | ||
63 | } | ||
64 | $data = file_get_contents($remote); | ||
65 | } | ||
66 | |||
67 | return str_replace( | ||
68 | [self::$VERSION_START_TAG, self::$VERSION_END_TAG, PHP_EOL], | ||
69 | ['', '', ''], | ||
70 | $data | ||
71 | ); | ||
72 | } | ||
73 | |||
74 | /** | ||
75 | * Checks if a new Shaarli version has been published on the Git repository | ||
76 | * | ||
77 | * Updates checks are run periodically, according to the following criteria: | ||
78 | * - the update checks are enabled (install, global config); | ||
79 | * - the user is logged in (or this is an open instance); | ||
80 | * - the last check is older than a given interval; | ||
81 | * - the check is non-blocking if the HTTPS connection to Git fails; | ||
82 | * - in case of failure, the update file's modification date is updated, | ||
83 | * to avoid intempestive connection attempts. | ||
84 | * | ||
85 | * @param string $currentVersion the current version code | ||
86 | * @param string $updateFile the file where to store the latest version code | ||
87 | * @param int $checkInterval the minimum interval between update checks (in seconds | ||
88 | * @param bool $enableCheck whether to check for new versions | ||
89 | * @param bool $isLoggedIn whether the user is logged in | ||
90 | * @param string $branch check update for the given branch | ||
91 | * | ||
92 | * @throws Exception an invalid branch has been set for update checks | ||
93 | * | ||
94 | * @return mixed the new version code if available and greater, else 'false' | ||
95 | */ | ||
96 | public static function checkUpdate( | ||
97 | $currentVersion, | ||
98 | $updateFile, | ||
99 | $checkInterval, | ||
100 | $enableCheck, | ||
101 | $isLoggedIn, | ||
102 | $branch = 'stable' | ||
103 | ) { | ||
104 | // Do not check versions for visitors | ||
105 | // Do not check if the user doesn't want to | ||
106 | // Do not check with dev version | ||
107 | if (!$isLoggedIn || empty($enableCheck) || $currentVersion === 'dev') { | ||
108 | return false; | ||
109 | } | ||
110 | |||
111 | if (is_file($updateFile) && (filemtime($updateFile) > time() - $checkInterval)) { | ||
112 | // Shaarli has checked for updates recently - skip HTTP query | ||
113 | $latestKnownVersion = file_get_contents($updateFile); | ||
114 | |||
115 | if (version_compare($latestKnownVersion, $currentVersion) == 1) { | ||
116 | return $latestKnownVersion; | ||
117 | } | ||
118 | return false; | ||
119 | } | ||
120 | |||
121 | if (!in_array($branch, self::$GIT_BRANCHES)) { | ||
122 | throw new Exception( | ||
123 | 'Invalid branch selected for updates: "' . $branch . '"' | ||
124 | ); | ||
125 | } | ||
126 | |||
127 | // Late Static Binding allows overriding within tests | ||
128 | // See http://php.net/manual/en/language.oop5.late-static-bindings.php | ||
129 | $latestVersion = static::getVersion( | ||
130 | self::$GIT_RAW_URL . '/' . $branch . '/' . self::$VERSION_FILE | ||
131 | ); | ||
132 | |||
133 | if (!$latestVersion) { | ||
134 | // Only update the file's modification date | ||
135 | file_put_contents($updateFile, $currentVersion); | ||
136 | return false; | ||
137 | } | ||
138 | |||
139 | // Update the file's content and modification date | ||
140 | file_put_contents($updateFile, $latestVersion); | ||
141 | |||
142 | if (version_compare($latestVersion, $currentVersion) == 1) { | ||
143 | return $latestVersion; | ||
144 | } | ||
145 | |||
146 | return false; | ||
147 | } | ||
148 | |||
149 | /** | ||
150 | * Checks the PHP version to ensure Shaarli can run | ||
151 | * | ||
152 | * @param string $minVersion minimum PHP required version | ||
153 | * @param string $curVersion current PHP version (use PHP_VERSION) | ||
154 | * | ||
155 | * @return bool true on success | ||
156 | * | ||
157 | * @throws Exception the PHP version is not supported | ||
158 | */ | ||
159 | public static function checkPHPVersion($minVersion, $curVersion) | ||
160 | { | ||
161 | if (version_compare($curVersion, $minVersion) < 0) { | ||
162 | $msg = t( | ||
163 | 'Your PHP version is obsolete!' | ||
164 | . ' Shaarli requires at least PHP %s, and thus cannot run.' | ||
165 | . ' Your PHP version has known security vulnerabilities and should be' | ||
166 | . ' updated as soon as possible.' | ||
167 | ); | ||
168 | throw new Exception(sprintf($msg, $minVersion)); | ||
169 | } | ||
170 | return true; | ||
171 | } | ||
172 | |||
173 | /** | ||
174 | * Checks Shaarli has the proper access permissions to its resources | ||
175 | * | ||
176 | * @param ConfigManager $conf Configuration Manager instance. | ||
177 | * @param bool $minimalMode In minimal mode we only check permissions to be able to display a template. | ||
178 | * Currently we only need to be able to read the theme and write in raintpl cache. | ||
179 | * | ||
180 | * @return array A list of the detected configuration issues | ||
181 | */ | ||
182 | public static function checkResourcePermissions(ConfigManager $conf, bool $minimalMode = false): array | ||
183 | { | ||
184 | $errors = []; | ||
185 | $rainTplDir = rtrim($conf->get('resource.raintpl_tpl'), '/'); | ||
186 | |||
187 | // Check script and template directories are readable | ||
188 | foreach ( | ||
189 | [ | ||
190 | 'application', | ||
191 | 'inc', | ||
192 | 'plugins', | ||
193 | $rainTplDir, | ||
194 | $rainTplDir . '/' . $conf->get('resource.theme'), | ||
195 | ] as $path | ||
196 | ) { | ||
197 | if (!is_readable(realpath($path))) { | ||
198 | $errors[] = '"' . $path . '" ' . t('directory is not readable'); | ||
199 | } | ||
200 | } | ||
201 | |||
202 | // Check cache and data directories are readable and writable | ||
203 | if ($minimalMode) { | ||
204 | $folders = [ | ||
205 | $conf->get('resource.raintpl_tmp'), | ||
206 | ]; | ||
207 | } else { | ||
208 | $folders = [ | ||
209 | $conf->get('resource.thumbnails_cache'), | ||
210 | $conf->get('resource.data_dir'), | ||
211 | $conf->get('resource.page_cache'), | ||
212 | $conf->get('resource.raintpl_tmp'), | ||
213 | ]; | ||
214 | } | ||
215 | |||
216 | foreach ($folders as $path) { | ||
217 | if (!is_readable(realpath($path))) { | ||
218 | $errors[] = '"' . $path . '" ' . t('directory is not readable'); | ||
219 | } | ||
220 | if (!is_writable(realpath($path))) { | ||
221 | $errors[] = '"' . $path . '" ' . t('directory is not writable'); | ||
222 | } | ||
223 | } | ||
224 | |||
225 | if ($minimalMode) { | ||
226 | return $errors; | ||
227 | } | ||
228 | |||
229 | // Check configuration files are readable and writable | ||
230 | foreach ( | ||
231 | [ | ||
232 | $conf->getConfigFileExt(), | ||
233 | $conf->get('resource.datastore'), | ||
234 | $conf->get('resource.ban_file'), | ||
235 | $conf->get('resource.log'), | ||
236 | $conf->get('resource.update_check'), | ||
237 | ] as $path | ||
238 | ) { | ||
239 | if (!is_file(realpath($path))) { | ||
240 | # the file may not exist yet | ||
241 | continue; | ||
242 | } | ||
243 | |||
244 | if (!is_readable(realpath($path))) { | ||
245 | $errors[] = '"' . $path . '" ' . t('file is not readable'); | ||
246 | } | ||
247 | if (!is_writable(realpath($path))) { | ||
248 | $errors[] = '"' . $path . '" ' . t('file is not writable'); | ||
249 | } | ||
250 | } | ||
251 | |||
252 | return $errors; | ||
253 | } | ||
254 | |||
255 | /** | ||
256 | * Returns a salted hash representing the current Shaarli version. | ||
257 | * | ||
258 | * Useful for assets browser cache. | ||
259 | * | ||
260 | * @param string $currentVersion of Shaarli | ||
261 | * @param string $salt User personal salt, also used for the authentication | ||
262 | * | ||
263 | * @return string version hash | ||
264 | */ | ||
265 | public static function getVersionHash($currentVersion, $salt) | ||
266 | { | ||
267 | return hash_hmac('sha256', $currentVersion, $salt); | ||
268 | } | ||
269 | |||
270 | /** | ||
271 | * Get a list of PHP extensions used by Shaarli. | ||
272 | * | ||
273 | * @return array[] List of extension with following keys: | ||
274 | * - name: extension name | ||
275 | * - required: whether the extension is required to use Shaarli | ||
276 | * - desc: short description of extension usage in Shaarli | ||
277 | * - loaded: whether the extension is properly loaded or not | ||
278 | */ | ||
279 | public static function getPhpExtensionsRequirement(): array | ||
280 | { | ||
281 | $extensions = [ | ||
282 | ['name' => 'json', 'required' => true, 'desc' => t('Configuration parsing')], | ||
283 | ['name' => 'simplexml', 'required' => true, 'desc' => t('Slim Framework (routing, etc.)')], | ||
284 | ['name' => 'mbstring', 'required' => true, 'desc' => t('Multibyte (Unicode) string support')], | ||
285 | ['name' => 'gd', 'required' => false, 'desc' => t('Required to use thumbnails')], | ||
286 | ['name' => 'intl', 'required' => false, 'desc' => t('Localized text sorting (e.g. e->è->f)')], | ||
287 | ['name' => 'curl', 'required' => false, 'desc' => t('Better retrieval of bookmark metadata and thumbnail')], | ||
288 | ['name' => 'gettext', 'required' => false, 'desc' => t('Use the translation system in gettext mode')], | ||
289 | ['name' => 'ldap', 'required' => false, 'desc' => t('Login using LDAP server')], | ||
290 | ]; | ||
291 | |||
292 | foreach ($extensions as &$extension) { | ||
293 | $extension['loaded'] = extension_loaded($extension['name']); | ||
294 | } | ||
295 | |||
296 | return $extensions; | ||
297 | } | ||
298 | |||
299 | /** | ||
300 | * Return the EOL date of given PHP version. If the version is unknown, | ||
301 | * we return today + 2 years. | ||
302 | * | ||
303 | * @param string $fullVersion PHP version, e.g. 7.4.7 | ||
304 | * | ||
305 | * @return string Date format: YYYY-MM-DD | ||
306 | */ | ||
307 | public static function getPhpEol(string $fullVersion): string | ||
308 | { | ||
309 | preg_match('/(\d+\.\d+)\.\d+/', $fullVersion, $matches); | ||
310 | |||
311 | return [ | ||
312 | '7.1' => '2019-12-01', | ||
313 | '7.2' => '2020-11-30', | ||
314 | '7.3' => '2021-12-06', | ||
315 | '7.4' => '2022-11-28', | ||
316 | '8.0' => '2023-12-01', | ||
317 | ][$matches[1]] ?? (new \DateTime('+2 year'))->format('Y-m-d'); | ||
318 | } | ||
319 | } | ||
diff --git a/application/helper/DailyPageHelper.php b/application/helper/DailyPageHelper.php new file mode 100644 index 00000000..5fabc907 --- /dev/null +++ b/application/helper/DailyPageHelper.php | |||
@@ -0,0 +1,208 @@ | |||
1 | <?php | ||
2 | |||
3 | declare(strict_types=1); | ||
4 | |||
5 | namespace Shaarli\Helper; | ||
6 | |||
7 | use Shaarli\Bookmark\Bookmark; | ||
8 | use Slim\Http\Request; | ||
9 | |||
10 | class DailyPageHelper | ||
11 | { | ||
12 | public const MONTH = 'month'; | ||
13 | public const WEEK = 'week'; | ||
14 | public const DAY = 'day'; | ||
15 | |||
16 | /** | ||
17 | * Extracts the type of the daily to display from the HTTP request parameters | ||
18 | * | ||
19 | * @param Request $request HTTP request | ||
20 | * | ||
21 | * @return string month/week/day | ||
22 | */ | ||
23 | public static function extractRequestedType(Request $request): string | ||
24 | { | ||
25 | if ($request->getQueryParam(static::MONTH) !== null) { | ||
26 | return static::MONTH; | ||
27 | } elseif ($request->getQueryParam(static::WEEK) !== null) { | ||
28 | return static::WEEK; | ||
29 | } | ||
30 | |||
31 | return static::DAY; | ||
32 | } | ||
33 | |||
34 | /** | ||
35 | * Extracts a DateTimeImmutable from provided HTTP request. | ||
36 | * If no parameter is provided, we rely on the creation date of the latest provided created bookmark. | ||
37 | * If the datastore is empty or no bookmark is provided, we use the current date. | ||
38 | * | ||
39 | * @param string $type month/week/day | ||
40 | * @param string|null $requestedDate Input string extracted from the request | ||
41 | * @param Bookmark|null $latestBookmark Latest bookmark found in the datastore (by date) | ||
42 | * | ||
43 | * @return \DateTimeImmutable from input or latest bookmark. | ||
44 | * | ||
45 | * @throws \Exception Type not supported. | ||
46 | */ | ||
47 | public static function extractRequestedDateTime( | ||
48 | string $type, | ||
49 | ?string $requestedDate, | ||
50 | Bookmark $latestBookmark = null | ||
51 | ): \DateTimeImmutable { | ||
52 | $format = static::getFormatByType($type); | ||
53 | if (empty($requestedDate)) { | ||
54 | return $latestBookmark instanceof Bookmark | ||
55 | ? new \DateTimeImmutable($latestBookmark->getCreated()->format(\DateTime::ATOM)) | ||
56 | : new \DateTimeImmutable() | ||
57 | ; | ||
58 | } | ||
59 | |||
60 | // W is not supported by createFromFormat... | ||
61 | if ($type === static::WEEK) { | ||
62 | return (new \DateTimeImmutable()) | ||
63 | ->setISODate((int) substr($requestedDate, 0, 4), (int) substr($requestedDate, 4, 2)) | ||
64 | ; | ||
65 | } | ||
66 | |||
67 | return \DateTimeImmutable::createFromFormat($format, $requestedDate); | ||
68 | } | ||
69 | |||
70 | /** | ||
71 | * Get the DateTime format used by provided type | ||
72 | * Examples: | ||
73 | * - day: 20201016 (<year><month><day>) | ||
74 | * - week: 202041 (<year><week number>) | ||
75 | * - month: 202010 (<year><month>) | ||
76 | * | ||
77 | * @param string $type month/week/day | ||
78 | * | ||
79 | * @return string DateTime compatible format | ||
80 | * | ||
81 | * @see https://www.php.net/manual/en/datetime.format.php | ||
82 | * | ||
83 | * @throws \Exception Type not supported. | ||
84 | */ | ||
85 | public static function getFormatByType(string $type): string | ||
86 | { | ||
87 | switch ($type) { | ||
88 | case static::MONTH: | ||
89 | return 'Ym'; | ||
90 | case static::WEEK: | ||
91 | return 'YW'; | ||
92 | case static::DAY: | ||
93 | return 'Ymd'; | ||
94 | default: | ||
95 | throw new \Exception('Unsupported daily format type'); | ||
96 | } | ||
97 | } | ||
98 | |||
99 | /** | ||
100 | * Get the first DateTime of the time period depending on given datetime and type. | ||
101 | * Note: DateTimeImmutable is required because we rely heavily on DateTime->modify() syntax | ||
102 | * and we don't want to alter original datetime. | ||
103 | * | ||
104 | * @param string $type month/week/day | ||
105 | * @param \DateTimeImmutable $requested DateTime extracted from request input | ||
106 | * (should come from extractRequestedDateTime) | ||
107 | * | ||
108 | * @return \DateTimeInterface First DateTime of the time period | ||
109 | * | ||
110 | * @throws \Exception Type not supported. | ||
111 | */ | ||
112 | public static function getStartDateTimeByType(string $type, \DateTimeImmutable $requested): \DateTimeInterface | ||
113 | { | ||
114 | switch ($type) { | ||
115 | case static::MONTH: | ||
116 | return $requested->modify('first day of this month midnight'); | ||
117 | case static::WEEK: | ||
118 | return $requested->modify('Monday this week midnight'); | ||
119 | case static::DAY: | ||
120 | return $requested->modify('Today midnight'); | ||
121 | default: | ||
122 | throw new \Exception('Unsupported daily format type'); | ||
123 | } | ||
124 | } | ||
125 | |||
126 | /** | ||
127 | * Get the last DateTime of the time period depending on given datetime and type. | ||
128 | * Note: DateTimeImmutable is required because we rely heavily on DateTime->modify() syntax | ||
129 | * and we don't want to alter original datetime. | ||
130 | * | ||
131 | * @param string $type month/week/day | ||
132 | * @param \DateTimeImmutable $requested DateTime extracted from request input | ||
133 | * (should come from extractRequestedDateTime) | ||
134 | * | ||
135 | * @return \DateTimeInterface Last DateTime of the time period | ||
136 | * | ||
137 | * @throws \Exception Type not supported. | ||
138 | */ | ||
139 | public static function getEndDateTimeByType(string $type, \DateTimeImmutable $requested): \DateTimeInterface | ||
140 | { | ||
141 | switch ($type) { | ||
142 | case static::MONTH: | ||
143 | return $requested->modify('last day of this month 23:59:59'); | ||
144 | case static::WEEK: | ||
145 | return $requested->modify('Sunday this week 23:59:59'); | ||
146 | case static::DAY: | ||
147 | return $requested->modify('Today 23:59:59'); | ||
148 | default: | ||
149 | throw new \Exception('Unsupported daily format type'); | ||
150 | } | ||
151 | } | ||
152 | |||
153 | /** | ||
154 | * Get localized description of the time period depending on given datetime and type. | ||
155 | * Example: for a month period, it returns `October, 2020`. | ||
156 | * | ||
157 | * @param string $type month/week/day | ||
158 | * @param \DateTimeImmutable $requested DateTime extracted from request input | ||
159 | * (should come from extractRequestedDateTime) | ||
160 | * | ||
161 | * @return string Localized time period description | ||
162 | * | ||
163 | * @throws \Exception Type not supported. | ||
164 | */ | ||
165 | public static function getDescriptionByType(string $type, \DateTimeImmutable $requested): string | ||
166 | { | ||
167 | switch ($type) { | ||
168 | case static::MONTH: | ||
169 | return $requested->format('F') . ', ' . $requested->format('Y'); | ||
170 | case static::WEEK: | ||
171 | $requested = $requested->modify('Monday this week'); | ||
172 | return t('Week') . ' ' . $requested->format('W') . ' (' . format_date($requested, false) . ')'; | ||
173 | case static::DAY: | ||
174 | $out = ''; | ||
175 | if ($requested->format('Ymd') === date('Ymd')) { | ||
176 | $out = t('Today') . ' - '; | ||
177 | } elseif ($requested->format('Ymd') === date('Ymd', strtotime('-1 days'))) { | ||
178 | $out = t('Yesterday') . ' - '; | ||
179 | } | ||
180 | return $out . format_date($requested, false); | ||
181 | default: | ||
182 | throw new \Exception('Unsupported daily format type'); | ||
183 | } | ||
184 | } | ||
185 | |||
186 | /** | ||
187 | * Get the number of items to display in the RSS feed depending on the given type. | ||
188 | * | ||
189 | * @param string $type month/week/day | ||
190 | * | ||
191 | * @return int number of elements | ||
192 | * | ||
193 | * @throws \Exception Type not supported. | ||
194 | */ | ||
195 | public static function getRssLengthByType(string $type): int | ||
196 | { | ||
197 | switch ($type) { | ||
198 | case static::MONTH: | ||
199 | return 12; // 1 year | ||
200 | case static::WEEK: | ||
201 | return 26; // ~6 months | ||
202 | case static::DAY: | ||
203 | return 30; // ~1 month | ||
204 | default: | ||
205 | throw new \Exception('Unsupported daily format type'); | ||
206 | } | ||
207 | } | ||
208 | } | ||
diff --git a/application/helper/FileUtils.php b/application/helper/FileUtils.php new file mode 100644 index 00000000..e8a2168c --- /dev/null +++ b/application/helper/FileUtils.php | |||
@@ -0,0 +1,140 @@ | |||
1 | <?php | ||
2 | |||
3 | namespace Shaarli\Helper; | ||
4 | |||
5 | use Shaarli\Exceptions\IOException; | ||
6 | |||
7 | /** | ||
8 | * Class FileUtils | ||
9 | * | ||
10 | * Utility class for file manipulation. | ||
11 | */ | ||
12 | class FileUtils | ||
13 | { | ||
14 | /** | ||
15 | * @var string | ||
16 | */ | ||
17 | protected static $phpPrefix = '<?php /* '; | ||
18 | |||
19 | /** | ||
20 | * @var string | ||
21 | */ | ||
22 | protected static $phpSuffix = ' */ ?>'; | ||
23 | |||
24 | /** | ||
25 | * Write data into a file (Shaarli database format). | ||
26 | * The data is stored in a PHP file, as a comment, in compressed base64 format. | ||
27 | * | ||
28 | * The file will be created if it doesn't exist. | ||
29 | * | ||
30 | * @param string $file File path. | ||
31 | * @param mixed $content Content to write. | ||
32 | * | ||
33 | * @return int|bool Number of bytes written or false if it fails. | ||
34 | * | ||
35 | * @throws IOException The destination file can't be written. | ||
36 | */ | ||
37 | public static function writeFlatDB($file, $content) | ||
38 | { | ||
39 | if (is_file($file) && !is_writeable($file)) { | ||
40 | // The datastore exists but is not writeable | ||
41 | throw new IOException($file); | ||
42 | } elseif (!is_file($file) && !is_writeable(dirname($file))) { | ||
43 | // The datastore does not exist and its parent directory is not writeable | ||
44 | throw new IOException(dirname($file)); | ||
45 | } | ||
46 | |||
47 | return file_put_contents( | ||
48 | $file, | ||
49 | self::$phpPrefix . base64_encode(gzdeflate(serialize($content))) . self::$phpSuffix | ||
50 | ); | ||
51 | } | ||
52 | |||
53 | /** | ||
54 | * Read data from a file containing Shaarli database format content. | ||
55 | * | ||
56 | * If the file isn't readable or doesn't exist, default data will be returned. | ||
57 | * | ||
58 | * @param string $file File path. | ||
59 | * @param mixed $default The default value to return if the file isn't readable. | ||
60 | * | ||
61 | * @return mixed The content unserialized, or default if the file isn't readable, or false if it fails. | ||
62 | */ | ||
63 | public static function readFlatDB($file, $default = null) | ||
64 | { | ||
65 | // Note that gzinflate is faster than gzuncompress. | ||
66 | // See: http://www.php.net/manual/en/function.gzdeflate.php#96439 | ||
67 | if (!is_readable($file)) { | ||
68 | return $default; | ||
69 | } | ||
70 | |||
71 | $data = file_get_contents($file); | ||
72 | if ($data == '') { | ||
73 | return $default; | ||
74 | } | ||
75 | |||
76 | return unserialize( | ||
77 | gzinflate( | ||
78 | base64_decode( | ||
79 | substr($data, strlen(self::$phpPrefix), -strlen(self::$phpSuffix)) | ||
80 | ) | ||
81 | ) | ||
82 | ); | ||
83 | } | ||
84 | |||
85 | /** | ||
86 | * Recursively deletes a folder content, and deletes itself optionally. | ||
87 | * If an excluded file is found, folders won't be deleted. | ||
88 | * | ||
89 | * Additional security: raise an exception if it tries to delete a folder outside of Shaarli directory. | ||
90 | * | ||
91 | * @param string $path | ||
92 | * @param bool $selfDelete Delete the provided folder if true, only its content if false. | ||
93 | * @param array $exclude | ||
94 | */ | ||
95 | public static function clearFolder(string $path, bool $selfDelete, array $exclude = []): bool | ||
96 | { | ||
97 | $skipped = false; | ||
98 | |||
99 | if (!is_dir($path)) { | ||
100 | throw new IOException(t('Provided path is not a directory.')); | ||
101 | } | ||
102 | |||
103 | if (!static::isPathInShaarliFolder($path)) { | ||
104 | throw new IOException(t('Trying to delete a folder outside of Shaarli path.')); | ||
105 | } | ||
106 | |||
107 | foreach (new \DirectoryIterator($path) as $file) { | ||
108 | if ($file->isDot()) { | ||
109 | continue; | ||
110 | } | ||
111 | |||
112 | if (in_array($file->getBasename(), $exclude, true)) { | ||
113 | $skipped = true; | ||
114 | continue; | ||
115 | } | ||
116 | |||
117 | if ($file->isFile()) { | ||
118 | unlink($file->getPathname()); | ||
119 | } elseif ($file->isDir()) { | ||
120 | $skipped = static::clearFolder($file->getRealPath(), true, $exclude) || $skipped; | ||
121 | } | ||
122 | } | ||
123 | |||
124 | if ($selfDelete && !$skipped) { | ||
125 | rmdir($path); | ||
126 | } | ||
127 | |||
128 | return $skipped; | ||
129 | } | ||
130 | |||
131 | /** | ||
132 | * Checks that the given path is inside Shaarli directory. | ||
133 | */ | ||
134 | public static function isPathInShaarliFolder(string $path): bool | ||
135 | { | ||
136 | $rootDirectory = dirname(dirname(dirname(__FILE__))); | ||
137 | |||
138 | return strpos(realpath($path), $rootDirectory) !== false; | ||
139 | } | ||
140 | } | ||