Completed
Push — master ( 6585ba...5aaa06 )
by Lukas
10:20
created

OC_Helper::getFileTemplateManager()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Arthur Schiwon <[email protected]>
6
 * @author Bart Visscher <[email protected]>
7
 * @author Björn Schießle <[email protected]>
8
 * @author Christopher Schäpers <[email protected]>
9
 * @author Clark Tomlinson <[email protected]>
10
 * @author Fabian Henze <[email protected]>
11
 * @author Felix Moeller <[email protected]>
12
 * @author Georg Ehrke <[email protected]>
13
 * @author Jakob Sack <[email protected]>
14
 * @author Jan-Christoph Borchardt <[email protected]>
15
 * @author Joas Schilling <[email protected]>
16
 * @author Jörn Friedrich Dreyer <[email protected]>
17
 * @author Lukas Reschke <[email protected]>
18
 * @author Michael Gapczynski <[email protected]>
19
 * @author Morris Jobke <[email protected]>
20
 * @author Olivier Paroz <[email protected]>
21
 * @author Pellaeon Lin <[email protected]>
22
 * @author Robin Appelman <[email protected]>
23
 * @author Robin McCorkell <[email protected]>
24
 * @author Roeland Jago Douma <[email protected]>
25
 * @author Simon Könnecke <[email protected]>
26
 * @author Thomas Müller <[email protected]>
27
 * @author Thomas Tanghus <[email protected]>
28
 * @author Vincent Petry <[email protected]>
29
 *
30
 * @license AGPL-3.0
31
 *
32
 * This code is free software: you can redistribute it and/or modify
33
 * it under the terms of the GNU Affero General Public License, version 3,
34
 * as published by the Free Software Foundation.
35
 *
36
 * This program is distributed in the hope that it will be useful,
37
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
38
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
39
 * GNU Affero General Public License for more details.
40
 *
41
 * You should have received a copy of the GNU Affero General Public License, version 3,
42
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
43
 *
44
 */
45
use Symfony\Component\Process\ExecutableFinder;
46
47
/**
48
 * Collection of useful functions
49
 */
50
class OC_Helper {
51
	private static $templateManager;
52
53
	/**
54
	 * Creates an absolute url for public use
55
	 * @param string $service id
56
	 * @param bool $add_slash
57
	 * @return string the url
58
	 *
59
	 * Returns a absolute url to the given service.
60
	 */
61
	public static function linkToPublic($service, $add_slash = false) {
62
		if ($service === 'files') {
63
			$url = OC::$server->getURLGenerator()->getAbsoluteURL('/s');
64
		} else {
65
			$url = OC::$server->getURLGenerator()->getAbsoluteURL(OC::$server->getURLGenerator()->linkTo('', 'public.php').'?service='.$service);
66
		}
67
		return $url . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '');
68
	}
69
70
	/**
71
	 * Make a human file size
72
	 * @param int $bytes file size in bytes
73
	 * @return string a human readable file size
74
	 *
75
	 * Makes 2048 to 2 kB.
76
	 */
77
	public static function humanFileSize($bytes) {
78
		if ($bytes < 0) {
79
			return "?";
80
		}
81
		if ($bytes < 1024) {
82
			return "$bytes B";
83
		}
84
		$bytes = round($bytes / 1024, 0);
85
		if ($bytes < 1024) {
86
			return "$bytes KB";
87
		}
88
		$bytes = round($bytes / 1024, 1);
89
		if ($bytes < 1024) {
90
			return "$bytes MB";
91
		}
92
		$bytes = round($bytes / 1024, 1);
93
		if ($bytes < 1024) {
94
			return "$bytes GB";
95
		}
96
		$bytes = round($bytes / 1024, 1);
97
		if ($bytes < 1024) {
98
			return "$bytes TB";
99
		}
100
101
		$bytes = round($bytes / 1024, 1);
102
		return "$bytes PB";
103
	}
104
105
	/**
106
	 * Make a php file size
107
	 * @param int $bytes file size in bytes
108
	 * @return string a php parseable file size
109
	 *
110
	 * Makes 2048 to 2k and 2^41 to 2048G
111
	 */
112
	public static function phpFileSize($bytes) {
113
		if ($bytes < 0) {
114
			return "?";
115
		}
116
		if ($bytes < 1024) {
117
			return $bytes . "B";
118
		}
119
		$bytes = round($bytes / 1024, 1);
120
		if ($bytes < 1024) {
121
			return $bytes . "K";
122
		}
123
		$bytes = round($bytes / 1024, 1);
124
		if ($bytes < 1024) {
125
			return $bytes . "M";
126
		}
127
		$bytes = round($bytes / 1024, 1);
128
		return $bytes . "G";
129
	}
