Completed
Push — master ( 9e91a7...244de6 )
by Joas
47:13 queued 38:24
created

OC_Util::copyr()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 30
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 20
nc 6
nop 2
dl 0
loc 30
rs 8.439
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Adam Williamson <[email protected]>
6
 * @author Andreas Fischer <[email protected]>
7
 * @author Arthur Schiwon <[email protected]>
8
 * @author Bart Visscher <[email protected]>
9
 * @author Bernhard Posselt <[email protected]>
10
 * @author Birk Borkason <[email protected]>
11
 * @author Björn Schießle <[email protected]>
12
 * @author Brice Maron <[email protected]>
13
 * @author Christopher Schäpers <[email protected]>
14
 * @author Christoph Wurst <[email protected]>
15
 * @author Clark Tomlinson <[email protected]>
16
 * @author cmeh <[email protected]>
17
 * @author Florin Peter <[email protected]>
18
 * @author Frank Karlitschek <[email protected]>
19
 * @author Georg Ehrke <[email protected]>
20
 * @author helix84 <[email protected]>
21
 * @author Individual IT Services <[email protected]>
22
 * @author Jakob Sack <[email protected]>
23
 * @author Joas Schilling <[email protected]>
24
 * @author Jörn Friedrich Dreyer <[email protected]>
25
 * @author Lukas Reschke <[email protected]>
26
 * @author Markus Goetz <[email protected]>
27
 * @author Martin Mattel <[email protected]>
28
 * @author Marvin Thomas Rabe <[email protected]>
29
 * @author Michael Gapczynski <[email protected]>
30
 * @author Morris Jobke <[email protected]>
31
 * @author Robin Appelman <[email protected]>
32
 * @author Robin McCorkell <[email protected]>
33
 * @author Roeland Jago Douma <[email protected]>
34
 * @author Stefan Rado <[email protected]>
35
 * @author Stefan Weil <[email protected]>
36
 * @author Thomas Müller <[email protected]>
37
 * @author Thomas Tanghus <[email protected]>
38
 * @author Victor Dubiniuk <[email protected]>
39
 * @author Vincent Petry <[email protected]>
40
 * @author Volkan Gezer <[email protected]>
41
 *
42
 * @license AGPL-3.0
43
 *
44
 * This code is free software: you can redistribute it and/or modify
45
 * it under the terms of the GNU Affero General Public License, version 3,
46
 * as published by the Free Software Foundation.
47
 *
48
 * This program is distributed in the hope that it will be useful,
49
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
50
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
51
 * GNU Affero General Public License for more details.
52
 *
53
 * You should have received a copy of the GNU Affero General Public License, version 3,
54
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
55
 *
56
 */
57
58
use OCP\IConfig;
59
use OCP\IGroupManager;
60
use OCP\IUser;
61
62
class OC_Util {
63
	public static $scripts = array();
64
	public static $styles = array();
65
	public static $headers = array();
66
	private static $rootMounted = false;
67
	private static $fsSetup = false;
68
69
	protected static function getAppManager() {
70
		return \OC::$server->getAppManager();
71
	}
72
73
	private static function initLocalStorageRootFS() {
74
		// mount local file backend as root
75
		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
76
		//first set up the local "root" storage
77
		\OC\Files\Filesystem::initMountManager();
78
		if (!self::$rootMounted) {
79
			\OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
80
			self::$rootMounted = true;
81
		}
82
	}
83
84
	/**
85
	 * mounting an object storage as the root fs will in essence remove the
86
	 * necessity of a data folder being present.
87
	 * TODO make home storage aware of this and use the object storage instead of local disk access
88
	 *
89
	 * @param array $config containing 'class' and optional 'arguments'
90
	 */
91
	private static function initObjectStoreRootFS($config) {
92
		// check misconfiguration
93
		if (empty($config['class'])) {
94
			\OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
95
		}
96
		if (!isset($config['arguments'])) {
97
			$config['arguments'] = array();
98
		}
99
100
		// instantiate object store implementation
101
		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
102
		// mount with plain / root object store implementation
103
		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
104
105
		// mount object storage as root
106
		\OC\Files\Filesystem::initMountManager();
107
		if (!self::$rootMounted) {
108
			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
109
			self::$rootMounted = true;
110
		}
111
	}
112
113
	/**
114
	 * Can be set up
115
	 *
116
	 * @param string $user
117
	 * @return boolean
118
	 * @description configure the initial filesystem based on the configuration
119
	 */
120
	public static function setupFS($user = '') {
121
		//setting up the filesystem twice can only lead to trouble
122
		if (self::$fsSetup) {
123
			return false;
124
		}
125
126
		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
127
128
		// If we are not forced to load a specific user we load the one that is logged in
129
		if ($user === null) {
130
			$user = '';
131
		} else if ($user == "" && OC_User::isLoggedIn()) {
0 ignored issues
show
Deprecated Code introduced by
The method OC_User::isLoggedIn() has been deprecated with message: use \OC::$server->getUserSession()->isLoggedIn()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
132
			$user = OC_User::getUser();
133
		}
134
135
		// load all filesystem apps before, so no setup-hook gets lost
136
		OC_App::loadApps(array('filesystem'));
137
138
		// the filesystem will finish when $user is not empty,
139
		// mark fs setup here to avoid doing the setup from loading
140
		// OC_Filesystem
141
		if ($user != '') {
142
			self::$fsSetup = true;
143
		}
144
145
		\OC\Files\Filesystem::initMountManager();
146
147
		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
148
		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
149
			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
150
				/** @var \OC\Files\Storage\Common $storage */
151
				$storage->setMountOptions($mount->getOptions());
152
			}
153
			return $storage;
154
		});
155
156
		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
157
			if (!$mount->getOption('enable_sharing', true)) {
158
				return new \OC\Files\Storage\Wrapper\PermissionsMask([
159
					'storage' => $storage,
160
					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
161
				]);
162
			}
163
			return $storage;
164
		});
165
166
		// install storage availability wrapper, before most other wrappers
167
		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, $storage) {
168
			/** @var \OCP\Files\Storage $storage */
169
			if (!$storage->instanceOfStorage('\OC\Files\Storage\Shared') && !$storage->isLocal()) {
170
				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
171
			}
172
			return $storage;
173
		});
174
175
		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
176
			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OC\Files\Storage\Shared') && !$storage->isLocal()) {
177
				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
178
			}
179
			return $storage;
180
		});
181
182
		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
