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