Passed
Push — master ( 0bca48...f312cf )
by Roeland
10:14
created
lib/private/legacy/OC_Helper.php 1 patch
Indentation   +552 added lines, -552 removed lines patch added patch discarded remove patch
@@ -50,556 +50,556 @@
 block discarded – undo
50 50
  * Collection of useful functions
51 51
  */
52 52
 class OC_Helper {
53
-	private static $templateManager;
54
-
55
-	/**
56
-	 * Make a human file size
57
-	 * @param int $bytes file size in bytes
58
-	 * @return string a human readable file size
59
-	 *
60
-	 * Makes 2048 to 2 kB.
61
-	 */
62
-	public static function humanFileSize($bytes) {
63
-		if ($bytes < 0) {
64
-			return "?";
65
-		}
66
-		if ($bytes < 1024) {
67
-			return "$bytes B";
68
-		}
69
-		$bytes = round($bytes / 1024, 0);
70
-		if ($bytes < 1024) {
71
-			return "$bytes KB";
72
-		}
73
-		$bytes = round($bytes / 1024, 1);
74
-		if ($bytes < 1024) {
75
-			return "$bytes MB";
76
-		}
77
-		$bytes = round($bytes / 1024, 1);
78
-		if ($bytes < 1024) {
79
-			return "$bytes GB";
80
-		}
81
-		$bytes = round($bytes / 1024, 1);
82
-		if ($bytes < 1024) {
83
-			return "$bytes TB";
84
-		}
85
-
86
-		$bytes = round($bytes / 1024, 1);
87
-		return "$bytes PB";
88
-	}
89
-
90
-	/**
91
-	 * Make a computer file size
92
-	 * @param string $str file size in human readable format
93
-	 * @return float|bool a file size in bytes
94
-	 *
95
-	 * Makes 2kB to 2048.
96
-	 *
97
-	 * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
98
-	 */
99
-	public static function computerFileSize($str) {
100
-		$str = strtolower($str);
101
-		if (is_numeric($str)) {
102
-			return (float)$str;
103
-		}
104
-
105
-		$bytes_array = [
106
-			'b' => 1,
107
-			'k' => 1024,
108
-			'kb' => 1024,
109
-			'mb' => 1024 * 1024,
110
-			'm' => 1024 * 1024,
111
-			'gb' => 1024 * 1024 * 1024,
112
-			'g' => 1024 * 1024 * 1024,
113
-			'tb' => 1024 * 1024 * 1024 * 1024,
114
-			't' => 1024 * 1024 * 1024 * 1024,
115
-			'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
116
-			'p' => 1024 * 1024 * 1024 * 1024 * 1024,
117
-		];
118
-
119
-		$bytes = (float)$str;
120
-
121
-		if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
122
-			$bytes *= $bytes_array[$matches[1]];
123
-		} else {
124
-			return false;
125
-		}
126
-
127
-		$bytes = round($bytes);
128
-
129
-		return $bytes;
130
-	}
131
-
132
-	/**
133
-	 * Recursive copying of folders
134
-	 * @param string $src source folder
135
-	 * @param string $dest target folder
136
-	 *
137
-	 */
138
-	public static function copyr($src, $dest) {
139
-		if (is_dir($src)) {
140
-			if (!is_dir($dest)) {
141
-				mkdir($dest);
142
-			}
143
-			$files = scandir($src);
144
-			foreach ($files as $file) {
145
-				if ($file != "." && $file != "..") {
146
-					self::copyr("$src/$file", "$dest/$file");
147
-				}
148
-			}
149
-		} elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
150
-			copy($src, $dest);
151
-		}
152
-	}
153
-
154
-	/**
155
-	 * Recursive deletion of folders
156
-	 * @param string $dir path to the folder
157
-	 * @param bool $deleteSelf if set to false only the content of the folder will be deleted
158
-	 * @return bool
159
-	 */
160
-	public static function rmdirr($dir, $deleteSelf = true) {
161
-		if (is_dir($dir)) {
162
-			$files = new RecursiveIteratorIterator(
163
-				new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
164
-				RecursiveIteratorIterator::CHILD_FIRST
165
-			);
166
-
167
-			foreach ($files as $fileInfo) {
168
-				/** @var SplFileInfo $fileInfo */
169
-				if ($fileInfo->isLink()) {
170
-					unlink($fileInfo->getPathname());
171
-				} elseif ($fileInfo->isDir()) {
172
-					rmdir($fileInfo->getRealPath());
173
-				} else {
174
-					unlink($fileInfo->getRealPath());
175
-				}
176
-			}
177
-			if ($deleteSelf) {
178
-				rmdir($dir);
179
-			}
180
-		} elseif (file_exists($dir)) {
181
-			if ($deleteSelf) {
182
-				unlink($dir);
183
-			}
184
-		}
185
-		if (!$deleteSelf) {
186
-			return true;
187
-		}
188
-
189
-		return !file_exists($dir);
190
-	}
191
-
192
-	/**
193
-	 * @deprecated 18.0.0
194
-	 * @return \OC\Files\Type\TemplateManager
195
-	 */
196
-	public static function getFileTemplateManager() {
197
-		if (!self::$templateManager) {
198
-			self::$templateManager = new \OC\Files\Type\TemplateManager();
199
-		}
200
-		return self::$templateManager;
201
-	}
202
-
203
-	/**
204
-	 * detect if a given program is found in the search PATH
205
-	 *
206
-	 * @param string $name
207
-	 * @param bool $path
208
-	 * @internal param string $program name
209
-	 * @internal param string $optional search path, defaults to $PATH
210
-	 * @return bool    true if executable program found in path
211
-	 */
212
-	public static function canExecute($name, $path = false) {
213
-		// path defaults to PATH from environment if not set
214
-		if ($path === false) {
215
-			$path = getenv("PATH");
216
-		}
217
-		// we look for an executable file of that name
218
-		$exts = [""];
219
-		$check_fn = "is_executable";
220
-		// Default check will be done with $path directories :
221
-		$dirs = explode(PATH_SEPARATOR, $path);
222
-		// WARNING : We have to check if open_basedir is enabled :
223
-		$obd = OC::$server->get(IniGetWrapper::class)->getString('open_basedir');
224
-		if ($obd != "none") {
225
-			$obd_values = explode(PATH_SEPARATOR, $obd);
226
-			if (count($obd_values) > 0 and $obd_values[0]) {
227
-				// open_basedir is in effect !
228
-				// We need to check if the program is in one of these dirs :
229
-				$dirs = $obd_values;
230
-			}
231
-		}
232
-		foreach ($dirs as $dir) {
233
-			foreach ($exts as $ext) {
234
-				if ($check_fn("$dir/$name" . $ext)) {
235
-					return true;
236
-				}
237
-			}
238
-		}
239
-		return false;
240
-	}
241
-
242
-	/**
243
-	 * copy the contents of one stream to another
244
-	 *
245
-	 * @param resource $source
246
-	 * @param resource $target
247
-	 * @return array the number of bytes copied and result
248
-	 */
249
-	public static function streamCopy($source, $target) {
250
-		if (!$source or !$target) {
251
-			return [0, false];
252
-		}
253
-		$bufSize = 8192;
254
-		$result = true;
255
-		$count = 0;
256
-		while (!feof($source)) {
257
-			$buf = fread($source, $bufSize);
258
-			$bytesWritten = fwrite($target, $buf);
259
-			if ($bytesWritten !== false) {
260
-				$count += $bytesWritten;
261
-			}
262
-			// note: strlen is expensive so only use it when necessary,
263
-			// on the last block
264
-			if ($bytesWritten === false
265
-				|| ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
266
-			) {
267
-				// write error, could be disk full ?
268
-				$result = false;
269
-				break;
270
-			}
271
-		}
272
-		return [$count, $result];
273
-	}
274
-
275
-	/**
276
-	 * Adds a suffix to the name in case the file exists
277
-	 *
278
-	 * @param string $path
279
-	 * @param string $filename
280
-	 * @return string
281
-	 */
282
-	public static function buildNotExistingFileName($path, $filename) {
283
-		$view = \OC\Files\Filesystem::getView();
284
-		return self::buildNotExistingFileNameForView($path, $filename, $view);
285
-	}
286
-
287
-	/**
288
-	 * Adds a suffix to the name in case the file exists
289
-	 *
290
-	 * @param string $path
291
-	 * @param string $filename
292
-	 * @return string
293
-	 */
294
-	public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
295
-		if ($path === '/') {
296
-			$path = '';
297
-		}
298
-		if ($pos = strrpos($filename, '.')) {
299
-			$name = substr($filename, 0, $pos);
300
-			$ext = substr($filename, $pos);
301
-		} else {
302
-			$name = $filename;
303
-			$ext = '';
304
-		}
305
-
306
-		$newpath = $path . '/' . $filename;
307
-		if ($view->file_exists($newpath)) {
308
-			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
309
-				//Replace the last "(number)" with "(number+1)"
310
-				$last_match = count($matches[0]) - 1;
311
-				$counter = $matches[1][$last_match][0] + 1;
312
-				$offset = $matches[0][$last_match][1];
313
-				$match_length = strlen($matches[0][$last_match][0]);
314
-			} else {
315
-				$counter = 2;
316
-				$match_length = 0;
317
-				$offset = false;
318
-			}
319
-			do {
320
-				if ($offset) {
321
-					//Replace the last "(number)" with "(number+1)"
322
-					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
323
-				} else {
324
-					$newname = $name . ' (' . $counter . ')';
325
-				}
326
-				$newpath = $path . '/' . $newname . $ext;
327
-				$counter++;
328
-			} while ($view->file_exists($newpath));
329
-		}
330
-
331
-		return $newpath;
332
-	}
333
-
334
-	/**
335
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
336
-	 *
337
-	 * @param array $input The array to work on
338
-	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
339
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
340
-	 * @return array
341
-	 *
342
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
343
-	 * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
344
-	 *
345
-	 */
346
-	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
347
-		$case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
348
-		$ret = [];
349
-		foreach ($input as $k => $v) {
350
-			$ret[mb_convert_case($k, $case, $encoding)] = $v;
351
-		}
352
-		return $ret;
353
-	}
354
-
355
-	/**
356
-	 * performs a search in a nested array
357
-	 * @param array $haystack the array to be searched
358
-	 * @param string $needle the search string
359
-	 * @param mixed $index optional, only search this key name
360
-	 * @return mixed the key of the matching field, otherwise false
361
-	 *
362
-	 * performs a search in a nested array
363
-	 *
364
-	 * taken from http://www.php.net/manual/en/function.array-search.php#97645
365
-	 */
366
-	public static function recursiveArraySearch($haystack, $needle, $index = null) {
367
-		$aIt = new RecursiveArrayIterator($haystack);
368
-		$it = new RecursiveIteratorIterator($aIt);
369
-
370
-		while ($it->valid()) {
371
-			if (((isset($index) and ($it->key() == $index)) or !isset($index)) and ($it->current() == $needle)) {
372
-				return $aIt->key();
373
-			}
374
-
375
-			$it->next();
376
-		}
377
-
378
-		return false;
379
-	}
380
-
381
-	/**
382
-	 * calculates the maximum upload size respecting system settings, free space and user quota
383
-	 *
384
-	 * @param string $dir the current folder where the user currently operates
385
-	 * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
386
-	 * @return int number of bytes representing
387
-	 */
388
-	public static function maxUploadFilesize($dir, $freeSpace = null) {
389
-		if (is_null($freeSpace) || $freeSpace < 0) {
390
-			$freeSpace = self::freeSpace($dir);
391
-		}
392
-		return min($freeSpace, self::uploadLimit());
393
-	}
394
-
395
-	/**
396
-	 * Calculate free space left within user quota
397
-	 *
398
-	 * @param string $dir the current folder where the user currently operates
399
-	 * @return int number of bytes representing
400
-	 */
401
-	public static function freeSpace($dir) {
402
-		$freeSpace = \OC\Files\Filesystem::free_space($dir);
403
-		if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
404
-			$freeSpace = max($freeSpace, 0);
405
-			return $freeSpace;
406
-		} else {
407
-			return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
408
-		}
409
-	}
410
-
411
-	/**
412
-	 * Calculate PHP upload limit
413
-	 *
414
-	 * @return int PHP upload file size limit
415
-	 */
416
-	public static function uploadLimit() {
417
-		$ini = \OC::$server->get(IniGetWrapper::class);
418
-		$upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
419
-		$post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
420
-		if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
421
-			return INF;
422
-		} elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
423
-			return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
424
-		} else {
425
-			return min($upload_max_filesize, $post_max_size);
426
-		}
427
-	}
428
-
429
-	/**
430
-	 * Checks if a function is available
431
-	 *
432
-	 * @param string $function_name
433
-	 * @return bool
434
-	 */
435
-	public static function is_function_enabled($function_name) {
436
-		if (!function_exists($function_name)) {
437
-			return false;
438
-		}
439
-		$ini = \OC::$server->get(IniGetWrapper::class);
440
-		$disabled = explode(',', $ini->get('disable_functions') ?: '');
441
-		$disabled = array_map('trim', $disabled);
442
-		if (in_array($function_name, $disabled)) {
443
-			return false;
444
-		}
445
-		$disabled = explode(',', $ini->get('suhosin.executor.func.blacklist') ?: '');
446
-		$disabled = array_map('trim', $disabled);
447
-		if (in_array($function_name, $disabled)) {
448
-			return false;
449
-		}
450
-		return true;
451
-	}
452
-
453
-	/**
454
-	 * Try to find a program
455
-	 *
456
-	 * @param string $program
457
-	 * @return null|string
458
-	 */
459
-	public static function findBinaryPath($program) {
460
-		$memcache = \OC::$server->getMemCacheFactory()->createDistributed('findBinaryPath');
461
-		if ($memcache->hasKey($program)) {
462
-			return $memcache->get($program);
463
-		}
464
-		$result = null;
465
-		if (self::is_function_enabled('exec')) {
466
-			$exeSniffer = new ExecutableFinder();
467
-			// Returns null if nothing is found
468
-			$result = $exeSniffer->find($program, null, ['/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/sbin', '/bin', '/opt/bin']);
469
-		}
470
-		// store the value for 5 minutes
471
-		$memcache->set($program, $result, 300);
472
-		return $result;
473
-	}
474
-
475
-	/**
476
-	 * Calculate the disc space for the given path
477
-	 *
478
-	 * @param string $path
479
-	 * @param \OCP\Files\FileInfo $rootInfo (optional)
480
-	 * @return array
481
-	 * @throws \OCP\Files\NotFoundException
482
-	 */
483
-	public static function getStorageInfo($path, $rootInfo = null) {
484
-		// return storage info without adding mount points
485
-		$includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
486
-
487
-		if (!$rootInfo) {
488
-			$rootInfo = \OC\Files\Filesystem::getFileInfo($path, $includeExtStorage ? 'ext' : false);
489
-		}
490
-		if (!$rootInfo instanceof \OCP\Files\FileInfo) {
491
-			throw new \OCP\Files\NotFoundException();
492
-		}
493
-		$used = $rootInfo->getSize();
494
-		if ($used < 0) {
495
-			$used = 0;
496
-		}
497
-		$quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
498
-		$mount = $rootInfo->getMountPoint();
499
-		$storage = $mount->getStorage();
500
-		$sourceStorage = $storage;
501
-		if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
502
-			$includeExtStorage = false;
503
-			$sourceStorage = $storage->getSourceStorage();
504
-		}
505
-		if ($includeExtStorage) {
506
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
507
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
508
-			) {
509
-				/** @var \OC\Files\Storage\Home $storage */
510
-				$user = $storage->getUser();
511
-			} else {
512
-				$user = \OC::$server->getUserSession()->getUser();
513
-			}
514
-			$quota = OC_Util::getUserQuota($user);
515
-			if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
516
-				// always get free space / total space from root + mount points
517
-				return self::getGlobalStorageInfo($quota);
518
-			}
519
-		}
520
-
521
-		// TODO: need a better way to get total space from storage
522
-		if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
523
-			/** @var \OC\Files\Storage\Wrapper\Quota $storage */
524
-			$quota = $sourceStorage->getQuota();
525
-		}
526
-		$free = $sourceStorage->free_space($rootInfo->getInternalPath());
527
-		if ($free >= 0) {
528
-			$total = $free + $used;
529
-		} else {
530
-			$total = $free; //either unknown or unlimited
531
-		}
532
-		if ($total > 0) {
533
-			if ($quota > 0 && $total > $quota) {
534
-				$total = $quota;
535
-			}
536
-			// prevent division by zero or error codes (negative values)
537
-			$relative = round(($used / $total) * 10000) / 100;
538
-		} else {
539
-			$relative = 0;
540
-		}
541
-
542
-		$ownerId = $storage->getOwner($path);
543
-		$ownerDisplayName = '';
544
-		$owner = \OC::$server->getUserManager()->get($ownerId);
545
-		if ($owner) {
546
-			$ownerDisplayName = $owner->getDisplayName();
547
-		}
548
-		[,,,$mountPoint] = explode('/', $mount->getMountPoint(), 4);
549
-
550
-		return [
551
-			'free' => $free,
552
-			'used' => $used,
553
-			'quota' => $quota,
554
-			'total' => $total,
555
-			'relative' => $relative,
556
-			'owner' => $ownerId,
557
-			'ownerDisplayName' => $ownerDisplayName,
558
-			'mountType' => $mount->getMountType(),
559
-			'mountPoint' => trim($mountPoint, '/'),
560
-		];
561
-	}
562
-
563
-	/**
564
-	 * Get storage info including all mount points and quota
565
-	 *
566
-	 * @param int $quota
567
-	 * @return array
568
-	 */
569
-	private static function getGlobalStorageInfo($quota) {
570
-		$rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
571
-		$used = $rootInfo['size'];
572
-		if ($used < 0) {
573
-			$used = 0;
574
-		}
575
-
576
-		$total = $quota;
577
-		$free = $quota - $used;
578
-
579
-		if ($total > 0) {
580
-			if ($quota > 0 && $total > $quota) {
581
-				$total = $quota;
582
-			}
583
-			// prevent division by zero or error codes (negative values)
584
-			$relative = round(($used / $total) * 10000) / 100;
585
-		} else {
586
-			$relative = 0;
587
-		}
588
-
589
-		return [
590
-			'free' => $free,
591
-			'used' => $used,
592
-			'total' => $total,
593
-			'relative' => $relative,
594
-			'quota' => $quota
595
-		];
596
-	}
597
-
598
-	/**
599
-	 * Returns whether the config file is set manually to read-only
600
-	 * @return bool
601
-	 */
602
-	public static function isReadOnlyConfigEnabled() {
603
-		return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
604
-	}
53
+    private static $templateManager;
54
+
55
+    /**
56
+     * Make a human file size
57
+     * @param int $bytes file size in bytes
58
+     * @return string a human readable file size
59
+     *
60
+     * Makes 2048 to 2 kB.
61
+     */
62
+    public static function humanFileSize($bytes) {
63
+        if ($bytes < 0) {
64
+            return "?";
65
+        }
66
+        if ($bytes < 1024) {
67
+            return "$bytes B";
68
+        }
69
+        $bytes = round($bytes / 1024, 0);
70
+        if ($bytes < 1024) {
71
+            return "$bytes KB";
72
+        }
73
+        $bytes = round($bytes / 1024, 1);
74
+        if ($bytes < 1024) {
75
+            return "$bytes MB";
76
+        }
77
+        $bytes = round($bytes / 1024, 1);
78
+        if ($bytes < 1024) {
79
+            return "$bytes GB";
80
+        }
81
+        $bytes = round($bytes / 1024, 1);
82
+        if ($bytes < 1024) {
83
+            return "$bytes TB";
84
+        }
85
+
86
+        $bytes = round($bytes / 1024, 1);
87
+        return "$bytes PB";
88
+    }
89
+
90
+    /**
91
+     * Make a computer file size
92
+     * @param string $str file size in human readable format
93
+     * @return float|bool a file size in bytes
94
+     *
95
+     * Makes 2kB to 2048.
96
+     *
97
+     * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
98
+     */
99
+    public static function computerFileSize($str) {
100
+        $str = strtolower($str);
101
+        if (is_numeric($str)) {
102
+            return (float)$str;
103
+        }
104
+
105
+        $bytes_array = [
106
+            'b' => 1,
107
+            'k' => 1024,
108
+            'kb' => 1024,
109
+            'mb' => 1024 * 1024,
110
+            'm' => 1024 * 1024,
111
+            'gb' => 1024 * 1024 * 1024,
112
+            'g' => 1024 * 1024 * 1024,
113
+            'tb' => 1024 * 1024 * 1024 * 1024,
114
+            't' => 1024 * 1024 * 1024 * 1024,
115
+            'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
116
+            'p' => 1024 * 1024 * 1024 * 1024 * 1024,
117
+        ];
118
+
119
+        $bytes = (float)$str;
120
+
121
+        if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
122
+            $bytes *= $bytes_array[$matches[1]];
123
+        } else {
124
+            return false;
125
+        }
126
+
127
+        $bytes = round($bytes);
128
+
129
+        return $bytes;
130
+    }
131
+
132
+    /**
133
+     * Recursive copying of folders
134
+     * @param string $src source folder
135
+     * @param string $dest target folder
136
+     *
137
+     */
138
+    public static function copyr($src, $dest) {
139
+        if (is_dir($src)) {
140
+            if (!is_dir($dest)) {
141
+                mkdir($dest);
142
+            }
143
+            $files = scandir($src);
144
+            foreach ($files as $file) {
145
+                if ($file != "." && $file != "..") {
146
+                    self::copyr("$src/$file", "$dest/$file");
147
+                }
148
+            }
149
+        } elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
150
+            copy($src, $dest);
151
+        }
152
+    }
153
+
154
+    /**
155
+     * Recursive deletion of folders
156
+     * @param string $dir path to the folder
157
+     * @param bool $deleteSelf if set to false only the content of the folder will be deleted
158
+     * @return bool
159
+     */
160
+    public static function rmdirr($dir, $deleteSelf = true) {
161
+        if (is_dir($dir)) {
162
+            $files = new RecursiveIteratorIterator(
163
+                new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
164
+                RecursiveIteratorIterator::CHILD_FIRST
165
+            );
166
+
167
+            foreach ($files as $fileInfo) {
168
+                /** @var SplFileInfo $fileInfo */
169
+                if ($fileInfo->isLink()) {
170
+                    unlink($fileInfo->getPathname());
171
+                } elseif ($fileInfo->isDir()) {
172
+                    rmdir($fileInfo->getRealPath());
173
+                } else {
174
+                    unlink($fileInfo->getRealPath());
175
+                }
176
+            }
177
+            if ($deleteSelf) {
178
+                rmdir($dir);
179
+            }
180
+        } elseif (file_exists($dir)) {
181
+            if ($deleteSelf) {
182
+                unlink($dir);
183
+            }
184
+        }
185
+        if (!$deleteSelf) {
186
+            return true;
187
+        }
188
+
189
+        return !file_exists($dir);
190
+    }
191
+
192
+    /**
193
+     * @deprecated 18.0.0
194
+     * @return \OC\Files\Type\TemplateManager
195
+     */
196
+    public static function getFileTemplateManager() {
197
+        if (!self::$templateManager) {
198
+            self::$templateManager = new \OC\Files\Type\TemplateManager();
199
+        }
200
+        return self::$templateManager;
201
+    }
202
+
203
+    /**
204
+     * detect if a given program is found in the search PATH
205
+     *
206
+     * @param string $name
207
+     * @param bool $path
208
+     * @internal param string $program name
209
+     * @internal param string $optional search path, defaults to $PATH
210
+     * @return bool    true if executable program found in path
211
+     */
212
+    public static function canExecute($name, $path = false) {
213
+        // path defaults to PATH from environment if not set
214
+        if ($path === false) {
215
+            $path = getenv("PATH");
216
+        }
217
+        // we look for an executable file of that name
218
+        $exts = [""];
219
+        $check_fn = "is_executable";
220
+        // Default check will be done with $path directories :
221
+        $dirs = explode(PATH_SEPARATOR, $path);
222
+        // WARNING : We have to check if open_basedir is enabled :
223
+        $obd = OC::$server->get(IniGetWrapper::class)->getString('open_basedir');
224
+        if ($obd != "none") {
225
+            $obd_values = explode(PATH_SEPARATOR, $obd);
226
+            if (count($obd_values) > 0 and $obd_values[0]) {
227
+                // open_basedir is in effect !
228
+                // We need to check if the program is in one of these dirs :
229
+                $dirs = $obd_values;
230
+            }
231
+        }
232
+        foreach ($dirs as $dir) {
233
+            foreach ($exts as $ext) {
234
+                if ($check_fn("$dir/$name" . $ext)) {
235
+                    return true;
236
+                }
237
+            }
238
+        }
239
+        return false;
240
+    }
241
+
242
+    /**
243
+     * copy the contents of one stream to another
244
+     *
245
+     * @param resource $source
246
+     * @param resource $target
247
+     * @return array the number of bytes copied and result
248
+     */
249
+    public static function streamCopy($source, $target) {
250
+        if (!$source or !$target) {
251
+            return [0, false];
252
+        }
253
+        $bufSize = 8192;
254
+        $result = true;
255
+        $count = 0;
256
+        while (!feof($source)) {
257
+            $buf = fread($source, $bufSize);
258
+            $bytesWritten = fwrite($target, $buf);
259
+            if ($bytesWritten !== false) {
260
+                $count += $bytesWritten;
261
+            }
262
+            // note: strlen is expensive so only use it when necessary,
263
+            // on the last block
264
+            if ($bytesWritten === false
265
+                || ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
266
+            ) {
267
+                // write error, could be disk full ?
268
+                $result = false;
269
+                break;
270
+            }
271
+        }
272
+        return [$count, $result];
273
+    }
274
+
275
+    /**
276
+     * Adds a suffix to the name in case the file exists
277
+     *
278
+     * @param string $path
279
+     * @param string $filename
280
+     * @return string
281
+     */
282
+    public static function buildNotExistingFileName($path, $filename) {
283
+        $view = \OC\Files\Filesystem::getView();
284
+        return self::buildNotExistingFileNameForView($path, $filename, $view);
285
+    }
286
+
287
+    /**
288
+     * Adds a suffix to the name in case the file exists
289
+     *
290
+     * @param string $path
291
+     * @param string $filename
292
+     * @return string
293
+     */
294
+    public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
295
+        if ($path === '/') {
296
+            $path = '';
297
+        }
298
+        if ($pos = strrpos($filename, '.')) {
299
+            $name = substr($filename, 0, $pos);
300
+            $ext = substr($filename, $pos);
301
+        } else {
302
+            $name = $filename;
303
+            $ext = '';
304
+        }
305
+
306
+        $newpath = $path . '/' . $filename;
307
+        if ($view->file_exists($newpath)) {
308
+            if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
309
+                //Replace the last "(number)" with "(number+1)"
310
+                $last_match = count($matches[0]) - 1;
311
+                $counter = $matches[1][$last_match][0] + 1;
312
+                $offset = $matches[0][$last_match][1];
313
+                $match_length = strlen($matches[0][$last_match][0]);
314
+            } else {
315
+                $counter = 2;
316
+                $match_length = 0;
317
+                $offset = false;
318
+            }
319
+            do {
320
+                if ($offset) {
321
+                    //Replace the last "(number)" with "(number+1)"
322
+                    $newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
323
+                } else {
324
+                    $newname = $name . ' (' . $counter . ')';
325
+                }
326
+                $newpath = $path . '/' . $newname . $ext;
327
+                $counter++;
328
+            } while ($view->file_exists($newpath));
329
+        }
330
+
331
+        return $newpath;
332
+    }
333
+
334
+    /**
335
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
336
+     *
337
+     * @param array $input The array to work on
338
+     * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
339
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
340
+     * @return array
341
+     *
342
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
343
+     * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
344
+     *
345
+     */
346
+    public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
347
+        $case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
348
+        $ret = [];
349
+        foreach ($input as $k => $v) {
350
+            $ret[mb_convert_case($k, $case, $encoding)] = $v;
351
+        }
352
+        return $ret;
353
+    }
354
+
355
+    /**
356
+     * performs a search in a nested array
357
+     * @param array $haystack the array to be searched
358
+     * @param string $needle the search string
359
+     * @param mixed $index optional, only search this key name
360
+     * @return mixed the key of the matching field, otherwise false
361
+     *
362
+     * performs a search in a nested array
363
+     *
364
+     * taken from http://www.php.net/manual/en/function.array-search.php#97645
365
+     */
366
+    public static function recursiveArraySearch($haystack, $needle, $index = null) {
367
+        $aIt = new RecursiveArrayIterator($haystack);
368
+        $it = new RecursiveIteratorIterator($aIt);
369
+
370
+        while ($it->valid()) {
371
+            if (((isset($index) and ($it->key() == $index)) or !isset($index)) and ($it->current() == $needle)) {
372
+                return $aIt->key();
373
+            }
374
+
375
+            $it->next();
376
+        }
377
+
378
+        return false;
379
+    }
380
+
381
+    /**
382
+     * calculates the maximum upload size respecting system settings, free space and user quota
383
+     *
384
+     * @param string $dir the current folder where the user currently operates
385
+     * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
386
+     * @return int number of bytes representing
387
+     */
388
+    public static function maxUploadFilesize($dir, $freeSpace = null) {
389
+        if (is_null($freeSpace) || $freeSpace < 0) {
390
+            $freeSpace = self::freeSpace($dir);
391
+        }
392
+        return min($freeSpace, self::uploadLimit());
393
+    }
394
+
395
+    /**
396
+     * Calculate free space left within user quota
397
+     *
398
+     * @param string $dir the current folder where the user currently operates
399
+     * @return int number of bytes representing
400
+     */
401
+    public static function freeSpace($dir) {
402
+        $freeSpace = \OC\Files\Filesystem::free_space($dir);
403
+        if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
404
+            $freeSpace = max($freeSpace, 0);
405
+            return $freeSpace;
406
+        } else {
407
+            return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
408
+        }
409
+    }
410
+
411
+    /**
412
+     * Calculate PHP upload limit
413
+     *
414
+     * @return int PHP upload file size limit
415
+     */
416
+    public static function uploadLimit() {
417
+        $ini = \OC::$server->get(IniGetWrapper::class);
418
+        $upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
419
+        $post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
420
+        if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
421
+            return INF;
422
+        } elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
423
+            return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
424
+        } else {
425
+            return min($upload_max_filesize, $post_max_size);
426
+        }
427
+    }
428
+
429
+    /**
430
+     * Checks if a function is available
431
+     *
432
+     * @param string $function_name
433
+     * @return bool
434
+     */
435
+    public static function is_function_enabled($function_name) {
436
+        if (!function_exists($function_name)) {
437
+            return false;
438
+        }
439
+        $ini = \OC::$server->get(IniGetWrapper::class);
440
+        $disabled = explode(',', $ini->get('disable_functions') ?: '');
441
+        $disabled = array_map('trim', $disabled);
442
+        if (in_array($function_name, $disabled)) {
443
+            return false;
444
+        }
445
+        $disabled = explode(',', $ini->get('suhosin.executor.func.blacklist') ?: '');
446
+        $disabled = array_map('trim', $disabled);
447
+        if (in_array($function_name, $disabled)) {
448
+            return false;
449
+        }
450
+        return true;
451
+    }
452
+
453
+    /**
454
+     * Try to find a program
455
+     *
456
+     * @param string $program
457
+     * @return null|string
458
+     */
459
+    public static function findBinaryPath($program) {
460
+        $memcache = \OC::$server->getMemCacheFactory()->createDistributed('findBinaryPath');
461
+        if ($memcache->hasKey($program)) {
462
+            return $memcache->get($program);
463
+        }
464
+        $result = null;
465
+        if (self::is_function_enabled('exec')) {
466
+            $exeSniffer = new ExecutableFinder();
467
+            // Returns null if nothing is found
468
+            $result = $exeSniffer->find($program, null, ['/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/sbin', '/bin', '/opt/bin']);
469
+        }
470
+        // store the value for 5 minutes
471
+        $memcache->set($program, $result, 300);
472
+        return $result;
473
+    }
474
+
475
+    /**
476
+     * Calculate the disc space for the given path
477
+     *
478
+     * @param string $path
479
+     * @param \OCP\Files\FileInfo $rootInfo (optional)
480
+     * @return array
481
+     * @throws \OCP\Files\NotFoundException
482
+     */
483
+    public static function getStorageInfo($path, $rootInfo = null) {
484
+        // return storage info without adding mount points
485
+        $includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
486
+
487
+        if (!$rootInfo) {
488
+            $rootInfo = \OC\Files\Filesystem::getFileInfo($path, $includeExtStorage ? 'ext' : false);
489
+        }
490
+        if (!$rootInfo instanceof \OCP\Files\FileInfo) {
491
+            throw new \OCP\Files\NotFoundException();
492
+        }
493
+        $used = $rootInfo->getSize();
494
+        if ($used < 0) {
495
+            $used = 0;
496
+        }
497
+        $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
498
+        $mount = $rootInfo->getMountPoint();
499
+        $storage = $mount->getStorage();
500
+        $sourceStorage = $storage;
501
+        if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
502
+            $includeExtStorage = false;
503
+            $sourceStorage = $storage->getSourceStorage();
504
+        }
505
+        if ($includeExtStorage) {
506
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
507
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
508
+            ) {
509
+                /** @var \OC\Files\Storage\Home $storage */
510
+                $user = $storage->getUser();
511
+            } else {
512
+                $user = \OC::$server->getUserSession()->getUser();
513
+            }
514
+            $quota = OC_Util::getUserQuota($user);
515
+            if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
516
+                // always get free space / total space from root + mount points
517
+                return self::getGlobalStorageInfo($quota);
518
+            }
519
+        }
520
+
521
+        // TODO: need a better way to get total space from storage
522
+        if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
523
+            /** @var \OC\Files\Storage\Wrapper\Quota $storage */
524
+            $quota = $sourceStorage->getQuota();
525
+        }
526
+        $free = $sourceStorage->free_space($rootInfo->getInternalPath());
527
+        if ($free >= 0) {
528
+            $total = $free + $used;
529
+        } else {
530
+            $total = $free; //either unknown or unlimited
531
+        }
532
+        if ($total > 0) {
533
+            if ($quota > 0 && $total > $quota) {
534
+                $total = $quota;
535
+            }
536
+            // prevent division by zero or error codes (negative values)
537
+            $relative = round(($used / $total) * 10000) / 100;
538
+        } else {
539
+            $relative = 0;
540
+        }
541
+
542
+        $ownerId = $storage->getOwner($path);
543
+        $ownerDisplayName = '';
544
+        $owner = \OC::$server->getUserManager()->get($ownerId);
545
+        if ($owner) {
546
+            $ownerDisplayName = $owner->getDisplayName();
547
+        }
548
+        [,,,$mountPoint] = explode('/', $mount->getMountPoint(), 4);
549
+
550
+        return [
551
+            'free' => $free,
552
+            'used' => $used,
553
+            'quota' => $quota,
554
+            'total' => $total,
555
+            'relative' => $relative,
556
+            'owner' => $ownerId,
557
+            'ownerDisplayName' => $ownerDisplayName,
558
+            'mountType' => $mount->getMountType(),
559
+            'mountPoint' => trim($mountPoint, '/'),
560
+        ];
561
+    }
562
+
563
+    /**
564
+     * Get storage info including all mount points and quota
565
+     *
566
+     * @param int $quota
567
+     * @return array
568
+     */
569
+    private static function getGlobalStorageInfo($quota) {
570
+        $rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
571
+        $used = $rootInfo['size'];
572
+        if ($used < 0) {
573
+            $used = 0;
574
+        }
575
+
576
+        $total = $quota;
577
+        $free = $quota - $used;
578
+
579
+        if ($total > 0) {
580
+            if ($quota > 0 && $total > $quota) {
581
+                $total = $quota;
582
+            }
583
+            // prevent division by zero or error codes (negative values)
584
+            $relative = round(($used / $total) * 10000) / 100;
585
+        } else {
586
+            $relative = 0;
587
+        }
588
+
589
+        return [
590
+            'free' => $free,
591
+            'used' => $used,
592
+            'total' => $total,
593
+            'relative' => $relative,
594
+            'quota' => $quota
595
+        ];
596
+    }
597
+
598
+    /**
599
+     * Returns whether the config file is set manually to read-only
600
+     * @return bool
601
+     */
602
+    public static function isReadOnlyConfigEnabled() {
603
+        return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
604
+    }
605 605
 }