183
			// set up quota for home storages, even for other users
184
			// which can happen when using sharing
185
186
			/**
187
			 * @var \OC\Files\Storage\Storage $storage
188
			 */
189
			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
190
				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
191
			) {
192
				/** @var \OC\Files\Storage\Home $storage */
193
				if (is_object($storage->getUser())) {
194
					$user = $storage->getUser()->getUID();
195
					$quota = OC_Util::getUserQuota($user);
196
					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
197
						return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
198
					}
199
				}
200
			}
201
202
			return $storage;
203
		});
204
205
		OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
206
		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
207
208
		//check if we are using an object storage
209
		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
210
		if (isset($objectStore)) {
211
			self::initObjectStoreRootFS($objectStore);
212
		} else {
213
			self::initLocalStorageRootFS();
214
		}
215
216
		if ($user != '' && !OCP\User::userExists($user)) {
0 ignored issues
show
Deprecated Code introduced by
The method OCP\User::userExists() has been deprecated with message: 8.1.0 use method userExists() of \OCP\IUserManager - \OC::$server->getUserManager()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
217
			\OC::$server->getEventLogger()->end('setup_fs');
218
			return false;
219
		}
220
221
		//if we aren't logged in, there is no use to set up the filesystem
222
		if ($user != "") {
223
224
			$userDir = '/' . $user . '/files';
225
226
			//jail the user into his "home" directory
227
			\OC\Files\Filesystem::init($user, $userDir);
228
229
			OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
230
		}
231
		\OC::$server->getEventLogger()->end('setup_fs');
232
		return true;
233
	}
234
235
	/**
236
	 * check if a password is required for each public link
237
	 *
238
	 * @return boolean
239
	 */
240
	public static function isPublicLinkPasswordRequired() {
241
		$appConfig = \OC::$server->getAppConfig();
242
		$enforcePassword = $appConfig->getValue('core', 'shareapi_enforce_links_password', 'no');
0 ignored issues
show
Deprecated Code introduced by
The method OCP\IAppConfig::getValue() has been deprecated with message: 8.0.0 use method getAppValue of \OCP\IConfig This function gets a value from the appconfig table. If the key does
not exist the default value will be returned

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
243
		return ($enforcePassword === 'yes') ? true : false;
244
	}
245
246
	/**
247
	 * check if sharing is disabled for the current user
248
	 * @param IConfig $config
249
	 * @param IGroupManager $groupManager
250
	 * @param IUser|null $user
251
	 * @return bool
252
	 */
253
	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
254
		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
255
			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
256
			$excludedGroups = json_decode($groupsList);
257 View Code Duplication
			if (is_null($excludedGroups)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
258
				$excludedGroups = explode(',', $groupsList);
259
				$newValue = json_encode($excludedGroups);
260
				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
261
			}
262
			$usersGroups = $groupManager->getUserGroupIds($user);
0 ignored issues
show
Bug introduced by
It seems like $user defined by parameter $user on line 253 can be null; however, OCP\IGroupManager::getUserGroupIds() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
263 View Code Duplication
			if (!empty($usersGroups)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
264
				$remainingGroups = array_diff($usersGroups, $excludedGroups);
265
				// if the user is only in groups which are disabled for sharing then
266
				// sharing is also disabled for the user
267
				if (empty($remainingGroups)) {
268
					return true;
269
				}
270
			}
271
		}
272
		return false;
273
	}
274
275
	/**
276
	 * check if share API enforces a default expire date
277
	 *
278
	 * @return boolean
279
	 */
280
	public static function isDefaultExpireDateEnforced() {
281
		$isDefaultExpireDateEnabled = \OCP\Config::getAppValue('core', 'shareapi_default_expire_date', 'no');
0 ignored issues
show
Deprecated Code introduced by
The method OCP\Config::getAppValue() has been deprecated with message: 8.0.0 use method getAppValue of \OCP\IConfig This function gets a value from the appconfig table. If the key does
not exist the default value will be returned

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
282
		$enforceDefaultExpireDate = false;
283
		if ($isDefaultExpireDateEnabled === 'yes') {
284
			$value = \OCP\Config::getAppValue('core', 'shareapi_enforce_expire_date', 'no');
0 ignored issues
show
Deprecated Code introduced by
The method OCP\Config::getAppValue() has been deprecated with message: 8.0.0 use method getAppValue of \OCP\IConfig This function gets a value from the appconfig table. If the key does
not exist the default value will be returned

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
285
			$enforceDefaultExpireDate = ($value === 'yes') ? true : false;
286
		}
287
288
		return $enforceDefaultExpireDate;
289
	}
290
291
	/**
292
	 * Get the quota of a user
293
	 *
294
	 * @param string $userId
295
	 * @return int Quota bytes
296
	 */
297
	public static function getUserQuota($userId) {
298
		$user = \OC::$server->getUserManager()->get($userId);
299
		if (is_null($user)) {
300
			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
301
		}
302
		$userQuota = $user->getQuota();
303
		if($userQuota === 'none') {
304
			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
305
		}
306
		return OC_Helper::computerFileSize($userQuota);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression \OC_Helper::computerFileSize($userQuota); of type double|false adds false to the return on line 306 which is incompatible with the return type documented by OC_Util::getUserQuota of type integer. It seems like you forgot to handle an error condition.
Loading history...
307
	}
308
309
	/**
310
	 * copies the skeleton to the users /files
311
	 *
312
	 * @param String $userId
313
	 * @param \OCP\Files\Folder $userDirectory
314
	 */
315
	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
316
317
		$skeletonDirectory = \OCP\Config::getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
0 ignored issues
show
Deprecated Code introduced by
The method OCP\Config::getSystemValue() has been deprecated with message: 8.0.0 use method getSystemValue of \OCP\IConfig This function gets the value from config.php. If it does not exist,
$default will be returned.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
318
319
		if (!empty($skeletonDirectory)) {
320
			\OCP\Util::writeLog(
321
				'files_skeleton',
322
				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
323
				\OCP\Util::DEBUG
324
			);
325
			self::copyr($skeletonDirectory, $userDirectory);
326
			// update the file cache
327
			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
328
		}
329
	}
330
331
	/**
332
	 * copies a directory recursively by using streams
333
	 *
334
	 * @param string $source
335
	 * @param \OCP\Files\Folder $target
336
	 * @return void
337
	 */
