Completed
Push — stable9 ( e5645a...980d90 )
by Blizzz
14:13 queued 13:48
created

OC_Helper::isReadOnlyConfigEnabled()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Arthur Schiwon <[email protected]>
4
 * @author Bart Visscher <[email protected]>
5
 * @author Björn Schießle <[email protected]>
6
 * @author Christopher Schäpers <[email protected]>
7
 * @author Clark Tomlinson <[email protected]>
8
 * @author Fabian Henze <[email protected]>
9
 * @author Felix Moeller <[email protected]>
10
 * @author Georg Ehrke <[email protected]>
11
 * @author Jakob Sack <[email protected]>
12
 * @author Jan-Christoph Borchardt <[email protected]>
13
 * @author Joas Schilling <[email protected]>
14
 * @author Jörn Friedrich Dreyer <[email protected]>
15
 * @author Lukas Reschke <[email protected]>
16
 * @author Michael Gapczynski <[email protected]>
17
 * @author Morris Jobke <[email protected]>
18
 * @author Olivier Paroz <[email protected]>
19
 * @author Pellaeon Lin <[email protected]>
20
 * @author Robin Appelman <[email protected]>
21
 * @author Robin McCorkell <[email protected]>
22
 * @author Roeland Jago Douma <[email protected]>
23
 * @author Simon Könnecke <[email protected]>
24
 * @author Thomas Müller <[email protected]>
25
 * @author Thomas Tanghus <[email protected]>
26
 * @author Vincent Petry <[email protected]>
27
 *
28
 * @copyright Copyright (c) 2016, ownCloud, Inc.
29
 * @license AGPL-3.0
30
 *
31
 * This code is free software: you can redistribute it and/or modify
32
 * it under the terms of the GNU Affero General Public License, version 3,
33
 * as published by the Free Software Foundation.
34
 *
35
 * This program is distributed in the hope that it will be useful,
36
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
37
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
38
 * GNU Affero General Public License for more details.
39
 *
40
 * You should have received a copy of the GNU Affero General Public License, version 3,
41
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
42
 *
43
 */
44
use Symfony\Component\Process\ExecutableFinder;
45
46
/**
47
 * Collection of useful functions
48
 */
49
class OC_Helper {
50
	private static $templateManager;
51
52
	/**
53
	 * Creates an absolute url for public use
54
	 * @param string $service id
55
	 * @param bool $add_slash
56
	 * @return string the url
57
	 *
58
	 * Returns a absolute url to the given service.
59
	 */
60
	public static function linkToPublic($service, $add_slash = false) {
61
		if ($service === 'files') {
62
			$url = OC::$server->getURLGenerator()->getAbsoluteURL('/s');
63
		} else {
64
			$url = OC::$server->getURLGenerator()->getAbsoluteURL(OC::$server->getURLGenerator()->linkTo('', 'public.php').'?service='.$service);
65
		}
66
		return $url . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '');
67
	}
68
69
	/**
70
	 * get path to preview of file
71
	 * @param string $path path
72
	 * @return string the url
73
	 *
74
	 * Returns the path to the preview of the file.
75
	 */
76
	public static function previewIcon($path) {
77
		return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_preview', ['x' => 32, 'y' => 32, 'file' => $path]);
78
	}
79
80
	public static function publicPreviewIcon( $path, $token ) {
81
		return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_public_preview', ['x' => 32, 'y' => 32, 'file' => $path, 't' => $token]);
82
	}
83
84
	/**
85
	 * Make a human file size
86
	 * @param int $bytes file size in bytes
87
	 * @return string a human readable file size
88
	 *
89
	 * Makes 2048 to 2 kB.
90
	 */
91
	public static function humanFileSize($bytes) {
92
		if ($bytes < 0) {
93
			return "?";
94
		}
95
		if ($bytes < 1024) {
96
			return "$bytes B";
97
		}
98
		$bytes = round($bytes / 1024, 0);
99
		if ($bytes < 1024) {
100
			return "$bytes KB";
101
		}
102
		$bytes = round($bytes / 1024, 1);
103
		if ($bytes < 1024) {
104
			return "$bytes MB";
105
		}
106
		$bytes = round($bytes / 1024, 1);
107
		if ($bytes < 1024) {
108
			return "$bytes GB";
109
		}
110
		$bytes = round($bytes / 1024, 1);
111
		if ($bytes < 1024) {
112
			return "$bytes TB";
113
		}
114
115
		$bytes = round($bytes / 1024, 1);
116
		return "$bytes PB";
117
	}
