Passed
Push — master ( 23e8ae...e8872f )
by Robin
16:16 queued 12s
created

OC_Util::setupRootFS()   C

Complexity

Conditions 15
Paths 3

Size

Total Lines 105
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 15
eloc 51
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 105
rs 5.9166

4 Methods

Rating   Name   Duplication   Size   Complexity  
A OC_Util::isPublicLinkPasswordRequired() 0 4 1
A OC_Util::getUserQuota() 0 9 3
A OC_Util::isDefaultExpireDateEnforced() 0 4 1
A OC_Util::isSharingDisabledForUser() 0 5 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Arthur Schiwon <[email protected]>
6
 * @author Bart Visscher <[email protected]>
7
 * @author Bernhard Posselt <[email protected]>
8
 * @author Birk Borkason <[email protected]>
9
 * @author Bjoern Schiessle <[email protected]>
10
 * @author Björn Schießle <[email protected]>
11
 * @author Brice Maron <[email protected]>
12
 * @author Christopher Schäpers <[email protected]>
13
 * @author Christoph Wurst <[email protected]>
14
 * @author Clark Tomlinson <[email protected]>
15
 * @author cmeh <[email protected]>
16
 * @author Eric Masseran <[email protected]>
17
 * @author Felix Epp <[email protected]>
18
 * @author Florin Peter <[email protected]>
19
 * @author Frank Karlitschek <[email protected]>
20
 * @author Georg Ehrke <[email protected]>
21
 * @author helix84 <[email protected]>
22
 * @author Ilja Neumann <[email protected]>
23
 * @author Individual IT Services <[email protected]>
24
 * @author Jakob Sack <[email protected]>
25
 * @author Joas Schilling <[email protected]>
26
 * @author John Molakvoæ <[email protected]>
27
 * @author Jörn Friedrich Dreyer <[email protected]>
28
 * @author Julius Härtl <[email protected]>
29
 * @author Kawohl <[email protected]>
30
 * @author Lukas Reschke <[email protected]>
31
 * @author Markus Goetz <[email protected]>
32
 * @author Martin Mattel <[email protected]>
33
 * @author Marvin Thomas Rabe <[email protected]>
34
 * @author Michael Gapczynski <[email protected]>
35
 * @author Morris Jobke <[email protected]>
36
 * @author rakekniven <[email protected]>
37
 * @author Robert Dailey <[email protected]>
38
 * @author Robin Appelman <[email protected]>
39
 * @author Robin McCorkell <[email protected]>
40
 * @author Roeland Jago Douma <[email protected]>
41
 * @author Sebastian Wessalowski <[email protected]>
42
 * @author Stefan Rado <[email protected]>
43
 * @author Stefan Weil <[email protected]>
44
 * @author Thomas Müller <[email protected]>
45
 * @author Thomas Tanghus <[email protected]>
46
 * @author Valdnet <[email protected]>
47
 * @author Victor Dubiniuk <[email protected]>
48
 * @author Vincent Petry <[email protected]>
49
 * @author Volkan Gezer <[email protected]>
50
 *
51
 * @license AGPL-3.0
52
 *
53
 * This code is free software: you can redistribute it and/or modify
54
 * it under the terms of the GNU Affero General Public License, version 3,
55
 * as published by the Free Software Foundation.
56
 *
57
 * This program is distributed in the hope that it will be useful,
58
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
59
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
60
 * GNU Affero General Public License for more details.
61
 *
62
 * You should have received a copy of the GNU Affero General Public License, version 3,
63
 * along with this program. If not, see <http://www.gnu.org/licenses/>
64
 *
65
 */
66
67
use bantu\IniGetWrapper\IniGetWrapper;
68
use OC\AppFramework\Http\Request;
69
use OC\Files\SetupManager;
70
use OCP\Files\Template\ITemplateManager;
71
use OCP\IConfig;
72
use OCP\IGroupManager;
73
use OCP\IURLGenerator;
74
use OCP\IUser;
75
use OCP\Share\IManager;
76
use Psr\Log\LoggerInterface;
77
78
class OC_Util {
79
	public static $scripts = [];
80
	public static $styles = [];
81
	public static $headers = [];
82
83
	/** @var array Local cache of version.php */
84
	private static $versionCache = null;
85
86
	protected static function getAppManager() {
87
		return \OC::$server->getAppManager();
88
	}
89
90
	/**
91
	 * Setup the file system
92
	 *
93
	 * @param string|null $user
94
	 * @return boolean
95
	 * @description configure the initial filesystem based on the configuration
96
	 * @suppress PhanDeprecatedFunction
97
	 * @suppress PhanAccessMethodInternal
98
	 */
99
	public static function setupFS(?string $user = '') {
100
		// If we are not forced to load a specific user we load the one that is logged in
101
		if ($user === '') {
102
			$userObject = \OC::$server->get(\OCP\IUserSession::class)->getUser();
103
		} else {
104
			$userObject = \OC::$server->get(\OCP\IUserManager::class)->get($user);
105
		}
106
107
		/** @var SetupManager $setupManager */
108
		$setupManager = \OC::$server->get(SetupManager::class);
109
110
		if ($userObject) {
111
			$setupManager->setupForUser($userObject);
112
		} else {
113
			$setupManager->setupRoot();
114
		}
115
		return true;
116
	}
117
118
	/**
119
	 * check if a password is required for each public link
120
	 *
121
	 * @return boolean
122
	 * @suppress PhanDeprecatedFunction
123
	 */
124
	public static function isPublicLinkPasswordRequired() {
125
		/** @var IManager $shareManager */
126
		$shareManager = \OC::$server->get(IManager::class);
127
		return $shareManager->shareApiLinkEnforcePassword();
128
	}
129
130
	/**
131
	 * check if sharing is disabled for the current user
132
	 * @param IConfig $config
133
	 * @param IGroupManager $groupManager
134
	 * @param IUser|null $user
135
	 * @return bool
136
	 */
137
	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
0 ignored issues
show
Unused Code introduced by
The parameter $groupManager is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

137
	public static function isSharingDisabledForUser(IConfig $config, /** @scrutinizer ignore-unused */ IGroupManager $groupManager, $user) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $config is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

137
	public static function isSharingDisabledForUser(/** @scrutinizer ignore-unused */ IConfig $config, IGroupManager $groupManager, $user) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
138
		/** @var IManager $shareManager */
139
		$shareManager = \OC::$server->get(IManager::class);
140
		$userId = $user ? $user->getUID() : null;
141
		return $shareManager->sharingDisabledForUser($userId);
142
	}