338
	public static function copyr($source, \OCP\Files\Folder $target) {
339
		$logger = \OC::$server->getLogger();
340
341
		// Verify if folder exists
342
		$dir = opendir($source);
343
		if($dir === false) {
344
			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
345
			return;
346
		}
347
348
		// Copy the files
349
		while (false !== ($file = readdir($dir))) {
350
			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
351
				if (is_dir($source . '/' . $file)) {
352
					$child = $target->newFolder($file);
353
					self::copyr($source . '/' . $file, $child);
354
				} else {
355
					$child = $target->newFile($file);
356
					$sourceStream = fopen($source . '/' . $file, 'r');
357
					if($sourceStream === false) {
358
						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
359
						closedir($dir);
360
						return;
361
					}
362
					stream_copy_to_stream($sourceStream, $child->fopen('w'));
363
				}
364
			}
365
		}
366
		closedir($dir);
367
	}
368
369
	/**
370
	 * @return void
371
	 */
372
	public static function tearDownFS() {
373
		\OC\Files\Filesystem::tearDown();
374
		\OC::$server->getRootFolder()->clearCache();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface OCP\Files\IRootFolder as the method clearCache() does only exist in the following implementations of said interface: OC\Files\Node\Root.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
375
		self::$fsSetup = false;
376
		self::$rootMounted = false;
377
	}
378
379
	/**
380
	 * get the current installed version of ownCloud
381
	 *
382
	 * @return array
383
	 */
384
	public static function getVersion() {
385
		OC_Util::loadVersion();
386
		return \OC::$server->getSession()->get('OC_Version');
387
	}
388
389
	/**
390
	 * get the current installed version string of ownCloud
391
	 *
392
	 * @return string
393
	 */
394
	public static function getVersionString() {
395
		OC_Util::loadVersion();
396
		return \OC::$server->getSession()->get('OC_VersionString');
397
	}
398
399
	/**
400
	 * @deprecated the value is of no use anymore
401
	 * @return string
402
	 */
403
	public static function getEditionString() {
404
		return '';
405
	}
406
407
	/**
408
	 * @description get the update channel of the current installed of ownCloud.
409
	 * @return string
410
	 */
411
	public static function getChannel() {
412
		OC_Util::loadVersion();
413
		return \OC::$server->getSession()->get('OC_Channel');
414
	}
415
416
	/**
417
	 * @description get the build number of the current installed of ownCloud.
418
	 * @return string
419
	 */
420
	public static function getBuild() {
421
		OC_Util::loadVersion();
422
		return \OC::$server->getSession()->get('OC_Build');
423
	}
424
425
	/**
426
	 * @description load the version.php into the session as cache
427
	 */
428
	private static function loadVersion() {
429
		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
430
		if (!\OC::$server->getSession()->exists('OC_Version') or OC::$server->getSession()->get('OC_Version_Timestamp') != $timestamp) {
431
			require OC::$SERVERROOT . '/version.php';
432
			$session = \OC::$server->getSession();
433
			/** @var $timestamp int */
434
			$session->set('OC_Version_Timestamp', $timestamp);
435
			/** @var $OC_Version string */
436
			$session->set('OC_Version', $OC_Version);
0 ignored issues
show
Bug introduced by
The variable $OC_Version does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
437
			/** @var $OC_VersionString string */
438
			$session->set('OC_VersionString', $OC_VersionString);
0 ignored issues
show
Bug introduced by
The variable $OC_VersionString does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
439
			/** @var $OC_Build string */
440
			$session->set('OC_Build', $OC_Build);
0 ignored issues
show
Bug introduced by
The variable $OC_Build does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
441
			
442
			// Allow overriding update channel
443
			
444 View Code Duplication
			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
445
				$channel = \OC::$server->getAppConfig()->getValue('core', 'OC_Channel');
0 ignored issues
show
Deprecated Code introduced by
The method OCP\IAppConfig::getValue() has been deprecated with message: 8.0.0 use method getAppValue of \OCP\IConfig This function gets a value from the appconfig table. If the key does
not exist the default value will be returned

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
446
			} else {
447
				/** @var $OC_Channel string */
448
				$channel = $OC_Channel;
0 ignored issues
show
Bug introduced by
The variable $OC_Channel does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
449
			}
450
			
451
			if (!is_null($channel)) {
452
				$session->set('OC_Channel', $channel);
453
			} else {
454
				/** @var $OC_Channel string */
455
				$session->set('OC_Channel', $OC_Channel);
456
			}
457
		}
458
	}
459
460
	/**
461
	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
462
	 *
463
	 * @param string $application application to get the files from
464
	 * @param string $directory directory within this application (css, js, vendor, etc)
465
	 * @param string $file the file inside of the above folder
466
	 * @return string the path
467
	 */
468
	private static function generatePath($application, $directory, $file) {
469
		if (is_null($file)) {
470
			$file = $application;
471
			$application = "";
472
		}
473
		if (!empty($application)) {
474
			return "$application/$directory/$file";
475
		} else {
476
			return "$directory/$file";
477
		}
478
	}
479
480
	/**
481
	 * add a javascript file
482
	 *
483
	 * @param string $application application id
484
	 * @param string|null $file filename
485
	 * @param bool $prepend prepend the Script to the beginning of the list
486
	 * @return void
487
	 */
488
	public static function addScript($application, $file = null, $prepend = false) {
489
		$path = OC_Util::generatePath($application, 'js', $file);
490
491
		// core js files need separate handling
492
		if ($application !== 'core' && $file !== null) {
493
			self::addTranslations ( $application );
494
		}
495
		self::addExternalResource($application, $prepend, $path, "script");
496
	}
497
498
	/**
499
	 * add a javascript file from the vendor sub folder
500
	 *
501
	 * @param string $application application id
502
	 * @param string|null $file filename
503
	 * @param bool $prepend prepend the Script to the beginning of the list
504
	 * @return void
505
	 */
506
	public static function addVendorScript($application, $file = null, $prepend = false) {
507
		$path = OC_Util::generatePath($application, 'vendor', $file);
508
		self::addExternalResource($application, $prepend, $path, "script");
509
	}
510
511
	/**
512
	 * add a translation JS file
513
	 *
514
	 * @param string $application application id
515
	 * @param string $languageCode language code, defaults to the current language
516
	 * @param bool $prepend prepend the Script to the beginning of the list 
517
	 */
