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