143
144
	/**
145
	 * check if share API enforces a default expire date
146
	 *
147
	 * @return boolean
148
	 * @suppress PhanDeprecatedFunction
149
	 */
150
	public static function isDefaultExpireDateEnforced() {
151
		/** @var IManager $shareManager */
152
		$shareManager = \OC::$server->get(IManager::class);
153
		return $shareManager->shareApiLinkDefaultExpireDateEnforced();
154
	}
155
156
	/**
157
	 * Get the quota of a user
158
	 *
159
	 * @param IUser|null $user
160
	 * @return float Quota bytes
161
	 */
162
	public static function getUserQuota(?IUser $user) {
163
		if (is_null($user)) {
164
			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
165
		}
166
		$userQuota = $user->getQuota();
167
		if ($userQuota === 'none') {
168
			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
169
		}
170
		return OC_Helper::computerFileSize($userQuota);
0 ignored issues
show
Bug Best Practice introduced by
The expression return OC_Helper::computerFileSize($userQuota) could also return false which is incompatible with the documented return type double. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
171
	}
172
173
	/**
174
	 * copies the skeleton to the users /files
175
	 *
176
	 * @param string $userId
177
	 * @param \OCP\Files\Folder $userDirectory
178
	 * @throws \OCP\Files\NotFoundException
179
	 * @throws \OCP\Files\NotPermittedException
180
	 * @suppress PhanDeprecatedFunction
181
	 */
182
	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
183
		/** @var LoggerInterface $logger */
184
		$logger = \OC::$server->get(LoggerInterface::class);
185
186
		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
187
		$userLang = \OC::$server->getL10NFactory()->findLanguage();
188
		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
189
190
		if (!file_exists($skeletonDirectory)) {
191
			$dialectStart = strpos($userLang, '_');
192
			if ($dialectStart !== false) {
193
				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
194
			}
195
			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
196
				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
197
			}
198
			if (!file_exists($skeletonDirectory)) {
199
				$skeletonDirectory = '';
200
			}
201
		}
202
203
		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
204
205
		if ($instanceId === null) {
206
			throw new \RuntimeException('no instance id!');
207
		}
208
		$appdata = 'appdata_' . $instanceId;
209
		if ($userId === $appdata) {
210
			throw new \RuntimeException('username is reserved name: ' . $appdata);
211
		}
212
213
		if (!empty($skeletonDirectory)) {
214
			$logger->debug('copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'), ['app' => 'files_skeleton']);
215
			self::copyr($skeletonDirectory, $userDirectory);
216
			// update the file cache
217
			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
218
219
			/** @var ITemplateManager $templateManager */
220
			$templateManager = \OC::$server->get(ITemplateManager::class);
221
			$templateManager->initializeTemplateDirectory(null, $userId);
222
		}
223
	}
224
225
	/**
226
	 * copies a directory recursively by using streams
227
	 *
228
	 * @param string $source
229
	 * @param \OCP\Files\Folder $target
230
	 * @return void
231
	 */
232
	public static function copyr($source, \OCP\Files\Folder $target) {
233
		$logger = \OC::$server->getLogger();
234
235
		// Verify if folder exists
236
		$dir = opendir($source);
237
		if ($dir === false) {
238
			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
239
			return;
240
		}
241
242
		// Copy the files
243
		while (false !== ($file = readdir($dir))) {
244
			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
245
				if (is_dir($source . '/' . $file)) {
246
					$child = $target->newFolder($file);
247
					self::copyr($source . '/' . $file, $child);
248
				} else {
249
					$child = $target->newFile($file);
250
					$sourceStream = fopen($source . '/' . $file, 'r');
251
					if ($sourceStream === false) {
252
						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
253
						closedir($dir);
254
						return;
255
					}
256
					stream_copy_to_stream($sourceStream, $child->fopen('w'));
257
				}
258
			}
259
		}
260
		closedir($dir);
261
	}
262
263
	/**
264
	 * @return void
265
	 * @suppress PhanUndeclaredMethod
266
	 */
