Completed
Push — master ( f212c6...e9c6ec )
by Morris
36s
created
lib/private/legacy/util.php 2 patches
Spacing   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
 
81 81
 	private static function initLocalStorageRootFS() {
82 82
 		// mount local file backend as root
83
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
83
+		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT."/data");
84 84
 		//first set up the local "root" storage
85 85
 		\OC\Files\Filesystem::initMountManager();
86 86
 		if (!self::$rootMounted) {
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 		\OC\Files\Filesystem::initMountManager();
203 203
 
204 204
 		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
205
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
205
+		\OC\Files\Filesystem::addStorageWrapper('mount_options', function($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
206 206
 			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
207 207
 				/** @var \OC\Files\Storage\Common $storage */
208 208
 				$storage->setMountOptions($mount->getOptions());
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
 			return $storage;
211 211
 		});
212 212
 
213
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
213
+		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
214 214
 			if (!$mount->getOption('enable_sharing', true)) {
215 215
 				return new \OC\Files\Storage\Wrapper\PermissionsMask([
216 216
 					'storage' => $storage,
@@ -221,21 +221,21 @@  discard block
 block discarded – undo
221 221
 		});
222 222
 
223 223
 		// install storage availability wrapper, before most other wrappers
224
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
224
+		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function($mountPoint, \OCP\Files\Storage\IStorage $storage) {
225 225
 			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
226 226
 				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
227 227
 			}
228 228
 			return $storage;
229 229
 		});
230 230
 
231
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
231
+		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
232 232
 			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
233 233
 				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
234 234
 			}
235 235
 			return $storage;
236 236
 		});
237 237
 
238
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
238
+		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function($mountPoint, $storage) {
239 239
 			// set up quota for home storages, even for other users
240 240
 			// which can happen when using sharing
241 241
 
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
 			return $storage;
259 259
 		});
260 260
 
261
-		\OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
261
+		\OC\Files\Filesystem::addStorageWrapper('readonly', function($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
262 262
 			/*
263 263
 			 * Do not allow any operations that modify the storage
264 264
 			 */
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
 		//if we aren't logged in, there is no use to set up the filesystem
300 300
 		if ($user != "") {
301 301
 
302
-			$userDir = '/' . $user . '/files';
302
+			$userDir = '/'.$user.'/files';
303 303
 
304 304
 			//jail the user into his "home" directory
305 305
 			\OC\Files\Filesystem::init($user, $userDir);
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
 			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
380 380
 		}
381 381
 		$userQuota = $user->getQuota();
382
-		if($userQuota === 'none') {
382
+		if ($userQuota === 'none') {
383 383
 			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
384 384
 		}
385 385
 		return OC_Helper::computerFileSize($userQuota);
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
 	 */
396 396
 	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
397 397
 
398
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
398
+		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT.'/core/skeleton');
399 399
 		$userLang = \OC::$server->getL10NFactory()->findLanguage();
400 400
 		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
401 401
 
@@ -417,9 +417,9 @@  discard block
 block discarded – undo
417 417
 		if ($instanceId === null) {
418 418
 			throw new \RuntimeException('no instance id!');
419 419
 		}
420
-		$appdata = 'appdata_' . $instanceId;
420
+		$appdata = 'appdata_'.$instanceId;
421 421
 		if ($userId === $appdata) {
422
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
422
+			throw new \RuntimeException('username is reserved name: '.$appdata);
423 423
 		}
424 424
 
425 425
 		if (!empty($skeletonDirectory)) {
@@ -446,7 +446,7 @@  discard block
 block discarded – undo
446 446
 
447 447
 		// Verify if folder exists
448 448
 		$dir = opendir($source);
449
-		if($dir === false) {
449
+		if ($dir === false) {
450 450
 			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
451 451
 			return;
452 452
 		}
@@ -454,14 +454,14 @@  discard block
 block discarded – undo
454 454
 		// Copy the files
455 455
 		while (false !== ($file = readdir($dir))) {
456 456
 			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
457
-				if (is_dir($source . '/' . $file)) {
457
+				if (is_dir($source.'/'.$file)) {
458 458
 					$child = $target->newFolder($file);
459
-					self::copyr($source . '/' . $file, $child);
459
+					self::copyr($source.'/'.$file, $child);
460 460
 				} else {
461 461
 					$child = $target->newFile($file);
462
-					$sourceStream = fopen($source . '/' . $file, 'r');
463
-					if($sourceStream === false) {
464
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
462
+					$sourceStream = fopen($source.'/'.$file, 'r');
463
+					if ($sourceStream === false) {
464
+						$logger->error(sprintf('Could not fopen "%s"', $source.'/'.$file), ['app' => 'core']);
465 465
 						closedir($dir);
466 466
 						return;
467 467
 					}
@@ -538,8 +538,8 @@  discard block
 block discarded – undo
538 538
 			return;
539 539
 		}
540 540
 
541
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
542
-		require OC::$SERVERROOT . '/version.php';
541
+		$timestamp = filemtime(OC::$SERVERROOT.'/version.php');
542
+		require OC::$SERVERROOT.'/version.php';
543 543
 		/** @var $timestamp int */
544 544
 		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
545 545
 		/** @var $OC_Version string */
@@ -586,7 +586,7 @@  discard block
 block discarded – undo
586 586
 
587 587
 		// core js files need separate handling
588 588
 		if ($application !== 'core' && $file !== null) {
589
-			self::addTranslations ( $application );
589
+			self::addTranslations($application);
590 590
 		}
591 591
 		self::addExternalResource($application, $prepend, $path, "script");
592 592
 	}
@@ -663,7 +663,7 @@  discard block
 block discarded – undo
663 663
 		if ($type === "style") {
664 664
 			if (!in_array($path, self::$styles)) {
665 665
 				if ($prepend === true) {
666
-					array_unshift ( self::$styles, $path );
666
+					array_unshift(self::$styles, $path);
667 667
 				} else {
668 668
 					self::$styles[] = $path;
669 669
 				}
@@ -671,7 +671,7 @@  discard block
 block discarded – undo
671 671
 		} elseif ($type === "script") {
672 672
 			if (!in_array($path, self::$scripts)) {
673 673
 				if ($prepend === true) {
674
-					array_unshift ( self::$scripts, $path );
674
+					array_unshift(self::$scripts, $path);
675 675
 				} else {
676 676
 					self::$scripts [] = $path;
677 677
 				}
@@ -687,7 +687,7 @@  discard block
 block discarded – undo
687 687
 	 * @param array $attributes array of attributes for the element
688 688
 	 * @param string $text the text content for the element
689 689
 	 */
690
-	public static function addHeader($tag, $attributes, $text=null) {
690
+	public static function addHeader($tag, $attributes, $text = null) {
691 691
 		self::$headers[] = array(
692 692
 			'tag' => $tag,
693 693
 			'attributes' => $attributes,
@@ -727,7 +727,7 @@  discard block
 block discarded – undo
727 727
 	public static function checkServer(\OC\SystemConfig $config) {
728 728
 		$l = \OC::$server->getL10N('lib');
729 729
 		$errors = array();
730
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
730
+		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT.'/data');
731 731
 
732 732
 		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
733 733
 			// this check needs to be done every time
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
 		}
763 763
 
764 764
 		// Check if config folder is writable.
765
-		if(!OC_Helper::isReadOnlyConfigEnabled()) {
765
+		if (!OC_Helper::isReadOnlyConfigEnabled()) {
766 766
 			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
767 767
 				$errors[] = array(
768 768
 					'error' => $l->t('Cannot write into "config" directory'),
@@ -902,15 +902,15 @@  discard block
 block discarded – undo
902 902
 			}
903 903
 		}
904 904
 
905
-		foreach($missingDependencies as $missingDependency) {
905
+		foreach ($missingDependencies as $missingDependency) {
906 906
 			$errors[] = array(
907 907
 				'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
908 908
 				'hint' => $moduleHint
909 909
 			);
910 910
 			$webServerRestart = true;
911 911
 		}
912
-		foreach($invalidIniSettings as $setting) {
913
-			if(is_bool($setting[1])) {
912
+		foreach ($invalidIniSettings as $setting) {
913
+			if (is_bool($setting[1])) {
914 914
 				$setting[1] = $setting[1] ? 'on' : 'off';
915 915
 			}
916 916
 			$errors[] = [
@@ -928,7 +928,7 @@  discard block
 block discarded – undo
928 928
 		 * TODO: Should probably be implemented in the above generic dependency
929 929
 		 *       check somehow in the long-term.
930 930
 		 */
931
-		if($iniWrapper->getBool('mbstring.func_overload') !== null &&
931
+		if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
932 932
 			$iniWrapper->getBool('mbstring.func_overload') === true) {
933 933
 			$errors[] = array(
934 934
 				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
@@ -936,16 +936,16 @@  discard block
 block discarded – undo
936 936
 			);
937 937
 		}
938 938
 
939
-		if(function_exists('xml_parser_create') &&
940
-			LIBXML_LOADED_VERSION < 20700 ) {
939
+		if (function_exists('xml_parser_create') &&
940
+			LIBXML_LOADED_VERSION < 20700) {
941 941
 			$version = LIBXML_LOADED_VERSION;
942
-			$major = floor($version/10000);
942
+			$major = floor($version / 10000);
943 943
 			$version -= ($major * 10000);
944
-			$minor = floor($version/100);
944
+			$minor = floor($version / 100);
945 945
 			$version -= ($minor * 100);
946 946
 			$patch = $version;
947 947
 			$errors[] = array(
948
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
948
+				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major.'.'.$minor.'.'.$patch]),
949 949
 				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
950 950
 			);
951 951
 		}
@@ -1011,7 +1011,7 @@  discard block
 block discarded – undo
1011 1011
 	 * @return array arrays with error messages and hints
1012 1012
 	 */
1013 1013
 	public static function checkDataDirectoryPermissions($dataDirectory) {
1014
-		if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1014
+		if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1015 1015
 			return  [];
1016 1016
 		}
1017 1017
 		$l = \OC::$server->getL10N('lib');
@@ -1049,10 +1049,10 @@  discard block
 block discarded – undo
1049 1049
 				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1050 1050
 			];
1051 1051
 		}
1052
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1052
+		if (!file_exists($dataDirectory.'/.ocdata')) {
1053 1053
 			$errors[] = [
1054 1054
 				'error' => $l->t('Your data directory is invalid'),
1055
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1055
+				'hint' => $l->t('Ensure there is a file called ".ocdata"'.
1056 1056
 					' in the root of the data directory.')
1057 1057
 			];
1058 1058
 		}
@@ -1068,7 +1068,7 @@  discard block
 block discarded – undo
1068 1068
 	public static function checkLoggedIn() {
1069 1069
 		// Check if we are a user
1070 1070
 		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1071
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1071
+			header('Location: '.\OC::$server->getURLGenerator()->linkToRoute(
1072 1072
 						'core.login.showLoginForm',
1073 1073
 						[
1074 1074
 							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
@@ -1079,7 +1079,7 @@  discard block
 block discarded – undo
1079 1079
 		}
1080 1080
 		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1081 1081
 		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1082
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1082
+			header('Location: '.\OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1083 1083
 			exit();
1084 1084
 		}
1085 1085
 	}
@@ -1092,7 +1092,7 @@  discard block
 block discarded – undo
1092 1092
 	public static function checkAdminUser() {
1093 1093
 		OC_Util::checkLoggedIn();
1094 1094
 		if (!OC_User::isAdminUser(OC_User::getUser())) {
1095
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1095
+			header('Location: '.\OCP\Util::linkToAbsolute('', 'index.php'));
1096 1096
 			exit();
1097 1097
 		}
1098 1098
 	}
@@ -1106,12 +1106,12 @@  discard block
 block discarded – undo
1106 1106
 		OC_Util::checkLoggedIn();
1107 1107
 		$userObject = \OC::$server->getUserSession()->getUser();
1108 1108
 		$isSubAdmin = false;
1109
-		if($userObject !== null) {
1109
+		if ($userObject !== null) {
1110 1110
 			$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1111 1111
 		}
1112 1112
 
1113 1113
 		if (!$isSubAdmin) {
1114
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1114
+			header('Location: '.\OCP\Util::linkToAbsolute('', 'index.php'));
1115 1115
 			exit();
1116 1116
 		}
1117 1117
 		return true;
@@ -1148,10 +1148,10 @@  discard block
 block discarded – undo
1148 1148
 					}
1149 1149
 				}
1150 1150
 
1151
-				if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1152
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1151
+				if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1152
+					$location = $urlGenerator->getAbsoluteURL('/apps/'.$appId.'/');
1153 1153
 				} else {
1154
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1154
+					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/'.$appId.'/');
1155 1155
 				}
1156 1156
 			}
1157 1157
 		}
@@ -1165,7 +1165,7 @@  discard block
 block discarded – undo
1165 1165
 	 */
1166 1166
 	public static function redirectToDefaultPage() {
1167 1167
 		$location = self::getDefaultPageUrl();
1168
-		header('Location: ' . $location);
1168
+		header('Location: '.$location);
1169 1169
 		exit();
1170 1170
 	}
1171 1171
 
@@ -1178,7 +1178,7 @@  discard block
 block discarded – undo
1178 1178
 		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1179 1179
 		if (is_null($id)) {
1180 1180
 			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1181
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1181
+			$id = 'oc'.\OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1182 1182
 			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1183 1183
 		}
1184 1184
 		return $id;
@@ -1200,7 +1200,7 @@  discard block
 block discarded – undo
1200 1200
 			}, $value);
1201 1201
 		} else {
1202 1202
 			// Specify encoding for PHP<5.4
1203
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1203
+			$value = htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
1204 1204
 		}
1205 1205
 		return $value;
1206 1206
 	}
@@ -1233,7 +1233,7 @@  discard block
 block discarded – undo
1233 1233
 		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1234 1234
 
1235 1235
 		// creating a test file
1236
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1236
+		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT.'/data').'/'.$fileName;
1237 1237
 
1238 1238
 		if (file_exists($testFile)) {// already running this test, possible recursive call
1239 1239
 			return false;
@@ -1242,7 +1242,7 @@  discard block
 block discarded – undo
1242 1242
 		$fp = @fopen($testFile, 'w');
1243 1243
 		if (!$fp) {
1244 1244
 			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1245
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1245
+				'Make sure it is possible for the webserver to write to '.$testFile);
1246 1246
 		}
1247 1247
 		fwrite($fp, $testContent);
1248 1248
 		fclose($fp);
@@ -1269,10 +1269,10 @@  discard block
 block discarded – undo
1269 1269
 		}
1270 1270
 
1271 1271
 		$fileName = '/htaccesstest.txt';
1272
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1272
+		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT.'/data').'/'.$fileName;
1273 1273
 
1274 1274
 		// accessing the file via http
1275
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1275
+		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT.'/data'.$fileName);
1276 1276
 		try {
1277 1277
 			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1278 1278
 		} catch (\Exception $e) {
@@ -1363,7 +1363,7 @@  discard block
 block discarded – undo
1363 1363
 		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1364 1364
 
1365 1365
 		if ($theme === '') {
1366
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1366
+			if (is_dir(OC::$SERVERROOT.'/themes/default')) {
1367 1367
 				$theme = 'default';
1368 1368
 			}
1369 1369
 		}
@@ -1436,13 +1436,13 @@  discard block
 block discarded – undo
1436 1436
 	 * @return bool|string
1437 1437
 	 */
1438 1438
 	public static function normalizeUnicode($value) {
1439
-		if(Normalizer::isNormalized($value)) {
1439
+		if (Normalizer::isNormalized($value)) {
1440 1440
 			return $value;
1441 1441
 		}
1442 1442
 
1443 1443
 		$normalizedValue = Normalizer::normalize($value);
1444 1444
 		if ($normalizedValue === null || $normalizedValue === false) {
1445
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1445
+			\OC::$server->getLogger()->warning('normalizing failed for "'.$value.'"', ['app' => 'core']);
1446 1446
 			return $value;
1447 1447
 		}
1448 1448
 
@@ -1458,7 +1458,7 @@  discard block
 block discarded – undo
1458 1458
 		$version = OC_Util::getVersionString();
1459 1459
 		$build = OC_Util::getBuild();
1460 1460
 		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1461
-			$version .= ' Build:' . $build;
1461
+			$version .= ' Build:'.$build;
1462 1462
 		}
1463 1463
 		return $version;
1464 1464
 	}
@@ -1480,7 +1480,7 @@  discard block
 block discarded – undo
1480 1480
 		}
1481 1481
 
1482 1482
 		// detect part files
1483
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1483
+		if (preg_match('/'.\OCP\Files\FileInfo::BLACKLIST_FILES_REGEX.'/', $trimmed) !== 0) {
1484 1484
 			return false;
1485 1485
 		}
1486 1486
 
@@ -1511,19 +1511,19 @@  discard block
 block discarded – undo
1511 1511
 			} else if ($config->getValue('debug', false) && $versionDiff < 0) {
1512 1512
 				// downgrade with debug
1513 1513
 				$installedMajor = explode('.', $installedVersion);
1514
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1514
+				$installedMajor = $installedMajor[0].'.'.$installedMajor[1];
1515 1515
 				$currentMajor = explode('.', $currentVersion);
1516
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1516
+				$currentMajor = $currentMajor[0].'.'.$currentMajor[1];
1517 1517
 				if ($installedMajor === $currentMajor) {
1518 1518
 					// Same major, allow downgrade for developers
1519 1519
 					return true;
1520 1520
 				} else {
1521 1521
 					// downgrade attempt, throw exception
1522
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1522
+					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from '.$installedVersion.' to '.$currentVersion.')');
1523 1523
 				}
1524 1524
 			} else if ($versionDiff < 0) {
1525 1525
 				// downgrade attempt, throw exception
1526
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1526
+				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from '.$installedVersion.' to '.$currentVersion.')');
1527 1527
 			}
1528 1528
 
1529 1529
 			// also check for upgrades for apps (independently from the user)
Please login to merge, or discard this patch.
Indentation   +1447 added lines, -1447 removed lines patch added patch discarded remove patch
@@ -66,1457 +66,1457 @@
 block discarded – undo
66 66
 use OCP\IUser;
67 67
 
68 68
 class OC_Util {
69
-	public static $scripts = array();
70
-	public static $styles = array();
71
-	public static $headers = array();
72
-	private static $rootMounted = false;
73
-	private static $fsSetup = false;
74
-
75
-	/** @var array Local cache of version.php */
76
-	private static $versionCache = null;
77
-
78
-	protected static function getAppManager() {
79
-		return \OC::$server->getAppManager();
80
-	}
81
-
82
-	private static function initLocalStorageRootFS() {
83
-		// mount local file backend as root
84
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
85
-		//first set up the local "root" storage
86
-		\OC\Files\Filesystem::initMountManager();
87
-		if (!self::$rootMounted) {
88
-			\OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
89
-			self::$rootMounted = true;
90
-		}
91
-	}
92
-
93
-	/**
94
-	 * mounting an object storage as the root fs will in essence remove the
95
-	 * necessity of a data folder being present.
96
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
97
-	 *
98
-	 * @param array $config containing 'class' and optional 'arguments'
99
-	 * @suppress PhanDeprecatedFunction
100
-	 */
101
-	private static function initObjectStoreRootFS($config) {
102
-		// check misconfiguration
103
-		if (empty($config['class'])) {
104
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
105
-		}
106
-		if (!isset($config['arguments'])) {
107
-			$config['arguments'] = array();
108
-		}
109
-
110
-		// instantiate object store implementation
111
-		$name = $config['class'];
112
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
113
-			$segments = explode('\\', $name);
114
-			OC_App::loadApp(strtolower($segments[1]));
115
-		}
116
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
117
-		// mount with plain / root object store implementation
118
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
119
-
120
-		// mount object storage as root
121
-		\OC\Files\Filesystem::initMountManager();
122
-		if (!self::$rootMounted) {
123
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
124
-			self::$rootMounted = true;
125
-		}
126
-	}
127
-
128
-	/**
129
-	 * mounting an object storage as the root fs will in essence remove the
130
-	 * necessity of a data folder being present.
131
-	 *
132
-	 * @param array $config containing 'class' and optional 'arguments'
133
-	 * @suppress PhanDeprecatedFunction
134
-	 */
135
-	private static function initObjectStoreMultibucketRootFS($config) {
136
-		// check misconfiguration
137
-		if (empty($config['class'])) {
138
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
139
-		}
140
-		if (!isset($config['arguments'])) {
141
-			$config['arguments'] = array();
142
-		}
143
-
144
-		// instantiate object store implementation
145
-		$name = $config['class'];
146
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
147
-			$segments = explode('\\', $name);
148
-			OC_App::loadApp(strtolower($segments[1]));
149
-		}
150
-
151
-		if (!isset($config['arguments']['bucket'])) {
152
-			$config['arguments']['bucket'] = '';
153
-		}
154
-		// put the root FS always in first bucket for multibucket configuration
155
-		$config['arguments']['bucket'] .= '0';
156
-
157
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
158
-		// mount with plain / root object store implementation
159
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
160
-
161
-		// mount object storage as root
162
-		\OC\Files\Filesystem::initMountManager();
163
-		if (!self::$rootMounted) {
164
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
165
-			self::$rootMounted = true;
166
-		}
167
-	}
168
-
169
-	/**
170
-	 * Can be set up
171
-	 *
172
-	 * @param string $user
173
-	 * @return boolean
174
-	 * @description configure the initial filesystem based on the configuration
175
-	 * @suppress PhanDeprecatedFunction
176
-	 * @suppress PhanAccessMethodInternal
177
-	 */
178
-	public static function setupFS($user = '') {
179
-		//setting up the filesystem twice can only lead to trouble
180
-		if (self::$fsSetup) {
181
-			return false;
182
-		}
183
-
184
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
185
-
186
-		// If we are not forced to load a specific user we load the one that is logged in
187
-		if ($user === null) {
188
-			$user = '';
189
-		} else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
190
-			$user = OC_User::getUser();
191
-		}
192
-
193
-		// load all filesystem apps before, so no setup-hook gets lost
194
-		OC_App::loadApps(array('filesystem'));
195
-
196
-		// the filesystem will finish when $user is not empty,
197
-		// mark fs setup here to avoid doing the setup from loading
198
-		// OC_Filesystem
199
-		if ($user != '') {
200
-			self::$fsSetup = true;
201
-		}
202
-
203
-		\OC\Files\Filesystem::initMountManager();
204
-
205
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
206
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
207
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
208
-				/** @var \OC\Files\Storage\Common $storage */
209
-				$storage->setMountOptions($mount->getOptions());
210
-			}
211
-			return $storage;
212
-		});
213
-
214
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
215
-			if (!$mount->getOption('enable_sharing', true)) {
216
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
217
-					'storage' => $storage,
218
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
219
-				]);
220
-			}
221
-			return $storage;
222
-		});
223
-
224
-		// install storage availability wrapper, before most other wrappers
225
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
226
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
227
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
228
-			}
229
-			return $storage;
230
-		});
231
-
232
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
233
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
234
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
235
-			}
236
-			return $storage;
237
-		});
238
-
239
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
240
-			// set up quota for home storages, even for other users
241
-			// which can happen when using sharing
242
-
243
-			/**
244
-			 * @var \OC\Files\Storage\Storage $storage
245
-			 */
246
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
247
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
248
-			) {
249
-				/** @var \OC\Files\Storage\Home $storage */
250
-				if (is_object($storage->getUser())) {
251
-					$user = $storage->getUser()->getUID();
252
-					$quota = OC_Util::getUserQuota($user);
253
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
254
-						return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
255
-					}
256
-				}
257
-			}
258
-
259
-			return $storage;
260
-		});
261
-
262
-		\OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
263
-			/*
69
+    public static $scripts = array();
70
+    public static $styles = array();
71
+    public static $headers = array();
72
+    private static $rootMounted = false;
73
+    private static $fsSetup = false;
74
+
75
+    /** @var array Local cache of version.php */
76
+    private static $versionCache = null;
77
+
78
+    protected static function getAppManager() {
79
+        return \OC::$server->getAppManager();
80
+    }
81
+
82
+    private static function initLocalStorageRootFS() {
83
+        // mount local file backend as root
84
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
85
+        //first set up the local "root" storage
86
+        \OC\Files\Filesystem::initMountManager();
87
+        if (!self::$rootMounted) {
88
+            \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
89
+            self::$rootMounted = true;
90
+        }
91
+    }
92
+
93
+    /**
94
+     * mounting an object storage as the root fs will in essence remove the
95
+     * necessity of a data folder being present.
96
+     * TODO make home storage aware of this and use the object storage instead of local disk access
97
+     *
98
+     * @param array $config containing 'class' and optional 'arguments'
99
+     * @suppress PhanDeprecatedFunction
100
+     */
101
+    private static function initObjectStoreRootFS($config) {
102
+        // check misconfiguration
103
+        if (empty($config['class'])) {
104
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
105
+        }
106
+        if (!isset($config['arguments'])) {
107
+            $config['arguments'] = array();
108
+        }
109
+
110
+        // instantiate object store implementation
111
+        $name = $config['class'];
112
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
113
+            $segments = explode('\\', $name);
114
+            OC_App::loadApp(strtolower($segments[1]));
115
+        }
116
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
117
+        // mount with plain / root object store implementation
118
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
119
+
120
+        // mount object storage as root
121
+        \OC\Files\Filesystem::initMountManager();
122
+        if (!self::$rootMounted) {
123
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
124
+            self::$rootMounted = true;
125
+        }
126
+    }
127
+
128
+    /**
129
+     * mounting an object storage as the root fs will in essence remove the
130
+     * necessity of a data folder being present.
131
+     *
132
+     * @param array $config containing 'class' and optional 'arguments'
133
+     * @suppress PhanDeprecatedFunction
134
+     */
135
+    private static function initObjectStoreMultibucketRootFS($config) {
136
+        // check misconfiguration
137
+        if (empty($config['class'])) {
138
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
139
+        }
140
+        if (!isset($config['arguments'])) {
141
+            $config['arguments'] = array();
142
+        }
143
+
144
+        // instantiate object store implementation
145
+        $name = $config['class'];
146
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
147
+            $segments = explode('\\', $name);
148
+            OC_App::loadApp(strtolower($segments[1]));
149
+        }
150
+
151
+        if (!isset($config['arguments']['bucket'])) {
152
+            $config['arguments']['bucket'] = '';
153
+        }
154
+        // put the root FS always in first bucket for multibucket configuration
155
+        $config['arguments']['bucket'] .= '0';
156
+
157
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
158
+        // mount with plain / root object store implementation
159
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
160
+
161
+        // mount object storage as root
162
+        \OC\Files\Filesystem::initMountManager();
163
+        if (!self::$rootMounted) {
164
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
165
+            self::$rootMounted = true;
166
+        }
167
+    }
168
+
169
+    /**
170
+     * Can be set up
171
+     *
172
+     * @param string $user
173
+     * @return boolean
174
+     * @description configure the initial filesystem based on the configuration
175
+     * @suppress PhanDeprecatedFunction
176
+     * @suppress PhanAccessMethodInternal
177
+     */
178
+    public static function setupFS($user = '') {
179
+        //setting up the filesystem twice can only lead to trouble
180
+        if (self::$fsSetup) {
181
+            return false;
182
+        }
183
+
184
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
185
+
186
+        // If we are not forced to load a specific user we load the one that is logged in
187
+        if ($user === null) {
188
+            $user = '';
189
+        } else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
190
+            $user = OC_User::getUser();
191
+        }
192
+
193
+        // load all filesystem apps before, so no setup-hook gets lost
194
+        OC_App::loadApps(array('filesystem'));
195
+
196
+        // the filesystem will finish when $user is not empty,
197
+        // mark fs setup here to avoid doing the setup from loading
198
+        // OC_Filesystem
199
+        if ($user != '') {
200
+            self::$fsSetup = true;
201
+        }
202
+
203
+        \OC\Files\Filesystem::initMountManager();
204
+
205
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
206
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
207
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
208
+                /** @var \OC\Files\Storage\Common $storage */
209
+                $storage->setMountOptions($mount->getOptions());
210
+            }
211
+            return $storage;
212
+        });
213
+
214
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
215
+            if (!$mount->getOption('enable_sharing', true)) {
216
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
217
+                    'storage' => $storage,
218
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
219
+                ]);
220
+            }
221
+            return $storage;
222
+        });
223
+
224
+        // install storage availability wrapper, before most other wrappers
225
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
226
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
227
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
228
+            }
229
+            return $storage;
230
+        });
231
+
232
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
233
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
234
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
235
+            }
236
+            return $storage;
237
+        });
238
+
239
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
240
+            // set up quota for home storages, even for other users
241
+            // which can happen when using sharing
242
+
243
+            /**
244
+             * @var \OC\Files\Storage\Storage $storage
245
+             */
246
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
247
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
248
+            ) {
249
+                /** @var \OC\Files\Storage\Home $storage */
250
+                if (is_object($storage->getUser())) {
251
+                    $user = $storage->getUser()->getUID();
252
+                    $quota = OC_Util::getUserQuota($user);
253
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
254
+                        return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
255
+                    }
256
+                }
257
+            }
258
+
259
+            return $storage;
260
+        });
261
+
262
+        \OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
263
+            /*
264 264
 			 * Do not allow any operations that modify the storage
265 265
 			 */