118
119
	/**
120
	 * Make a php file size
121
	 * @param int $bytes file size in bytes
122
	 * @return string a php parseable file size
123
	 *
124
	 * Makes 2048 to 2k and 2^41 to 2048G
125
	 */
126
	public static function phpFileSize($bytes) {
127
		if ($bytes < 0) {
128
			return "?";
129
		}
130
		if ($bytes < 1024) {
131
			return $bytes . "B";
132
		}
133
		$bytes = round($bytes / 1024, 1);
134
		if ($bytes < 1024) {
135
			return $bytes . "K";
136
		}
137
		$bytes = round($bytes / 1024, 1);
138
		if ($bytes < 1024) {
139
			return $bytes . "M";
140
		}
141
		$bytes = round($bytes / 1024, 1);
142
		return $bytes . "G";
143
	}
144
145
	/**
146
	 * Make a computer file size
147
	 * @param string $str file size in human readable format
148
	 * @return float a file size in bytes
149
	 *
150
	 * Makes 2kB to 2048.
151
	 *
152
	 * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
153
	 */
154
	public static function computerFileSize($str) {
155
		$str = strtolower($str);
156
		if (is_numeric($str)) {
157
			return floatval($str);
158
		}
159
160
		$bytes_array = array(
161
			'b' => 1,
162
			'k' => 1024,
163
			'kb' => 1024,
164
			'mb' => 1024 * 1024,
165
			'm' => 1024 * 1024,
166
			'gb' => 1024 * 1024 * 1024,
167
			'g' => 1024 * 1024 * 1024,
168
			'tb' => 1024 * 1024 * 1024 * 1024,
169
			't' => 1024 * 1024 * 1024 * 1024,
170
			'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
171
			'p' => 1024 * 1024 * 1024 * 1024 * 1024,
172
		);
173
174
		$bytes = floatval($str);
175
176
		if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
177
			$bytes *= $bytes_array[$matches[1]];
178
		} else {
179
			return false;
180
		}
181
182
		$bytes = round($bytes);
183
184
		return $bytes;
185
	}
186
187
	/**
188
	 * Recursive copying of folders
189
	 * @param string $src source folder
190
	 * @param string $dest target folder
191
	 *
192
	 */
193
	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...
194
		if (is_dir($src)) {
195
			if (!is_dir($dest)) {
196
				mkdir($dest);
197
			}
198
			$files = scandir($src);
199
			foreach ($files as $file) {
200
				if ($file != "." && $file != "..") {
201
					self::copyr("$src/$file", "$dest/$file");
202
				}
203
			}
204
		} elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
205
			copy($src, $dest);
206
		}
207
	}
208
209
	/**
210
	 * Recursive deletion of folders
211
	 * @param string $dir path to the folder
212
	 * @param bool $deleteSelf if set to false only the content of the folder will be deleted
213
	 * @return bool
214
	 */
215
	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...
216
		if (is_dir($dir)) {
217
			$files = new RecursiveIteratorIterator(
218
				new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
219
				RecursiveIteratorIterator::CHILD_FIRST
220
			);
221
222
			foreach ($files as $fileInfo) {
223
				/** @var SplFileInfo $fileInfo */
224
				if ($fileInfo->isLink()) {
225
					unlink($fileInfo->getPathname());
226
				} else if ($fileInfo->isDir()) {
227
					rmdir($fileInfo->getRealPath());
228
				} else {
229
					unlink($fileInfo->getRealPath());
230
				}
231
			}
232
			if ($deleteSelf) {
233
				rmdir($dir);
234
			}
235
		} elseif (file_exists($dir)) {
236
			if ($deleteSelf) {
237
				unlink($dir);
238
			}
239
		}
240
		if (!$deleteSelf) {
241
			return true;
242
		}
243
244
		return !file_exists($dir);
245
	}
246
247
	/**
248
	 * @return \OC\Files\Type\TemplateManager
249
	 */
250
	static public function getFileTemplateManager() {
251
		if (!self::$templateManager) {
252
			self::$templateManager = new \OC\Files\Type\TemplateManager();
253
		}
254
		return self::$templateManager;
255
	}
256
257
	/**
258
	 * detect if a given program is found in the search PATH
259
	 *
260
	 * @param string $name
261
	 * @param bool $path
262
	 * @internal param string $program name
263
	 * @internal param string $optional search path, defaults to $PATH
264
	 * @return bool    true if executable program found in path
265
	 */