267
	public static function tearDownFS() {
268
		/** @var SetupManager $setupManager */
269
		$setupManager = \OC::$server->get(SetupManager::class);
270
		$setupManager->tearDown();
271
	}
272
273
	/**
274
	 * get the current installed version of ownCloud
275
	 *
276
	 * @return array
277
	 */
278
	public static function getVersion() {
279
		OC_Util::loadVersion();
280
		return self::$versionCache['OC_Version'];
281
	}
282
283
	/**
284
	 * get the current installed version string of ownCloud
285
	 *
286
	 * @return string
287
	 */
288
	public static function getVersionString() {
289
		OC_Util::loadVersion();
290
		return self::$versionCache['OC_VersionString'];
291
	}
292
293
	/**
294
	 * @deprecated the value is of no use anymore
295
	 * @return string
296
	 */
297
	public static function getEditionString() {
298
		return '';
299
	}
300
301
	/**
302
	 * @description get the update channel of the current installed of ownCloud.
303
	 * @return string
304
	 */
305
	public static function getChannel() {
306
		OC_Util::loadVersion();
307
		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
308
	}
309
310
	/**
311
	 * @description get the build number of the current installed of ownCloud.
312
	 * @return string
313
	 */
314
	public static function getBuild() {
315
		OC_Util::loadVersion();
316
		return self::$versionCache['OC_Build'];
317
	}
318
319
	/**
320
	 * @description load the version.php into the session as cache
321
	 * @suppress PhanUndeclaredVariable
322
	 */
323
	private static function loadVersion() {
324
		if (self::$versionCache !== null) {
0 ignored issues
show
introduced by
The condition self::versionCache !== null is always true.
Loading history...
325
			return;
326
		}
327
328
		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
329
		require OC::$SERVERROOT . '/version.php';
330
		/** @var int $timestamp */
331
		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
332
		/** @var string $OC_Version */
333
		self::$versionCache['OC_Version'] = $OC_Version;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $OC_Version seems to be never defined.
Loading history...
334
		/** @var string $OC_VersionString */
335
		self::$versionCache['OC_VersionString'] = $OC_VersionString;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $OC_VersionString seems to be never defined.
Loading history...
336
		/** @var string $OC_Build */
337
		self::$versionCache['OC_Build'] = $OC_Build;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $OC_Build seems to be never defined.
Loading history...
338
339
		/** @var string $OC_Channel */
340
		self::$versionCache['OC_Channel'] = $OC_Channel;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $OC_Channel seems to be never defined.
Loading history...
341
	}
342
343
	/**
344
	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
345
	 *
346
	 * @param string $application application to get the files from
347
	 * @param string $directory directory within this application (css, js, vendor, etc)
348
	 * @param string $file the file inside of the above folder
349
	 * @return string the path
350
	 */
351
	private static function generatePath($application, $directory, $file) {
352
		if (is_null($file)) {
0 ignored issues
show
introduced by
The condition is_null($file) is always false.
Loading history...
353
			$file = $application;
354
			$application = "";
355
		}
356
		if (!empty($application)) {
357
			return "$application/$directory/$file";
358
		} else {
359
			return "$directory/$file";
360
		}
361
	}
362
363
	/**
364
	 * add a javascript file
365
	 *
366
	 * @deprecated 24.0.0 - Use \OCP\Util::addScript
367
	 *
368
	 * @param string $application application id
369
	 * @param string|null $file filename
370
	 * @param bool $prepend prepend the Script to the beginning of the list
371
	 * @return void
372
	 */
373
	public static function addScript($application, $file = null, $prepend = false) {
374
		$path = OC_Util::generatePath($application, 'js', $file);
375
376
		// core js files need separate handling
377
		if ($application !== 'core' && $file !== null) {
378
			self::addTranslations($application);
379
		}
380
		self::addExternalResource($application, $prepend, $path, "script");
381
	}
382
383
	/**
384
	 * add a javascript file from the vendor sub folder
385
	 *
386
	 * @param string $application application id
387
	 * @param string|null $file filename
388
	 * @param bool $prepend prepend the Script to the beginning of the list
389
	 * @return void
390
	 */
391
	public static function addVendorScript($application, $file = null, $prepend = false) {
392
		$path = OC_Util::generatePath($application, 'vendor', $file);
393
		self::addExternalResource($application, $prepend, $path, "script");
394
	}
395
396
	/**
397
	 * add a translation JS file
398
	 *
399
	 * @deprecated 24.0.0
400
	 *
401
	 * @param string $application application id
402
	 * @param string|null $languageCode language code, defaults to the current language
403
	 * @param bool|null $prepend prepend the Script to the beginning of the list
404
	 */
405
	public static function addTranslations($application, $languageCode = null, $prepend = false) {
406
		if (is_null($languageCode)) {
407
			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
408
		}
409
		if (!empty($application)) {
410
			$path = "$application/l10n/$languageCode";
411
		} else {
412
			$path = "l10n/$languageCode";
413
		}
414
		self::addExternalResource($application, $prepend, $path, "script");
415
	}
416
417
	/**
418
	 * add a css file
419
	 *
420
	 * @param string $application application id
421
	 * @param string|null $file filename
422
	 * @param bool $prepend prepend the Style to the beginning of the list
423
	 * @return void
424
	 */