266
-			if ($mount->getOption('readonly', false)) {
267
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
268
-					'storage' => $storage,
269
-					'mask' => \OCP\Constants::PERMISSION_ALL & ~(
270
-						\OCP\Constants::PERMISSION_UPDATE |
271
-						\OCP\Constants::PERMISSION_CREATE |
272
-						\OCP\Constants::PERMISSION_DELETE
273
-					),
274
-				]);
275
-			}
276
-			return $storage;
277
-		});
278
-
279
-		OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
280
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
281
-
282
-		//check if we are using an object storage
283
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
284
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
285
-
286
-		// use the same order as in ObjectHomeMountProvider
287
-		if (isset($objectStoreMultibucket)) {
288
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
289
-		} elseif (isset($objectStore)) {
290
-			self::initObjectStoreRootFS($objectStore);
291
-		} else {
292
-			self::initLocalStorageRootFS();
293
-		}
294
-
295
-		if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
296
-			\OC::$server->getEventLogger()->end('setup_fs');
297
-			return false;
298
-		}
299
-
300
-		//if we aren't logged in, there is no use to set up the filesystem
301
-		if ($user != "") {
302
-
303
-			$userDir = '/' . $user . '/files';
304
-
305
-			//jail the user into his "home" directory
306
-			\OC\Files\Filesystem::init($user, $userDir);
307
-
308
-			OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
309
-		}
310
-		\OC::$server->getEventLogger()->end('setup_fs');
311
-		return true;
312
-	}
313
-
314
-	/**
315
-	 * check if a password is required for each public link
316
-	 *
317
-	 * @return boolean
318
-	 * @suppress PhanDeprecatedFunction
319
-	 */
320
-	public static function isPublicLinkPasswordRequired() {
321
-		$enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
322
-		return $enforcePassword === 'yes';
323
-	}
324
-
325
-	/**
326
-	 * check if sharing is disabled for the current user
327
-	 * @param IConfig $config
328
-	 * @param IGroupManager $groupManager
329
-	 * @param IUser|null $user
330
-	 * @return bool
331
-	 */
332
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
333
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
334
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
335
-			$excludedGroups = json_decode($groupsList);
336
-			if (is_null($excludedGroups)) {
337
-				$excludedGroups = explode(',', $groupsList);
338
-				$newValue = json_encode($excludedGroups);
339
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
340
-			}
341
-			$usersGroups = $groupManager->getUserGroupIds($user);
342
-			if (!empty($usersGroups)) {
343
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
344
-				// if the user is only in groups which are disabled for sharing then
345
-				// sharing is also disabled for the user
346
-				if (empty($remainingGroups)) {
347
-					return true;
348
-				}
349
-			}
350
-		}
351
-		return false;
352
-	}
353
-
354
-	/**
355
-	 * check if share API enforces a default expire date
356
-	 *
357
-	 * @return boolean
358
-	 * @suppress PhanDeprecatedFunction
359
-	 */
360
-	public static function isDefaultExpireDateEnforced() {
361
-		$isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
362
-		$enforceDefaultExpireDate = false;
363
-		if ($isDefaultExpireDateEnabled === 'yes') {
364
-			$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
365
-			$enforceDefaultExpireDate = $value === 'yes';
366
-		}
367
-
368
-		return $enforceDefaultExpireDate;
369
-	}
370
-
371
-	/**
372
-	 * Get the quota of a user
373
-	 *
374
-	 * @param string $userId
375
-	 * @return float Quota bytes
376
-	 */
377
-	public static function getUserQuota($userId) {
378
-		$user = \OC::$server->getUserManager()->get($userId);
379
-		if (is_null($user)) {
380
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
381
-		}
382
-		$userQuota = $user->getQuota();
383
-		if($userQuota === 'none') {
384
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
385
-		}
386
-		return OC_Helper::computerFileSize($userQuota);
387
-	}
388
-
389
-	/**
390
-	 * copies the skeleton to the users /files
391
-	 *
392
-	 * @param String $userId
393
-	 * @param \OCP\Files\Folder $userDirectory
394
-	 * @throws \RuntimeException
395
-	 * @suppress PhanDeprecatedFunction
396
-	 */
397
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
398
-
399
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
400
-		$userLang = \OC::$server->getL10NFactory()->findLanguage();
401
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
402
-
403
-		if (!file_exists($skeletonDirectory)) {
404
-			$dialectStart = strpos($userLang, '_');
405
-			if ($dialectStart !== false) {
406
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
407
-			}
408
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
409
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
410
-			}
411
-			if (!file_exists($skeletonDirectory)) {
412
-				$skeletonDirectory = '';
413
-			}
414
-		}
415
-
416
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
417
-
418
-		if ($instanceId === null) {
419
-			throw new \RuntimeException('no instance id!');
420
-		}
421
-		$appdata = 'appdata_' . $instanceId;
422
-		if ($userId === $appdata) {
423
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
424
-		}
425
-
426
-		if (!empty($skeletonDirectory)) {
427
-			\OCP\Util::writeLog(
428
-				'files_skeleton',
429
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
430
-				ILogger::DEBUG
431
-			);
432
-			self::copyr($skeletonDirectory, $userDirectory);
433
-			// update the file cache
434
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
435
-		}
436
-	}
437
-
438
-	/**
439
-	 * copies a directory recursively by using streams
440
-	 *
441
-	 * @param string $source
442
-	 * @param \OCP\Files\Folder $target
443
-	 * @return void
444
-	 */
445
-	public static function copyr($source, \OCP\Files\Folder $target) {
446
-		$logger = \OC::$server->getLogger();
447
-
448
-		// Verify if folder exists
449
-		$dir = opendir($source);
450
-		if($dir === false) {
451
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
452
-			return;
453
-		}
454
-
455
-		// Copy the files
456
-		while (false !== ($file = readdir($dir))) {
457
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
458
-				if (is_dir($source . '/' . $file)) {
459
-					$child = $target->newFolder($file);
460
-					self::copyr($source . '/' . $file, $child);
461
-				} else {
462
-					$child = $target->newFile($file);
463
-					$sourceStream = fopen($source . '/' . $file, 'r');
464
-					if($sourceStream === false) {
465
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
466
-						closedir($dir);
467
-						return;
468
-					}
469
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
470
-				}
471
-			}
472
-		}
473
-		closedir($dir);
474
-	}
475
-
476
-	/**
477
-	 * @return void
478
-	 * @suppress PhanUndeclaredMethod
479
-	 */
480
-	public static function tearDownFS() {
481
-		\OC\Files\Filesystem::tearDown();
482
-		\OC::$server->getRootFolder()->clearCache();
483
-		self::$fsSetup = false;
484
-		self::$rootMounted = false;
485
-	}
486
-
487
-	/**
488
-	 * get the current installed version of ownCloud
489
-	 *
490
-	 * @return array
491
-	 */
492
-	public static function getVersion() {
493
-		OC_Util::loadVersion();
494
-		return self::$versionCache['OC_Version'];
495
-	}
496
-
497
-	/**
498
-	 * get the current installed version string of ownCloud
499
-	 *
500
-	 * @return string
501
-	 */
502
-	public static function getVersionString() {
503
-		OC_Util::loadVersion();
504
-		return self::$versionCache['OC_VersionString'];
505
-	}
506
-
507
-	/**
508
-	 * @deprecated the value is of no use anymore
509
-	 * @return string
510
-	 */
511
-	public static function getEditionString() {
512
-		return '';
513
-	}
514
-
515
-	/**
516
-	 * @description get the update channel of the current installed of ownCloud.
517
-	 * @return string
518
-	 */
519
-	public static function getChannel() {
520
-		OC_Util::loadVersion();
521
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
522
-	}
523
-
524
-	/**
525
-	 * @description get the build number of the current installed of ownCloud.
526
-	 * @return string
527
-	 */
528
-	public static function getBuild() {
529
-		OC_Util::loadVersion();
530
-		return self::$versionCache['OC_Build'];
531
-	}
532
-
533
-	/**
534
-	 * @description load the version.php into the session as cache
535
-	 * @suppress PhanUndeclaredVariable
536
-	 */
537
-	private static function loadVersion() {
538
-		if (self::$versionCache !== null) {
539
-			return;
540
-		}
541
-
542
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
543
-		require OC::$SERVERROOT . '/version.php';
544
-		/** @var $timestamp int */
545
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
546
-		/** @var $OC_Version string */
547
-		self::$versionCache['OC_Version'] = $OC_Version;
548
-		/** @var $OC_VersionString string */
549
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
550
-		/** @var $OC_Build string */
551
-		self::$versionCache['OC_Build'] = $OC_Build;
552
-
553
-		/** @var $OC_Channel string */
554
-		self::$versionCache['OC_Channel'] = $OC_Channel;
555
-	}
556
-
557
-	/**
558
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
559
-	 *
560
-	 * @param string $application application to get the files from
561
-	 * @param string $directory directory within this application (css, js, vendor, etc)
562
-	 * @param string $file the file inside of the above folder
563
-	 * @return string the path
564
-	 */
565
-	private static function generatePath($application, $directory, $file) {
566
-		if (is_null($file)) {
567
-			$file = $application;
568
-			$application = "";
569
-		}
570
-		if (!empty($application)) {
571
-			return "$application/$directory/$file";
572
-		} else {
573
-			return "$directory/$file";
574
-		}
575
-	}
576
-
577
-	/**
578
-	 * add a javascript file
579
-	 *
580
-	 * @param string $application application id
581
-	 * @param string|null $file filename
582
-	 * @param bool $prepend prepend the Script to the beginning of the list
583
-	 * @return void
584
-	 */
585
-	public static function addScript($application, $file = null, $prepend = false) {
586
-		$path = OC_Util::generatePath($application, 'js', $file);
587
-
588
-		// core js files need separate handling
589
-		if ($application !== 'core' && $file !== null) {
590
-			self::addTranslations ( $application );
591
-		}
592
-		self::addExternalResource($application, $prepend, $path, "script");
593
-	}
594
-
595
-	/**
596
-	 * add a javascript file from the vendor sub folder
597
-	 *
598
-	 * @param string $application application id
599
-	 * @param string|null $file filename
600
-	 * @param bool $prepend prepend the Script to the beginning of the list
601
-	 * @return void
602
-	 */
603
-	public static function addVendorScript($application, $file = null, $prepend = false) {
604
-		$path = OC_Util::generatePath($application, 'vendor', $file);
605
-		self::addExternalResource($application, $prepend, $path, "script");
606
-	}
607
-
608
-	/**
609
-	 * add a translation JS file
610
-	 *
611
-	 * @param string $application application id
612
-	 * @param string|null $languageCode language code, defaults to the current language
613
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
614
-	 */
615
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
616
-		if (is_null($languageCode)) {
617
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
618
-		}
619
-		if (!empty($application)) {
620
-			$path = "$application/l10n/$languageCode";
621
-		} else {
622
-			$path = "l10n/$languageCode";
623
-		}
624
-		self::addExternalResource($application, $prepend, $path, "script");
625
-	}
626
-
627
-	/**
628
-	 * add a css file
629
-	 *
630
-	 * @param string $application application id
631
-	 * @param string|null $file filename
632
-	 * @param bool $prepend prepend the Style to the beginning of the list
633
-	 * @return void
634
-	 */
635
-	public static function addStyle($application, $file = null, $prepend = false) {
636
-		$path = OC_Util::generatePath($application, 'css', $file);
637
-		self::addExternalResource($application, $prepend, $path, "style");
638
-	}
639
-
640
-	/**
641
-	 * add a css file from the vendor sub folder
642
-	 *
643
-	 * @param string $application application id
644
-	 * @param string|null $file filename
645
-	 * @param bool $prepend prepend the Style to the beginning of the list
646
-	 * @return void
647
-	 */
648
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
649
-		$path = OC_Util::generatePath($application, 'vendor', $file);
650
-		self::addExternalResource($application, $prepend, $path, "style");
651
-	}
652
-
653
-	/**
654
-	 * add an external resource css/js file
655
-	 *
656
-	 * @param string $application application id
657
-	 * @param bool $prepend prepend the file to the beginning of the list
658
-	 * @param string $path
659
-	 * @param string $type (script or style)
660
-	 * @return void
661
-	 */
662
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
663
-
664
-		if ($type === "style") {
665
-			if (!in_array($path, self::$styles)) {
666
-				if ($prepend === true) {
667
-					array_unshift ( self::$styles, $path );
668
-				} else {
669
-					self::$styles[] = $path;
670
-				}
671
-			}
672
-		} elseif ($type === "script") {
673
-			if (!in_array($path, self::$scripts)) {
674
-				if ($prepend === true) {
675
-					array_unshift ( self::$scripts, $path );
676
-				} else {
677
-					self::$scripts [] = $path;
678
-				}
679
-			}
680
-		}
681
-	}
682
-
683
-	/**
684
-	 * Add a custom element to the header
685
-	 * If $text is null then the element will be written as empty element.
686
-	 * So use "" to get a closing tag.
687
-	 * @param string $tag tag name of the element
688
-	 * @param array $attributes array of attributes for the element
689
-	 * @param string $text the text content for the element
690
-	 */
691
-	public static function addHeader($tag, $attributes, $text=null) {
692
-		self::$headers[] = array(
693
-			'tag' => $tag,
694
-			'attributes' => $attributes,
695
-			'text' => $text
696
-		);
697
-	}
698
-
699
-	/**
700
-	 * check if the current server configuration is suitable for ownCloud
701
-	 *
702
-	 * @param \OC\SystemConfig $config
703
-	 * @return array arrays with error messages and hints
704
-	 */
705
-	public static function checkServer(\OC\SystemConfig $config) {
706
-		$l = \OC::$server->getL10N('lib');
707
-		$errors = array();
708
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
709
-
710
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
711
-			// this check needs to be done every time
712
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
713
-		}
714
-
715
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
716
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
717
-			return $errors;
718
-		}
719
-
720
-		$webServerRestart = false;
721
-		$setup = new \OC\Setup(
722
-			$config,
723
-			\OC::$server->getIniWrapper(),
724
-			\OC::$server->getL10N('lib'),
725
-			\OC::$server->query(\OCP\Defaults::class),
726
-			\OC::$server->getLogger(),
727
-			\OC::$server->getSecureRandom(),
728
-			\OC::$server->query(\OC\Installer::class)
729
-		);
730
-
731
-		$urlGenerator = \OC::$server->getURLGenerator();
732
-
733
-		$availableDatabases = $setup->getSupportedDatabases();
734
-		if (empty($availableDatabases)) {
735
-			$errors[] = array(
736
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
737
-				'hint' => '' //TODO: sane hint
738
-			);
739
-			$webServerRestart = true;
740
-		}
741
-
742
-		// Check if config folder is writable.
743
-		if(!OC_Helper::isReadOnlyConfigEnabled()) {
744
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
745
-				$errors[] = array(
746
-					'error' => $l->t('Cannot write into "config" directory'),
747
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
748
-						[$urlGenerator->linkToDocs('admin-dir_permissions')])
749
-				);
750
-			}
751
-		}
752
-
753
-		// Check if there is a writable install folder.
754
-		if ($config->getValue('appstoreenabled', true)) {
755
-			if (OC_App::getInstallPath() === null
756
-				|| !is_writable(OC_App::getInstallPath())
757
-				|| !is_readable(OC_App::getInstallPath())
758
-			) {
759
-				$errors[] = array(
760
-					'error' => $l->t('Cannot write into "apps" directory'),
761
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
762
-						. ' or disabling the appstore in the config file. See %s',
763
-						[$urlGenerator->linkToDocs('admin-dir_permissions')])
764
-				);
765
-			}
766
-		}
767
-		// Create root dir.
768
-		if ($config->getValue('installed', false)) {
769
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
770
-				$success = @mkdir($CONFIG_DATADIRECTORY);
771
-				if ($success) {
772
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
773
-				} else {
774
-					$errors[] = [
775
-						'error' => $l->t('Cannot create "data" directory'),
776
-						'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
777
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
778
-					];
779
-				}
780
-			} else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
781
-				//common hint for all file permissions error messages
782
-				$permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
783
-					[$urlGenerator->linkToDocs('admin-dir_permissions')]);
784
-				$errors[] = [
785
-					'error' => 'Your data directory is not writable',
786
-					'hint' => $permissionsHint
787
-				];
788
-			} else {
789
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
790
-			}
791
-		}
792
-
793
-		if (!OC_Util::isSetLocaleWorking()) {
794
-			$errors[] = array(
795
-				'error' => $l->t('Setting locale to %s failed',
796
-					array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
797
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
798
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
799
-			);
800
-		}
801
-
802
-		// Contains the dependencies that should be checked against
803
-		// classes = class_exists
804
-		// functions = function_exists
805
-		// defined = defined
806
-		// ini = ini_get
807
-		// If the dependency is not found the missing module name is shown to the EndUser
808
-		// When adding new checks always verify that they pass on Travis as well
809
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
810
-		$dependencies = array(
811
-			'classes' => array(
812
-				'ZipArchive' => 'zip',
813
-				'DOMDocument' => 'dom',
814
-				'XMLWriter' => 'XMLWriter',
815
-				'XMLReader' => 'XMLReader',
816
-			),
817
-			'functions' => [
818
-				'xml_parser_create' => 'libxml',
819
-				'mb_strcut' => 'mb multibyte',
820
-				'ctype_digit' => 'ctype',
821
-				'json_encode' => 'JSON',
822
-				'gd_info' => 'GD',
823
-				'gzencode' => 'zlib',
824
-				'iconv' => 'iconv',
825
-				'simplexml_load_string' => 'SimpleXML',
826
-				'hash' => 'HASH Message Digest Framework',
827
-				'curl_init' => 'cURL',
828
-				'openssl_verify' => 'OpenSSL',
829
-			],
830
-			'defined' => array(
831
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
832
-			),
833
-			'ini' => [
834
-				'default_charset' => 'UTF-8',
835
-			],
836
-		);
837
-		$missingDependencies = array();
838
-		$invalidIniSettings = [];
839
-		$moduleHint = $l->t('Please ask your server administrator to install the module.');
840
-
841
-		/**
842
-		 * FIXME: The dependency check does not work properly on HHVM on the moment
843
-		 *        and prevents installation. Once HHVM is more compatible with our
844
-		 *        approach to check for these values we should re-enable those
845
-		 *        checks.
846
-		 */
847
-		$iniWrapper = \OC::$server->getIniWrapper();
848
-		if (!self::runningOnHhvm()) {
849
-			foreach ($dependencies['classes'] as $class => $module) {
850
-				if (!class_exists($class)) {
851
-					$missingDependencies[] = $module;
852
-				}
853
-			}
854
-			foreach ($dependencies['functions'] as $function => $module) {
855
-				if (!function_exists($function)) {
856
-					$missingDependencies[] = $module;
857
-				}
858
-			}
859
-			foreach ($dependencies['defined'] as $defined => $module) {
860
-				if (!defined($defined)) {
861
-					$missingDependencies[] = $module;
862
-				}
863
-			}
864
-			foreach ($dependencies['ini'] as $setting => $expected) {
865
-				if (is_bool($expected)) {
866
-					if ($iniWrapper->getBool($setting) !== $expected) {
867
-						$invalidIniSettings[] = [$setting, $expected];
868
-					}
869
-				}
870
-				if (is_int($expected)) {
871
-					if ($iniWrapper->getNumeric($setting) !== $expected) {
872
-						$invalidIniSettings[] = [$setting, $expected];
873
-					}
874
-				}
875
-				if (is_string($expected)) {
876
-					if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
877
-						$invalidIniSettings[] = [$setting, $expected];
878
-					}
879
-				}
880
-			}
881
-		}
882
-
883
-		foreach($missingDependencies as $missingDependency) {
884
-			$errors[] = array(
885
-				'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
886
-				'hint' => $moduleHint
887
-			);
888
-			$webServerRestart = true;
889
-		}
890
-		foreach($invalidIniSettings as $setting) {
891
-			if(is_bool($setting[1])) {
892
-				$setting[1] = $setting[1] ? 'on' : 'off';
893
-			}
894
-			$errors[] = [
895
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
896
-				'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
897
-			];
898
-			$webServerRestart = true;
899
-		}
900
-
901
-		/**
902
-		 * The mbstring.func_overload check can only be performed if the mbstring
903
-		 * module is installed as it will return null if the checking setting is
904
-		 * not available and thus a check on the boolean value fails.
905
-		 *
906
-		 * TODO: Should probably be implemented in the above generic dependency
907
-		 *       check somehow in the long-term.
908
-		 */
909
-		if($iniWrapper->getBool('mbstring.func_overload') !== null &&
910
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
911
-			$errors[] = array(
912
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
913
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
914
-			);
915
-		}
916
-
917
-		if(function_exists('xml_parser_create') &&
918
-			LIBXML_LOADED_VERSION < 20700 ) {
919
-			$version = LIBXML_LOADED_VERSION;
920
-			$major = floor($version/10000);
921
-			$version -= ($major * 10000);
922
-			$minor = floor($version/100);
923
-			$version -= ($minor * 100);
924
-			$patch = $version;
925
-			$errors[] = array(
926
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
927
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
928
-			);
929
-		}
930
-
931
-		if (!self::isAnnotationsWorking()) {
932
-			$errors[] = array(
933
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
934
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
935
-			);
936
-		}
937
-
938
-		if (!\OC::$CLI && $webServerRestart) {
939
-			$errors[] = array(
940
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
941
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
942
-			);
943
-		}
944
-
945
-		$errors = array_merge($errors, self::checkDatabaseVersion());
946
-
947
-		// Cache the result of this function
948
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
949
-
950
-		return $errors;
951
-	}
952
-
953
-	/**
954
-	 * Check the database version
955
-	 *
956
-	 * @return array errors array
957
-	 */
958
-	public static function checkDatabaseVersion() {
959
-		$l = \OC::$server->getL10N('lib');
960
-		$errors = array();
961
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
962
-		if ($dbType === 'pgsql') {
963
-			// check PostgreSQL version
964
-			try {
965
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
966
-				$data = $result->fetchRow();
967
-				if (isset($data['server_version'])) {
968
-					$version = $data['server_version'];
969
-					if (version_compare($version, '9.0.0', '<')) {
970
-						$errors[] = array(
971
-							'error' => $l->t('PostgreSQL >= 9 required'),
972
-							'hint' => $l->t('Please upgrade your database version')
973
-						);
974
-					}
975
-				}
976
-			} catch (\Doctrine\DBAL\DBALException $e) {
977
-				$logger = \OC::$server->getLogger();
978
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
979
-				$logger->logException($e);
980
-			}
981
-		}
982
-		return $errors;
983
-	}
984
-
985
-	/**
986
-	 * Check for correct file permissions of data directory
987
-	 *
988
-	 * @param string $dataDirectory
989
-	 * @return array arrays with error messages and hints
990
-	 */
991
-	public static function checkDataDirectoryPermissions($dataDirectory) {
992
-		if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
993
-			return  [];
994
-		}
995
-		$l = \OC::$server->getL10N('lib');
996
-		$errors = [];
997
-		$permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
998
-			. ' cannot be listed by other users.');
999
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1000
-		if (substr($perms, -1) !== '0') {
1001
-			chmod($dataDirectory, 0770);
1002
-			clearstatcache();
1003
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1004
-			if ($perms[2] !== '0') {
1005
-				$errors[] = [
1006
-					'error' => $l->t('Your data directory is readable by other users'),
1007
-					'hint' => $permissionsModHint
1008
-				];
1009
-			}
1010
-		}
1011
-		return $errors;
1012
-	}
1013
-
1014
-	/**
1015
-	 * Check that the data directory exists and is valid by
1016
-	 * checking the existence of the ".ocdata" file.
1017
-	 *
1018
-	 * @param string $dataDirectory data directory path
1019
-	 * @return array errors found
1020
-	 */
1021
-	public static function checkDataDirectoryValidity($dataDirectory) {
1022
-		$l = \OC::$server->getL10N('lib');
1023
-		$errors = [];
1024
-		if ($dataDirectory[0] !== '/') {
1025
-			$errors[] = [
1026
-				'error' => $l->t('Your data directory must be an absolute path'),
1027
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1028
-			];
1029
-		}
1030
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1031
-			$errors[] = [
1032
-				'error' => $l->t('Your data directory is invalid'),
1033
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1034
-					' in the root of the data directory.')
1035
-			];
1036
-		}
1037
-		return $errors;
1038
-	}
1039
-
1040
-	/**
1041
-	 * Check if the user is logged in, redirects to home if not. With
1042
-	 * redirect URL parameter to the request URI.
1043
-	 *
1044
-	 * @return void
1045
-	 */
1046
-	public static function checkLoggedIn() {
1047
-		// Check if we are a user
1048
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1049
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1050
-						'core.login.showLoginForm',
1051
-						[
1052
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1053
-						]
1054
-					)
1055
-			);
1056
-			exit();
1057
-		}
1058
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1059
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1060
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1061
-			exit();
1062
-		}
1063
-	}
1064
-
1065
-	/**
1066
-	 * Check if the user is a admin, redirects to home if not
1067
-	 *
1068
-	 * @return void
1069
-	 */
1070
-	public static function checkAdminUser() {
1071
-		OC_Util::checkLoggedIn();
1072
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1073
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1074
-			exit();
1075
-		}
1076
-	}
1077
-
1078
-	/**
1079
-	 * Check if the user is a subadmin, redirects to home if not
1080
-	 *
1081
-	 * @return null|boolean $groups where the current user is subadmin
1082
-	 */
1083
-	public static function checkSubAdminUser() {
1084
-		OC_Util::checkLoggedIn();
1085
-		$userObject = \OC::$server->getUserSession()->getUser();
1086
-		$isSubAdmin = false;
1087
-		if($userObject !== null) {
1088
-			$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1089
-		}
1090
-
1091
-		if (!$isSubAdmin) {
1092
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1093
-			exit();
1094
-		}
1095
-		return true;
1096
-	}
1097
-
1098
-	/**
1099
-	 * Returns the URL of the default page
1100
-	 * based on the system configuration and
1101
-	 * the apps visible for the current user
1102
-	 *
1103
-	 * @return string URL
1104
-	 * @suppress PhanDeprecatedFunction
1105
-	 */
1106
-	public static function getDefaultPageUrl() {
1107
-		$urlGenerator = \OC::$server->getURLGenerator();
1108
-		// Deny the redirect if the URL contains a @
1109
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1110
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1111
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1112
-		} else {
1113
-			$defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1114
-			if ($defaultPage) {
1115
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1116
-			} else {
1117
-				$appId = 'files';
1118
-				$config = \OC::$server->getConfig();
1119
-				$defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1120
-				// find the first app that is enabled for the current user
1121
-				foreach ($defaultApps as $defaultApp) {
1122
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1123
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1124
-						$appId = $defaultApp;
1125
-						break;
1126
-					}
1127
-				}
1128
-
1129
-				if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1130
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1131
-				} else {
1132
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1133
-				}
1134
-			}
1135
-		}
1136
-		return $location;
1137
-	}
1138
-
1139
-	/**
1140
-	 * Redirect to the user default page
1141
-	 *
1142
-	 * @return void
1143
-	 */
1144
-	public static function redirectToDefaultPage() {
1145
-		$location = self::getDefaultPageUrl();
1146
-		header('Location: ' . $location);
1147
-		exit();
1148
-	}
1149
-
1150
-	/**
1151
-	 * get an id unique for this instance
1152
-	 *
1153
-	 * @return string
1154
-	 */
1155
-	public static function getInstanceId() {
1156
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1157
-		if (is_null($id)) {
1158
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1159
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1160
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1161
-		}
1162
-		return $id;
1163
-	}
1164
-
1165
-	/**
1166
-	 * Public function to sanitize HTML
1167
-	 *
1168
-	 * This function is used to sanitize HTML and should be applied on any
1169
-	 * string or array of strings before displaying it on a web page.
1170
-	 *
1171
-	 * @param string|array $value
1172
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1173
-	 */
1174
-	public static function sanitizeHTML($value) {
1175
-		if (is_array($value)) {
1176
-			$value = array_map(function($value) {
1177
-				return self::sanitizeHTML($value);
1178
-			}, $value);
1179
-		} else {
1180
-			// Specify encoding for PHP<5.4
1181
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1182
-		}
1183
-		return $value;
1184
-	}
1185
-
1186
-	/**
1187
-	 * Public function to encode url parameters
1188
-	 *
1189
-	 * This function is used to encode path to file before output.
1190
-	 * Encoding is done according to RFC 3986 with one exception:
1191
-	 * Character '/' is preserved as is.
1192
-	 *
1193
-	 * @param string $component part of URI to encode
1194
-	 * @return string
1195
-	 */
1196
-	public static function encodePath($component) {
1197
-		$encoded = rawurlencode($component);
1198
-		$encoded = str_replace('%2F', '/', $encoded);
1199
-		return $encoded;
1200
-	}
1201
-
1202
-
1203
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1204
-		// php dev server does not support htaccess
1205
-		if (php_sapi_name() === 'cli-server') {
1206
-			return false;
1207
-		}
1208
-
1209
-		// testdata
1210
-		$fileName = '/htaccesstest.txt';
1211
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1212
-
1213
-		// creating a test file
1214
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1215
-
1216
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1217
-			return false;
1218
-		}
1219
-
1220
-		$fp = @fopen($testFile, 'w');
1221
-		if (!$fp) {
1222
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1223
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1224
-		}
1225
-		fwrite($fp, $testContent);
1226
-		fclose($fp);
1227
-
1228
-		return $testContent;
1229
-	}
1230
-
1231
-	/**
1232
-	 * Check if the .htaccess file is working
1233
-	 * @param \OCP\IConfig $config
1234
-	 * @return bool
1235
-	 * @throws Exception
1236
-	 * @throws \OC\HintException If the test file can't get written.
1237
-	 */
1238
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1239
-
1240
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1241
-			return true;
1242
-		}
1243
-
1244
-		$testContent = $this->createHtaccessTestFile($config);
1245
-		if ($testContent === false) {
1246
-			return false;
1247
-		}
1248
-
1249
-		$fileName = '/htaccesstest.txt';
1250
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1251
-
1252
-		// accessing the file via http
1253
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1254
-		try {
1255
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1256
-		} catch (\Exception $e) {
1257
-			$content = false;
1258
-		}
1259
-
1260
-		// cleanup
1261
-		@unlink($testFile);
1262
-
1263
-		/*
266
+            if ($mount->getOption('readonly', false)) {
267
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
268
+                    'storage' => $storage,
269
+                    'mask' => \OCP\Constants::PERMISSION_ALL & ~(
270
+                        \OCP\Constants::PERMISSION_UPDATE |
271
+                        \OCP\Constants::PERMISSION_CREATE |
272
+                        \OCP\Constants::PERMISSION_DELETE
273
+                    ),
274
+                ]);
275
+            }
276
+            return $storage;
277
+        });
278
+
279
+        OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
280
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
281
+
282
+        //check if we are using an object storage
283
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
284
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
285
+
286
+        // use the same order as in ObjectHomeMountProvider
287
+        if (isset($objectStoreMultibucket)) {
288
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
289
+        } elseif (isset($objectStore)) {
290
+            self::initObjectStoreRootFS($objectStore);
291
+        } else {
292
+            self::initLocalStorageRootFS();
293
+        }
294
+
295
+        if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
296
+            \OC::$server->getEventLogger()->end('setup_fs');
297
+            return false;
298
+        }
299
+
300
+        //if we aren't logged in, there is no use to set up the filesystem
301
+        if ($user != "") {
302
+
303
+            $userDir = '/' . $user . '/files';
304
+
305
+            //jail the user into his "home" directory
306
+            \OC\Files\Filesystem::init($user, $userDir);
307
+
308
+            OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
309
+        }
310
+        \OC::$server->getEventLogger()->end('setup_fs');
311
+        return true;
312
+    }
313
+
314
+    /**
315
+     * check if a password is required for each public link
316
+     *
317
+     * @return boolean
318
+     * @suppress PhanDeprecatedFunction
319
+     */
320
+    public static function isPublicLinkPasswordRequired() {
321
+        $enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
322
+        return $enforcePassword === 'yes';
323
+    }
324
+
325
+    /**
326
+     * check if sharing is disabled for the current user
327
+     * @param IConfig $config
328
+     * @param IGroupManager $groupManager
329
+     * @param IUser|null $user
330
+     * @return bool
331
+     */
332
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
333
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
334
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
335
+            $excludedGroups = json_decode($groupsList);
336
+            if (is_null($excludedGroups)) {
337
+                $excludedGroups = explode(',', $groupsList);
338
+                $newValue = json_encode($excludedGroups);
339
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
340
+            }
341
+            $usersGroups = $groupManager->getUserGroupIds($user);
342
+            if (!empty($usersGroups)) {
343
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
344
+                // if the user is only in groups which are disabled for sharing then
345
+                // sharing is also disabled for the user
346
+                if (empty($remainingGroups)) {
347
+                    return true;
348
+                }
349
+            }
350
+        }
351
+        return false;
352
+    }
353
+
354
+    /**
355
+     * check if share API enforces a default expire date
356
+     *
357
+     * @return boolean
358
+     * @suppress PhanDeprecatedFunction
359
+     */
360
+    public static function isDefaultExpireDateEnforced() {
361
+        $isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
362
+        $enforceDefaultExpireDate = false;
363
+        if ($isDefaultExpireDateEnabled === 'yes') {
364
+            $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
365
+            $enforceDefaultExpireDate = $value === 'yes';
366
+        }
367
+
368
+        return $enforceDefaultExpireDate;
369
+    }
370
+
371
+    /**
372
+     * Get the quota of a user
373
+     *
374
+     * @param string $userId
375
+     * @return float Quota bytes
376
+     */
377
+    public static function getUserQuota($userId) {
378
+        $user = \OC::$server->getUserManager()->get($userId);
379
+        if (is_null($user)) {
380
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
381
+        }
382
+        $userQuota = $user->getQuota();
383
+        if($userQuota === 'none') {
384
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
385
+        }
386
+        return OC_Helper::computerFileSize($userQuota);
387
+    }
388
+
389
+    /**
390
+     * copies the skeleton to the users /files
391
+     *
392
+     * @param String $userId
393
+     * @param \OCP\Files\Folder $userDirectory
394
+     * @throws \RuntimeException
395
+     * @suppress PhanDeprecatedFunction
396
+     */
397
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
398
+
399
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
400
+        $userLang = \OC::$server->getL10NFactory()->findLanguage();
401
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
402
+
403
+        if (!file_exists($skeletonDirectory)) {
404
+            $dialectStart = strpos($userLang, '_');
405
+            if ($dialectStart !== false) {
406
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
407
+            }
408
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
409
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
410
+            }
411
+            if (!file_exists($skeletonDirectory)) {
412
+                $skeletonDirectory = '';
413
+            }
414
+        }
415
+
416
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
417
+
418
+        if ($instanceId === null) {
419
+            throw new \RuntimeException('no instance id!');
420
+        }
421
+        $appdata = 'appdata_' . $instanceId;
422
+        if ($userId === $appdata) {
423
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
424
+        }
425
+
426
+        if (!empty($skeletonDirectory)) {
427
+            \OCP\Util::writeLog(
428
+                'files_skeleton',
429
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
430
+                ILogger::DEBUG
431
+            );
432
+            self::copyr($skeletonDirectory, $userDirectory);
433
+            // update the file cache
434
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
435
+        }
436
+    }
437
+
438
+    /**
439
+     * copies a directory recursively by using streams
440
+     *
441
+     * @param string $source
442
+     * @param \OCP\Files\Folder $target
443
+     * @return void
444
+     */
445
+    public static function copyr($source, \OCP\Files\Folder $target) {
446
+        $logger = \OC::$server->getLogger();
447
+
448
+        // Verify if folder exists
449
+        $dir = opendir($source);
450
+        if($dir === false) {
451
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
452
+            return;
453
+        }
454
+
455
+        // Copy the files
456
+        while (false !== ($file = readdir($dir))) {
457
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
458
+                if (is_dir($source . '/' . $file)) {
459
+                    $child = $target->newFolder($file);
460
+                    self::copyr($source . '/' . $file, $child);
461
+                } else {
462
+                    $child = $target->newFile($file);
463
+                    $sourceStream = fopen($source . '/' . $file, 'r');
464
+                    if($sourceStream === false) {
465
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
466
+                        closedir($dir);
467
+                        return;
468
+                    }
469
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
470
+                }
471
+            }
472
+        }
473
+        closedir($dir);
474
+    }
475
+
476
+    /**
477
+     * @return void
478
+     * @suppress PhanUndeclaredMethod
479
+     */
480
+    public static function tearDownFS() {
481
+        \OC\Files\Filesystem::tearDown();
482
+        \OC::$server->getRootFolder()->clearCache();
483
+        self::$fsSetup = false;
484
+        self::$rootMounted = false;
485
+    }
486
+
487
+    /**
488
+     * get the current installed version of ownCloud
489
+     *
490
+     * @return array
491
+     */
492
+    public static function getVersion() {
493
+        OC_Util::loadVersion();
494
+        return self::$versionCache['OC_Version'];
495
+    }
496
+
497
+    /**
498
+     * get the current installed version string of ownCloud
499
+     *
500
+     * @return string
501
+     */
502
+    public static function getVersionString() {
503
+        OC_Util::loadVersion();
504
+        return self::$versionCache['OC_VersionString'];
505
+    }
506
+
507
+    /**
508
+     * @deprecated the value is of no use anymore
509
+     * @return string
510
+     */
511
+    public static function getEditionString() {
512
+        return '';
513
+    }
514
+
515
+    /**
516
+     * @description get the update channel of the current installed of ownCloud.
517
+     * @return string
518
+     */
519
+    public static function getChannel() {
520
+        OC_Util::loadVersion();
521
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
522
+    }
523
+
524
+    /**
525
+     * @description get the build number of the current installed of ownCloud.
526
+     * @return string
527
+     */
528
+    public static function getBuild() {
529
+        OC_Util::loadVersion();
530
+        return self::$versionCache['OC_Build'];
531
+    }
532
+
533
+    /**
534
+     * @description load the version.php into the session as cache
535
+     * @suppress PhanUndeclaredVariable
536
+     */
537
+    private static function loadVersion() {
538
+        if (self::$versionCache !== null) {
539
+            return;
540
+        }
541
+
542
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
543
+        require OC::$SERVERROOT . '/version.php';
544
+        /** @var $timestamp int */
545
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
546
+        /** @var $OC_Version string */
547
+        self::$versionCache['OC_Version'] = $OC_Version;
548
+        /** @var $OC_VersionString string */
549
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
550
+        /** @var $OC_Build string */
551
+        self::$versionCache['OC_Build'] = $OC_Build;
552
+
553
+        /** @var $OC_Channel string */
554
+        self::$versionCache['OC_Channel'] = $OC_Channel;
555
+    }
556
+
557
+    /**
558
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
559
+     *
560
+     * @param string $application application to get the files from
561
+     * @param string $directory directory within this application (css, js, vendor, etc)
562
+     * @param string $file the file inside of the above folder
563
+     * @return string the path
564
+     */
565
+    private static function generatePath($application, $directory, $file) {
566
+        if (is_null($file)) {
567
+            $file = $application;
568
+            $application = "";
569
+        }
570
+        if (!empty($application)) {
571
+            return "$application/$directory/$file";
572
+        } else {
573
+            return "$directory/$file";
574
+        }
575
+    }
576
+
577
+    /**
578
+     * add a javascript file
579
+     *
580
+     * @param string $application application id
581
+     * @param string|null $file filename
582
+     * @param bool $prepend prepend the Script to the beginning of the list
583
+     * @return void
584
+     */
585
+    public static function addScript($application, $file = null, $prepend = false) {
586
+        $path = OC_Util::generatePath($application, 'js', $file);
587
+
588
+        // core js files need separate handling
589
+        if ($application !== 'core' && $file !== null) {
590
+            self::addTranslations ( $application );
591
+        }
592
+        self::addExternalResource($application, $prepend, $path, "script");
593
+    }
594
+
595
+    /**
596
+     * add a javascript file from the vendor sub folder
597
+     *
598
+     * @param string $application application id
599
+     * @param string|null $file filename
600
+     * @param bool $prepend prepend the Script to the beginning of the list
601
+     * @return void
602
+     */
603
+    public static function addVendorScript($application, $file = null, $prepend = false) {
604
+        $path = OC_Util::generatePath($application, 'vendor', $file);
605
+        self::addExternalResource($application, $prepend, $path, "script");
606
+    }
607
+
608
+    /**
609
+     * add a translation JS file
610
+     *
611
+     * @param string $application application id
612
+     * @param string|null $languageCode language code, defaults to the current language
613
+     * @param bool|null $prepend prepend the Script to the beginning of the list
614
+     */
615
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
616
+        if (is_null($languageCode)) {
617
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
618
+        }
619
+        if (!empty($application)) {
620
+            $path = "$application/l10n/$languageCode";
621
+        } else {
622
+            $path = "l10n/$languageCode";
623
+        }
624
+        self::addExternalResource($application, $prepend, $path, "script");
625
+    }
626
+
627
+    /**
628
+     * add a css file
629
+     *
630
+     * @param string $application application id
631
+     * @param string|null $file filename
632
+     * @param bool $prepend prepend the Style to the beginning of the list
633
+     * @return void
634
+     */
635
+    public static function addStyle($application, $file = null, $prepend = false) {
636
+        $path = OC_Util::generatePath($application, 'css', $file);
637
+        self::addExternalResource($application, $prepend, $path, "style");
638
+    }
639
+
640
+    /**
641
+     * add a css file from the vendor sub folder
642
+     *
643
+     * @param string $application application id
644
+     * @param string|null $file filename
645
+     * @param bool $prepend prepend the Style to the beginning of the list
646
+     * @return void
647
+     */
648
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
649
+        $path = OC_Util::generatePath($application, 'vendor', $file);
650
+        self::addExternalResource($application, $prepend, $path, "style");
651
+    }
652
+
653
+    /**
654
+     * add an external resource css/js file
655
+     *
656
+     * @param string $application application id
657
+     * @param bool $prepend prepend the file to the beginning of the list
658
+     * @param string $path
659
+     * @param string $type (script or style)
660
+     * @return void
661
+     */
662
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
663
+
664
+        if ($type === "style") {
665
+            if (!in_array($path, self::$styles)) {
666
+                if ($prepend === true) {
667
+                    array_unshift ( self::$styles, $path );
668
+                } else {
669
+                    self::$styles[] = $path;
670
+                }
671
+            }
672
+        } elseif ($type === "script") {
673
+            if (!in_array($path, self::$scripts)) {
674
+                if ($prepend === true) {
675
+                    array_unshift ( self::$scripts, $path );
676
+                } else {
677
+                    self::$scripts [] = $path;
678
+                }
679
+            }
680
+        }
681
+    }
682
+
683
+    /**
684
+     * Add a custom element to the header
685
+     * If $text is null then the element will be written as empty element.
686
+     * So use "" to get a closing tag.
687
+     * @param string $tag tag name of the element
688
+     * @param array $attributes array of attributes for the element
689
+     * @param string $text the text content for the element
690
+     */
691
+    public static function addHeader($tag, $attributes, $text=null) {
692
+        self::$headers[] = array(
693
+            'tag' => $tag,
694
+            'attributes' => $attributes,
695
+            'text' => $text
696
+        );
697
+    }
698
+
699
+    /**
700
+     * check if the current server configuration is suitable for ownCloud
701
+     *
702
+     * @param \OC\SystemConfig $config
703
+     * @return array arrays with error messages and hints
704
+     */
705
+    public static function checkServer(\OC\SystemConfig $config) {
706
+        $l = \OC::$server->getL10N('lib');
707
+        $errors = array();
708
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
709
+
710
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
711
+            // this check needs to be done every time
712
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
713
+        }
714
+
715
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
716
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
717
+            return $errors;
718
+        }
719
+
720
+        $webServerRestart = false;
721
+        $setup = new \OC\Setup(
722
+            $config,
723
+            \OC::$server->getIniWrapper(),
724
+            \OC::$server->getL10N('lib'),
725
+            \OC::$server->query(\OCP\Defaults::class),
726
+            \OC::$server->getLogger(),
727
+            \OC::$server->getSecureRandom(),
728
+            \OC::$server->query(\OC\Installer::class)
729
+        );
730
+
731
+        $urlGenerator = \OC::$server->getURLGenerator();
732
+
733
+        $availableDatabases = $setup->getSupportedDatabases();
734
+        if (empty($availableDatabases)) {
735
+            $errors[] = array(
736
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
737
+                'hint' => '' //TODO: sane hint
738
+            );
739
+            $webServerRestart = true;
740
+        }
741
+
742
+        // Check if config folder is writable.
743
+        if(!OC_Helper::isReadOnlyConfigEnabled()) {
744
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
745
+                $errors[] = array(
746
+                    'error' => $l->t('Cannot write into "config" directory'),
747
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
748
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')])
749
+                );
750
+            }
751
+        }
752
+
753
+        // Check if there is a writable install folder.
754
+        if ($config->getValue('appstoreenabled', true)) {
755
+            if (OC_App::getInstallPath() === null
756
+                || !is_writable(OC_App::getInstallPath())
757
+                || !is_readable(OC_App::getInstallPath())
758
+            ) {
759
+                $errors[] = array(
760
+                    'error' => $l->t('Cannot write into "apps" directory'),
761
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
762
+                        . ' or disabling the appstore in the config file. See %s',
763
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')])
764
+                );
765
+            }
766
+        }
767
+        // Create root dir.
768
+        if ($config->getValue('installed', false)) {
769
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
770
+                $success = @mkdir($CONFIG_DATADIRECTORY);
771
+                if ($success) {
772
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
773
+                } else {
774
+                    $errors[] = [
775
+                        'error' => $l->t('Cannot create "data" directory'),
776
+                        'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
777
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
778
+                    ];
779
+                }
780
+            } else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
781
+                //common hint for all file permissions error messages
782
+                $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
783
+                    [$urlGenerator->linkToDocs('admin-dir_permissions')]);
784
+                $errors[] = [
785
+                    'error' => 'Your data directory is not writable',
786
+                    'hint' => $permissionsHint
787
+                ];
788
+            } else {
789
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
790
+            }
791
+        }
792
+
793
+        if (!OC_Util::isSetLocaleWorking()) {
794
+            $errors[] = array(
795
+                'error' => $l->t('Setting locale to %s failed',
796
+                    array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
797
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
798
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
799
+            );
800
+        }
801
+
802
+        // Contains the dependencies that should be checked against
803
+        // classes = class_exists
804
+        // functions = function_exists
805
+        // defined = defined
806
+        // ini = ini_get
807
+        // If the dependency is not found the missing module name is shown to the EndUser
808
+        // When adding new checks always verify that they pass on Travis as well
809
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
810
+        $dependencies = array(
811
+            'classes' => array(
812
+                'ZipArchive' => 'zip',
813
+                'DOMDocument' => 'dom',
814
+                'XMLWriter' => 'XMLWriter',
815
+                'XMLReader' => 'XMLReader',
816
+            ),
817
+            'functions' => [
818
+                'xml_parser_create' => 'libxml',
819
+                'mb_strcut' => 'mb multibyte',
820
+                'ctype_digit' => 'ctype',
821
+                'json_encode' => 'JSON',
822
+                'gd_info' => 'GD',
823
+                'gzencode' => 'zlib',
824
+                'iconv' => 'iconv',
825
+                'simplexml_load_string' => 'SimpleXML',
826
+                'hash' => 'HASH Message Digest Framework',
827
+                'curl_init' => 'cURL',
828
+                'openssl_verify' => 'OpenSSL',
829
+            ],
830
+            'defined' => array(
831
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
832
+            ),
833
+            'ini' => [
834
+                'default_charset' => 'UTF-8',
835
+            ],
836
+        );
837
+        $missingDependencies = array();
838
+        $invalidIniSettings = [];
839
+        $moduleHint = $l->t('Please ask your server administrator to install the module.');
840
+
841
+        /**
842
+         * FIXME: The dependency check does not work properly on HHVM on the moment
843
+         *        and prevents installation. Once HHVM is more compatible with our
844
+         *        approach to check for these values we should re-enable those
845
+         *        checks.
846
+         */
847
+        $iniWrapper = \OC::$server->getIniWrapper();
848
+        if (!self::runningOnHhvm()) {
849
+            foreach ($dependencies['classes'] as $class => $module) {
850
+                if (!class_exists($class)) {
851
+                    $missingDependencies[] = $module;
852
+                }
853
+            }
854
+            foreach ($dependencies['functions'] as $function => $module) {
855
+                if (!function_exists($function)) {
856
+                    $missingDependencies[] = $module;
857
+                }
858
+            }
859
+            foreach ($dependencies['defined'] as $defined => $module) {
860
+                if (!defined($defined)) {
861
+                    $missingDependencies[] = $module;
862
+                }
863
+            }
864
+            foreach ($dependencies['ini'] as $setting => $expected) {
865
+                if (is_bool($expected)) {
866
+                    if ($iniWrapper->getBool($setting) !== $expected) {
867
+                        $invalidIniSettings[] = [$setting, $expected];
868
+                    }
869
+                }
870
+                if (is_int($expected)) {
871
+                    if ($iniWrapper->getNumeric($setting) !== $expected) {
872
+                        $invalidIniSettings[] = [$setting, $expected];
873
+                    }
874
+                }
875
+                if (is_string($expected)) {
876
+                    if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
877
+                        $invalidIniSettings[] = [$setting, $expected];
878
+                    }
879
+                }
880
+            }
881
+        }
882
+
883
+        foreach($missingDependencies as $missingDependency) {
884
+            $errors[] = array(
885
+                'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
886
+                'hint' => $moduleHint
887
+            );
888
+            $webServerRestart = true;
889
+        }
890
+        foreach($invalidIniSettings as $setting) {
891
+            if(is_bool($setting[1])) {
892
+                $setting[1] = $setting[1] ? 'on' : 'off';
893
+            }
894
+            $errors[] = [
895
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
896
+                'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
897
+            ];
898
+            $webServerRestart = true;
899
+        }
900
+
901
+        /**
902
+         * The mbstring.func_overload check can only be performed if the mbstring
903
+         * module is installed as it will return null if the checking setting is
904
+         * not available and thus a check on the boolean value fails.
905
+         *
906
+         * TODO: Should probably be implemented in the above generic dependency
907
+         *       check somehow in the long-term.
908
+         */
909
+        if($iniWrapper->getBool('mbstring.func_overload') !== null &&
910
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
911
+            $errors[] = array(
912
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
913
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
914
+            );
915
+        }
916
+
917
+        if(function_exists('xml_parser_create') &&
918
+            LIBXML_LOADED_VERSION < 20700 ) {
919
+            $version = LIBXML_LOADED_VERSION;
920
+            $major = floor($version/10000);
921
+            $version -= ($major * 10000);
922
+            $minor = floor($version/100);
923
+            $version -= ($minor * 100);
924
+            $patch = $version;
925
+            $errors[] = array(
926
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
927
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
928
+            );
929
+        }
930
+
931
+        if (!self::isAnnotationsWorking()) {
932
+            $errors[] = array(
933
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
934
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
935
+            );
936
+        }
937
+
938
+        if (!\OC::$CLI && $webServerRestart) {
939
+            $errors[] = array(
940
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
941
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
942
+            );
943
+        }
944
+
945
+        $errors = array_merge($errors, self::checkDatabaseVersion());
946
+
947
+        // Cache the result of this function
948
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
949
+
950
+        return $errors;
951
+    }
952
+
953
+    /**
954
+     * Check the database version
955
+     *
956
+     * @return array errors array
957
+     */
958
+    public static function checkDatabaseVersion() {
959
+        $l = \OC::$server->getL10N('lib');
960
+        $errors = array();
961
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
962
+        if ($dbType === 'pgsql') {
963
+            // check PostgreSQL version
964
+            try {
965
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
966
+                $data = $result->fetchRow();
967
+                if (isset($data['server_version'])) {
968
+                    $version = $data['server_version'];
969
+                    if (version_compare($version, '9.0.0', '<')) {
970
+                        $errors[] = array(
971
+                            'error' => $l->t('PostgreSQL >= 9 required'),
972
+                            'hint' => $l->t('Please upgrade your database version')
973
+                        );
974
+                    }
975
+                }
976
+            } catch (\Doctrine\DBAL\DBALException $e) {
977
+                $logger = \OC::$server->getLogger();
978
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
979
+                $logger->logException($e);
980
+            }
981
+        }
982
+        return $errors;
983
+    }
984
+
985
+    /**
986
+     * Check for correct file permissions of data directory
987
+     *
988
+     * @param string $dataDirectory
989
+     * @return array arrays with error messages and hints
990
+     */
991
+    public static function checkDataDirectoryPermissions($dataDirectory) {
992
+        if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
993
+            return  [];
994
+        }
995
+        $l = \OC::$server->getL10N('lib');
996
+        $errors = [];
997
+        $permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
998
+            . ' cannot be listed by other users.');
999
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1000
+        if (substr($perms, -1) !== '0') {
1001
+            chmod($dataDirectory, 0770);
1002
+            clearstatcache();
1003
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1004
+            if ($perms[2] !== '0') {
1005
+                $errors[] = [
1006
+                    'error' => $l->t('Your data directory is readable by other users'),
1007
+                    'hint' => $permissionsModHint
1008
+                ];
1009
+            }
1010
+        }
1011
+        return $errors;
1012
+    }
1013
+
1014
+    /**
1015
+     * Check that the data directory exists and is valid by
1016
+     * checking the existence of the ".ocdata" file.
1017
+     *
1018
+     * @param string $dataDirectory data directory path
1019
+     * @return array errors found
1020
+     */
1021
+    public static function checkDataDirectoryValidity($dataDirectory) {
1022
+        $l = \OC::$server->getL10N('lib');
1023
+        $errors = [];
1024
+        if ($dataDirectory[0] !== '/') {
1025
+            $errors[] = [
1026
+                'error' => $l->t('Your data directory must be an absolute path'),
1027
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1028
+            ];
1029
+        }
1030
+        if (!file_exists($dataDirectory . '/.ocdata')) {
1031
+            $errors[] = [
1032
+                'error' => $l->t('Your data directory is invalid'),
1033
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1034
+                    ' in the root of the data directory.')
1035
+            ];
1036
+        }
1037
+        return $errors;
1038
+    }
1039
+
1040
+    /**
1041
+     * Check if the user is logged in, redirects to home if not. With
1042
+     * redirect URL parameter to the request URI.
1043
+     *
1044
+     * @return void
1045
+     */
1046
+    public static function checkLoggedIn() {
1047
+        // Check if we are a user
1048
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1049
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1050
+                        'core.login.showLoginForm',
1051
+                        [
1052
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1053
+                        ]
1054
+                    )
1055
+            );
1056
+            exit();
1057
+        }
1058
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1059
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1060
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1061
+            exit();
1062
+        }
1063
+    }
1064
+
1065
+    /**
1066
+     * Check if the user is a admin, redirects to home if not
1067
+     *
1068
+     * @return void
1069
+     */
1070
+    public static function checkAdminUser() {
1071
+        OC_Util::checkLoggedIn();
1072
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1073
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1074
+            exit();
1075
+        }
1076
+    }
1077
+
1078
+    /**
1079
+     * Check if the user is a subadmin, redirects to home if not
1080
+     *
1081
+     * @return null|boolean $groups where the current user is subadmin
1082
+     */
1083
+    public static function checkSubAdminUser() {
1084
+        OC_Util::checkLoggedIn();
1085
+        $userObject = \OC::$server->getUserSession()->getUser();
1086
+        $isSubAdmin = false;
1087
+        if($userObject !== null) {
1088
+            $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1089
+        }
1090
+
1091
+        if (!$isSubAdmin) {
1092
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1093
+            exit();
1094
+        }
1095
+        return true;
1096
+    }
1097
+
1098
+    /**
1099
+     * Returns the URL of the default page
1100
+     * based on the system configuration and
1101
+     * the apps visible for the current user
1102
+     *
1103
+     * @return string URL
1104
+     * @suppress PhanDeprecatedFunction
1105
+     */
1106
+    public static function getDefaultPageUrl() {
1107
+        $urlGenerator = \OC::$server->getURLGenerator();
1108
+        // Deny the redirect if the URL contains a @
1109
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1110
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1111
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1112
+        } else {
1113
+            $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1114
+            if ($defaultPage) {
1115
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1116
+            } else {
1117
+                $appId = 'files';
1118
+                $config = \OC::$server->getConfig();
1119
+                $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1120
+                // find the first app that is enabled for the current user
1121
+                foreach ($defaultApps as $defaultApp) {
1122
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1123
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1124
+                        $appId = $defaultApp;
1125
+                        break;
1126
+                    }
1127
+                }
1128
+
1129
+                if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1130
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1131
+                } else {
1132
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1133
+                }
1134
+            }
1135
+        }
1136
+        return $location;
1137
+    }
1138
+
1139
+    /**
1140
+     * Redirect to the user default page
1141
+     *
1142
+     * @return void
1143
+     */
1144
+    public static function redirectToDefaultPage() {
1145
+        $location = self::getDefaultPageUrl();
1146
+        header('Location: ' . $location);
1147
+        exit();
1148
+    }
1149
+
1150
+    /**
1151
+     * get an id unique for this instance
1152
+     *
1153
+     * @return string
1154
+     */
1155
+    public static function getInstanceId() {
1156
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1157
+        if (is_null($id)) {
1158
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1159
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1160
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1161
+        }
1162
+        return $id;
1163
+    }
1164
+
1165
+    /**
1166
+     * Public function to sanitize HTML
1167
+     *
1168
+     * This function is used to sanitize HTML and should be applied on any
1169
+     * string or array of strings before displaying it on a web page.
1170
+     *
1171
+     * @param string|array $value
1172
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1173
+     */
1174
+    public static function sanitizeHTML($value) {
1175
+        if (is_array($value)) {
1176
+            $value = array_map(function($value) {
1177
+                return self::sanitizeHTML($value);
1178
+            }, $value);
1179
+        } else {
1180
+            // Specify encoding for PHP<5.4
1181
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1182
+        }
1183
+        return $value;
1184
+    }
1185
+
1186
+    /**
1187
+     * Public function to encode url parameters
1188
+     *
1189
+     * This function is used to encode path to file before output.
1190
+     * Encoding is done according to RFC 3986 with one exception:
1191
+     * Character '/' is preserved as is.
1192
+     *
1193
+     * @param string $component part of URI to encode
1194
+     * @return string
1195
+     */
1196
+    public static function encodePath($component) {
1197
+        $encoded = rawurlencode($component);
1198
+        $encoded = str_replace('%2F', '/', $encoded);
1199
+        return $encoded;
1200
+    }
1201
+
1202
+
1203
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1204
+        // php dev server does not support htaccess
1205
+        if (php_sapi_name() === 'cli-server') {
1206
+            return false;
1207
+        }
1208
+
1209
+        // testdata
1210
+        $fileName = '/htaccesstest.txt';
1211
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1212
+
1213
+        // creating a test file
1214
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1215
+
1216
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1217
+            return false;
1218
+        }
1219
+
1220
+        $fp = @fopen($testFile, 'w');
1221
+        if (!$fp) {
1222
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1223
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1224
+        }
1225
+        fwrite($fp, $testContent);
1226
+        fclose($fp);
1227
+
1228
+        return $testContent;
1229
+    }
1230
+
1231
+    /**
1232
+     * Check if the .htaccess file is working
1233
+     * @param \OCP\IConfig $config
1234
+     * @return bool
1235
+     * @throws Exception
1236
+     * @throws \OC\HintException If the test file can't get written.
1237
+     */
1238
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1239
+
1240
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1241
+            return true;
1242
+        }
1243
+
1244
+        $testContent = $this->createHtaccessTestFile($config);
1245
+        if ($testContent === false) {
1246
+            return false;
1247
+        }
1248
+
1249
+        $fileName = '/htaccesstest.txt';
1250
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1251
+
1252
+        // accessing the file via http
1253
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1254
+        try {
1255
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1256
+        } catch (\Exception $e) {
1257
+            $content = false;
1258
+        }
1259
+
1260
+        // cleanup
1261
+        @unlink($testFile);
1262
+
1263
+        /*
1264 1264
 		 * If the content is not equal to test content our .htaccess
1265 1265
 		 * is working as required
1266 1266
 		 */