Please login to merge, or discard this patch.
apps/files/lib/Helper.php 1 patch
Indentation   +210 added lines, -210 removed lines patch added patch discarded remove patch
@@ -41,233 +41,233 @@
 block discarded – undo
41 41
  * Helper class for manipulating file information
42 42
  */
43 43
 class Helper {
44
-	/**
45
-	 * @param string $dir
46
-	 * @return array
47
-	 * @throws \OCP\Files\NotFoundException
48
-	 */
49
-	public static function buildFileStorageStatistics($dir) {
50
-		// information about storage capacities
51
-		$storageInfo = \OC_Helper::getStorageInfo($dir);
52
-		$l = \OC::$server->getL10N('files');
53
-		$maxUploadFileSize = \OCP\Util::maxUploadFilesize($dir, $storageInfo['free']);
54
-		$maxHumanFileSize = \OCP\Util::humanFileSize($maxUploadFileSize);
55
-		$maxHumanFileSize = $l->t('Upload (max. %s)', [$maxHumanFileSize]);
44
+    /**
45
+     * @param string $dir
46
+     * @return array
47
+     * @throws \OCP\Files\NotFoundException
48
+     */
49
+    public static function buildFileStorageStatistics($dir) {
50
+        // information about storage capacities
51
+        $storageInfo = \OC_Helper::getStorageInfo($dir);
52
+        $l = \OC::$server->getL10N('files');
53
+        $maxUploadFileSize = \OCP\Util::maxUploadFilesize($dir, $storageInfo['free']);
54
+        $maxHumanFileSize = \OCP\Util::humanFileSize($maxUploadFileSize);
55
+        $maxHumanFileSize = $l->t('Upload (max. %s)', [$maxHumanFileSize]);
56 56
 
57
-		return [
58
-			'uploadMaxFilesize' => $maxUploadFileSize,
59
-			'maxHumanFilesize'  => $maxHumanFileSize,
60
-			'freeSpace' => $storageInfo['free'],
61
-			'quota' => $storageInfo['quota'],
62
-			'used' => $storageInfo['used'],
63
-			'usedSpacePercent'  => (int)$storageInfo['relative'],
64
-			'owner' => $storageInfo['owner'],
65
-			'ownerDisplayName' => $storageInfo['ownerDisplayName'],
66
-			'mountType' => $storageInfo['mountType'],
67
-			'mountPoint' => $storageInfo['mountPoint'],
68
-		];
69
-	}
57
+        return [
58
+            'uploadMaxFilesize' => $maxUploadFileSize,
59
+            'maxHumanFilesize'  => $maxHumanFileSize,
60
+            'freeSpace' => $storageInfo['free'],
61
+            'quota' => $storageInfo['quota'],
62
+            'used' => $storageInfo['used'],
63
+            'usedSpacePercent'  => (int)$storageInfo['relative'],
64
+            'owner' => $storageInfo['owner'],
65
+            'ownerDisplayName' => $storageInfo['ownerDisplayName'],
66
+            'mountType' => $storageInfo['mountType'],
67
+            'mountPoint' => $storageInfo['mountPoint'],
68
+        ];
69
+    }
70 70
 
71
-	/**
72
-	 * Determine icon for a given file
73
-	 *
74
-	 * @param \OCP\Files\FileInfo $file file info
75
-	 * @return string icon URL
76
-	 */
77
-	public static function determineIcon($file) {
78
-		if ($file['type'] === 'dir') {
79
-			$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir');
80
-			// TODO: move this part to the client side, using mountType
81
-			if ($file->isShared()) {
82
-				$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-shared');
83
-			} elseif ($file->isMounted()) {
84
-				$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-external');
85
-			}
86
-		} else {
87
-			$icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon($file->getMimetype());
88
-		}
71
+    /**
72
+     * Determine icon for a given file
73
+     *
74
+     * @param \OCP\Files\FileInfo $file file info
75
+     * @return string icon URL
76
+     */
77
+    public static function determineIcon($file) {
78
+        if ($file['type'] === 'dir') {
79
+            $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir');
80
+            // TODO: move this part to the client side, using mountType
81
+            if ($file->isShared()) {
82
+                $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-shared');
83
+            } elseif ($file->isMounted()) {
84
+                $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon('dir-external');
85
+            }
86
+        } else {
87
+            $icon = \OC::$server->getMimeTypeDetector()->mimeTypeIcon($file->getMimetype());
88
+        }
89 89
 
90
-		return substr($icon, 0, -3) . 'svg';
91
-	}
90
+        return substr($icon, 0, -3) . 'svg';
91
+    }
92 92
 
93
-	/**
94
-	 * Comparator function to sort files alphabetically and have
95
-	 * the directories appear first
96
-	 *
97
-	 * @param \OCP\Files\FileInfo $a file
98
-	 * @param \OCP\Files\FileInfo $b file
99
-	 * @return int -1 if $a must come before $b, 1 otherwise
100
-	 */
101
-	public static function compareFileNames(FileInfo $a, FileInfo $b) {
102
-		$aType = $a->getType();
103
-		$bType = $b->getType();
104
-		if ($aType === 'dir' and $bType !== 'dir') {
105
-			return -1;
106
-		} elseif ($aType !== 'dir' and $bType === 'dir') {
107
-			return 1;
108
-		} else {
109
-			return \OCP\Util::naturalSortCompare($a->getName(), $b->getName());
110
-		}
111
-	}
93
+    /**
94
+     * Comparator function to sort files alphabetically and have
95
+     * the directories appear first
96
+     *
97
+     * @param \OCP\Files\FileInfo $a file
98
+     * @param \OCP\Files\FileInfo $b file
99
+     * @return int -1 if $a must come before $b, 1 otherwise
100
+     */
101
+    public static function compareFileNames(FileInfo $a, FileInfo $b) {
102
+        $aType = $a->getType();
103
+        $bType = $b->getType();
104
+        if ($aType === 'dir' and $bType !== 'dir') {
105
+            return -1;
106
+        } elseif ($aType !== 'dir' and $bType === 'dir') {
107
+            return 1;
108
+        } else {
109
+            return \OCP\Util::naturalSortCompare($a->getName(), $b->getName());
110
+        }
111
+    }
112 112
 
113
-	/**
114
-	 * Comparator function to sort files by date
115
-	 *
116
-	 * @param \OCP\Files\FileInfo $a file
117
-	 * @param \OCP\Files\FileInfo $b file
118
-	 * @return int -1 if $a must come before $b, 1 otherwise
119
-	 */
120
-	public static function compareTimestamp(FileInfo $a, FileInfo $b) {
121
-		$aTime = $a->getMTime();
122
-		$bTime = $b->getMTime();
123
-		return ($aTime < $bTime) ? -1 : 1;
124
-	}
113
+    /**
114
+     * Comparator function to sort files by date
115
+     *
116
+     * @param \OCP\Files\FileInfo $a file
117
+     * @param \OCP\Files\FileInfo $b file
118
+     * @return int -1 if $a must come before $b, 1 otherwise
119
+     */
120
+    public static function compareTimestamp(FileInfo $a, FileInfo $b) {
121
+        $aTime = $a->getMTime();
122
+        $bTime = $b->getMTime();
123
+        return ($aTime < $bTime) ? -1 : 1;
124
+    }
125 125
 
126
-	/**
127
-	 * Comparator function to sort files by size
128
-	 *
129
-	 * @param \OCP\Files\FileInfo $a file
130
-	 * @param \OCP\Files\FileInfo $b file
131
-	 * @return int -1 if $a must come before $b, 1 otherwise
132
-	 */
133
-	public static function compareSize(FileInfo $a, FileInfo $b) {
134
-		$aSize = $a->getSize();
135
-		$bSize = $b->getSize();
136
-		return ($aSize < $bSize) ? -1 : 1;
137
-	}
126
+    /**
127
+     * Comparator function to sort files by size
128
+     *
129
+     * @param \OCP\Files\FileInfo $a file
130
+     * @param \OCP\Files\FileInfo $b file
131
+     * @return int -1 if $a must come before $b, 1 otherwise
132
+     */
133
+    public static function compareSize(FileInfo $a, FileInfo $b) {
134
+        $aSize = $a->getSize();
135
+        $bSize = $b->getSize();
136
+        return ($aSize < $bSize) ? -1 : 1;
137
+    }
138 138
 
139
-	/**
140
-	 * Formats the file info to be returned as JSON to the client.
141
-	 *
142
-	 * @param \OCP\Files\FileInfo $i
143
-	 * @return array formatted file info
144
-	 */
145
-	public static function formatFileInfo(FileInfo $i) {
146
-		$entry = [];
139
+    /**
140
+     * Formats the file info to be returned as JSON to the client.
141
+     *
142
+     * @param \OCP\Files\FileInfo $i
143
+     * @return array formatted file info
144
+     */
145
+    public static function formatFileInfo(FileInfo $i) {
146
+        $entry = [];
147 147
 
148
-		$entry['id'] = $i['fileid'];
149
-		$entry['parentId'] = $i['parent'];
150
-		$entry['mtime'] = $i['mtime'] * 1000;
151
-		// only pick out the needed attributes
152
-		$entry['name'] = $i->getName();
153
-		$entry['permissions'] = $i['permissions'];
154
-		$entry['mimetype'] = $i['mimetype'];
155
-		$entry['size'] = $i['size'];
156
-		$entry['type'] = $i['type'];
157
-		$entry['etag'] = $i['etag'];
158
-		if (isset($i['tags'])) {
159
-			$entry['tags'] = $i['tags'];
160
-		}
161
-		if (isset($i['displayname_owner'])) {
162
-			$entry['shareOwner'] = $i['displayname_owner'];
163
-		}
164
-		if (isset($i['is_share_mount_point'])) {
165
-			$entry['isShareMountPoint'] = $i['is_share_mount_point'];
166
-		}
167
-		$mountType = null;
168
-		$mount = $i->getMountPoint();
169
-		$mountType = $mount->getMountType();
170
-		if ($mountType !== '') {
171
-			if ($i->getInternalPath() === '') {
172
-				$mountType .= '-root';
173
-			}
174
-			$entry['mountType'] = $mountType;
175
-		}
176
-		if (isset($i['extraData'])) {
177
-			$entry['extraData'] = $i['extraData'];
178
-		}
179
-		return $entry;
180
-	}
148
+        $entry['id'] = $i['fileid'];
149
+        $entry['parentId'] = $i['parent'];
150
+        $entry['mtime'] = $i['mtime'] * 1000;
151
+        // only pick out the needed attributes
152
+        $entry['name'] = $i->getName();
153
+        $entry['permissions'] = $i['permissions'];
154
+        $entry['mimetype'] = $i['mimetype'];
155
+        $entry['size'] = $i['size'];
156
+        $entry['type'] = $i['type'];
157
+        $entry['etag'] = $i['etag'];
158
+        if (isset($i['tags'])) {
159
+            $entry['tags'] = $i['tags'];
160
+        }
161
+        if (isset($i['displayname_owner'])) {
162
+            $entry['shareOwner'] = $i['displayname_owner'];
163
+        }
164
+        if (isset($i['is_share_mount_point'])) {
165
+            $entry['isShareMountPoint'] = $i['is_share_mount_point'];
166
+        }
167
+        $mountType = null;
168
+        $mount = $i->getMountPoint();
169
+        $mountType = $mount->getMountType();
170
+        if ($mountType !== '') {
171
+            if ($i->getInternalPath() === '') {
172
+                $mountType .= '-root';
173
+            }
174
+            $entry['mountType'] = $mountType;
175
+        }
176
+        if (isset($i['extraData'])) {
177
+            $entry['extraData'] = $i['extraData'];
178
+        }
179
+        return $entry;
180
+    }
181 181
 
182
-	/**
183
-	 * Format file info for JSON
184
-	 * @param \OCP\Files\FileInfo[] $fileInfos file infos
185
-	 * @return array
186
-	 */
187
-	public static function formatFileInfos($fileInfos) {
188
-		$files = [];
189
-		foreach ($fileInfos as $i) {
190
-			$files[] = self::formatFileInfo($i);
191
-		}
182
+    /**
183
+     * Format file info for JSON
184
+     * @param \OCP\Files\FileInfo[] $fileInfos file infos
185
+     * @return array
186
+     */
187
+    public static function formatFileInfos($fileInfos) {
188
+        $files = [];
189
+        foreach ($fileInfos as $i) {
190
+            $files[] = self::formatFileInfo($i);
191
+        }
192 192
 
193
-		return $files;
194
-	}
193
+        return $files;
194
+    }
195 195
 
196
-	/**
197
-	 * Retrieves the contents of the given directory and
198
-	 * returns it as a sorted array of FileInfo.
199
-	 *
200
-	 * @param string $dir path to the directory
201
-	 * @param string $sortAttribute attribute to sort on
202
-	 * @param bool $sortDescending true for descending sort, false otherwise
203
-	 * @param string $mimetypeFilter limit returned content to this mimetype or mimepart
204
-	 * @return \OCP\Files\FileInfo[] files
205
-	 */
206
-	public static function getFiles($dir, $sortAttribute = 'name', $sortDescending = false, $mimetypeFilter = '') {
207
-		$content = \OC\Files\Filesystem::getDirectoryContent($dir, $mimetypeFilter);
196
+    /**
197
+     * Retrieves the contents of the given directory and
198
+     * returns it as a sorted array of FileInfo.
199
+     *
200
+     * @param string $dir path to the directory
201
+     * @param string $sortAttribute attribute to sort on
202
+     * @param bool $sortDescending true for descending sort, false otherwise
203
+     * @param string $mimetypeFilter limit returned content to this mimetype or mimepart
204
+     * @return \OCP\Files\FileInfo[] files
205
+     */
206
+    public static function getFiles($dir, $sortAttribute = 'name', $sortDescending = false, $mimetypeFilter = '') {
207
+        $content = \OC\Files\Filesystem::getDirectoryContent($dir, $mimetypeFilter);
208 208
 
209
-		return self::sortFiles($content, $sortAttribute, $sortDescending);
210
-	}
209
+        return self::sortFiles($content, $sortAttribute, $sortDescending);
210
+    }
211 211
 
212
-	/**
213
-	 * Populate the result set with file tags
214
-	 *
215
-	 * @param array $fileList
216
-	 * @param string $fileIdentifier identifier attribute name for values in $fileList
217
-	 * @param ITagManager $tagManager
218
-	 * @return array file list populated with tags
219
-	 */
220
-	public static function populateTags(array $fileList, $fileIdentifier = 'fileid', ITagManager $tagManager) {
221
-		$ids = [];
222
-		foreach ($fileList as $fileData) {
223
-			$ids[] = $fileData[$fileIdentifier];
224
-		}
225
-		$tagger = $tagManager->load('files');
226
-		$tags = $tagger->getTagsForObjects($ids);
212
+    /**
213
+     * Populate the result set with file tags
214
+     *
215
+     * @param array $fileList
216
+     * @param string $fileIdentifier identifier attribute name for values in $fileList
217
+     * @param ITagManager $tagManager
218
+     * @return array file list populated with tags
219
+     */
220
+    public static function populateTags(array $fileList, $fileIdentifier = 'fileid', ITagManager $tagManager) {
221
+        $ids = [];
222
+        foreach ($fileList as $fileData) {
223
+            $ids[] = $fileData[$fileIdentifier];
224
+        }
225
+        $tagger = $tagManager->load('files');
226
+        $tags = $tagger->getTagsForObjects($ids);
227 227
 
228
-		if (!is_array($tags)) {
229
-			throw new \UnexpectedValueException('$tags must be an array');
230
-		}
228
+        if (!is_array($tags)) {
229
+            throw new \UnexpectedValueException('$tags must be an array');
230
+        }
231 231
 
232
-		// Set empty tag array
233
-		foreach ($fileList as $key => $fileData) {
234
-			$fileList[$key]['tags'] = [];
235
-		}
232
+        // Set empty tag array
233
+        foreach ($fileList as $key => $fileData) {
234
+            $fileList[$key]['tags'] = [];
235
+        }
236 236
 
237
-		if (!empty($tags)) {
238
-			foreach ($tags as $fileId => $fileTags) {
239
-				foreach ($fileList as $key => $fileData) {
240
-					if ($fileId !== $fileData[$fileIdentifier]) {
241
-						continue;
242
-					}
237
+        if (!empty($tags)) {
238
+            foreach ($tags as $fileId => $fileTags) {
239
+                foreach ($fileList as $key => $fileData) {
240
+                    if ($fileId !== $fileData[$fileIdentifier]) {
241
+                        continue;
242
+                    }
243 243
 
244
-					$fileList[$key]['tags'] = $fileTags;
245
-				}
246
-			}
247
-		}
244
+                    $fileList[$key]['tags'] = $fileTags;
245
+                }
246
+            }
247
+        }
248 248
 
249
-		return $fileList;
250
-	}
249
+        return $fileList;
250
+    }
251 251
 
252
-	/**
253
-	 * Sort the given file info array
254
-	 *
255
-	 * @param \OCP\Files\FileInfo[] $files files to sort
256
-	 * @param string $sortAttribute attribute to sort on
257
-	 * @param bool $sortDescending true for descending sort, false otherwise
258
-	 * @return \OCP\Files\FileInfo[] sorted files
259
-	 */
260
-	public static function sortFiles($files, $sortAttribute = 'name', $sortDescending = false) {
261
-		$sortFunc = 'compareFileNames';
262
-		if ($sortAttribute === 'mtime') {
263
-			$sortFunc = 'compareTimestamp';
264
-		} elseif ($sortAttribute === 'size') {
265
-			$sortFunc = 'compareSize';
266
-		}
267
-		usort($files, [Helper::class, $sortFunc]);
268
-		if ($sortDescending) {
269
-			$files = array_reverse($files);
270
-		}
271
-		return $files;
272
-	}
252
+    /**
253
+     * Sort the given file info array
254
+     *
255
+     * @param \OCP\Files\FileInfo[] $files files to sort
256
+     * @param string $sortAttribute attribute to sort on
257
+     * @param bool $sortDescending true for descending sort, false otherwise
258
+     * @return \OCP\Files\FileInfo[] sorted files
259
+     */
260
+    public static function sortFiles($files, $sortAttribute = 'name', $sortDescending = false) {
261
+        $sortFunc = 'compareFileNames';
262
+        if ($sortAttribute === 'mtime') {
263
+            $sortFunc = 'compareTimestamp';
264
+        } elseif ($sortAttribute === 'size') {
265
+            $sortFunc = 'compareSize';
266
+        }
267
+        usort($files, [Helper::class, $sortFunc]);
268
+        if ($sortDescending) {
269
+            $files = array_reverse($files);
270
+        }
271
+        return $files;
272
+    }
273 273
 }
Please login to merge, or discard this patch.