425
	public static function addStyle($application, $file = null, $prepend = false) {
426
		$path = OC_Util::generatePath($application, 'css', $file);
427
		self::addExternalResource($application, $prepend, $path, "style");
428
	}
429
430
	/**
431
	 * add a css file from the vendor sub folder
432
	 *
433
	 * @param string $application application id
434
	 * @param string|null $file filename
435
	 * @param bool $prepend prepend the Style to the beginning of the list
436
	 * @return void
437
	 */
438
	public static function addVendorStyle($application, $file = null, $prepend = false) {
439
		$path = OC_Util::generatePath($application, 'vendor', $file);
440
		self::addExternalResource($application, $prepend, $path, "style");
441
	}
442
443
	/**
444
	 * add an external resource css/js file
445
	 *
446
	 * @param string $application application id
447
	 * @param bool $prepend prepend the file to the beginning of the list
448
	 * @param string $path
449
	 * @param string $type (script or style)
450
	 * @return void
451
	 */
452
	private static function addExternalResource($application, $prepend, $path, $type = "script") {
0 ignored issues
show
Unused Code introduced by
The parameter $application is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

452
	private static function addExternalResource(/** @scrutinizer ignore-unused */ $application, $prepend, $path, $type = "script") {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
453
		if ($type === "style") {
454
			if (!in_array($path, self::$styles)) {
455
				if ($prepend === true) {
456
					array_unshift(self::$styles, $path);
457
				} else {
458
					self::$styles[] = $path;
459
				}
460
			}
461
		} elseif ($type === "script") {
462
			if (!in_array($path, self::$scripts)) {
463
				if ($prepend === true) {
464
					array_unshift(self::$scripts, $path);
465
				} else {
466
					self::$scripts [] = $path;
467
				}
468
			}
469
		}
470
	}
471
472
	/**
473
	 * Add a custom element to the header
474
	 * If $text is null then the element will be written as empty element.
475
	 * So use "" to get a closing tag.
476
	 * @param string $tag tag name of the element
477
	 * @param array $attributes array of attributes for the element
478
	 * @param string $text the text content for the element
479
	 * @param bool $prepend prepend the header to the beginning of the list
480
	 */
481
	public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
482
		$header = [
483
			'tag' => $tag,
484
			'attributes' => $attributes,
485
			'text' => $text
486
		];
487
		if ($prepend === true) {
488
			array_unshift(self::$headers, $header);
489
		} else {
490
			self::$headers[] = $header;
491
		}
492
	}
493
494
	/**
495
	 * check if the current server configuration is suitable for ownCloud
496
	 *
497
	 * @param \OC\SystemConfig $config
498
	 * @return array arrays with error messages and hints
499
	 */
500
	public static function checkServer(\OC\SystemConfig $config) {
501
		$l = \OC::$server->getL10N('lib');
502
		$errors = [];
503
		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
504
505
		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
506
			// this check needs to be done every time
507
			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
508
		}
509
510
		// Assume that if checkServer() succeeded before in this session, then all is fine.
511
		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
512
			return $errors;
513
		}
514
515
		$webServerRestart = false;
516
		$setup = new \OC\Setup(
517
			$config,
518
			\OC::$server->get(IniGetWrapper::class),
519
			\OC::$server->getL10N('lib'),
520
			\OC::$server->get(\OCP\Defaults::class),
521
			\OC::$server->get(LoggerInterface::class),
522
			\OC::$server->getSecureRandom(),
523
			\OC::$server->get(\OC\Installer::class)
524
		);
525
526
		$urlGenerator = \OC::$server->getURLGenerator();
527
528
		$availableDatabases = $setup->getSupportedDatabases();
529
		if (empty($availableDatabases)) {
530
			$errors[] = [
531
				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
532
				'hint' => '' //TODO: sane hint
533
			];
534
			$webServerRestart = true;
535
		}
536
537
		// Check if config folder is writable.
538
		if (!OC_Helper::isReadOnlyConfigEnabled()) {
539
			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
540
				$errors[] = [
541
					'error' => $l->t('Cannot write into "config" directory.'),
542
					'hint' => $l->t('This can usually be fixed by giving the web server write access to the config directory. See %s',
543
						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
544
						. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
545
						[ $urlGenerator->linkToDocs('admin-config') ])
546
				];
547
			}
548
		}
549
550
		// Check if there is a writable install folder.
551
		if ($config->getValue('appstoreenabled', true)) {
552
			if (OC_App::getInstallPath() === null
553
				|| !is_writable(OC_App::getInstallPath())
554
				|| !is_readable(OC_App::getInstallPath())
555
			) {
556
				$errors[] = [
557
					'error' => $l->t('Cannot write into "apps" directory.'),
558
					'hint' => $l->t('This can usually be fixed by giving the web server write access to the apps directory'
559
						. ' or disabling the App Store in the config file.')
560
				];
561
			}
562
		}
563
		// Create root dir.