1267
-		return $content !== $testContent;
1268
-	}
1269
-
1270
-	/**
1271
-	 * Check if the setlocal call does not work. This can happen if the right
1272
-	 * local packages are not available on the server.
1273
-	 *
1274
-	 * @return bool
1275
-	 */
1276
-	public static function isSetLocaleWorking() {
1277
-		\Patchwork\Utf8\Bootup::initLocale();
1278
-		if ('' === basename('§')) {
1279
-			return false;
1280
-		}
1281
-		return true;
1282
-	}
1283
-
1284
-	/**
1285
-	 * Check if it's possible to get the inline annotations
1286
-	 *
1287
-	 * @return bool
1288
-	 */
1289
-	public static function isAnnotationsWorking() {
1290
-		$reflection = new \ReflectionMethod(__METHOD__);
1291
-		$docs = $reflection->getDocComment();
1292
-
1293
-		return (is_string($docs) && strlen($docs) > 50);
1294
-	}
1295
-
1296
-	/**
1297
-	 * Check if the PHP module fileinfo is loaded.
1298
-	 *
1299
-	 * @return bool
1300
-	 */
1301
-	public static function fileInfoLoaded() {
1302
-		return function_exists('finfo_open');
1303
-	}
1304
-
1305
-	/**
1306
-	 * clear all levels of output buffering
1307
-	 *
1308
-	 * @return void
1309
-	 */
1310
-	public static function obEnd() {
1311
-		while (ob_get_level()) {
1312
-			ob_end_clean();
1313
-		}
1314
-	}
1315
-
1316
-	/**
1317
-	 * Checks whether the server is running on Mac OS X
1318
-	 *
1319
-	 * @return bool true if running on Mac OS X, false otherwise
1320
-	 */
1321
-	public static function runningOnMac() {
1322
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1323
-	}
1324
-
1325
-	/**
1326
-	 * Checks whether server is running on HHVM
1327
-	 *
1328
-	 * @return bool True if running on HHVM, false otherwise
1329
-	 */
1330
-	public static function runningOnHhvm() {
1331
-		return defined('HHVM_VERSION');
1332
-	}
1333
-
1334
-	/**
1335
-	 * Handles the case that there may not be a theme, then check if a "default"
1336
-	 * theme exists and take that one
1337
-	 *
1338
-	 * @return string the theme
1339
-	 */
1340
-	public static function getTheme() {
1341
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1342
-
1343
-		if ($theme === '') {
1344
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1345
-				$theme = 'default';
1346
-			}
1347
-		}
1348
-
1349
-		return $theme;
1350
-	}
1351
-
1352
-	/**
1353
-	 * Clear a single file from the opcode cache
1354
-	 * This is useful for writing to the config file
1355
-	 * in case the opcode cache does not re-validate files
1356
-	 * Returns true if successful, false if unsuccessful:
1357
-	 * caller should fall back on clearing the entire cache
1358
-	 * with clearOpcodeCache() if unsuccessful
1359
-	 *
1360
-	 * @param string $path the path of the file to clear from the cache
1361
-	 * @return bool true if underlying function returns true, otherwise false
1362
-	 */
1363
-	public static function deleteFromOpcodeCache($path) {
1364
-		$ret = false;
1365
-		if ($path) {
1366
-			// APC >= 3.1.1
1367
-			if (function_exists('apc_delete_file')) {
1368
-				$ret = @apc_delete_file($path);
1369
-			}
1370
-			// Zend OpCache >= 7.0.0, PHP >= 5.5.0
1371
-			if (function_exists('opcache_invalidate')) {
1372
-				$ret = opcache_invalidate($path);
1373
-			}
1374
-		}
1375
-		return $ret;
1376
-	}
1377
-
1378
-	/**
1379
-	 * Clear the opcode cache if one exists
1380
-	 * This is necessary for writing to the config file
1381
-	 * in case the opcode cache does not re-validate files
1382
-	 *
1383
-	 * @return void
1384
-	 * @suppress PhanDeprecatedFunction
1385
-	 * @suppress PhanUndeclaredConstant
1386
-	 */
1387
-	public static function clearOpcodeCache() {
1388
-		// APC
1389
-		if (function_exists('apc_clear_cache')) {
1390
-			apc_clear_cache();
1391
-		}
1392
-		// Zend Opcache
1393
-		if (function_exists('accelerator_reset')) {
1394
-			accelerator_reset();
1395
-		}
1396
-		// XCache
1397
-		if (function_exists('xcache_clear_cache')) {
1398
-			if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1399
-				\OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', ILogger::WARN);
1400
-			} else {
1401
-				@xcache_clear_cache(XC_TYPE_PHP, 0);
1402
-			}
1403
-		}
1404
-		// Opcache (PHP >= 5.5)
1405
-		if (function_exists('opcache_reset')) {
1406
-			opcache_reset();
1407
-		}
1408
-	}
1409
-
1410
-	/**
1411
-	 * Normalize a unicode string
1412
-	 *
1413
-	 * @param string $value a not normalized string
1414
-	 * @return bool|string
1415
-	 */
1416
-	public static function normalizeUnicode($value) {
1417
-		if(Normalizer::isNormalized($value)) {
1418
-			return $value;
1419
-		}
1420
-
1421
-		$normalizedValue = Normalizer::normalize($value);
1422
-		if ($normalizedValue === null || $normalizedValue === false) {
1423
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1424
-			return $value;
1425
-		}
1426
-
1427
-		return $normalizedValue;
1428
-	}
1429
-
1430
-	/**
1431
-	 * A human readable string is generated based on version and build number
1432
-	 *
1433
-	 * @return string
1434
-	 */
1435
-	public static function getHumanVersion() {
1436
-		$version = OC_Util::getVersionString();
1437
-		$build = OC_Util::getBuild();
1438
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1439
-			$version .= ' Build:' . $build;
1440
-		}
1441
-		return $version;
1442
-	}
1443
-
1444
-	/**
1445
-	 * Returns whether the given file name is valid
1446
-	 *
1447
-	 * @param string $file file name to check
1448
-	 * @return bool true if the file name is valid, false otherwise
1449
-	 * @deprecated use \OC\Files\View::verifyPath()
1450
-	 */
1451
-	public static function isValidFileName($file) {
1452
-		$trimmed = trim($file);
1453
-		if ($trimmed === '') {
1454
-			return false;
1455
-		}
1456
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1457
-			return false;
1458
-		}
1459
-
1460
-		// detect part files
1461
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1462
-			return false;
1463
-		}
1464
-
1465
-		foreach (str_split($trimmed) as $char) {
1466
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1467
-				return false;
1468
-			}
1469
-		}
1470
-		return true;
1471
-	}
1472
-
1473
-	/**
1474
-	 * Check whether the instance needs to perform an upgrade,
1475
-	 * either when the core version is higher or any app requires
1476
-	 * an upgrade.
1477
-	 *
1478
-	 * @param \OC\SystemConfig $config
1479
-	 * @return bool whether the core or any app needs an upgrade
1480
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1481
-	 */
1482
-	public static function needUpgrade(\OC\SystemConfig $config) {
1483
-		if ($config->getValue('installed', false)) {
1484
-			$installedVersion = $config->getValue('version', '0.0.0');
1485
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1486
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1487
-			if ($versionDiff > 0) {
1488
-				return true;
1489
-			} else if ($config->getValue('debug', false) && $versionDiff < 0) {
1490
-				// downgrade with debug
1491
-				$installedMajor = explode('.', $installedVersion);
1492
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1493
-				$currentMajor = explode('.', $currentVersion);
1494
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1495
-				if ($installedMajor === $currentMajor) {
1496
-					// Same major, allow downgrade for developers
1497
-					return true;
1498
-				} else {
1499
-					// downgrade attempt, throw exception
1500
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1501
-				}
1502
-			} else if ($versionDiff < 0) {
1503
-				// downgrade attempt, throw exception
1504
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1505
-			}
1506
-
1507
-			// also check for upgrades for apps (independently from the user)
1508
-			$apps = \OC_App::getEnabledApps(false, true);
1509
-			$shouldUpgrade = false;
1510
-			foreach ($apps as $app) {
1511
-				if (\OC_App::shouldUpgrade($app)) {
1512
-					$shouldUpgrade = true;
1513
-					break;
1514
-				}
1515
-			}
1516
-			return $shouldUpgrade;
1517
-		} else {
1518
-			return false;
1519
-		}
1520
-	}
1267
+        return $content !== $testContent;
1268
+    }
1269
+
1270
+    /**
1271
+     * Check if the setlocal call does not work. This can happen if the right
1272
+     * local packages are not available on the server.
1273
+     *
1274
+     * @return bool
1275
+     */
1276
+    public static function isSetLocaleWorking() {
1277
+        \Patchwork\Utf8\Bootup::initLocale();
1278
+        if ('' === basename('§')) {
1279
+            return false;
1280
+        }
1281
+        return true;
1282
+    }
1283
+
1284
+    /**
1285
+     * Check if it's possible to get the inline annotations
1286
+     *
1287
+     * @return bool
1288
+     */
1289
+    public static function isAnnotationsWorking() {
1290
+        $reflection = new \ReflectionMethod(__METHOD__);
1291
+        $docs = $reflection->getDocComment();
1292
+
1293
+        return (is_string($docs) && strlen($docs) > 50);
1294
+    }
1295
+
1296
+    /**
1297
+     * Check if the PHP module fileinfo is loaded.
1298
+     *
1299
+     * @return bool
1300
+     */
1301
+    public static function fileInfoLoaded() {
1302
+        return function_exists('finfo_open');
1303
+    }
1304
+
1305
+    /**
1306
+     * clear all levels of output buffering
1307
+     *
1308
+     * @return void
1309
+     */
1310
+    public static function obEnd() {
1311
+        while (ob_get_level()) {
1312
+            ob_end_clean();
1313
+        }
1314
+    }
1315
+
1316
+    /**
1317
+     * Checks whether the server is running on Mac OS X
1318
+     *
1319
+     * @return bool true if running on Mac OS X, false otherwise
1320
+     */
1321
+    public static function runningOnMac() {
1322
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1323
+    }
1324
+
1325
+    /**
1326
+     * Checks whether server is running on HHVM
1327
+     *
1328
+     * @return bool True if running on HHVM, false otherwise
1329
+     */
1330
+    public static function runningOnHhvm() {
1331
+        return defined('HHVM_VERSION');
1332
+    }
1333
+
1334
+    /**
1335
+     * Handles the case that there may not be a theme, then check if a "default"
1336
+     * theme exists and take that one
1337
+     *
1338
+     * @return string the theme
1339
+     */
1340
+    public static function getTheme() {
1341
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1342
+
1343
+        if ($theme === '') {
1344
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1345
+                $theme = 'default';
1346
+            }
1347
+        }
1348
+
1349
+        return $theme;
1350
+    }
1351
+
1352
+    /**
1353
+     * Clear a single file from the opcode cache
1354
+     * This is useful for writing to the config file
1355
+     * in case the opcode cache does not re-validate files
1356
+     * Returns true if successful, false if unsuccessful:
1357
+     * caller should fall back on clearing the entire cache
1358
+     * with clearOpcodeCache() if unsuccessful
1359
+     *
1360
+     * @param string $path the path of the file to clear from the cache
1361
+     * @return bool true if underlying function returns true, otherwise false
1362
+     */
1363
+    public static function deleteFromOpcodeCache($path) {
1364
+        $ret = false;
1365
+        if ($path) {
1366
+            // APC >= 3.1.1
1367
+            if (function_exists('apc_delete_file')) {
1368
+                $ret = @apc_delete_file($path);
1369
+            }
1370
+            // Zend OpCache >= 7.0.0, PHP >= 5.5.0
1371
+            if (function_exists('opcache_invalidate')) {
1372
+                $ret = opcache_invalidate($path);
1373
+            }
1374
+        }
1375
+        return $ret;
1376
+    }
1377
+
1378
+    /**
1379
+     * Clear the opcode cache if one exists
1380
+     * This is necessary for writing to the config file
1381
+     * in case the opcode cache does not re-validate files
1382
+     *
1383
+     * @return void
1384
+     * @suppress PhanDeprecatedFunction
1385
+     * @suppress PhanUndeclaredConstant
1386
+     */
1387
+    public static function clearOpcodeCache() {
1388
+        // APC
1389
+        if (function_exists('apc_clear_cache')) {
1390
+            apc_clear_cache();
1391
+        }
1392
+        // Zend Opcache
1393
+        if (function_exists('accelerator_reset')) {
1394
+            accelerator_reset();
1395
+        }
1396
+        // XCache
1397
+        if (function_exists('xcache_clear_cache')) {
1398
+            if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1399
+                \OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', ILogger::WARN);
1400
+            } else {
1401
+                @xcache_clear_cache(XC_TYPE_PHP, 0);
1402
+            }
1403
+        }
1404
+        // Opcache (PHP >= 5.5)
1405
+        if (function_exists('opcache_reset')) {
1406
+            opcache_reset();
1407
+        }
1408
+    }
1409
+
1410
+    /**
1411
+     * Normalize a unicode string
1412
+     *
1413
+     * @param string $value a not normalized string
1414
+     * @return bool|string
1415
+     */
1416
+    public static function normalizeUnicode($value) {
1417
+        if(Normalizer::isNormalized($value)) {
1418
+            return $value;
1419
+        }
1420
+
1421
+        $normalizedValue = Normalizer::normalize($value);
1422
+        if ($normalizedValue === null || $normalizedValue === false) {
1423
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1424
+            return $value;
1425
+        }
1426
+
1427
+        return $normalizedValue;
1428
+    }
1429
+
1430
+    /**
1431
+     * A human readable string is generated based on version and build number
1432
+     *
1433
+     * @return string
1434
+     */
1435
+    public static function getHumanVersion() {
1436
+        $version = OC_Util::getVersionString();
1437
+        $build = OC_Util::getBuild();
1438
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1439
+            $version .= ' Build:' . $build;
1440
+        }
1441
+        return $version;
1442
+    }
1443
+
1444
+    /**
1445
+     * Returns whether the given file name is valid
1446
+     *
1447
+     * @param string $file file name to check
1448
+     * @return bool true if the file name is valid, false otherwise
1449
+     * @deprecated use \OC\Files\View::verifyPath()
1450
+     */
1451
+    public static function isValidFileName($file) {
1452
+        $trimmed = trim($file);
1453
+        if ($trimmed === '') {
1454
+            return false;
1455
+        }
1456
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1457
+            return false;
1458
+        }
1459
+
1460
+        // detect part files
1461
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1462
+            return false;
1463
+        }
1464
+
1465
+        foreach (str_split($trimmed) as $char) {
1466
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1467
+                return false;
1468
+            }
1469
+        }
1470
+        return true;
1471
+    }
1472
+
1473
+    /**
1474
+     * Check whether the instance needs to perform an upgrade,
1475
+     * either when the core version is higher or any app requires
1476
+     * an upgrade.
1477
+     *
1478
+     * @param \OC\SystemConfig $config
1479
+     * @return bool whether the core or any app needs an upgrade
1480
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1481
+     */
1482
+    public static function needUpgrade(\OC\SystemConfig $config) {
1483
+        if ($config->getValue('installed', false)) {
1484
+            $installedVersion = $config->getValue('version', '0.0.0');
1485
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1486
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1487
+            if ($versionDiff > 0) {
1488
+                return true;
1489
+            } else if ($config->getValue('debug', false) && $versionDiff < 0) {
1490
+                // downgrade with debug
1491
+                $installedMajor = explode('.', $installedVersion);
1492
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1493
+                $currentMajor = explode('.', $currentVersion);
1494
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1495
+                if ($installedMajor === $currentMajor) {
1496
+                    // Same major, allow downgrade for developers
1497
+                    return true;
1498
+                } else {
1499
+                    // downgrade attempt, throw exception
1500
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1501
+                }
1502
+            } else if ($versionDiff < 0) {
1503
+                // downgrade attempt, throw exception
1504
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1505
+            }
1506
+
1507
+            // also check for upgrades for apps (independently from the user)
1508
+            $apps = \OC_App::getEnabledApps(false, true);
1509
+            $shouldUpgrade = false;
1510
+            foreach ($apps as $app) {
1511
+                if (\OC_App::shouldUpgrade($app)) {
1512
+                    $shouldUpgrade = true;
1513
+                    break;
1514
+                }
1515
+            }
1516
+            return $shouldUpgrade;
1517
+        } else {
1518
+            return false;
1519
+        }
1520
+    }
1521 1521
 