266
	public static function canExecute($name, $path = false) {
267
		// path defaults to PATH from environment if not set
268
		if ($path === false) {
269
			$path = getenv("PATH");
270
		}
271
		// check method depends on operating system
272
		if (!strncmp(PHP_OS, "WIN", 3)) {
273
			// on Windows an appropriate COM or EXE file needs to exist
274
			$exts = array(".exe", ".com");
275
			$check_fn = "file_exists";
276
		} else {
277
			// anywhere else we look for an executable file of that name
278
			$exts = array("");
279
			$check_fn = "is_executable";
280
		}
281
		// Default check will be done with $path directories :
282
		$dirs = explode(PATH_SEPARATOR, $path);
283
		// WARNING : We have to check if open_basedir is enabled :
284
		$obd = OC::$server->getIniWrapper()->getString('open_basedir');
285
		if ($obd != "none") {
286
			$obd_values = explode(PATH_SEPARATOR, $obd);
287
			if (count($obd_values) > 0 and $obd_values[0]) {
288
				// open_basedir is in effect !
289
				// We need to check if the program is in one of these dirs :
290
				$dirs = $obd_values;
291
			}
292
		}
293
		foreach ($dirs as $dir) {
294
			foreach ($exts as $ext) {
295
				if ($check_fn("$dir/$name" . $ext))
296
					return true;
297
			}
298
		}
299
		return false;
300
	}
301
302
	/**
303
	 * copy the contents of one stream to another
304
	 *
305
	 * @param resource $source
306
	 * @param resource $target
307
	 * @return array the number of bytes copied and result
308
	 */
309
	public static function streamCopy($source, $target) {
310
		if (!$source or !$target) {
311
			return array(0, false);
312
		}
313
		$bufSize = 8192;
314
		$result = true;
315
		$count = 0;
316
		while (!feof($source)) {
317
			$buf = fread($source, $bufSize);
318
			$bytesWritten = fwrite($target, $buf);
319
			if ($bytesWritten !== false) {
320
				$count += $bytesWritten;
321
			}
322
			// note: strlen is expensive so only use it when necessary,
323
			// on the last block
324
			if ($bytesWritten === false
325
				|| ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
326
			) {
327
				// write error, could be disk full ?
328
				$result = false;
329
				break;
330
			}
331
		}
332
		return array($count, $result);
333
	}
334
335
	/**
336
	 * Adds a suffix to the name in case the file exists
337
	 *
338
	 * @param string $path
339
	 * @param string $filename
340
	 * @return string
341
	 */
342
	public static function buildNotExistingFileName($path, $filename) {
343
		$view = \OC\Files\Filesystem::getView();
344
		return self::buildNotExistingFileNameForView($path, $filename, $view);
345
	}
346
347
	/**
348
	 * Adds a suffix to the name in case the file exists
349
	 *
350
	 * @param string $path
351
	 * @param string $filename
352
	 * @return string
353
	 */
354
	public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
355
		if ($path === '/') {
356
			$path = '';
357
		}
358
		if ($pos = strrpos($filename, '.')) {
359
			$name = substr($filename, 0, $pos);
360
			$ext = substr($filename, $pos);
361
		} else {
362
			$name = $filename;
363
			$ext = '';
364
		}
365
366
		$newpath = $path . '/' . $filename;
367
		if ($view->file_exists($newpath)) {
368
			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
369
				//Replace the last "(number)" with "(number+1)"
370
				$last_match = count($matches[0]) - 1;
371
				$counter = $matches[1][$last_match][0] + 1;
372
				$offset = $matches[0][$last_match][1];
373
				$match_length = strlen($matches[0][$last_match][0]);
374
			} else {
375
				$counter = 2;
376
				$match_length = 0;
377
				$offset = false;
378
			}
379
			do {
380
				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...
381
					//Replace the last "(number)" with "(number+1)"
382
					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
383
				} else {
384
					$newname = $name . ' (' . $counter . ')';
385
				}
386
				$newpath = $path . '/' . $newname . $ext;
387
				$counter++;
388
			} while ($view->file_exists($newpath));
389
		}
390
391
		return $newpath;
392
	}
393
394
	/**
395
	 * Checks if $sub is a subdirectory of $parent
396
	 *
397
	 * @param string $sub
398
	 * @param string $parent
399
	 * @return bool
400
	 */
401
	public static function isSubDirectory($sub, $parent) {
402
		$realpathSub = realpath($sub);
403
		$realpathParent = realpath($parent);
404
405
		// realpath() may return false in case the directory does not exist
406
		// since we can not be sure how different PHP versions may behave here
407
		// we do an additional check whether realpath returned false
408
		if($realpathSub === false ||  $realpathParent === false) {
409
			return false;
410
		}
411
412
		// Check whether $sub is a subdirectory of $parent
413
		if (strpos($realpathSub, $realpathParent) === 0) {
414
			return true;
415
		}
416
417
		return false;
418
	}