564
		if ($config->getValue('installed', false)) {
565
			if (!is_dir($CONFIG_DATADIRECTORY)) {
566
				$success = @mkdir($CONFIG_DATADIRECTORY);
567
				if ($success) {
568
					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
569
				} else {
570
					$errors[] = [
571
						'error' => $l->t('Cannot create "data" directory.'),
572
						'hint' => $l->t('This can usually be fixed by giving the web server write access to the root directory. See %s',
573
							[$urlGenerator->linkToDocs('admin-dir_permissions')])
574
					];
575
				}
576
			} elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
577
				// is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
578
				$testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
579
				$handle = fopen($testFile, 'w');
580
				if (!$handle || fwrite($handle, 'Test write operation') === false) {
0 ignored issues
show
introduced by
$handle is of type resource, thus it always evaluated to false.
Loading history...
581
					$permissionsHint = $l->t('Permissions can usually be fixed by giving the web server write access to the root directory. See %s.',
582
						[$urlGenerator->linkToDocs('admin-dir_permissions')]);
583
					$errors[] = [
584
						'error' => $l->t('Your data directory is not writable.'),
585
						'hint' => $permissionsHint
586
					];
587
				} else {
588
					fclose($handle);
589
					unlink($testFile);
590
				}
591
			} else {
592
				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
593
			}
594
		}
595
596
		if (!OC_Util::isSetLocaleWorking()) {
597
			$errors[] = [
598
				'error' => $l->t('Setting locale to %s failed.',
599
					['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
600
						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
601
				'hint' => $l->t('Please install one of these locales on your system and restart your web server.')
602
			];
603
		}
604
605
		// Contains the dependencies that should be checked against
606
		// classes = class_exists
607
		// functions = function_exists
608
		// defined = defined
609
		// ini = ini_get
610
		// If the dependency is not found the missing module name is shown to the EndUser
611
		// When adding new checks always verify that they pass on Travis as well
612
		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
613
		$dependencies = [
614
			'classes' => [
615
				'ZipArchive' => 'zip',
616
				'DOMDocument' => 'dom',
617
				'XMLWriter' => 'XMLWriter',
618
				'XMLReader' => 'XMLReader',
619
			],
620
			'functions' => [
621
				'xml_parser_create' => 'libxml',
622
				'mb_strcut' => 'mbstring',
623
				'ctype_digit' => 'ctype',
624
				'json_encode' => 'JSON',
625
				'gd_info' => 'GD',
626
				'gzencode' => 'zlib',
627
				'simplexml_load_string' => 'SimpleXML',
628
				'hash' => 'HASH Message Digest Framework',
629
				'curl_init' => 'cURL',
630
				'openssl_verify' => 'OpenSSL',
631
			],
632
			'defined' => [
633
				'PDO::ATTR_DRIVER_NAME' => 'PDO'
634
			],
635
			'ini' => [
636
				'default_charset' => 'UTF-8',
637
			],
638
		];
639
		$missingDependencies = [];
640
		$invalidIniSettings = [];
641
642
		$iniWrapper = \OC::$server->get(IniGetWrapper::class);
643
		foreach ($dependencies['classes'] as $class => $module) {
644
			if (!class_exists($class)) {
645
				$missingDependencies[] = $module;
646
			}
647
		}
648
		foreach ($dependencies['functions'] as $function => $module) {
649
			if (!function_exists($function)) {
650
				$missingDependencies[] = $module;
651
			}
652
		}
653
		foreach ($dependencies['defined'] as $defined => $module) {
654
			if (!defined($defined)) {
655
				$missingDependencies[] = $module;
656
			}
657
		}
658
		foreach ($dependencies['ini'] as $setting => $expected) {
659
			if (is_bool($expected)) {
660
				if ($iniWrapper->getBool($setting) !== $expected) {
661
					$invalidIniSettings[] = [$setting, $expected];
662
				}
663
			}
664
			if (is_int($expected)) {
665
				if ($iniWrapper->getNumeric($setting) !== $expected) {
666
					$invalidIniSettings[] = [$setting, $expected];
667
				}
668
			}
669
			if (is_string($expected)) {
670
				if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
671
					$invalidIniSettings[] = [$setting, $expected];
672
				}
673
			}
674
		}
675
676
		foreach ($missingDependencies as $missingDependency) {
677
			$errors[] = [
678
				'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
679
				'hint' => $l->t('Please ask your server administrator to install the module.'),
680
			];
681
			$webServerRestart = true;
682
		}
683
		foreach ($invalidIniSettings as $setting) {
684
			if (is_bool($setting[1])) {
685
				$setting[1] = $setting[1] ? 'on' : 'off';
686
			}
687
			$errors[] = [
688
				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
689
				'hint' => $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
690
			];
691
			$webServerRestart = true;
692
		}
693
694
		/**
695
		 * The mbstring.func_overload check can only be performed if the mbstring
696
		 * module is installed as it will return null if the checking setting is
697
		 * not available and thus a check on the boolean value fails.
698
		 *
699
		 * TODO: Should probably be implemented in the above generic dependency
700
		 *       check somehow in the long-term.
701
		 */
702
		if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
703
			$iniWrapper->getBool('mbstring.func_overload') === true) {
704
			$errors[] = [
705
				'error' => $l->t('<code>mbstring.func_overload</code> is set to <code>%s</code> instead of the expected value <code>0</code>.', [$iniWrapper->getString('mbstring.func_overload')]),
706
				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini.')
707
			];
708
		}