518
	public static function addTranslations($application, $languageCode = null, $prepend = false) {
519
		if (is_null($languageCode)) {
520
			$languageCode = \OC_L10N::findLanguage($application);
0 ignored issues
show
Deprecated Code introduced by
The method OC_L10N::findLanguage() has been deprecated with message: 9.0.0 Use \OC::$server->getL10NFactory()->findLanguage() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
521
		}
522
		if (!empty($application)) {
523
			$path = "$application/l10n/$languageCode";
524
		} else {
525
			$path = "l10n/$languageCode";
526
		}
527
		self::addExternalResource($application, $prepend, $path, "script");
528
	}
529
530
	/**
531
	 * add a css file
532
	 *
533
	 * @param string $application application id
534
	 * @param string|null $file filename
535
	 * @param bool $prepend prepend the Style to the beginning of the list
536
	 * @return void
537
	 */
538
	public static function addStyle($application, $file = null, $prepend = false) {
539
		$path = OC_Util::generatePath($application, 'css', $file);
540
		self::addExternalResource($application, $prepend, $path, "style");
541
	}
542
543
	/**
544
	 * add a css file from the vendor sub folder
545
	 *
546
	 * @param string $application application id
547
	 * @param string|null $file filename
548
	 * @param bool $prepend prepend the Style to the beginning of the list
549
	 * @return void
550
	 */
551
	public static function addVendorStyle($application, $file = null, $prepend = false) {
552
		$path = OC_Util::generatePath($application, 'vendor', $file);
553
		self::addExternalResource($application, $prepend, $path, "style");
554
	}
555
556
	/**
557
	 * add an external resource css/js file
558
	 *
559
	 * @param string $application application id
560
	 * @param bool $prepend prepend the file to the beginning of the list
561
	 * @param string $path 
562
	 * @param string $type (script or style)
563
	 * @return void
564
	 */
565
	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.

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

Loading history...
566
567
		if ($type === "style") {
568 View Code Duplication
			if (!in_array($path, self::$styles)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
569
				if ($prepend === true) {
570
					array_unshift ( self::$styles, $path );
571
				} else {
572
					self::$styles[] = $path;
573
				}
574
			}
575 View Code Duplication
		} elseif ($type === "script") {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
576
			if (!in_array($path, self::$scripts)) {
577
				if ($prepend === true) {
578
					array_unshift ( self::$scripts, $path );
579
				} else {
580
					self::$scripts [] = $path;
581
				}
582
			}
583
		}
584
	}
585
586
	/**
587
	 * Add a custom element to the header
588
	 * If $text is null then the element will be written as empty element.
589
	 * So use "" to get a closing tag.
590
	 * @param string $tag tag name of the element
591
	 * @param array $attributes array of attributes for the element
592
	 * @param string $text the text content for the element
593
	 */
594 View Code Duplication
	public static function addHeader($tag, $attributes, $text=null) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
595
		self::$headers[] = array(
596
			'tag' => $tag,
597
			'attributes' => $attributes,
598
			'text' => $text
599
		);
600
	}
601
602
	/**
603
	 * formats a timestamp in the "right" way
604
	 *
605
	 * @param int $timestamp
606
	 * @param bool $dateOnly option to omit time from the result
607
	 * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
608
	 * @return string timestamp
609
	 *
610
	 * @deprecated Use \OC::$server->query('DateTimeFormatter') instead
611
	 */
612
	public static function formatDate($timestamp, $dateOnly = false, $timeZone = null) {
613
		if ($timeZone !== null && !$timeZone instanceof \DateTimeZone) {
614
			$timeZone = new \DateTimeZone($timeZone);
615
		}
616
617
		/** @var \OC\DateTimeFormatter $formatter */
618
		$formatter = \OC::$server->query('DateTimeFormatter');
619
		if ($dateOnly) {
620
			return $formatter->formatDate($timestamp, 'long', $timeZone);
621
		}
622
		return $formatter->formatDateTime($timestamp, 'long', 'long', $timeZone);
623
	}
624
625
	/**
626
	 * check if the current server configuration is suitable for ownCloud
627
	 *
628
	 * @param \OCP\IConfig $config
629
	 * @return array arrays with error messages and hints
630
	 */
631
	public static function checkServer(\OCP\IConfig $config) {
632
		$l = \OC::$server->getL10N('lib');
633
		$errors = array();
634
		$CONFIG_DATADIRECTORY = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data');
635
636
		if (!self::needUpgrade($config) && $config->getSystemValue('installed', false)) {
637
			// this check needs to be done every time
638
			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
639
		}
640
641
		// Assume that if checkServer() succeeded before in this session, then all is fine.
642
		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
643
			return $errors;
644
		}
645
646
		$webServerRestart = false;
647
		$setup = new \OC\Setup($config, \OC::$server->getIniWrapper(), \OC::$server->getL10N('lib'),
648
			\OC::$server->getThemingDefaults(), \OC::$server->getLogger(), \OC::$server->getSecureRandom());
649
650
		$urlGenerator = \OC::$server->getURLGenerator();
651
652
		$availableDatabases = $setup->getSupportedDatabases();
653
		if (empty($availableDatabases)) {
654
			$errors[] = array(
655
				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
656
				'hint' => '' //TODO: sane hint
657
			);
658
			$webServerRestart = true;
659
		}
660
661
		// Check if server running on Windows platform
662 View Code Duplication
		if(OC_Util::runningOnWindows()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
663
			$errors[] = [
664
				'error' => $l->t('Microsoft Windows Platform is not supported'),
665
				'hint' => $l->t('Running Nextcloud Server on the Microsoft Windows platform is not supported. We suggest you ' .
666
					'use a Linux server in a virtual machine if you have no option for migrating the server itself.')
667
			];
668
		}
669
670
		// Check if config folder is writable.
671
		if(!OC_Helper::isReadOnlyConfigEnabled()) {
672
			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
673
				$errors[] = array(
674
					'error' => $l->t('Cannot write into "config" directory'),
675
					'hint' => $l->t('This can usually be fixed by '
676
						. '%sgiving the webserver write access to the config directory%s.',
677
						array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>'))
678
				);
679
			}
680
		}
681
682
		// Check if there is a writable install folder.