1522 1522
 }
Please login to merge, or discard this patch.
apps/files_external/templates/settings.php 1 patch
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -1,48 +1,48 @@  discard block
 block discarded – undo
1 1
 <?php
2
-	use \OCA\Files_External\Lib\Backend\Backend;
3
-	use \OCA\Files_External\Lib\Auth\AuthMechanism;
4
-	use \OCA\Files_External\Lib\DefinitionParameter;
5
-	use \OCA\Files_External\Service\BackendService;
2
+    use \OCA\Files_External\Lib\Backend\Backend;
3
+    use \OCA\Files_External\Lib\Auth\AuthMechanism;
4
+    use \OCA\Files_External\Lib\DefinitionParameter;
5
+    use \OCA\Files_External\Service\BackendService;
6 6
 
7
-	$canCreateMounts = $_['visibilityType'] === BackendService::VISIBILITY_ADMIN || $_['allowUserMounting'];
7
+    $canCreateMounts = $_['visibilityType'] === BackendService::VISIBILITY_ADMIN || $_['allowUserMounting'];
8 8
 
9
-	$l->t("Enable encryption");
10
-	$l->t("Enable previews");
11
-	$l->t("Enable sharing");
12
-	$l->t("Check for changes");
13
-	$l->t("Never");
14
-	$l->t("Once every direct access");
15
-	$l->t('Read only');
9
+    $l->t("Enable encryption");
10
+    $l->t("Enable previews");
11
+    $l->t("Enable sharing");
12
+    $l->t("Check for changes");
13
+    $l->t("Never");
14
+    $l->t("Once every direct access");
15
+    $l->t('Read only');
16 16
 