709
710
		if (function_exists('xml_parser_create') &&
711
			LIBXML_LOADED_VERSION < 20700) {
712
			$version = LIBXML_LOADED_VERSION;
713
			$major = floor($version / 10000);
714
			$version -= ($major * 10000);
715
			$minor = floor($version / 100);
716
			$version -= ($minor * 100);
717
			$patch = $version;
718
			$errors[] = [
719
				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
720
				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
721
			];
722
		}
723
724
		if (!self::isAnnotationsWorking()) {
725
			$errors[] = [
726
				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
727
				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
728
			];
729
		}
730
731
		if (!\OC::$CLI && $webServerRestart) {
732
			$errors[] = [
733
				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
734
				'hint' => $l->t('Please ask your server administrator to restart the web server.')
735
			];
736
		}
737
738
		$errors = array_merge($errors, self::checkDatabaseVersion());
739
740
		// Cache the result of this function
741
		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
742
743
		return $errors;
744
	}
745
746
	/**
747
	 * Check the database version
748
	 *
749
	 * @return array errors array
750
	 */
751
	public static function checkDatabaseVersion() {
752
		$l = \OC::$server->getL10N('lib');
753
		$errors = [];
754
		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
755
		if ($dbType === 'pgsql') {
756
			// check PostgreSQL version
757
			try {
758
				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
759
				$data = $result->fetchRow();
0 ignored issues
show
Deprecated Code introduced by
The function OC_DB_StatementWrapper::fetchRow() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

759
				$data = /** @scrutinizer ignore-deprecated */ $result->fetchRow();
Loading history...
760
				$result->closeCursor();
761
				if (isset($data['server_version'])) {
762
					$version = $data['server_version'];
763
					if (version_compare($version, '9.0.0', '<')) {
764
						$errors[] = [
765
							'error' => $l->t('PostgreSQL >= 9 required.'),
766
							'hint' => $l->t('Please upgrade your database version.')
767
						];
768
					}
769
				}
770
			} catch (\Doctrine\DBAL\Exception $e) {
771
				$logger = \OC::$server->getLogger();
772
				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
773
				$logger->logException($e);
774
			}
775
		}
776
		return $errors;
777
	}
778
779
	/**
780
	 * Check for correct file permissions of data directory
781
	 *
782
	 * @param string $dataDirectory
783
	 * @return array arrays with error messages and hints
784
	 */
785
	public static function checkDataDirectoryPermissions($dataDirectory) {
786
		if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
787
			return  [];
788
		}
789
790
		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
791
		if (substr($perms, -1) !== '0') {
792
			chmod($dataDirectory, 0770);
793
			clearstatcache();
794
			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
795
			if ($perms[2] !== '0') {
796
				$l = \OC::$server->getL10N('lib');
797
				return [[
798
					'error' => $l->t('Your data directory is readable by other users.'),
799
					'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
800
				]];
801
			}
802
		}
803
		return [];
804
	}
805
806
	/**
807
	 * Check that the data directory exists and is valid by
808
	 * checking the existence of the ".ocdata" file.
809
	 *
810
	 * @param string $dataDirectory data directory path
811
	 * @return array errors found
812
	 */
813
	public static function checkDataDirectoryValidity($dataDirectory) {
814
		$l = \OC::$server->getL10N('lib');
815
		$errors = [];
816
		if ($dataDirectory[0] !== '/') {
817
			$errors[] = [
818
				'error' => $l->t('Your data directory must be an absolute path.'),
819
				'hint' => $l->t('Check the value of "datadirectory" in your configuration.')
820
			];
821
		}
822
		if (!file_exists($dataDirectory . '/.ocdata')) {
823
			$errors[] = [
824
				'error' => $l->t('Your data directory is invalid.'),
825
				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
826
					' in the root of the data directory.')
827
			];
828
		}
829
		return $errors;
830
	}
831
832
	/**
833
	 * Check if the user is logged in, redirects to home if not. With
834
	 * redirect URL parameter to the request URI.
835
	 *
836
	 * @return void
837
	 */
838
	public static function checkLoggedIn() {
839
		// Check if we are a user
840
		if (!\OC::$server->getUserSession()->isLoggedIn()) {
841
			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
842
						'core.login.showLoginForm',
843
						[
844
							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
845
						]
846
					)
847
			);
848
			exit();
849
		}
850
		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
851
		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
852
			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
853
			exit();
854
		}
855
	}
856
857
	/**
858
	 * Check if the user is a admin, redirects to home if not
859
	 *
860
	 * @return void
861
	 */
862
	public static function checkAdminUser() {
863
		OC_Util::checkLoggedIn();
864
		if (!OC_User::isAdminUser(OC_User::getUser())) {
865
			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
866
			exit();
867
		}
868
	}
869
870
	/**
871
	 * Returns the URL of the default page
872
	 * based on the system configuration and
873
	 * the apps visible for the current user
874
	 *
875
	 * @return string URL
876
	 * @suppress PhanDeprecatedFunction
877
	 */
878
	public static function getDefaultPageUrl() {
879
		/** @var IURLGenerator $urlGenerator */
880
		$urlGenerator = \OC::$server->get(IURLGenerator::class);
881
		return $urlGenerator->linkToDefaultPageUrl();
882
	}
883
884
	/**
885
	 * Redirect to the user default page
886
	 *
887
	 * @return void
888
	 */
889
	public static function redirectToDefaultPage() {
890
		$location = self::getDefaultPageUrl();
891
		header('Location: ' . $location);
892
		exit();
893
	}