683
		if ($config->getSystemValue('appstoreenabled', true)) {
684
			if (OC_App::getInstallPath() === null
685
				|| !is_writable(OC_App::getInstallPath())
686
				|| !is_readable(OC_App::getInstallPath())
687
			) {
688
				$errors[] = array(
689
					'error' => $l->t('Cannot write into "apps" directory'),
690
					'hint' => $l->t('This can usually be fixed by '
691
						. '%sgiving the webserver write access to the apps directory%s'
692
						. ' or disabling the appstore in the config file.',
693
						array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>'))
694
				);
695
			}
696
		}
697
		// Create root dir.
698
		if ($config->getSystemValue('installed', false)) {
699
			if (!is_dir($CONFIG_DATADIRECTORY)) {
700
				$success = @mkdir($CONFIG_DATADIRECTORY);
701
				if ($success) {
702
					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
703
				} else {
704
					$errors[] = array(
705
						'error' => $l->t('Cannot create "data" directory (%s)', array($CONFIG_DATADIRECTORY)),
706
						'hint' => $l->t('This can usually be fixed by '
707
							. '<a href="%s" target="_blank" rel="noreferrer">giving the webserver write access to the root directory</a>.',
708
							array($urlGenerator->linkToDocs('admin-dir_permissions')))
709
					);
710
				}
711
			} else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
712
				//common hint for all file permissions error messages
713
				$permissionsHint = $l->t('Permissions can usually be fixed by '
714
					. '%sgiving the webserver write access to the root directory%s.',
715
					array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>'));
716
				$errors[] = array(
717
					'error' => 'Data directory (' . $CONFIG_DATADIRECTORY . ') not writable',
718
					'hint' => $permissionsHint
719
				);
720
			} else {
721
				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
722
			}
723
		}
724
725 View Code Duplication
		if (!OC_Util::isSetLocaleWorking()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
726
			$errors[] = array(
727
				'error' => $l->t('Setting locale to %s failed',
728
					array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
729
						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
730
				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
731
			);
732
		}
733
734
		// Contains the dependencies that should be checked against
735
		// classes = class_exists
736
		// functions = function_exists
737
		// defined = defined
738
		// ini = ini_get
739
		// If the dependency is not found the missing module name is shown to the EndUser
740
		// When adding new checks always verify that they pass on Travis as well
741
		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
742
		$dependencies = array(
743
			'classes' => array(
744
				'ZipArchive' => 'zip',
745
				'DOMDocument' => 'dom',
746
				'XMLWriter' => 'XMLWriter',
747
				'XMLReader' => 'XMLReader',
748
			),
749
			'functions' => [
750
				'xml_parser_create' => 'libxml',
751
				'mb_strcut' => 'mb multibyte',
752
				'ctype_digit' => 'ctype',
753
				'json_encode' => 'JSON',
754
				'gd_info' => 'GD',
755
				'gzencode' => 'zlib',
756
				'iconv' => 'iconv',
757
				'simplexml_load_string' => 'SimpleXML',
758
				'hash' => 'HASH Message Digest Framework',
759
				'curl_init' => 'cURL',
760
			],
761
			'defined' => array(
762
				'PDO::ATTR_DRIVER_NAME' => 'PDO'
763
			),
764
			'ini' => [
765
				'default_charset' => 'UTF-8',
766
			],
767
		);
768
		$missingDependencies = array();
769
		$invalidIniSettings = [];
770
		$moduleHint = $l->t('Please ask your server administrator to install the module.');
771
772
		/**
773
		 * FIXME: The dependency check does not work properly on HHVM on the moment
774
		 *        and prevents installation. Once HHVM is more compatible with our
775
		 *        approach to check for these values we should re-enable those
776
		 *        checks.
777
		 */
778
		$iniWrapper = \OC::$server->getIniWrapper();
779
		if (!self::runningOnHhvm()) {
780
			foreach ($dependencies['classes'] as $class => $module) {
781
				if (!class_exists($class)) {
782
					$missingDependencies[] = $module;
783
				}
784
			}
785
			foreach ($dependencies['functions'] as $function => $module) {
786
				if (!function_exists($function)) {
787
					$missingDependencies[] = $module;
788
				}
789
			}
790
			foreach ($dependencies['defined'] as $defined => $module) {
791
				if (!defined($defined)) {
792
					$missingDependencies[] = $module;
793
				}
794
			}
795
			foreach ($dependencies['ini'] as $setting => $expected) {
796
				if (is_bool($expected)) {
797
					if ($iniWrapper->getBool($setting) !== $expected) {
798
						$invalidIniSettings[] = [$setting, $expected];
799
					}
800
				}
801
				if (is_int($expected)) {
802
					if ($iniWrapper->getNumeric($setting) !== $expected) {
803
						$invalidIniSettings[] = [$setting, $expected];
804
					}
805
				}
806
				if (is_string($expected)) {
807
					if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
808
						$invalidIniSettings[] = [$setting, $expected];
809
					}
810
				}
811
			}
812
		}
813
814
		foreach($missingDependencies as $missingDependency) {
815
			$errors[] = array(
816
				'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
817
				'hint' => $moduleHint
818
			);
819
			$webServerRestart = true;
820
		}
821
		foreach($invalidIniSettings as $setting) {
822
			if(is_bool($setting[1])) {
823
				$setting[1] = ($setting[1]) ? 'on' : 'off';
824
			}
825
			$errors[] = [
826
				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
827
				'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
828
			];
829
			$webServerRestart = true;
830
		}
831
832
		/**
833
		 * The mbstring.func_overload check can only be performed if the mbstring
834
		 * module is installed as it will return null if the checking setting is
835
		 * not available and thus a check on the boolean value fails.
836
		 *
837
		 * TODO: Should probably be implemented in the above generic dependency
838
		 *       check somehow in the long-term.
839
		 */
840
		if($iniWrapper->getBool('mbstring.func_overload') !== null &&
841
			$iniWrapper->getBool('mbstring.func_overload') === true) {
842
			$errors[] = array(
843
				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
844
				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
845
			);
846
		}
847
848
		if(function_exists('xml_parser_create') &&
849
			LIBXML_LOADED_VERSION < 20700 ) {
850
			$version = LIBXML_LOADED_VERSION;
851
			$major = floor($version/10000);
852
			$version -= ($major * 10000);
853
			$minor = floor($version/100);
854
			$version -= ($minor * 100);
855
			$patch = $version;
856
			$errors[] = array(
857
				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
858
				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
859
			);
860
		}
861
862
		if (!self::isAnnotationsWorking()) {
863
			$errors[] = array(
864
				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
865
				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
866
			);
867
		}
868
869
		if (!\OC::$CLI && $webServerRestart) {
870
			$errors[] = array(
871
				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
872
				'hint' => $l->t('Please ask your server administrator to restart the web server.')
873
			);
874
		}
875
876
		$errors = array_merge($errors, self::checkDatabaseVersion());
877
878
		// Cache the result of this function
879
		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
880
881
		return $errors;
882
	}