17
-	script('files_external', 'settings');
18
-	style('files_external', 'settings');
17
+    script('files_external', 'settings');
18
+    style('files_external', 'settings');
19 19
 
20
-	// load custom JS
21
-	foreach ($_['backends'] as $backend) {
22
-		/** @var Backend $backend */
23
-		$scripts = $backend->getCustomJs();
24
-		foreach ($scripts as $script) {
25
-			script('files_external', $script);
26
-		}
27
-	}
28
-	foreach ($_['authMechanisms'] as $authMechanism) {
29
-		/** @var AuthMechanism $authMechanism */
30
-		$scripts = $authMechanism->getCustomJs();
31
-		foreach ($scripts as $script) {
32
-			script('files_external', $script);
33
-		}
34
-	}
20
+    // load custom JS
21
+    foreach ($_['backends'] as $backend) {
22
+        /** @var Backend $backend */
23
+        $scripts = $backend->getCustomJs();
24
+        foreach ($scripts as $script) {
25
+            script('files_external', $script);
26
+        }
27
+    }
28
+    foreach ($_['authMechanisms'] as $authMechanism) {
29
+        /** @var AuthMechanism $authMechanism */
30
+        $scripts = $authMechanism->getCustomJs();
31
+        foreach ($scripts as $script) {
32
+            script('files_external', $script);
33
+        }
34
+    }
35 35
 