894
895
	/**
896
	 * get an id unique for this instance
897
	 *
898
	 * @return string
899
	 */
900
	public static function getInstanceId() {
901
		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
902
		if (is_null($id)) {
903
			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
904
			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
905
			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
906
		}
907
		return $id;
908
	}
909
910
	/**
911
	 * Public function to sanitize HTML
912
	 *
913
	 * This function is used to sanitize HTML and should be applied on any
914
	 * string or array of strings before displaying it on a web page.
915
	 *
916
	 * @param string|string[] $value
917
	 * @return string|string[] an array of sanitized strings or a single sanitized string, depends on the input parameter.
918
	 */
919
	public static function sanitizeHTML($value) {
920
		if (is_array($value)) {
921
			/** @var string[] $value */
922
			$value = array_map(function ($value) {
923
				return self::sanitizeHTML($value);
924
			}, $value);
925
		} else {
926
			// Specify encoding for PHP<5.4
927
			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
928
		}
929
		return $value;
930
	}
931
932
	/**
933
	 * Public function to encode url parameters
934
	 *
935
	 * This function is used to encode path to file before output.
936
	 * Encoding is done according to RFC 3986 with one exception:
937
	 * Character '/' is preserved as is.
938
	 *
939
	 * @param string $component part of URI to encode
940
	 * @return string
941
	 */
942
	public static function encodePath($component) {
943
		$encoded = rawurlencode($component);
944
		$encoded = str_replace('%2F', '/', $encoded);
945
		return $encoded;
946
	}
947
948
949
	public function createHtaccessTestFile(\OCP\IConfig $config) {
950
		// php dev server does not support htaccess
951
		if (php_sapi_name() === 'cli-server') {
952
			return false;
953
		}
954
955
		// testdata
956
		$fileName = '/htaccesstest.txt';
957
		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
958
959
		// creating a test file
960
		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
961
962
		if (file_exists($testFile)) {// already running this test, possible recursive call
963
			return false;
964
		}
965
966
		$fp = @fopen($testFile, 'w');
967
		if (!$fp) {
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
968
			throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.',
969
				'Make sure it is possible for the web server to write to ' . $testFile);
970
		}
971
		fwrite($fp, $testContent);
972
		fclose($fp);
973
974
		return $testContent;
975
	}
976
977
	/**
978
	 * Check if the .htaccess file is working
979
	 *
980
	 * @param \OCP\IConfig $config
981
	 * @return bool
982
	 * @throws Exception
983
	 * @throws \OCP\HintException If the test file can't get written.
984
	 */
985
	public function isHtaccessWorking(\OCP\IConfig $config) {
986
		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
987
			return true;
988
		}
989
990
		$testContent = $this->createHtaccessTestFile($config);
991
		if ($testContent === false) {
0 ignored issues
show
introduced by
The condition $testContent === false is always true.
Loading history...
992
			return false;
993
		}
994
995
		$fileName = '/htaccesstest.txt';
996
		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
997
998
		// accessing the file via http
999
		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1000
		try {
1001
			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1002
		} catch (\Exception $e) {
1003
			$content = false;
1004
		}
1005
1006
		if (strpos($url, 'https:') === 0) {
1007
			$url = 'http:' . substr($url, 6);
1008
		} else {
1009
			$url = 'https:' . substr($url, 5);
1010
		}
1011
1012
		try {
1013
			$fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1014
		} catch (\Exception $e) {
1015
			$fallbackContent = false;
1016
		}
1017
1018
		// cleanup
1019
		@unlink($testFile);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

1019
		/** @scrutinizer ignore-unhandled */ @unlink($testFile);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1020
1021
		/*
1022
		 * If the content is not equal to test content our .htaccess
1023
		 * is working as required
1024
		 */
1025
		return $content !== $testContent && $fallbackContent !== $testContent;
1026
	}
1027
1028
	/**
1029
	 * Check if current locale is non-UTF8
1030
	 *
1031
	 * @return bool
1032
	 */
1033
	private static function isNonUTF8Locale() {
1034
		if (function_exists('escapeshellcmd')) {
1035
			return '' === escapeshellcmd('§');
1036
		} elseif (function_exists('escapeshellarg')) {
1037
			return '\'\'' === escapeshellarg('§');
1038
		} else {
1039
			return 0 === preg_match('/utf-?8/i', setlocale(LC_CTYPE, 0));
1040
		}
1041
	}
1042
1043
	/**
1044
	 * Check if the setlocale call does not work. This can happen if the right
1045
	 * local packages are not available on the server.
1046
	 *
1047
	 * @return bool
1048
	 */
1049
	public static function isSetLocaleWorking() {
1050
		if (self::isNonUTF8Locale()) {
1051
			// Borrowed from \Patchwork\Utf8\Bootup::initLocale
1052
			setlocale(LC_ALL, 'C.UTF-8', 'C');
1053
			setlocale(LC_CTYPE, 'en_US.UTF-8', 'fr_FR.UTF-8', 'es_ES.UTF-8', 'de_DE.UTF-8', 'ru_RU.UTF-8', 'pt_BR.UTF-8', 'it_IT.UTF-8', 'ja_JP.UTF-8', 'zh_CN.UTF-8', '0');
1054
1055
			// Check again
1056
			if (self::isNonUTF8Locale()) {
1057
				return false;
1058
			}
1059
		}
1060
1061
		return true;
1062
	}