883
884
	/**
885
	 * Check the database version
886
	 *
887
	 * @return array errors array
888
	 */
889
	public static function checkDatabaseVersion() {
890
		$l = \OC::$server->getL10N('lib');
891
		$errors = array();
892
		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
893
		if ($dbType === 'pgsql') {
894
			// check PostgreSQL version
895
			try {
896
				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
897
				$data = $result->fetchRow();
898
				if (isset($data['server_version'])) {
899
					$version = $data['server_version'];
900
					if (version_compare($version, '9.0.0', '<')) {
901
						$errors[] = array(
902
							'error' => $l->t('PostgreSQL >= 9 required'),
903
							'hint' => $l->t('Please upgrade your database version')
904
						);
905
					}
906
				}
907
			} catch (\Doctrine\DBAL\DBALException $e) {
0 ignored issues
show
Bug introduced by
The class Doctrine\DBAL\DBALException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
908
				$logger = \OC::$server->getLogger();
909
				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
910
				$logger->logException($e);
911
			}
912
		}
913
		return $errors;
914
	}
915
916
	/**
917
	 * Check for correct file permissions of data directory
918
	 *
919
	 * @param string $dataDirectory
920
	 * @return array arrays with error messages and hints
921
	 */
922
	public static function checkDataDirectoryPermissions($dataDirectory) {
923
		$l = \OC::$server->getL10N('lib');
924
		$errors = array();
925
		$permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
926
			. ' cannot be listed by other users.');
927
		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
928
		if (substr($perms, -1) != '0') {
929
			chmod($dataDirectory, 0770);
930
			clearstatcache();
931
			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
932 View Code Duplication
			if (substr($perms, 2, 1) != '0') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
933
				$errors[] = array(
934
					'error' => $l->t('Data directory (%s) is readable by other users', array($dataDirectory)),
935
					'hint' => $permissionsModHint
936
				);
937
			}
938
		}
939
		return $errors;
940
	}
941
942
	/**
943
	 * Check that the data directory exists and is valid by
944
	 * checking the existence of the ".ocdata" file.
945
	 *
946
	 * @param string $dataDirectory data directory path
947
	 * @return array errors found
948
	 */
949
	public static function checkDataDirectoryValidity($dataDirectory) {
950
		$l = \OC::$server->getL10N('lib');
951
		$errors = [];
952 View Code Duplication
		if ($dataDirectory[0] !== '/') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
953
			$errors[] = [
954
				'error' => $l->t('Data directory (%s) must be an absolute path', [$dataDirectory]),
955
				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
956
			];
957
		}
958 View Code Duplication
		if (!file_exists($dataDirectory . '/.ocdata')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
959
			$errors[] = [
960
				'error' => $l->t('Data directory (%s) is invalid', [$dataDirectory]),
961
				'hint' => $l->t('Please check that the data directory contains a file' .
962
					' ".ocdata" in its root.')
963
			];
964
		}
965
		return $errors;
966
	}
967
968
	/**
969
	 * Check if the user is logged in, redirects to home if not. With
970
	 * redirect URL parameter to the request URI.
971
	 *
972
	 * @return void
973
	 */
974
	public static function checkLoggedIn() {
975
		// Check if we are a user
976
		if (!OC_User::isLoggedIn()) {
0 ignored issues
show
Deprecated Code introduced by
The method OC_User::isLoggedIn() has been deprecated with message: use \OC::$server->getUserSession()->isLoggedIn()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
977
			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
978
						'core.login.showLoginForm',
979
						[
980
							'redirect_url' => urlencode(\OC::$server->getRequest()->getRequestUri()),
981
						]
982
					)
983
			);
984
			exit();
985
		}
986
		// Redirect to index page if 2FA challenge was not solved yet
987
		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
988
			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
989
			exit();
990
		}
991
	}
992
993
	/**
994
	 * Check if the user is a admin, redirects to home if not
995
	 *
996
	 * @return void
997
	 */
998
	public static function checkAdminUser() {
999
		OC_Util::checkLoggedIn();
1000
		if (!OC_User::isAdminUser(OC_User::getUser())) {
1001
			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1002
			exit();
1003
		}
1004
	}
1005
1006
	/**
1007
	 * Check if it is allowed to remember login.
1008
	 *
1009
	 * @note Every app can set 'rememberlogin' to 'false' to disable the remember login feature
1010
	 *
1011
	 * @return bool
1012
	 */
1013
	public static function rememberLoginAllowed() {
1014
1015
		$apps = OC_App::getEnabledApps();
1016
1017
		foreach ($apps as $app) {
1018
			$appInfo = OC_App::getAppInfo($app);
1019
			if (isset($appInfo['rememberlogin']) && $appInfo['rememberlogin'] === 'false') {
1020
				return false;
1021
			}
1022
1023
		}
1024
		return true;
1025
	}
1026
1027
	/**
1028
	 * Check if the user is a subadmin, redirects to home if not
1029
	 *
1030
	 * @return null|boolean $groups where the current user is subadmin
1031
	 */
1032
	public static function checkSubAdminUser() {
1033
		OC_Util::checkLoggedIn();
1034
		$userObject = \OC::$server->getUserSession()->getUser();
1035
		$isSubAdmin = false;
1036
		if($userObject !== null) {
1037
			$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1038
		}
1039
1040
		if (!$isSubAdmin) {
1041
			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1042
			exit();
1043
		}
1044
		return true;
1045
	}
1046
1047
	/**
1048
	 * Returns the URL of the default page
1049
	 * based on the system configuration and
1050
	 * the apps visible for the current user
1051
	 *
1052
	 * @return string URL
1053
	 */