130
131
	/**
132
	 * Make a computer file size
133
	 * @param string $str file size in human readable format
134
	 * @return float a file size in bytes
135
	 *
136
	 * Makes 2kB to 2048.
137
	 *
138
	 * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
139
	 */
140
	public static function computerFileSize($str) {
141
		$str = strtolower($str);
142
		if (is_numeric($str)) {
143
			return floatval($str);
144
		}
145
146
		$bytes_array = array(
147
			'b' => 1,
148
			'k' => 1024,
149
			'kb' => 1024,
150
			'mb' => 1024 * 1024,
151
			'm' => 1024 * 1024,
152
			'gb' => 1024 * 1024 * 1024,
153
			'g' => 1024 * 1024 * 1024,
154
			'tb' => 1024 * 1024 * 1024 * 1024,
155
			't' => 1024 * 1024 * 1024 * 1024,
156
			'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
157
			'p' => 1024 * 1024 * 1024 * 1024 * 1024,
158
		);
159
160
		$bytes = floatval($str);
161
162
		if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
163
			$bytes *= $bytes_array[$matches[1]];
164
		} else {
165
			return false;
166
		}
167
168
		$bytes = round($bytes);
169
170
		return $bytes;
171
	}
172
173
	/**
174
	 * Recursive copying of folders
175
	 * @param string $src source folder
176
	 * @param string $dest target folder
177
	 *
178
	 */
179
	static function copyr($src, $dest) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
180
		if (is_dir($src)) {
181
			if (!is_dir($dest)) {
182
				mkdir($dest);
183
			}
184
			$files = scandir($src);
185
			foreach ($files as $file) {
186
				if ($file != "." && $file != "..") {
187
					self::copyr("$src/$file", "$dest/$file");
188
				}
189
			}
190
		} elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
191
			copy($src, $dest);
192
		}
193
	}
194
195
	/**
196
	 * Recursive deletion of folders
197
	 * @param string $dir path to the folder
198
	 * @param bool $deleteSelf if set to false only the content of the folder will be deleted
199
	 * @return bool
200
	 */
201
	static function rmdirr($dir, $deleteSelf = true) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
202
		if (is_dir($dir)) {
203
			$files = new RecursiveIteratorIterator(
204
				new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
205
				RecursiveIteratorIterator::CHILD_FIRST
206
			);
207
208
			foreach ($files as $fileInfo) {
209
				/** @var SplFileInfo $fileInfo */
210
				if ($fileInfo->isLink()) {
211
					unlink($fileInfo->getPathname());
212
				} else if ($fileInfo->isDir()) {
213
					rmdir($fileInfo->getRealPath());
214
				} else {
215
					unlink($fileInfo->getRealPath());
216
				}
217
			}
218
			if ($deleteSelf) {
219
				rmdir($dir);
220
			}
221
		} elseif (file_exists($dir)) {
222
			if ($deleteSelf) {
223
				unlink($dir);
224
			}
225
		}
226
		if (!$deleteSelf) {
227
			return true;
228
		}
229
230
		return !file_exists($dir);
231
	}
232
233
	/**
234
	 * @return \OC\Files\Type\TemplateManager
235
	 */
236
	static public function getFileTemplateManager() {
237
		if (!self::$templateManager) {
238
			self::$templateManager = new \OC\Files\Type\TemplateManager();
239
		}
240
		return self::$templateManager;
241
	}
242
243
	/**
244
	 * detect if a given program is found in the search PATH
245
	 *
246
	 * @param string $name
247
	 * @param bool $path
248
	 * @internal param string $program name
249
	 * @internal param string $optional search path, defaults to $PATH
250
	 * @return bool    true if executable program found in path
251
	 */
252
	public static function canExecute($name, $path = false) {
253
		// path defaults to PATH from environment if not set
254
		if ($path === false) {
255
			$path = getenv("PATH");
256
		}
257
		// check method depends on operating system
258
		if (!strncmp(PHP_OS, "WIN", 3)) {
259
			// on Windows an appropriate COM or EXE file needs to exist
260
			$exts = array(".exe", ".com");
261
			$check_fn = "file_exists";
262
		} else {
263
			// anywhere else we look for an executable file of that name
264
			$exts = array("");
265
			$check_fn = "is_executable";
266
		}
267
		// Default check will be done with $path directories :
268
		$dirs = explode(PATH_SEPARATOR, $path);
269
		// WARNING : We have to check if open_basedir is enabled :
270
		$obd = OC::$server->getIniWrapper()->getString('open_basedir');
271
		if ($obd != "none") {
272
			$obd_values = explode(PATH_SEPARATOR, $obd);
273
			if (count($obd_values) > 0 and $obd_values[0]) {
274
				// open_basedir is in effect !
275
				// We need to check if the program is in one of these dirs :
276
				$dirs = $obd_values;
277
			}
278
		}
279
		foreach ($dirs as $dir) {
280
			foreach ($exts as $ext) {
281
				if ($check_fn("$dir/$name" . $ext))
282
					return true;
283
			}
284
		}
285
		return false;
286
	}