36
-	function writeParameterInput($parameter, $options, $classes = []) {
37
-		$value = '';
38
-		if (isset($options[$parameter->getName()])) {
39
-			$value = $options[$parameter->getName()];
40
-		}
41
-		$placeholder = $parameter->getText();
42
-		$is_optional = $parameter->isFlagSet(DefinitionParameter::FLAG_OPTIONAL);
36
+    function writeParameterInput($parameter, $options, $classes = []) {
37
+        $value = '';
38
+        if (isset($options[$parameter->getName()])) {
39
+            $value = $options[$parameter->getName()];
40
+        }
41
+        $placeholder = $parameter->getText();
42
+        $is_optional = $parameter->isFlagSet(DefinitionParameter::FLAG_OPTIONAL);
43 43
 
44
-		switch ($parameter->getType()) {
45
-		case DefinitionParameter::VALUE_PASSWORD: ?>
44
+        switch ($parameter->getType()) {
45
+        case DefinitionParameter::VALUE_PASSWORD: ?>
46 46
 			<?php if ($is_optional) { $classes[] = 'optional'; } ?>
47 47
 			<input type="password"
48 48
 				<?php if (!empty($classes)): ?> class="<?php p(implode(' ', $classes)); ?>"<?php endif; ?>
@@ -51,8 +51,8 @@  discard block
 block discarded – undo
51 51
 				placeholder="<?php p($placeholder); ?>"
52 52
 			/>
53 53
 			<?php
54
-			break;
55
-		case DefinitionParameter::VALUE_BOOLEAN: ?>
54
+            break;
55
+        case DefinitionParameter::VALUE_BOOLEAN: ?>
56 56
 			<?php $checkboxId = uniqid("checkbox_"); ?>
57 57
 			<div>
58 58
 			<label>
@@ -66,16 +66,16 @@  discard block
 block discarded – undo
66 66
 			</label>
67 67
 			</div>
68 68
 			<?php
69
-			break;
70
-		case DefinitionParameter::VALUE_HIDDEN: ?>
69
+            break;
70
+        case DefinitionParameter::VALUE_HIDDEN: ?>
71 71
 			<input type="hidden"
72 72
 				<?php if (!empty($classes)): ?> class="<?php p(implode(' ', $classes)); ?>"<?php endif; ?>
73 73
 				data-parameter="<?php p($parameter->getName()); ?>"
74 74
 				value="<?php p($value); ?>"
75 75
 			/>
76 76
 			<?php
77
-			break;
78
-		default: ?>
77
+            break;
78
+        default: ?>
79 79
 			<?php if ($is_optional) { $classes[] = 'optional'; } ?>
80 80
 			<input type="text"
81 81
 				<?php if (!empty($classes)): ?> class="<?php p(implode(' ', $classes)); ?>"<?php endif; ?>
@@ -84,8 +84,8 @@  discard block
 block discarded – undo
84 84
 				placeholder="<?php p($placeholder); ?>"
85 85
 			/>
86 86
 			<?php
87
-		}
88
-	}
87
+        }
88
+    }
89 89
 ?>
90 90
 
91 91
 <div id="emptycontent" class="hidden">
@@ -128,13 +128,13 @@  discard block
 block discarded – undo
128 128
 							<?php p($l->t('Add storage')); ?>
129 129
 						</option>
130 130
 						<?php
131
-							$sortedBackends = array_filter($_['backends'], function($backend) use ($_) {
132
-								return $backend->isVisibleFor($_['visibilityType']);
133
-							});
134
-							uasort($sortedBackends, function($a, $b) {
135
-								return strcasecmp($a->getText(), $b->getText());
136
-							});
137
-						?>
131
+                            $sortedBackends = array_filter($_['backends'], function($backend) use ($_) {
132
+                                return $backend->isVisibleFor($_['visibilityType']);
133
+                            });
134
+                            uasort($sortedBackends, function($a, $b) {
135
+                                return strcasecmp($a->getText(), $b->getText());
136
+                            });
137
+                        ?>
138 138
 						<?php foreach ($sortedBackends as $backend): ?>
139 139
 							<?php if ($backend->getDeprecateTo()) continue; // ignore deprecated backends ?>
140 140
 							<option value="<?php p($backend->getIdentifier()); ?>"><?php p($backend->getText()); ?></option>
@@ -181,10 +181,10 @@  discard block
 block discarded – undo
181 181
 		<p id="userMountingBackends"<?php if (!$_['allowUserMounting']): ?> class="hidden"<?php endif; ?>>
182 182
 			<?php p($l->t('Allow users to mount the following external storage')); ?><br />
183 183
 			<?php
184
-				$userBackends = array_filter($_['backends'], function($backend) {
185
-					return $backend->isAllowedVisibleFor(BackendService::VISIBILITY_PERSONAL);
186
-				});
187
-			?>
184
+                $userBackends = array_filter($_['backends'], function($backend) {
185
+                    return $backend->isAllowedVisibleFor(BackendService::VISIBILITY_PERSONAL);
186
+                });
187
+            ?>
188 188
 			<?php $i = 0; foreach ($userBackends as $backend): ?>
189 189
 				<?php if ($deprecateTo = $backend->getDeprecateTo()): ?>
190 190
 					<input type="hidden" id="allowUserMountingBackends<?php p($i); ?>" name="allowUserMountingBackends[]" value="<?php p($backend->getIdentifier()); ?>" data-deprecate-to="<?php p($deprecateTo->getIdentifier()); ?>" />
Please login to merge, or discard this patch.
apps/files_external/lib/Command/ListCommand.php 2 patches
Indentation   +211 added lines, -211 removed lines patch added patch discarded remove patch
@@ -38,240 +38,240 @@
 block discarded – undo
38 38
 use Symfony\Component\Console\Output\OutputInterface;
39 39
 