1054
	public static function getDefaultPageUrl() {
1055
		$urlGenerator = \OC::$server->getURLGenerator();
1056
		// Deny the redirect if the URL contains a @
1057
		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1058
		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1059
			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1060
		} else {
1061
			$defaultPage = \OC::$server->getAppConfig()->getValue('core', 'defaultpage');
0 ignored issues
show
Deprecated Code introduced by
The method OCP\IAppConfig::getValue() has been deprecated with message: 8.0.0 use method getAppValue of \OCP\IConfig This function gets a value from the appconfig table. If the key does
not exist the default value will be returned

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1062
			if ($defaultPage) {
1063
				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1064
			} else {
1065
				$appId = 'files';
1066
				$defaultApps = explode(',', \OCP\Config::getSystemValue('defaultapp', 'files'));
0 ignored issues
show
Deprecated Code introduced by
The method OCP\Config::getSystemValue() has been deprecated with message: 8.0.0 use method getSystemValue of \OCP\IConfig This function gets the value from config.php. If it does not exist,
$default will be returned.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1067
				// find the first app that is enabled for the current user
1068
				foreach ($defaultApps as $defaultApp) {
1069
					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1070
					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1071
						$appId = $defaultApp;
1072
						break;
1073
					}
1074
				}
1075
1076
				if(getenv('front_controller_active') === 'true') {
1077
					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1078
				} else {
1079
					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1080
				}
1081
			}
1082
		}
1083
		return $location;
1084
	}
1085
1086
	/**
1087
	 * Redirect to the user default page
1088
	 *
1089
	 * @return void
1090
	 */
1091
	public static function redirectToDefaultPage() {
1092
		$location = self::getDefaultPageUrl();
1093
		header('Location: ' . $location);
1094
		exit();
1095
	}
1096
1097
	/**
1098
	 * get an id unique for this instance
1099
	 *
1100
	 * @return string
1101
	 */
1102
	public static function getInstanceId() {
1103
		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1104
		if (is_null($id)) {
1105
			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1106
			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1107
			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1108
		}
1109
		return $id;
1110
	}
1111
1112
	/**
1113
	 * Public function to sanitize HTML
1114
	 *
1115
	 * This function is used to sanitize HTML and should be applied on any
1116
	 * string or array of strings before displaying it on a web page.
1117
	 *
1118
	 * @param string|array $value
1119
	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1120
	 */
1121
	public static function sanitizeHTML($value) {
1122
		if (is_array($value)) {
1123
			$value = array_map(function($value) {
1124
				return self::sanitizeHTML($value);
1125
			}, $value);
1126
		} else {
1127
			// Specify encoding for PHP<5.4
1128
			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1129
		}
1130
		return $value;
1131
	}
1132
1133
	/**
1134
	 * Public function to encode url parameters
1135
	 *
1136
	 * This function is used to encode path to file before output.
1137
	 * Encoding is done according to RFC 3986 with one exception:
1138
	 * Character '/' is preserved as is.
1139
	 *
1140
	 * @param string $component part of URI to encode
1141
	 * @return string
1142
	 */
1143
	public static function encodePath($component) {
1144
		$encoded = rawurlencode($component);
1145
		$encoded = str_replace('%2F', '/', $encoded);
1146
		return $encoded;
1147
	}
1148
1149
1150
	public function createHtaccessTestFile(\OCP\IConfig $config) {
1151
		// php dev server does not support htaccess
1152
		if (php_sapi_name() === 'cli-server') {
1153
			return false;
1154
		}
1155
1156
		// testdata
1157
		$fileName = '/htaccesstest.txt';
1158
		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1159
1160
		// creating a test file
1161
		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1162
1163
		if (file_exists($testFile)) {// already running this test, possible recursive call
1164
			return false;
1165
		}
1166
1167
		$fp = @fopen($testFile, 'w');
1168
		if (!$fp) {
1169
			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1170
				'Make sure it is possible for the webserver to write to ' . $testFile);
1171
		}
1172
		fwrite($fp, $testContent);
1173
		fclose($fp);
1174
	}
1175
1176
	/**
1177
	 * Check if the .htaccess file is working
1178
	 * @param \OCP\IConfig $config
1179
	 * @return bool
1180
	 * @throws Exception
1181
	 * @throws \OC\HintException If the test file can't get written.
1182
	 */
1183
	public function isHtaccessWorking(\OCP\IConfig $config) {
1184
1185
		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1186
			return true;
1187
		}
1188
1189
		$testContent = $this->createHtaccessTestFile($config);
1190
		if ($testContent === false) {
1191
			return false;
1192
		}
1193
1194
		$fileName = '/htaccesstest.txt';
1195
		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1196
1197
		// accessing the file via http
1198
		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1199
		try {
1200
			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1201
		} catch (\Exception $e) {
1202
			$content = false;
1203
		}
1204
1205
		// cleanup
1206
		@unlink($testFile);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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...
1207
1208
		/*
1209
		 * If the content is not equal to test content our .htaccess
1210
		 * is working as required
1211
		 */
1212
		return $content !== $testContent;
1213
	}
1214
1215
	/**
1216
	 * Check if the setlocal call does not work. This can happen if the right
1217
	 * local packages are not available on the server.
1218
	 *
1219
	 * @return bool
1220
	 */
1221
	public static function isSetLocaleWorking() {
1222
		\Patchwork\Utf8\Bootup::initLocale();
1223
		if ('' === basename('§')) {
1224
			return false;
1225
		}
1226
		return true;
1227
	}
1228
1229
	/**
1230
	 * Check if it's possible to get the inline annotations
1231
	 *
1232
	 * @return bool
1233
	 */
1234
	public static function isAnnotationsWorking() {
1235
		$reflection = new \ReflectionMethod(__METHOD__);
1236
		$docs = $reflection->getDocComment();
1237
1238
		return (is_string($docs) && strlen($docs) > 50);
1239
	}
1240
1241
	/**
1242
	 * Check if the PHP module fileinfo is loaded.
1243
	 *
1244
	 * @return bool
1245
	 */
1246
	public static function fileInfoLoaded() {
1247
		return function_exists('finfo_open');
1248
	}
1249
1250
	/**
1251
	 * clear all levels of output buffering
1252
	 *
1253
	 * @return void
1254
	 */
1255
	public static function obEnd() {
1256
		while (ob_get_level()) {
1257
			ob_end_clean();
1258
		}
1259
	}
1260
1261
	/**
1262
	 * Checks whether the server is running on Windows
1263
	 *
1264
	 * @return bool true if running on Windows, false otherwise
1265
	 */
1266
	public static function runningOnWindows() {
1267
		return (substr(PHP_OS, 0, 3) === "WIN");
1268
	}
1269
1270
	/**
1271
	 * Checks whether the server is running on Mac OS X
1272
	 *
1273
	 * @return bool true if running on Mac OS X, false otherwise
1274
	 */
1275
	public static function runningOnMac() {
1276
		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1277
	}
1278
1279
	/**
1280
	 * Checks whether server is running on HHVM
1281
	 *
1282
	 * @return bool True if running on HHVM, false otherwise
1283
	 */