419
420
	/**
421
	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
422
	 *
423
	 * @param array $input The array to work on
424
	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
425
	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
426
	 * @return array
427
	 *
428
	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
429
	 * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
430
	 *
431
	 */
432
	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
433
		$case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
434
		$ret = array();
435
		foreach ($input as $k => $v) {
436
			$ret[mb_convert_case($k, $case, $encoding)] = $v;
437
		}
438
		return $ret;
439
	}
440
441
	/**
442
	 * performs a search in a nested array
443
	 * @param array $haystack the array to be searched
444
	 * @param string $needle the search string
445
	 * @param string $index optional, only search this key name
446
	 * @return mixed the key of the matching field, otherwise false
447
	 *
448
	 * performs a search in a nested array
449
	 *
450
	 * taken from http://www.php.net/manual/en/function.array-search.php#97645
451
	 */
452
	public static function recursiveArraySearch($haystack, $needle, $index = null) {
453
		$aIt = new RecursiveArrayIterator($haystack);
454
		$it = new RecursiveIteratorIterator($aIt);
455
456
		while ($it->valid()) {
457
			if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
458
				return $aIt->key();
459
			}
460
461
			$it->next();
462
		}
463
464
		return false;
465
	}
466
467
	/**
468
	 * Shortens str to maxlen by replacing characters in the middle with '...', eg.
469
	 * ellipsis('a very long string with lots of useless info to make a better example', 14) becomes 'a very ...example'
470
	 *
471
	 * @param string $str the string
472
	 * @param string $maxlen the maximum length of the result
473
	 * @return string with at most maxlen characters
474
	 */
475
	public static function ellipsis($str, $maxlen) {
476
		if (strlen($str) > $maxlen) {
477
			$characters = floor($maxlen / 2);
478
			return substr($str, 0, $characters) . '...' . substr($str, -1 * $characters);
479
		}
480
		return $str;
481
	}
482
483
	/**
484
	 * calculates the maximum upload size respecting system settings, free space and user quota
485
	 *
486
	 * @param string $dir the current folder where the user currently operates
487
	 * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
488
	 * @return int number of bytes representing
489
	 */
490
	public static function maxUploadFilesize($dir, $freeSpace = null) {
491
		if (is_null($freeSpace) || $freeSpace < 0){
492
			$freeSpace = self::freeSpace($dir);
493
		}
494
		return min($freeSpace, self::uploadLimit());
495
	}
496
497
	/**
498
	 * Calculate free space left within user quota
499
	 *
500
	 * @param string $dir the current folder where the user currently operates
501
	 * @return int number of bytes representing
502
	 */
503
	public static function freeSpace($dir) {
504
		$freeSpace = \OC\Files\Filesystem::free_space($dir);
505 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...
506
			$freeSpace = max($freeSpace, 0);
507
			return $freeSpace;
508
		} else {
509
			return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
510
		}
511
	}
512
513
	/**
514
	 * Calculate PHP upload limit
515
	 *
516
	 * @return int PHP upload file size limit
517
	 */
518
	public static function uploadLimit() {
519
		$ini = \OC::$server->getIniWrapper();
520
		$upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
521
		$post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
522
		if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
523
			return INF;
524
		} elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
525
			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 525 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...
526
		} else {
527
			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 527 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...
528
		}
529
	}
530
531
	/**
532
	 * Checks if a function is available
533
	 *
534
	 * @param string $function_name
535
	 * @return bool
536
	 */
537
	public static function is_function_enabled($function_name) {
538
		if (!function_exists($function_name)) {
539
			return false;
540
		}
541
		$ini = \OC::$server->getIniWrapper();
542
		$disabled = explode(',', $ini->get('disable_functions'));
543
		$disabled = array_map('trim', $disabled);
544
		if (in_array($function_name, $disabled)) {
545
			return false;
546
		}
547
		$disabled = explode(',', $ini->get('suhosin.executor.func.blacklist'));
548
		$disabled = array_map('trim', $disabled);
549
		if (in_array($function_name, $disabled)) {
550
			return false;
551
		}
552
		return true;
553
	}
554
555
	/**
556
	 * Try to find a program
557
	 * Note: currently windows is not supported
558
	 *
559
	 * @param string $program
560
	 * @return null|string
561
	 */