287
288
	/**
289
	 * copy the contents of one stream to another
290
	 *
291
	 * @param resource $source
292
	 * @param resource $target
293
	 * @return array the number of bytes copied and result
294
	 */
295
	public static function streamCopy($source, $target) {
296
		if (!$source or !$target) {
297
			return array(0, false);
298
		}
299
		$bufSize = 8192;
300
		$result = true;
301
		$count = 0;
302
		while (!feof($source)) {
303
			$buf = fread($source, $bufSize);
304
			$bytesWritten = fwrite($target, $buf);
305
			if ($bytesWritten !== false) {
306
				$count += $bytesWritten;
307
			}
308
			// note: strlen is expensive so only use it when necessary,
309
			// on the last block
310
			if ($bytesWritten === false
311
				|| ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
312
			) {
313
				// write error, could be disk full ?
314
				$result = false;
315
				break;
316
			}
317
		}
318
		return array($count, $result);
319
	}
320
321
	/**
322
	 * Adds a suffix to the name in case the file exists
323
	 *
324
	 * @param string $path
325
	 * @param string $filename
326
	 * @return string
327
	 */
328
	public static function buildNotExistingFileName($path, $filename) {
329
		$view = \OC\Files\Filesystem::getView();
330
		return self::buildNotExistingFileNameForView($path, $filename, $view);
331
	}
332
333
	/**
334
	 * Adds a suffix to the name in case the file exists
335
	 *
336
	 * @param string $path
337
	 * @param string $filename
338
	 * @return string
339
	 */
340
	public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
341
		if ($path === '/') {
342
			$path = '';
343
		}
344
		if ($pos = strrpos($filename, '.')) {
345
			$name = substr($filename, 0, $pos);
346
			$ext = substr($filename, $pos);
347
		} else {
348
			$name = $filename;
349
			$ext = '';
350
		}
351
352
		$newpath = $path . '/' . $filename;
353
		if ($view->file_exists($newpath)) {
354
			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
355
				//Replace the last "(number)" with "(number+1)"
356
				$last_match = count($matches[0]) - 1;
357
				$counter = $matches[1][$last_match][0] + 1;
358
				$offset = $matches[0][$last_match][1];
359
				$match_length = strlen($matches[0][$last_match][0]);
360
			} else {
361
				$counter = 2;
362
				$match_length = 0;
363
				$offset = false;
364
			}
365
			do {
366
				if ($offset) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $offset of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
367
					//Replace the last "(number)" with "(number+1)"
368
					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
369
				} else {
370
					$newname = $name . ' (' . $counter . ')';
371
				}
372
				$newpath = $path . '/' . $newname . $ext;
373
				$counter++;
374
			} while ($view->file_exists($newpath));
375
		}
376
377
		return $newpath;
378
	}
379
380
	/**
381
	 * Checks if $sub is a subdirectory of $parent
382
	 *
383
	 * @param string $sub
384
	 * @param string $parent
385
	 * @return bool
386
	 */
387
	public static function isSubDirectory($sub, $parent) {
388
		$realpathSub = realpath($sub);
389
		$realpathParent = realpath($parent);
390
391
		// realpath() may return false in case the directory does not exist
392
		// since we can not be sure how different PHP versions may behave here
393
		// we do an additional check whether realpath returned false
394
		if($realpathSub === false ||  $realpathParent === false) {
395
			return false;
396
		}
397
398
		// Check whether $sub is a subdirectory of $parent
399
		if (strpos($realpathSub, $realpathParent) === 0) {
400
			return true;
401
		}
402
403
		return false;
404
	}
405
406
	/**
407
	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
408
	 *
409
	 * @param array $input The array to work on
410
	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
411
	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
412
	 * @return array
413
	 *
414
	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
415
	 * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
416
	 *
417
	 */
418
	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
419
		$case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
420
		$ret = array();
421
		foreach ($input as $k => $v) {
422
			$ret[mb_convert_case($k, $case, $encoding)] = $v;
423
		}
424
		return $ret;
425
	}