40 40
 class ListCommand extends Base {
41
-	/**
42
-	 * @var GlobalStoragesService
43
-	 */
44
-	protected $globalService;
41
+    /**
42
+     * @var GlobalStoragesService
43
+     */
44
+    protected $globalService;
45 45
 
46
-	/**
47
-	 * @var UserStoragesService
48
-	 */
49
-	protected $userService;
46
+    /**
47
+     * @var UserStoragesService
48
+     */
49
+    protected $userService;
50 50
 
51
-	/**
52
-	 * @var IUserSession
53
-	 */
54
-	protected $userSession;
51
+    /**
52
+     * @var IUserSession
53
+     */
54
+    protected $userSession;
55 55
 
56
-	/**
57
-	 * @var IUserManager
58
-	 */
59
-	protected $userManager;
56
+    /**
57
+     * @var IUserManager
58
+     */
59
+    protected $userManager;
60 60
 
61
-	const ALL = -1;
61
+    const ALL = -1;
62 62
 
63
-	function __construct(GlobalStoragesService $globalService, UserStoragesService $userService, IUserSession $userSession, IUserManager $userManager) {
64
-		parent::__construct();
65
-		$this->globalService = $globalService;
66
-		$this->userService = $userService;
67
-		$this->userSession = $userSession;
68
-		$this->userManager = $userManager;
69
-	}
63
+    function __construct(GlobalStoragesService $globalService, UserStoragesService $userService, IUserSession $userSession, IUserManager $userManager) {
64
+        parent::__construct();
65
+        $this->globalService = $globalService;
66
+        $this->userService = $userService;
67
+        $this->userSession = $userSession;
68
+        $this->userManager = $userManager;
69
+    }
70 70
 
71
-	protected function configure() {
72
-		$this
73
-			->setName('files_external:list')
74
-			->setDescription('List configured admin or personal mounts')
75
-			->addArgument(
76
-				'user_id',
77
-				InputArgument::OPTIONAL,
78
-				'user id to list the personal mounts for, if no user is provided admin mounts will be listed'
79
-			)->addOption(
80
-				'show-password',
81
-				'',
82
-				InputOption::VALUE_NONE,
83
-				'show passwords and secrets'
84
-			)->addOption(
85
-				'full',
86
-				null,
87
-				InputOption::VALUE_NONE,
88
-				'don\'t truncate long values in table output'
89
-			)->addOption(
90
-				'all',
91
-				'a',
92
-				InputOption::VALUE_NONE,
93
-				'show both system wide mounts and all personal mounts'
94
-			);
95
-		parent::configure();
96
-	}
71
+    protected function configure() {
72
+        $this
73
+            ->setName('files_external:list')
74
+            ->setDescription('List configured admin or personal mounts')
75
+            ->addArgument(
76
+                'user_id',
77
+                InputArgument::OPTIONAL,
78
+                'user id to list the personal mounts for, if no user is provided admin mounts will be listed'
79
+            )->addOption(
80
+                'show-password',
81
+                '',
82
+                InputOption::VALUE_NONE,
83
+                'show passwords and secrets'
84
+            )->addOption(
85
+                'full',
86
+                null,
87
+                InputOption::VALUE_NONE,
88
+                'don\'t truncate long values in table output'
89
+            )->addOption(
90
+                'all',
91
+                'a',
92
+                InputOption::VALUE_NONE,
93
+                'show both system wide mounts and all personal mounts'
94
+            );
95
+        parent::configure();
96
+    }
97 97
 
98
-	protected function execute(InputInterface $input, OutputInterface $output) {
99
-		if ($input->getOption('all')) {
100
-			/** @var  $mounts StorageConfig[] */
101
-			$mounts = $this->globalService->getStorageForAllUsers();
102
-			$userId = self::ALL;
103
-		} else {
104
-			$userId = $input->getArgument('user_id');
105
-			$storageService = $this->getStorageService($userId);
98
+    protected function execute(InputInterface $input, OutputInterface $output) {
99
+        if ($input->getOption('all')) {
100
+            /** @var  $mounts StorageConfig[] */
101
+            $mounts = $this->globalService->getStorageForAllUsers();
102
+            $userId = self::ALL;
103
+        } else {
104
+            $userId = $input->getArgument('user_id');
105
+            $storageService = $this->getStorageService($userId);
106 106
 
107
-			/** @var  $mounts StorageConfig[] */
108
-			$mounts = $storageService->getAllStorages();
109
-		}
107
+            /** @var  $mounts StorageConfig[] */
108
+            $mounts = $storageService->getAllStorages();
109
+        }
110 110
 
111
-		$this->listMounts($userId, $mounts, $input, $output);
112
-	}
111
+        $this->listMounts($userId, $mounts, $input, $output);
112
+    }
113 113
 
114
-	/**
115
-	 * @param $userId $userId
116
-	 * @param StorageConfig[] $mounts
117
-	 * @param InputInterface $input
118
-	 * @param OutputInterface $output
119
-	 */
120
-	public function listMounts($userId, array $mounts, InputInterface $input, OutputInterface $output) {
121
-		$outputType = $input->getOption('output');
122
-		if (count($mounts) === 0) {
123
-			if ($outputType === self::OUTPUT_FORMAT_JSON || $outputType === self::OUTPUT_FORMAT_JSON_PRETTY) {
124
-				$output->writeln('[]');
125
-			} else {
126
-				if ($userId === self::ALL) {
127
-					$output->writeln("<info>No mounts configured</info>");
128
-				} else if ($userId) {
129
-					$output->writeln("<info>No mounts configured by $userId</info>");
130
-				} else {
131
-					$output->writeln("<info>No admin mounts configured</info>");
132
-				}
133
-			}
134
-			return;
135
-		}
114
+    /**
115
+     * @param $userId $userId
116
+     * @param StorageConfig[] $mounts
117
+     * @param InputInterface $input
118
+     * @param OutputInterface $output
119
+     */
120
+    public function listMounts($userId, array $mounts, InputInterface $input, OutputInterface $output) {
121
+        $outputType = $input->getOption('output');
122
+        if (count($mounts) === 0) {
123
+            if ($outputType === self::OUTPUT_FORMAT_JSON || $outputType === self::OUTPUT_FORMAT_JSON_PRETTY) {
124
+                $output->writeln('[]');
125
+            } else {
126
+                if ($userId === self::ALL) {
127
+                    $output->writeln("<info>No mounts configured</info>");
128
+                } else if ($userId) {
129
+                    $output->writeln("<info>No mounts configured by $userId</info>");
130
+                } else {
131
+                    $output->writeln("<info>No admin mounts configured</info>");
132
+                }
133
+            }
134
+            return;
135
+        }
136 136
 
137
-		$headers = ['Mount ID', 'Mount Point', 'Storage', 'Authentication Type', 'Configuration', 'Options'];
137
+        $headers = ['Mount ID', 'Mount Point', 'Storage', 'Authentication Type', 'Configuration', 'Options'];
138 138
 
139
-		if (!$userId || $userId === self::ALL) {
140
-			$headers[] = 'Applicable Users';
141
-			$headers[] = 'Applicable Groups';
142
-		}
143
-		if ($userId === self::ALL) {
144
-			$headers[] = 'Type';
145
-		}
139
+        if (!$userId || $userId === self::ALL) {
140
+            $headers[] = 'Applicable Users';
141
+            $headers[] = 'Applicable Groups';
142
+        }
143
+        if ($userId === self::ALL) {
144
+            $headers[] = 'Type';
145
+        }
146 146
 
147
-		if (!$input->getOption('show-password')) {
148
-			$hideKeys = ['password', 'refresh_token', 'token', 'client_secret', 'public_key', 'private_key'];
149
-			foreach ($mounts as $mount) {
150
-				$config = $mount->getBackendOptions();
151
-				foreach ($config as $key => $value) {
152
-					if (in_array($key, $hideKeys)) {
153
-						$mount->setBackendOption($key, '***');
154
-					}
155
-				}
156
-			}
157
-		}
147
+        if (!$input->getOption('show-password')) {
148
+            $hideKeys = ['password', 'refresh_token', 'token', 'client_secret', 'public_key', 'private_key'];
149
+            foreach ($mounts as $mount) {
150
+                $config = $mount->getBackendOptions();
151
+                foreach ($config as $key => $value) {
152
+                    if (in_array($key, $hideKeys)) {
153
+                        $mount->setBackendOption($key, '***');
154
+                    }
155
+                }
156
+            }
157
+        }
158 158
 
159
-		if ($outputType === self::OUTPUT_FORMAT_JSON || $outputType === self::OUTPUT_FORMAT_JSON_PRETTY) {
160
-			$keys = array_map(function ($header) {
161
-				return strtolower(str_replace(' ', '_', $header));
162
-			}, $headers);
159
+        if ($outputType === self::OUTPUT_FORMAT_JSON || $outputType === self::OUTPUT_FORMAT_JSON_PRETTY) {
160
+            $keys = array_map(function ($header) {
161
+                return strtolower(str_replace(' ', '_', $header));
162
+            }, $headers);
163 163
 
164
-			$pairs = array_map(function (StorageConfig $config) use ($keys, $userId) {
165
-				$values = [
166
-					$config->getId(),
167
-					$config->getMountPoint(),
168
-					$config->getBackend()->getStorageClass(),
169
-					$config->getAuthMechanism()->getIdentifier(),
170
-					$config->getBackendOptions(),
171
-					$config->getMountOptions()
172
-				];
173
-				if (!$userId || $userId === self::ALL) {
174
-					$values[] = $config->getApplicableUsers();
175
-					$values[] = $config->getApplicableGroups();
176
-				}
177
-				if ($userId === self::ALL) {
178
-					$values[] = $config->getType() === StorageConfig::MOUNT_TYPE_ADMIN ? 'admin' : 'personal';
179
-				}
164
+            $pairs = array_map(function (StorageConfig $config) use ($keys, $userId) {
165
+                $values = [
166
+                    $config->getId(),
167
+                    $config->getMountPoint(),
168
+                    $config->getBackend()->getStorageClass(),
169
+                    $config->getAuthMechanism()->getIdentifier(),
170
+                    $config->getBackendOptions(),
171
+                    $config->getMountOptions()
172
+                ];
173
+                if (!$userId || $userId === self::ALL) {
174
+                    $values[] = $config->getApplicableUsers();
175
+                    $values[] = $config->getApplicableGroups();
176
+                }
177
+                if ($userId === self::ALL) {
178
+                    $values[] = $config->getType() === StorageConfig::MOUNT_TYPE_ADMIN ? 'admin' : 'personal';
179
+                }
180 180
 
181
-				return array_combine($keys, $values);
182
-			}, $mounts);
183
-			if ($outputType === self::OUTPUT_FORMAT_JSON) {
184
-				$output->writeln(json_encode(array_values($pairs)));
185
-			} else {
186
-				$output->writeln(json_encode(array_values($pairs), JSON_PRETTY_PRINT));
187
-			}
188
-		} else {
189
-			$full = $input->getOption('full');
190
-			$defaultMountOptions = [
191
-				'encrypt' => true,
192
-				'previews' => true,
193
-				'filesystem_check_changes' => 1,
194
-				'enable_sharing' => false,
195
-				'encoding_compatibility' => false,
196
-				'readonly' => false,
197
-			];
198
-			$rows = array_map(function (StorageConfig $config) use ($userId, $defaultMountOptions, $full) {
199
-				$storageConfig = $config->getBackendOptions();
200
-				$keys = array_keys($storageConfig);
201
-				$values = array_values($storageConfig);
181
+                return array_combine($keys, $values);
182
+            }, $mounts);
183
+            if ($outputType === self::OUTPUT_FORMAT_JSON) {
184
+                $output->writeln(json_encode(array_values($pairs)));
185
+            } else {
186
+                $output->writeln(json_encode(array_values($pairs), JSON_PRETTY_PRINT));
187
+            }
188
+        } else {
189
+            $full = $input->getOption('full');
190
+            $defaultMountOptions = [
191
+                'encrypt' => true,
192
+                'previews' => true,
193
+                'filesystem_check_changes' => 1,
194
+                'enable_sharing' => false,
195
+                'encoding_compatibility' => false,
196
+                'readonly' => false,
197
+            ];
198
+            $rows = array_map(function (StorageConfig $config) use ($userId, $defaultMountOptions, $full) {
199
+                $storageConfig = $config->getBackendOptions();
200
+                $keys = array_keys($storageConfig);
201
+                $values = array_values($storageConfig);
202 202
 
203
-				if (!$full) {
204
-					$values = array_map(function ($value) {
205
-						if (is_string($value) && strlen($value) > 32) {
206
-							return substr($value, 0, 6) . '...' . substr($value, -6, 6);
207
-						} else {
208
-							return $value;
209
-						}
210
-					}, $values);
211
-				}
203
+                if (!$full) {
204
+                    $values = array_map(function ($value) {
205
+                        if (is_string($value) && strlen($value) > 32) {
206
+                            return substr($value, 0, 6) . '...' . substr($value, -6, 6);
207
+                        } else {
208
+                            return $value;
209
+                        }
210
+                    }, $values);
211
+                }
212 212
 
213
-				$configStrings = array_map(function ($key, $value) {
214
-					return $key . ': ' . json_encode($value);
215
-				}, $keys, $values);
216
-				$configString = implode(', ', $configStrings);
213
+                $configStrings = array_map(function ($key, $value) {
214
+                    return $key . ': ' . json_encode($value);
215
+                }, $keys, $values);
216
+                $configString = implode(', ', $configStrings);
217 217
 
218
-				$mountOptions = $config->getMountOptions();
219
-				// hide defaults
220
-				foreach ($mountOptions as $key => $value) {
221
-					if ($value === $defaultMountOptions[$key]) {
222
-						unset($mountOptions[$key]);
223
-					}
224
-				}
225
-				$keys = array_keys($mountOptions);
226
-				$values = array_values($mountOptions);
218
+                $mountOptions = $config->getMountOptions();
219
+                // hide defaults
220
+                foreach ($mountOptions as $key => $value) {
221
+                    if ($value === $defaultMountOptions[$key]) {
222
+                        unset($mountOptions[$key]);
223
+                    }
224
+                }
225
+                $keys = array_keys($mountOptions);
226
+                $values = array_values($mountOptions);
227 227
 
228
-				$optionsStrings = array_map(function ($key, $value) {
229
-					return $key . ': ' . json_encode($value);
230
-				}, $keys, $values);
231
-				$optionsString = implode(', ', $optionsStrings);
228
+                $optionsStrings = array_map(function ($key, $value) {
229
+                    return $key . ': ' . json_encode($value);
230
+                }, $keys, $values);
231
+                $optionsString = implode(', ', $optionsStrings);
232 232
 
233
-				$values = [
234
-					$config->getId(),
235
-					$config->getMountPoint(),
236
-					$config->getBackend()->getText(),
237
-					$config->getAuthMechanism()->getText(),
238
-					$configString,
239
-					$optionsString
240
-				];
233
+                $values = [
234
+                    $config->getId(),
235
+                    $config->getMountPoint(),
236
+                    $config->getBackend()->getText(),
237
+                    $config->getAuthMechanism()->getText(),
238
+                    $configString,
239
+                    $optionsString
240
+                ];
241 241
 
242
-				if (!$userId || $userId === self::ALL) {
243
-					$applicableUsers = implode(', ', $config->getApplicableUsers());
244
-					$applicableGroups = implode(', ', $config->getApplicableGroups());
245
-					if ($applicableUsers === '' && $applicableGroups === '') {
246
-						$applicableUsers = 'All';
247
-					}
248
-					$values[] = $applicableUsers;
249
-					$values[] = $applicableGroups;
250
-				}
251
-				if ($userId === self::ALL) {
252
-					$values[] = $config->getType() === StorageConfig::MOUNT_TYPE_ADMIN ? 'Admin' : 'Personal';
253
-				}
242
+                if (!$userId || $userId === self::ALL) {
243
+                    $applicableUsers = implode(', ', $config->getApplicableUsers());
244
+                    $applicableGroups = implode(', ', $config->getApplicableGroups());
245
+                    if ($applicableUsers === '' && $applicableGroups === '') {
246
+                        $applicableUsers = 'All';
247
+                    }
248
+                    $values[] = $applicableUsers;
249
+                    $values[] = $applicableGroups;
250
+                }
251
+                if ($userId === self::ALL) {
252
+                    $values[] = $config->getType() === StorageConfig::MOUNT_TYPE_ADMIN ? 'Admin' : 'Personal';
253
+                }
254 254
 
255
-				return $values;
256
-			}, $mounts);
255
+                return $values;
256
+            }, $mounts);
257 257
 
258
-			$table = new Table($output);
259
-			$table->setHeaders($headers);
260
-			$table->setRows($rows);
261
-			$table->render();
262
-		}
263
-	}
258
+            $table = new Table($output);
259
+            $table->setHeaders($headers);
260
+            $table->setRows($rows);
261
+            $table->render();
262
+        }
263
+    }
264 264
 
265
-	protected function getStorageService($userId) {
266
-		if (!empty($userId)) {
267
-			$user = $this->userManager->get($userId);
268
-			if (is_null($user)) {
269
-				throw new NoUserException("user $userId not found");
270
-			}
271
-			$this->userSession->setUser($user);
272
-			return $this->userService;
273
-		} else {
274
-			return $this->globalService;
275
-		}
276
-	}
265
+    protected function getStorageService($userId) {
266
+        if (!empty($userId)) {
267
+            $user = $this->userManager->get($userId);
268
+            if (is_null($user)) {
269
+                throw new NoUserException("user $userId not found");
270
+            }
271
+            $this->userSession->setUser($user);
272
+            return $this->userService;
273
+        } else {
274
+            return $this->globalService;
275
+        }
276
+    }
277 277
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -157,11 +157,11 @@  discard block
 block discarded – undo
157 157
 		}
158 158
 