562
	public static function findBinaryPath($program) {
563
		$memcache = \OC::$server->getMemCacheFactory()->create('findBinaryPath');
564
		if ($memcache->hasKey($program)) {
565
			return $memcache->get($program);
566
		}
567
		$result = null;
568
		if (!\OC_Util::runningOnWindows() && self::is_function_enabled('exec')) {
569
			$exeSniffer = new ExecutableFinder();
570
			// Returns null if nothing is found
571
			$result = $exeSniffer->find($program);
572
			if (empty($result)) {
573
				$paths = getenv('PATH');
574
				if (empty($paths)) {
575
					$paths = '/usr/local/bin /usr/bin /opt/bin /bin';
576
				} else {
577
					$paths = str_replace(':',' ',getenv('PATH'));
578
				}
579
				$command = 'find ' . $paths . ' -name ' . escapeshellarg($program) . ' 2> /dev/null';
580
				exec($command, $output, $returnCode);
581
				if (count($output) > 0) {
582
					$result = escapeshellcmd($output[0]);
583
				}
584
			}
585
		}
586
		// store the value for 5 minutes
587
		$memcache->set($program, $result, 300);
588
		return $result;
589
	}
590
591
	/**
592
	 * Calculate the disc space for the given path
593
	 *
594
	 * @param string $path
595
	 * @param \OCP\Files\FileInfo $rootInfo (optional)
596
	 * @return array
597
	 * @throws \OCP\Files\NotFoundException
598
	 */
599
	public static function getStorageInfo($path, $rootInfo = null) {
600
		// return storage info without adding mount points
601
		$includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
602
603
		if (!$rootInfo) {
604
			$rootInfo = \OC\Files\Filesystem::getFileInfo($path, false);
605
		}
606
		if (!$rootInfo instanceof \OCP\Files\FileInfo) {
607
			throw new \OCP\Files\NotFoundException();
608
		}
609
		$used = $rootInfo->getSize();
610
		if ($used < 0) {
611
			$used = 0;
612
		}
613
		$quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
614
		$storage = $rootInfo->getStorage();
615
		$sourceStorage = $storage;
616
		if ($storage->instanceOfStorage('\OC\Files\Storage\Shared')) {
617
			$includeExtStorage = false;
618
			$sourceStorage = $storage->getSourceStorage();
619
		}
620
		if ($includeExtStorage) {
621
			$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...
622
			if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
623
				// always get free space / total space from root + mount points
624
				return self::getGlobalStorageInfo();
625
			}
626
		}
627
628
		// TODO: need a better way to get total space from storage
629
		if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
630
			/** @var \OC\Files\Storage\Wrapper\Quota $storage */
631
			$quota = $sourceStorage->getQuota();
632
		}
633
		$free = $storage->free_space('');
634
		if ($free >= 0) {
635
			$total = $free + $used;
636
		} else {
637
			$total = $free; //either unknown or unlimited
638
		}
639 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...
640
			if ($quota > 0 && $total > $quota) {
641
				$total = $quota;
642
			}
643
			// prevent division by zero or error codes (negative values)
644
			$relative = round(($used / $total) * 10000) / 100;
645
		} else {
646
			$relative = 0;
647
		}
648
649
		$ownerId = $storage->getOwner($path);
650
		$ownerDisplayName = '';
651
		$owner = \OC::$server->getUserManager()->get($ownerId);
652
		if($owner) {
653
			$ownerDisplayName = $owner->getDisplayName();
654
		}
655
656
		return [
657
			'free' => $free,
658
			'used' => $used,
659
			'quota' => $quota,
660
			'total' => $total,
661
			'relative' => $relative,
662
			'owner' => $ownerId,
663
			'ownerDisplayName' => $ownerDisplayName,
664
		];
665
	}
666
667
	/**
668
	 * Get storage info including all mount points and quota
669
	 *
670
	 * @return array
671
	 */
672
	private static function getGlobalStorageInfo() {
673
		$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...
674
675
		$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...
676
		$used = $rootInfo['size'];
677
		if ($used < 0) {
678
			$used = 0;
679
		}
680
681
		$total = $quota;
682
		$free = $quota - $used;
683
684 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...
685
			if ($quota > 0 && $total > $quota) {
686
				$total = $quota;
687
			}
688
			// prevent division by zero or error codes (negative values)
689
			$relative = round(($used / $total) * 10000) / 100;
690
		} else {
691
			$relative = 0;
692
		}
693
694
		return array('free' => $free, 'used' => $used, 'total' => $total, 'relative' => $relative);
695
696
	}
697
698
	/**
699
	 * Returns whether the config file is set manually to read-only
700
	 * @return bool
701
	 */
702
	public static function isReadOnlyConfigEnabled() {
703
		return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
704
	}
705
}
706