426
427
	/**
428
	 * performs a search in a nested array
429
	 * @param array $haystack the array to be searched
430
	 * @param string $needle the search string
431
	 * @param string $index optional, only search this key name
432
	 * @return mixed the key of the matching field, otherwise false
433
	 *
434
	 * performs a search in a nested array
435
	 *
436
	 * taken from http://www.php.net/manual/en/function.array-search.php#97645
437
	 */
438
	public static function recursiveArraySearch($haystack, $needle, $index = null) {
439
		$aIt = new RecursiveArrayIterator($haystack);
440
		$it = new RecursiveIteratorIterator($aIt);
441
442
		while ($it->valid()) {
443
			if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
444
				return $aIt->key();
445
			}
446
447
			$it->next();
448
		}
449
450
		return false;
451
	}
452
453
	/**
454
	 * calculates the maximum upload size respecting system settings, free space and user quota
455
	 *
456
	 * @param string $dir the current folder where the user currently operates
457
	 * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
458
	 * @return int number of bytes representing
459
	 */
460
	public static function maxUploadFilesize($dir, $freeSpace = null) {
461
		if (is_null($freeSpace) || $freeSpace < 0){
462
			$freeSpace = self::freeSpace($dir);
463
		}
464
		return min($freeSpace, self::uploadLimit());
465
	}
466
467
	/**
468
	 * Calculate free space left within user quota
469
	 *
470
	 * @param string $dir the current folder where the user currently operates
471
	 * @return int number of bytes representing
472
	 */
473
	public static function freeSpace($dir) {
474
		$freeSpace = \OC\Files\Filesystem::free_space($dir);
475 View Code Duplication
		if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
476
			$freeSpace = max($freeSpace, 0);
477
			return $freeSpace;
478
		} else {
479
			return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
480
		}
481
	}
482
483
	/**
484
	 * Calculate PHP upload limit
485
	 *
486
	 * @return int PHP upload file size limit
487
	 */
488
	public static function uploadLimit() {
489
		$ini = \OC::$server->getIniWrapper();
490
		$upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
491
		$post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
492
		if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
493
			return INF;
494
		} elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
495
			return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression max($upload_max_filesize, $post_max_size); of type double|false adds false to the return on line 495 which is incompatible with the return type documented by OC_Helper::uploadLimit of type integer. It seems like you forgot to handle an error condition.
Loading history...
496
		} else {
497
			return min($upload_max_filesize, $post_max_size);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression min($upload_max_filesize, $post_max_size); of type double|false adds false to the return on line 497 which is incompatible with the return type documented by OC_Helper::uploadLimit of type integer. It seems like you forgot to handle an error condition.
Loading history...
498
		}
499
	}
500
501
	/**
502
	 * Checks if a function is available
503
	 *
504
	 * @param string $function_name
505
	 * @return bool
506
	 */
507
	public static function is_function_enabled($function_name) {
508
		if (!function_exists($function_name)) {
509
			return false;
510
		}
511
		$ini = \OC::$server->getIniWrapper();
512
		$disabled = explode(',', $ini->get('disable_functions'));
513
		$disabled = array_map('trim', $disabled);
514
		if (in_array($function_name, $disabled)) {
515
			return false;
516
		}
517
		$disabled = explode(',', $ini->get('suhosin.executor.func.blacklist'));
518
		$disabled = array_map('trim', $disabled);
519
		if (in_array($function_name, $disabled)) {
520
			return false;
521
		}
522
		return true;
523
	}
524
525
	/**
526
	 * Try to find a program
527
	 * Note: currently windows is not supported
528
	 *
529
	 * @param string $program
530
	 * @return null|string
531
	 */
532
	public static function findBinaryPath($program) {
533
		$memcache = \OC::$server->getMemCacheFactory()->create('findBinaryPath');
534
		if ($memcache->hasKey($program)) {
0 ignored issues
show
Deprecated Code introduced by
The method OCP\ICache::hasKey() has been deprecated with message: 9.1.0 Directly read from GET to prevent race conditions

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
535
			return $memcache->get($program);
536
		}
537
		$result = null;
538
		if (self::is_function_enabled('exec')) {
539
			$exeSniffer = new ExecutableFinder();
540
			// Returns null if nothing is found
541
			$result = $exeSniffer->find($program);
542
			if (empty($result)) {
543
				$paths = getenv('PATH');
544
				if (empty($paths)) {
545
					$paths = '/usr/local/bin /usr/bin /opt/bin /bin';
546
				} else {
547
					$paths = str_replace(':',' ',getenv('PATH'));
548
				}
549
				$command = 'find ' . $paths . ' -name ' . escapeshellarg($program) . ' 2> /dev/null';
550
				exec($command, $output, $returnCode);
551
				if (count($output) > 0) {
552
					$result = escapeshellcmd($output[0]);
553
				}
554
			}
555
		}
556
		// store the value for 5 minutes
557
		$memcache->set($program, $result, 300);
558
		return $result;
559
	}