1063
1064
	/**
1065
	 * Check if it's possible to get the inline annotations
1066
	 *
1067
	 * @return bool
1068
	 */
1069
	public static function isAnnotationsWorking() {
1070
		$reflection = new \ReflectionMethod(__METHOD__);
1071
		$docs = $reflection->getDocComment();
1072
1073
		return (is_string($docs) && strlen($docs) > 50);
1074
	}
1075
1076
	/**
1077
	 * Check if the PHP module fileinfo is loaded.
1078
	 *
1079
	 * @return bool
1080
	 */
1081
	public static function fileInfoLoaded() {
1082
		return function_exists('finfo_open');
1083
	}
1084
1085
	/**
1086
	 * clear all levels of output buffering
1087
	 *
1088
	 * @return void
1089
	 */
1090
	public static function obEnd() {
1091
		while (ob_get_level()) {
1092
			ob_end_clean();
1093
		}
1094
	}
1095
1096
	/**
1097
	 * Checks whether the server is running on Mac OS X
1098
	 *
1099
	 * @return bool true if running on Mac OS X, false otherwise
1100
	 */
1101
	public static function runningOnMac() {
1102
		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1103
	}
1104
1105
	/**
1106
	 * Handles the case that there may not be a theme, then check if a "default"
1107
	 * theme exists and take that one
1108
	 *
1109
	 * @return string the theme
1110
	 */
1111
	public static function getTheme() {
1112
		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1113
1114
		if ($theme === '') {
1115
			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1116
				$theme = 'default';
1117
			}
1118
		}
1119
1120
		return $theme;
1121
	}
1122
1123
	/**
1124
	 * Normalize a unicode string
1125
	 *
1126
	 * @param string $value a not normalized string
1127
	 * @return bool|string
1128
	 */
1129
	public static function normalizeUnicode($value) {
1130
		if (Normalizer::isNormalized($value)) {
1131
			return $value;
1132
		}
1133
1134
		$normalizedValue = Normalizer::normalize($value);
1135
		if ($normalizedValue === null || $normalizedValue === false) {
1136
			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1137
			return $value;
1138
		}
1139
1140
		return $normalizedValue;
1141
	}
1142
1143
	/**
1144
	 * A human readable string is generated based on version and build number
1145
	 *
1146
	 * @return string
1147
	 */
1148
	public static function getHumanVersion() {
1149
		$version = OC_Util::getVersionString();
1150
		$build = OC_Util::getBuild();
1151
		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1152
			$version .= ' Build:' . $build;
1153
		}
1154
		return $version;
1155
	}
1156
1157
	/**
1158
	 * Returns whether the given file name is valid
1159
	 *
1160
	 * @param string $file file name to check
1161
	 * @return bool true if the file name is valid, false otherwise
1162
	 * @deprecated use \OC\Files\View::verifyPath()
1163
	 */
1164
	public static function isValidFileName($file) {
1165
		$trimmed = trim($file);
1166
		if ($trimmed === '') {
1167
			return false;
1168
		}
1169
		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1170
			return false;
1171
		}
1172
1173
		// detect part files
1174
		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1175
			return false;
1176
		}
1177
1178
		foreach (str_split($trimmed) as $char) {
1179
			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1180
				return false;
1181
			}
1182
		}
1183
		return true;
1184
	}
1185
1186
	/**
1187
	 * Check whether the instance needs to perform an upgrade,
1188
	 * either when the core version is higher or any app requires
1189
	 * an upgrade.
1190
	 *
1191
	 * @param \OC\SystemConfig $config
1192
	 * @return bool whether the core or any app needs an upgrade
1193
	 * @throws \OCP\HintException When the upgrade from the given version is not allowed
1194
	 */
1195
	public static function needUpgrade(\OC\SystemConfig $config) {
1196
		if ($config->getValue('installed', false)) {
1197
			$installedVersion = $config->getValue('version', '0.0.0');
1198
			$currentVersion = implode('.', \OCP\Util::getVersion());
1199
			$versionDiff = version_compare($currentVersion, $installedVersion);
1200
			if ($versionDiff > 0) {
1201
				return true;
1202
			} elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1203
				// downgrade with debug
1204
				$installedMajor = explode('.', $installedVersion);
1205
				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1206
				$currentMajor = explode('.', $currentVersion);
1207
				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1208
				if ($installedMajor === $currentMajor) {
1209
					// Same major, allow downgrade for developers
1210
					return true;
1211
				} else {
1212
					// downgrade attempt, throw exception
1213
					throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1214
				}
1215
			} elseif ($versionDiff < 0) {
1216
				// downgrade attempt, throw exception
1217
				throw new \OCP\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1218
			}
1219
1220
			// also check for upgrades for apps (independently from the user)
1221
			$apps = \OC_App::getEnabledApps(false, true);
1222
			$shouldUpgrade = false;
1223
			foreach ($apps as $app) {
1224
				if (\OC_App::shouldUpgrade($app)) {
1225
					$shouldUpgrade = true;
1226
					break;
1227
				}
1228
			}
1229
			return $shouldUpgrade;
1230
		} else {
1231
			return false;
1232
		}
1233
	}
1234
}
1235