1284
	public static function runningOnHhvm() {
1285
		return defined('HHVM_VERSION');
1286
	}
1287
1288
	/**
1289
	 * Handles the case that there may not be a theme, then check if a "default"
1290
	 * theme exists and take that one
1291
	 *
1292
	 * @return string the theme
1293
	 */
1294
	public static function getTheme() {
1295
		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1296
1297
		if ($theme === '') {
1298
			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1299
				$theme = 'default';
1300
			}
1301
		}
1302
1303
		return $theme;
1304
	}
1305
1306
	/**
1307
	 * Clear a single file from the opcode cache
1308
	 * This is useful for writing to the config file
1309
	 * in case the opcode cache does not re-validate files
1310
	 * Returns true if successful, false if unsuccessful:
1311
	 * caller should fall back on clearing the entire cache
1312
	 * with clearOpcodeCache() if unsuccessful
1313
	 *
1314
	 * @param string $path the path of the file to clear from the cache
1315
	 * @return bool true if underlying function returns true, otherwise false
1316
	 */
1317
	public static function deleteFromOpcodeCache($path) {
1318
		$ret = false;
1319
		if ($path) {
1320
			// APC >= 3.1.1
1321
			if (function_exists('apc_delete_file')) {
1322
				$ret = @apc_delete_file($path);
1323
			}
1324
			// Zend OpCache >= 7.0.0, PHP >= 5.5.0
1325
			if (function_exists('opcache_invalidate')) {
1326
				$ret = opcache_invalidate($path);
1327
			}
1328
		}
1329
		return $ret;
1330
	}
1331
1332
	/**
1333
	 * Clear the opcode cache if one exists
1334
	 * This is necessary for writing to the config file
1335
	 * in case the opcode cache does not re-validate files
1336
	 *
1337
	 * @return void
1338
	 */
1339
	public static function clearOpcodeCache() {
1340
		// APC
1341
		if (function_exists('apc_clear_cache')) {
1342
			apc_clear_cache();
1343
		}
1344
		// Zend Opcache
1345
		if (function_exists('accelerator_reset')) {
1346
			accelerator_reset();
1347
		}
1348
		// XCache
1349
		if (function_exists('xcache_clear_cache')) {
1350
			if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1351
				\OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', \OCP\Util::WARN);
1352
			} else {
1353
				@xcache_clear_cache(XC_TYPE_PHP, 0);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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...
1354
			}
1355
		}
1356
		// Opcache (PHP >= 5.5)
1357
		if (function_exists('opcache_reset')) {
1358
			opcache_reset();
1359
		}
1360
	}
1361
1362
	/**
1363
	 * Normalize a unicode string
1364
	 *
1365
	 * @param string $value a not normalized string
1366
	 * @return bool|string
1367
	 */
1368
	public static function normalizeUnicode($value) {
1369
		if(Normalizer::isNormalized($value)) {
1370
			return $value;
1371
		}
1372
1373
		$normalizedValue = Normalizer::normalize($value);
1374
		if ($normalizedValue === null || $normalizedValue === false) {
1375
			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1376
			return $value;
1377
		}
1378
1379
		return $normalizedValue;
1380
	}
1381
1382
	/**
1383
	 * @param boolean|string $file
1384
	 * @return string
1385
	 */
1386
	public static function basename($file) {
1387
		$file = rtrim($file, '/');
1388
		$t = explode('/', $file);
1389
		return array_pop($t);
1390
	}
1391
1392
	/**
1393
	 * A human readable string is generated based on version, channel and build number
1394
	 *
1395
	 * @return string
1396
	 */
1397
	public static function getHumanVersion() {
1398
		$version = OC_Util::getVersionString() . ' (' . OC_Util::getChannel() . ')';
1399
		$build = OC_Util::getBuild();
1400
		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1401
			$version .= ' Build:' . $build;
1402
		}
1403
		return $version;
1404
	}
1405
1406
	/**
1407
	 * Returns whether the given file name is valid
1408
	 *
1409
	 * @param string $file file name to check
1410
	 * @return bool true if the file name is valid, false otherwise
1411
	 * @deprecated use \OC\Files\View::verifyPath()
1412
	 */
1413
	public static function isValidFileName($file) {
1414
		$trimmed = trim($file);
1415
		if ($trimmed === '') {
1416
			return false;
1417
		}
1418
		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1419
			return false;
1420
		}
1421
		foreach (str_split($trimmed) as $char) {
1422
			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1423
				return false;
1424
			}
1425
		}
1426
		return true;
1427
	}
1428
1429
	/**
1430
	 * Check whether the instance needs to perform an upgrade,
1431
	 * either when the core version is higher or any app requires
1432
	 * an upgrade.
1433
	 *
1434
	 * @param \OCP\IConfig $config
1435
	 * @return bool whether the core or any app needs an upgrade
1436
	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1437
	 */
1438
	public static function needUpgrade(\OCP\IConfig $config) {
1439
		if ($config->getSystemValue('installed', false)) {
1440
			$installedVersion = $config->getSystemValue('version', '0.0.0');
1441
			$currentVersion = implode('.', \OCP\Util::getVersion());
1442
			$versionDiff = version_compare($currentVersion, $installedVersion);
1443
			if ($versionDiff > 0) {
1444
				return true;
1445
			} else if ($config->getSystemValue('debug', false) && $versionDiff < 0) {
1446
				// downgrade with debug
1447
				$installedMajor = explode('.', $installedVersion);
1448
				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1449
				$currentMajor = explode('.', $currentVersion);
1450
				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1451
				if ($installedMajor === $currentMajor) {
1452
					// Same major, allow downgrade for developers
1453
					return true;
1454
				} else {
1455
					// downgrade attempt, throw exception
1456
					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1457
				}
1458
			} else if ($versionDiff < 0) {
1459
				// downgrade attempt, throw exception
1460
				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1461
			}
1462
1463
			// also check for upgrades for apps (independently from the user)
1464
			$apps = \OC_App::getEnabledApps(false, true);
1465
			$shouldUpgrade = false;
1466
			foreach ($apps as $app) {
1467
				if (\OC_App::shouldUpgrade($app)) {
1468
					$shouldUpgrade = true;
1469
					break;
1470
				}
1471
			}
1472
			return $shouldUpgrade;
1473
		} else {
1474
			return false;
1475
		}
1476
	}
1477
1478
}
1479