560
561
	/**
562
	 * Calculate the disc space for the given path
563
	 *
564
	 * @param string $path
565
	 * @param \OCP\Files\FileInfo $rootInfo (optional)
566
	 * @return array
567
	 * @throws \OCP\Files\NotFoundException
568
	 */
569
	public static function getStorageInfo($path, $rootInfo = null) {
570
		// return storage info without adding mount points
571
		$includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
572
573
		if (!$rootInfo) {
574
			$rootInfo = \OC\Files\Filesystem::getFileInfo($path, false);
575
		}
576
		if (!$rootInfo instanceof \OCP\Files\FileInfo) {
577
			throw new \OCP\Files\NotFoundException();
578
		}
579
		$used = $rootInfo->getSize();
580
		if ($used < 0) {
581
			$used = 0;
582
		}
583
		$quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
584
		$storage = $rootInfo->getStorage();
585
		$sourceStorage = $storage;
586
		if ($storage->instanceOfStorage('\OC\Files\Storage\Shared')) {
587
			$includeExtStorage = false;
588
			$sourceStorage = $storage->getSourceStorage();
589
		}
590
		if ($includeExtStorage) {
591
			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
592
				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
593
			) {
594
				/** @var \OC\Files\Storage\Home $storage */
595
				$user = $storage->getUser();
596
			} else {
597
				$user = \OC::$server->getUserSession()->getUser()->getUID();
598
			}
599
			if ($user) {
600
				$quota = OC_Util::getUserQuota($user);
601
			} else {
602
				$quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
603
			}
604
			if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
605
				// always get free space / total space from root + mount points
606
				return self::getGlobalStorageInfo();
607
			}
608
		}
609
610
		// TODO: need a better way to get total space from storage
611
		if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
612
			/** @var \OC\Files\Storage\Wrapper\Quota $storage */
613
			$quota = $sourceStorage->getQuota();
614
		}
615
		$free = $sourceStorage->free_space('');
616
		if ($free >= 0) {
617
			$total = $free + $used;
618
		} else {
619
			$total = $free; //either unknown or unlimited
620
		}
621 View Code Duplication
		if ($total > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
622
			if ($quota > 0 && $total > $quota) {
623
				$total = $quota;
624
			}
625
			// prevent division by zero or error codes (negative values)
626
			$relative = round(($used / $total) * 10000) / 100;
627
		} else {
628
			$relative = 0;
629
		}
630
631
		$ownerId = $storage->getOwner($path);
632
		$ownerDisplayName = '';
633
		$owner = \OC::$server->getUserManager()->get($ownerId);
634
		if($owner) {
635
			$ownerDisplayName = $owner->getDisplayName();
636
		}
637
638
		return [
639
			'free' => $free,
640
			'used' => $used,
641
			'quota' => $quota,
642
			'total' => $total,
643
			'relative' => $relative,
644
			'owner' => $ownerId,
645
			'ownerDisplayName' => $ownerDisplayName,
646
		];
647
	}
648
649
	/**
650
	 * Get storage info including all mount points and quota
651
	 *
652
	 * @return array
653
	 */
654
	private static function getGlobalStorageInfo() {
655
		$quota = OC_Util::getUserQuota(\OCP\User::getUser());
0 ignored issues
show
Deprecated Code introduced by
The method OCP\User::getUser() has been deprecated with message: 8.0.0 Use \OC::$server->getUserSession()->getUser()->getUID()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
656
657
		$rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
0 ignored issues
show
Documentation introduced by
'ext' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
658
		$used = $rootInfo['size'];
659
		if ($used < 0) {
660
			$used = 0;
661
		}
662
663
		$total = $quota;
664
		$free = $quota - $used;
665
666 View Code Duplication
		if ($total > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
667
			if ($quota > 0 && $total > $quota) {
668
				$total = $quota;
669
			}
670
			// prevent division by zero or error codes (negative values)
671
			$relative = round(($used / $total) * 10000) / 100;
672
		} else {
673
			$relative = 0;
674
		}
675
676
		return array('free' => $free, 'used' => $used, 'total' => $total, 'relative' => $relative);
677
678
	}
679
680
	/**
681
	 * Returns whether the config file is set manually to read-only
682
	 * @return bool
683
	 */
684
	public static function isReadOnlyConfigEnabled() {
685
		return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
686
	}
687
}
688