-
-
Notifications
You must be signed in to change notification settings - Fork 87
/
Util.php
455 lines (384 loc) · 12.7 KB
/
Util.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
<?php
declare(strict_types=1);
namespace OCA\Memories;
use OC\Files\Search\SearchBinaryOperator;
use OC\Files\Search\SearchComparison;
use OC\Files\Search\SearchQuery;
use OCA\Memories\AppInfo\Application;
use OCA\Memories\Settings\SystemConfig;
use OCP\App\IAppManager;
use OCP\Files\Node;
use OCP\Files\Search\ISearchBinaryOperator;
use OCP\Files\Search\ISearchComparison;
use OCP\IConfig;
class Util
{
use UtilController;
public const ARCHIVE_FOLDER = '.archive';
/**
* Get host CPU architecture (amd64 or aarch64).
*
* @psalm-return 'aarch64'|'amd64'|null
*/
public static function getArch(): ?string
{
$uname = strtolower(php_uname('m') ?: 'unknown');
if (str_contains($uname, 'aarch64') || str_contains($uname, 'arm64')) {
return 'aarch64';
}
if (str_contains($uname, 'x86_64') || str_contains($uname, 'amd64')) {
return 'amd64';
}
return null;
}
/**
* Get the libc type for host (glibc or musl).
*
* @psalm-return 'glibc'|'musl'|null
*/
public static function getLibc(): ?string
{
/** @psalm-suppress ForbiddenCode */
$ldd = strtolower(shell_exec('ldd --version 2>&1') ?: 'unknown');
if (str_contains($ldd, 'musl')) {
return 'musl';
}
if (str_contains($ldd, 'glibc')) {
return 'glibc';
}
return null;
}
/**
* Check if albums are enabled for this user.
*/
public static function albumsIsEnabled(): bool
{
$appManager = \OC::$server->get(IAppManager::class);
if (!$appManager->isEnabledForUser('photos')) {
return false;
}
$v = $appManager->getAppVersion('photos');
return version_compare($v, '1.7.0', '>=');
}
/**
* Check if tags is enabled for this user.
*/
public static function tagsIsEnabled(): bool
{
return \OC::$server->get(IAppManager::class)->isEnabledForUser('systemtags');
}
/**
* Check if recognize is enabled for this user.
*/
public static function recognizeIsEnabled(): bool
{
if (!self::recognizeIsInstalled()) {
return false;
}
$config = \OC::$server->get(IConfig::class);
if ('true' !== $config->getAppValue('recognize', 'faces.enabled', 'false')) {
return false;
}
return true;
}
/**
* Check if recognize is installed.
*/
public static function recognizeIsInstalled(): bool
{
$appManager = \OC::$server->get(IAppManager::class);
if (!$appManager->isEnabledForUser('recognize')) {
return false;
}
$v = $appManager->getAppVersion('recognize');
return version_compare($v, '3.8.0', '>=');
}
/**
* Check if Face Recognition is enabled by the user.
*/
public static function facerecognitionIsEnabled(): bool
{
if (!self::facerecognitionIsInstalled()) {
return false;
}
try {
return 'true' === \OC::$server->get(IConfig::class)
->getUserValue(self::getUID(), 'facerecognition', 'enabled', 'false')
;
} catch (\Exception) {
// not logged in
}
return false;
}
/**
* Check if Face Recognition is installed and enabled for this user.
*/
public static function facerecognitionIsInstalled(): bool
{
$appManager = \OC::$server->get(IAppManager::class);
if (!$appManager->isEnabledForUser('facerecognition')) {
return false;
}
$v = $appManager->getAppVersion('facerecognition');
return version_compare($v, '0.9.10-beta.2', '>=');
}
/**
* Check if preview generator is installed.
*/
public static function previewGeneratorIsEnabled(): bool
{
return \OC::$server->get(IAppManager::class)->isEnabledForUser('previewgenerator');
}
/**
* Check if link sharing is allowed.
*
* @todo Check if link sharing is enabled to show the button
*
* @psalm-suppress PossiblyUnusedMethod
*/
public static function isLinkSharingEnabled(): bool
{
$config = \OC::$server->get(IConfig::class);
// Check if the shareAPI is enabled
if ('yes' !== $config->getAppValue('core', 'shareapi_enabled', 'yes')) {
return false;
}
// Check whether public sharing is enabled
if ('yes' !== $config->getAppValue('core', 'shareapi_allow_links', 'yes')) {
return false;
}
return true;
}
/**
* Force permissions on a node.
*
* @param Node $node File to patch
* @param int $permissions Permissions to set
*/
public static function forcePermissions(Node &$node, int $permissions): void
{
/** @var \OC\Files\Node\Node $node */
$fileInfo = $node->getFileInfo();
/** @var \OC\Files\FileInfo $fileInfo */
$fileInfo['permissions'] = $permissions;
}
/**
* Convert permissions to string.
*/
public static function permissionsToStr(int $permissions): string
{
$str = '';
if ($permissions & \OCP\Constants::PERMISSION_CREATE) {
$str .= 'C';
}
if ($permissions & \OCP\Constants::PERMISSION_READ) {
$str .= 'R';
}
if ($permissions & \OCP\Constants::PERMISSION_UPDATE) {
$str .= 'U';
}
if ($permissions & \OCP\Constants::PERMISSION_DELETE) {
$str .= 'D';
}
if ($permissions & \OCP\Constants::PERMISSION_SHARE) {
$str .= 'S';
}
// Other permissions that are set elsewhere
// L - Disable download (negative permission)
return $str;
}
/**
* Add OG metadata to a page for a node.
*
* @param Node $node Node to get metadata from
* @param string $title Title of the page
* @param string $url URL of the page
* @param array $previewArgs Preview arguments (e.g. token)
*/
public static function addOgMetadata(Node $node, string $title, string $url, array $previewArgs): void
{
// Add title
\OCP\Util::addHeader('meta', ['property' => 'og:title', 'content' => $title]);
// Get first node if folder
if ($node instanceof \OCP\Files\Folder) {
if (null === ($node = self::getAnyMedia($node))) {
return; // no media in folder
}
}
// Add file type
$mimeType = $node->getMimeType();
if (str_starts_with($mimeType, 'image/')) {
\OCP\Util::addHeader('meta', ['property' => 'og:type', 'content' => 'image']);
} elseif (str_starts_with($mimeType, 'video/')) {
\OCP\Util::addHeader('meta', ['property' => 'og:type', 'content' => 'video']);
}
// Add OG url
\OCP\Util::addHeader('meta', ['property' => 'og:url', 'content' => $url]);
// Get URL generator
$urlGenerator = \OC::$server->get(\OCP\IURLGenerator::class);
// Add OG image
$preview = $urlGenerator->linkToRouteAbsolute('memories.Image.preview', array_merge($previewArgs, [
'id' => $node->getId(),
'x' => 1024,
'y' => 1024,
'a' => true,
]));
\OCP\Util::addHeader('meta', ['property' => 'og:image', 'content' => $preview]);
}
/**
* Get a random image or video from a given folder.
*/
public static function getAnyMedia(\OCP\Files\Folder $folder): ?Node
{
$query = new SearchQuery(new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_OR, [
new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', 'image/%'),
new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', 'video/%'),
]), 1, 0, [], null);
$nodes = $folder->search($query);
if (0 === \count($nodes)) {
return null;
}
return $nodes[0];
}
/**
* Check if any encryption is enabled that we can not cope with
* such as end-to-end encryption.
*/
public static function isEncryptionEnabled(): bool
{
$encryptionManager = \OC::$server->get(\OCP\Encryption\IManager::class);
if ($encryptionManager->isEnabled()) {
// Server-side encryption (OC_DEFAULT_MODULE) is okay, others like e2e are not
return 'OC_DEFAULT_MODULE' !== $encryptionManager->getDefaultEncryptionModuleId();
}
return false;
}
/**
* Get list of timeline paths as array.
*
* @return string[] List of paths
*/
public static function getTimelinePaths(string $uid): array
{
$paths = \OC::$server->get(IConfig::class)
->getUserValue($uid, Application::APPNAME, 'timelinePath', null)
?: SystemConfig::get('memories.timeline.default_path');
return array_map(
static fn ($path) => self::sanitizePath(trim($path))
?? throw new \InvalidArgumentException("Invalid timeline path: {$path}"),
explode(';', $paths),
);
}
/**
* Run a callback in a transaction.
* It returns the same type as the return type of the closure.
*
* @template T
*
* @psalm-param \Closure(): T $callback
*
* @psalm-return T
*/
public static function transaction(\Closure $callback): mixed
{
$connection = \OC::$server->get(\OCP\IDBConnection::class);
$connection->beginTransaction();
try {
$val = $callback();
$connection->commit();
return $val;
} catch (\Throwable $e) {
$connection->rollBack();
throw $e;
}
}
/**
* Sanitize a path to keep only ASCII characters and special characters.
* Null will be returned on error.
*/
public static function sanitizePath(string $path): ?string
{
// remove double slashes and such
$normalized = \OC\Files\Filesystem::normalizePath($path, false);
// look for invalid characters and pattern
if (!\OC\Files\Filesystem::isValidPath($normalized)) {
return null;
}
return $normalized;
}
/**
* Convert SQL UTC date to timestamp.
*/
public static function sqlUtcToTimestamp(string $sqlDate): int
{
try {
return (new \DateTime($sqlDate, new \DateTimeZone('UTC')))->getTimestamp();
} catch (\Throwable) {
return 0;
}
}
/**
* Explode a string into fixed number of components.
*
* @param non-empty-string $delimiter Delimiter
* @param string $string String to explode
* @param int $count Number of components
*
* @return string[] Array of components
*/
public static function explode_exact(string $delimiter, string $string, int $count): array
{
return array_pad(explode($delimiter, $string, $count), $count, '');
}
/**
* Checks if the API call was made from a native interface.
*/
public static function callerIsNative(): bool
{
// Should not use IRequest here since this method is called during registration
return 'gallery.memories' === ($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '')
|| str_contains($_SERVER['HTTP_USER_AGENT'] ?? '', 'MemoriesNative');
}
/**
* Get the version of the native caller.
*/
public static function callerNativeVersion(): ?string
{
$userAgent = \OC::$server->get(\OCP\IRequest::class)->getHeader('User-Agent');
$matches = [];
if (preg_match('/MemoriesNative\/([0-9.]+)/', $userAgent, $matches)) {
return $matches[1];
}
return null;
}
/**
* Register a signal handler with pcntl for SIGINT.
*/
public static function registerInterruptHandler(string $name, callable $callback): void
{
// Only register signal handlers in CLI mode
if (!\OC::$CLI || !\extension_loaded('pcntl')) {
return;
}
// Register handler only once
static $handlers = [];
if ($handlers[$name] ?? null) {
return;
}
// Check if this is the first handler
$registered = \count($handlers) > 0;
// Register handler
$handlers[$name] = $callback;
// pcntl_signal is already registered
if ($registered) {
return;
}
// Register handler
pcntl_signal(SIGINT, static function () use ($handlers): void {
foreach ($handlers as $handler) {
$handler();
}
exit(1);
});
}
}