159 159
 		if ($outputType === self::OUTPUT_FORMAT_JSON || $outputType === self::OUTPUT_FORMAT_JSON_PRETTY) {
160
-			$keys = array_map(function ($header) {
160
+			$keys = array_map(function($header) {
161 161
 				return strtolower(str_replace(' ', '_', $header));
162 162
 			}, $headers);
163 163
 
164
-			$pairs = array_map(function (StorageConfig $config) use ($keys, $userId) {
164
+			$pairs = array_map(function(StorageConfig $config) use ($keys, $userId) {
165 165
 				$values = [
166 166
 					$config->getId(),
167 167
 					$config->getMountPoint(),
@@ -195,23 +195,23 @@  discard block
 block discarded – undo
195 195
 				'encoding_compatibility' => false,
196 196
 				'readonly' => false,
197 197
 			];
198
-			$rows = array_map(function (StorageConfig $config) use ($userId, $defaultMountOptions, $full) {
198
+			$rows = array_map(function(StorageConfig $config) use ($userId, $defaultMountOptions, $full) {
199 199
 				$storageConfig = $config->getBackendOptions();
200 200
 				$keys = array_keys($storageConfig);
201 201
 				$values = array_values($storageConfig);
202 202
 
203 203
 				if (!$full) {
204
-					$values = array_map(function ($value) {
204
+					$values = array_map(function($value) {
205 205
 						if (is_string($value) && strlen($value) > 32) {
206
-							return substr($value, 0, 6) . '...' . substr($value, -6, 6);
206
+							return substr($value, 0, 6).'...'.substr($value, -6, 6);
207 207
 						} else {
208 208
 							return $value;
209 209
 						}
210 210
 					}, $values);
211 211
 				}
212 212
 
213
-				$configStrings = array_map(function ($key, $value) {
214
-					return $key . ': ' . json_encode($value);
213
+				$configStrings = array_map(function($key, $value) {
214
+					return $key.': '.json_encode($value);
215 215
 				}, $keys, $values);
216 216
 				$configString = implode(', ', $configStrings);
217 217
 
@@ -225,8 +225,8 @@  discard block
 block discarded – undo
225 225
 				$keys = array_keys($mountOptions);
226 226
 				$values = array_values($mountOptions);
227 227
 
228
-				$optionsStrings = array_map(function ($key, $value) {
229
-					return $key . ': ' . json_encode($value);
228
+				$optionsStrings = array_map(function($key, $value) {
229
+					return $key.': '.json_encode($value);
230 230
 				}, $keys, $values);
231 231
 				$optionsString = implode(', ', $optionsStrings);
232 232
 
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/Node.php 1 patch
Indentation   +322 added lines, -322 removed lines patch added patch discarded remove patch
@@ -44,332 +44,332 @@
 block discarded – undo
44 44
 
45 45
 abstract class Node implements \Sabre\DAV\INode {
46 46
 
47
-	/**
48
-	 * @var \OC\Files\View
49
-	 */
50
-	protected $fileView;
51
-
52
-	/**
53
-	 * The path to the current node
54
-	 *
55
-	 * @var string
56
-	 */
57
-	protected $path;
58
-
59
-	/**
60
-	 * node properties cache
61
-	 *
62
-	 * @var array
63
-	 */
64
-	protected $property_cache = null;
65
-
66
-	/**
67
-	 * @var \OCP\Files\FileInfo
68
-	 */
69
-	protected $info;
70
-
71
-	/**
72
-	 * @var IManager
73
-	 */
74
-	protected $shareManager;
75
-
76
-	/**
77
-	 * Sets up the node, expects a full path name
78
-	 *
79
-	 * @param \OC\Files\View $view
80
-	 * @param \OCP\Files\FileInfo $info
81
-	 * @param IManager $shareManager
82
-	 */
83
-	public function __construct(View $view, FileInfo $info, IManager $shareManager = null) {
84
-		$this->fileView = $view;
85
-		$this->path = $this->fileView->getRelativePath($info->getPath());
86
-		$this->info = $info;
87
-		if ($shareManager) {
88
-			$this->shareManager = $shareManager;
89
-		} else {
90
-			$this->shareManager = \OC::$server->getShareManager();
91
-		}
92
-	}
93
-
94
-	protected function refreshInfo() {
95
-		$this->info = $this->fileView->getFileInfo($this->path);
96
-	}
97
-
98
-	/**
99
-	 *  Returns the name of the node
100
-	 *
101
-	 * @return string
102
-	 */
103
-	public function getName() {
104
-		return $this->info->getName();
105
-	}
106
-
107
-	/**
108
-	 * Returns the full path
109
-	 *
110
-	 * @return string
111
-	 */
112
-	public function getPath() {
113
-		return $this->path;
114
-	}
115
-
116
-	/**
117
-	 * Renames the node
118
-	 *
119
-	 * @param string $name The new name
120
-	 * @throws \Sabre\DAV\Exception\BadRequest
121
-	 * @throws \Sabre\DAV\Exception\Forbidden
122
-	 */
123
-	public function setName($name) {
124
-
125
-		// rename is only allowed if the update privilege is granted
126
-		if (!$this->info->isUpdateable()) {
127
-			throw new \Sabre\DAV\Exception\Forbidden();
128
-		}
129
-
130
-		list($parentPath,) = \Sabre\Uri\split($this->path);
131
-		list(, $newName) = \Sabre\Uri\split($name);
132
-
133
-		// verify path of the target
134
-		$this->verifyPath();
135
-
136
-		$newPath = $parentPath . '/' . $newName;
137
-
138
-		$this->fileView->rename($this->path, $newPath);
139
-
140
-		$this->path = $newPath;
141
-
142
-		$this->refreshInfo();
143
-	}
144
-
145
-	public function setPropertyCache($property_cache) {
146
-		$this->property_cache = $property_cache;
147
-	}
148
-
149
-	/**
150
-	 * Returns the last modification time, as a unix timestamp
151
-	 *
152
-	 * @return int timestamp as integer
153
-	 */
154
-	public function getLastModified() {
155
-		$timestamp = $this->info->getMtime();
156
-		if (!empty($timestamp)) {
157
-			return (int)$timestamp;
158
-		}
159
-		return $timestamp;
160
-	}
161
-
162
-	/**
163
-	 *  sets the last modification time of the file (mtime) to the value given
164
-	 *  in the second parameter or to now if the second param is empty.
165
-	 *  Even if the modification time is set to a custom value the access time is set to now.
166
-	 */
167
-	public function touch($mtime) {
168
-		$mtime = $this->sanitizeMtime($mtime);
169
-		$this->fileView->touch($this->path, $mtime);
170
-		$this->refreshInfo();
171
-	}
172
-
173
-	/**
174
-	 * Returns the ETag for a file
175
-	 *
176
-	 * An ETag is a unique identifier representing the current version of the
177
-	 * file. If the file changes, the ETag MUST change.  The ETag is an
178
-	 * arbitrary string, but MUST be surrounded by double-quotes.
179
-	 *
180
-	 * Return null if the ETag can not effectively be determined
181
-	 *
182
-	 * @return string
183
-	 */
184
-	public function getETag() {
185
-		return '"' . $this->info->getEtag() . '"';
186
-	}
187
-
188
-	/**
189
-	 * Sets the ETag
190
-	 *
191
-	 * @param string $etag
192
-	 *
193
-	 * @return int file id of updated file or -1 on failure
194
-	 */
195
-	public function setETag($etag) {
196
-		return $this->fileView->putFileInfo($this->path, array('etag' => $etag));
197
-	}
198
-
199
-	/**
200
-	 * Returns the size of the node, in bytes
201
-	 *
202
-	 * @return integer
203
-	 */
204
-	public function getSize() {
205
-		return $this->info->getSize();
206
-	}
207
-
208
-	/**
209
-	 * Returns the cache's file id
210
-	 *
211
-	 * @return int
212
-	 */
213
-	public function getId() {
214
-		return $this->info->getId();
215
-	}
216
-
217
-	/**
218
-	 * @return string|null
219
-	 */
220
-	public function getFileId() {
221
-		if ($this->info->getId()) {
222
-			$instanceId = \OC_Util::getInstanceId();
223
-			$id = sprintf('%08d', $this->info->getId());
224
-			return $id . $instanceId;
225
-		}
226
-
227
-		return null;
228
-	}
229
-
230
-	/**
231
-	 * @return integer
232
-	 */
233
-	public function getInternalFileId() {
234
-		return $this->info->getId();
235
-	}
236
-
237
-	/**
238
-	 * @param string $user
239
-	 * @return int
240
-	 */
241
-	public function getSharePermissions($user) {
242
-
243
-		// check of we access a federated share
244
-		if ($user !== null) {
245
-			try {
246
-				$share = $this->shareManager->getShareByToken($user);
247
-				return $share->getPermissions();
248
-			} catch (ShareNotFound $e) {
249
-				// ignore
250
-			}
251
-		}
252
-
253
-		$storage = $this->info->getStorage();
254
-
255
-		$path = $this->info->getInternalPath();
256
-
257
-		if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
258
-			/** @var \OCA\Files_Sharing\SharedStorage $storage */
259
-			$permissions = (int)$storage->getShare()->getPermissions();
260
-		} else {
261
-			$permissions = $storage->getPermissions($path);
262
-		}
263
-
264
-		/*
47
+    /**
48
+     * @var \OC\Files\View
49
+     */
50
+    protected $fileView;
51
+
52
+    /**
53
+     * The path to the current node
54
+     *
55
+     * @var string
56
+     */
57
+    protected $path;
58
+
59
+    /**
60
+     * node properties cache
61
+     *
62
+     * @var array
63
+     */
64
+    protected $property_cache = null;
65
+
66
+    /**
67
+     * @var \OCP\Files\FileInfo
68
+     */
69
+    protected $info;
70
+
71
+    /**
72
+     * @var IManager
73
+     */
74
+    protected $shareManager;
75
+
76
+    /**
77
+     * Sets up the node, expects a full path name
78
+     *
79
+     * @param \OC\Files\View $view
80
+     * @param \OCP\Files\FileInfo $info
81
+     * @param IManager $shareManager
82
+     */
83
+    public function __construct(View $view, FileInfo $info, IManager $shareManager = null) {
84
+        $this->fileView = $view;
85
+        $this->path = $this->fileView->getRelativePath($info->getPath());
86
+        $this->info = $info;
87
+        if ($shareManager) {
88
+            $this->shareManager = $shareManager;
89
+        } else {
90
+            $this->shareManager = \OC::$server->getShareManager();
91
+        }
92
+    }
93
+
94
+    protected function refreshInfo() {
95
+        $this->info = $this->fileView->getFileInfo($this->path);
96
+    }
97
+
98
+    /**
99
+     *  Returns the name of the node
100
+     *
101
+     * @return string
102
+     */
103
+    public function getName() {
104
+        return $this->info->getName();
105
+    }
106
+
107
+    /**
108
+     * Returns the full path
109
+     *
110
+     * @return string
111
+     */
112
+    public function getPath() {
113
+        return $this->path;
114
+    }
115
+
116
+    /**
117
+     * Renames the node
118
+     *
119
+     * @param string $name The new name
120
+     * @throws \Sabre\DAV\Exception\BadRequest
121
+     * @throws \Sabre\DAV\Exception\Forbidden
122
+     */
123
+    public function setName($name) {
124
+
125
+        // rename is only allowed if the update privilege is granted
126
+        if (!$this->info->isUpdateable()) {
127
+            throw new \Sabre\DAV\Exception\Forbidden();
128
+        }
129
+
130
+        list($parentPath,) = \Sabre\Uri\split($this->path);
131
+        list(, $newName) = \Sabre\Uri\split($name);
132
+
133
+        // verify path of the target
134
+        $this->verifyPath();
135
+
136
+        $newPath = $parentPath . '/' . $newName;
137
+
138
+        $this->fileView->rename($this->path, $newPath);
139
+
140
+        $this->path = $newPath;
141
+
142
+        $this->refreshInfo();
143
+    }
144
+
145
+    public function setPropertyCache($property_cache) {
146
+        $this->property_cache = $property_cache;
147
+    }
148
+
149
+    /**
150
+     * Returns the last modification time, as a unix timestamp
151
+     *
152
+     * @return int timestamp as integer
153
+     */
154
+    public function getLastModified() {
155
+        $timestamp = $this->info->getMtime();
156
+        if (!empty($timestamp)) {
157
+            return (int)$timestamp;
158
+        }
159
+        return $timestamp;
160
+    }
161
+
162
+    /**
163
+     *  sets the last modification time of the file (mtime) to the value given
164
+     *  in the second parameter or to now if the second param is empty.
165
+     *  Even if the modification time is set to a custom value the access time is set to now.
166
+     */
167
+    public function touch($mtime) {
168
+        $mtime = $this->sanitizeMtime($mtime);
169
+        $this->fileView->touch($this->path, $mtime);
170
+        $this->refreshInfo();
171
+    }
172
+
173
+    /**
174
+     * Returns the ETag for a file
175
+     *
176
+     * An ETag is a unique identifier representing the current version of the
177
+     * file. If the file changes, the ETag MUST change.  The ETag is an
178
+     * arbitrary string, but MUST be surrounded by double-quotes.
179
+     *
180
+     * Return null if the ETag can not effectively be determined
181
+     *
182
+     * @return string
183
+     */
184
+    public function getETag() {
185
+        return '"' . $this->info->getEtag() . '"';
186
+    }
187
+
188
+    /**
189
+     * Sets the ETag
190
+     *
191
+     * @param string $etag
192
+     *
193
+     * @return int file id of updated file or -1 on failure
194
+     */
195
+    public function setETag($etag) {
196
+        return $this->fileView->putFileInfo($this->path, array('etag' => $etag));
197
+    }
198
+
199
+    /**
200
+     * Returns the size of the node, in bytes
201
+     *
202
+     * @return integer
203
+     */
204
+    public function getSize() {
205
+        return $this->info->getSize();
206
+    }
207
+
208
+    /**
209
+     * Returns the cache's file id
210
+     *
211
+     * @return int
212
+     */
213
+    public function getId() {
214
+        return $this->info->getId();
215
+    }
216
+
217
+    /**
218
+     * @return string|null
219
+     */
220
+    public function getFileId() {
221
+        if ($this->info->getId()) {
222
+            $instanceId = \OC_Util::getInstanceId();
223
+            $id = sprintf('%08d', $this->info->getId());
224
+            return $id . $instanceId;
225
+        }
226
+
227
+        return null;
228
+    }
229
+
230
+    /**
231
+     * @return integer
232
+     */
233
+    public function getInternalFileId() {
234
+        return $this->info->getId();
235
+    }
236
+
237
+    /**
238
+     * @param string $user
239
+     * @return int
240
+     */
241
+    public function getSharePermissions($user) {
242
+
243
+        // check of we access a federated share
244
+        if ($user !== null) {
245
+            try {
246
+                $share = $this->shareManager->getShareByToken($user);
247
+                return $share->getPermissions();
248
+            } catch (ShareNotFound $e) {
249
+                // ignore
250
+            }
251
+        }
252
+
253
+        $storage = $this->info->getStorage();
254
+
255
+        $path = $this->info->getInternalPath();
256
+
257
+        if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
258
+            /** @var \OCA\Files_Sharing\SharedStorage $storage */
259
+            $permissions = (int)$storage->getShare()->getPermissions();
260
+        } else {
261
+            $permissions = $storage->getPermissions($path);
262
+        }
263
+
264
+        /*
265 265
 		 * We can always share non moveable mount points with DELETE and UPDATE
266 266
 		 * Eventually we need to do this properly
267 267
 		 */
268
-		$mountpoint = $this->info->getMountPoint();
269
-		if (!($mountpoint instanceof MoveableMount)) {
270
-			$mountpointpath = $mountpoint->getMountPoint();
271
-			if (substr($mountpointpath, -1) === '/') {
272
-				$mountpointpath = substr($mountpointpath, 0, -1);
273
-			}
274
-
275
-			if (!$mountpoint->getOption('readonly', false) && $mountpointpath === $this->info->getPath()) {
276
-				$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
277
-			}
278
-		}
279
-
280
-		/*
268
+        $mountpoint = $this->info->getMountPoint();
269
+        if (!($mountpoint instanceof MoveableMount)) {
270
+            $mountpointpath = $mountpoint->getMountPoint();
271
+            if (substr($mountpointpath, -1) === '/') {
272
+                $mountpointpath = substr($mountpointpath, 0, -1);
273
+            }
274
+
275
+            if (!$mountpoint->getOption('readonly', false) && $mountpointpath === $this->info->getPath()) {
276
+                $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
277
+            }
278
+        }
279
+
280
+        /*
281 281
 		 * Files can't have create or delete permissions
282 282
 		 */
283
-		if ($this->info->getType() === \OCP\Files\FileInfo::TYPE_FILE) {
284
-			$permissions &= ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_DELETE);
285
-		}
286
-
287
-		return $permissions;
288
-	}
289
-
290
-	/**
291
-	 * @return string
292
-	 */
293
-	public function getDavPermissions() {
294
-		$p = '';
295
-		if ($this->info->isShared()) {
296
-			$p .= 'S';
297
-		}
298
-		if ($this->info->isShareable()) {
299
-			$p .= 'R';
300
-		}
301
-		if ($this->info->isMounted()) {
302
-			$p .= 'M';
303
-		}
304
-		if ($this->info->isReadable()) {
305
-			$p .= 'G';
306
-		}
307
-		if ($this->info->isDeletable()) {
308
-			$p .= 'D';
309
-		}
310
-		if ($this->info->isUpdateable()) {
311
-			$p .= 'NV'; // Renameable, Moveable
312
-		}
313
-		if ($this->info->getType() === \OCP\Files\FileInfo::TYPE_FILE) {
314
-			if ($this->info->isUpdateable()) {
315
-				$p .= 'W';
316
-			}
317
-		} else {
318
-			if ($this->info->isCreatable()) {
319
-				$p .= 'CK';
320
-			}
321
-		}
322
-		return $p;
323
-	}
324
-
325
-	public function getOwner() {
326
-		return $this->info->getOwner();
327
-	}
328
-
329
-	protected function verifyPath() {
330
-		try {
331
-			$fileName = basename($this->info->getPath());
332
-			$this->fileView->verifyPath($this->path, $fileName);
333
-		} catch (\OCP\Files\InvalidPathException $ex) {
334
-			throw new InvalidPath($ex->getMessage());
335
-		}
336
-	}
337
-
338
-	/**
339
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
340
-	 */
341
-	public function acquireLock($type) {
342
-		$this->fileView->lockFile($this->path, $type);
343
-	}
344
-
345
-	/**
346
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
347
-	 */
348
-	public function releaseLock($type) {
349
-		$this->fileView->unlockFile($this->path, $type);
350
-	}
351
-
352
-	/**
353
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
354
-	 */
355
-	public function changeLock($type) {
356
-		$this->fileView->changeLock($this->path, $type);
357
-	}
358
-
359
-	public function getFileInfo() {
360
-		return $this->info;
361
-	}
362
-
363
-	protected function sanitizeMtime($mtimeFromRequest) {
364
-		// In PHP 5.X "is_numeric" returns true for strings in hexadecimal
365
-		// notation. This is no longer the case in PHP 7.X, so this check
366
-		// ensures that strings with hexadecimal notations fail too in PHP 5.X.
367
-		$isHexadecimal = is_string($mtimeFromRequest) && preg_match('/^\s*0[xX]/', $mtimeFromRequest);
368
-		if ($isHexadecimal || !is_numeric($mtimeFromRequest)) {
369
-			throw new \InvalidArgumentException('X-OC-MTime header must be an integer (unix timestamp).');
370
-		}
371
-
372
-		return (int)$mtimeFromRequest;
373
-	}
283
+        if ($this->info->getType() === \OCP\Files\FileInfo::TYPE_FILE) {
284
+            $permissions &= ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_DELETE);
285
+        }
286
+
287
+        return $permissions;
288
+    }
289
+
290
+    /**
291
+     * @return string
292
+     */
293
+    public function getDavPermissions() {
294
+        $p = '';
295
+        if ($this->info->isShared()) {
296
+            $p .= 'S';
297
+        }
298
+        if ($this->info->isShareable()) {
299
+            $p .= 'R';
300
+        }
301
+        if ($this->info->isMounted()) {
302
+            $p .= 'M';
303
+        }
304
+        if ($this->info->isReadable()) {
305
+            $p .= 'G';
306
+        }
307
+        if ($this->info->isDeletable()) {
308
+            $p .= 'D';
309
+        }
310
+        if ($this->info->isUpdateable()) {
311
+            $p .= 'NV'; // Renameable, Moveable
312
+        }
313
+        if ($this->info->getType() === \OCP\Files\FileInfo::TYPE_FILE) {
314
+            if ($this->info->isUpdateable()) {
315
+                $p .= 'W';
316
+            }
317
+        } else {
318
+            if ($this->info->isCreatable()) {
319
+                $p .= 'CK';
320
+            }
321
+        }
322
+        return $p;
323
+    }
324
+
325
+    public function getOwner() {
326
+        return $this->info->getOwner();
327
+    }
328
+
329
+    protected function verifyPath() {
330
+        try {
331
+            $fileName = basename($this->info->getPath());
332
+            $this->fileView->verifyPath($this->path, $fileName);
333
+        } catch (\OCP\Files\InvalidPathException $ex) {
334
+            throw new InvalidPath($ex->getMessage());
335
+        }
336
+    }
337
+
338
+    /**
339
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
340
+     */
341
+    public function acquireLock($type) {
342
+        $this->fileView->lockFile($this->path, $type);
343
+    }
344
+
345
+    /**
346
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
347
+     */
348
+    public function releaseLock($type) {
349
+        $this->fileView->unlockFile($this->path, $type);
350
+    }
351
+
352
+    /**
353
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
354
+     */
355
+    public function changeLock($type) {
356
+        $this->fileView->changeLock($this->path, $type);
357
+    }
358
+
359
+    public function getFileInfo() {
360
+        return $this->info;
361
+    }
362
+
363
+    protected function sanitizeMtime($mtimeFromRequest) {
364
+        // In PHP 5.X "is_numeric" returns true for strings in hexadecimal
365
+        // notation. This is no longer the case in PHP 7.X, so this check
366
+        // ensures that strings with hexadecimal notations fail too in PHP 5.X.
367
+        $isHexadecimal = is_string($mtimeFromRequest) && preg_match('/^\s*0[xX]/', $mtimeFromRequest);
368
+        if ($isHexadecimal || !is_numeric($mtimeFromRequest)) {
369
+            throw new \InvalidArgumentException('X-OC-MTime header must be an integer (unix timestamp).');
370
+        }
371
+
372
+        return (int)$mtimeFromRequest;
373
+    }
374 374
 
375 375
 }
Please login to merge, or discard this patch.