Completed
Push — stable8 ( 42720e...c45eda )
by
unknown
35s
created

Server   F

Complexity

Total Complexity 68

Size/Duplication

Total Lines 710
Duplicated Lines 2.54 %

Coupling/Cohesion

Components 1
Dependencies 61

Importance

Changes 2
Bugs 1 Features 1
Metric Value
wmc 68
lcom 1
cbo 61
dl 18
loc 710
rs 1.0434
c 2
b 1
f 1

45 Methods

Rating   Name   Duplication   Size   Complexity  
D __construct() 8 265 15
A getContactsManager() 0 3 1
A getRequest() 0 3 1
A getPreviewManager() 0 3 1
A getTagManager() 0 3 1
A getAvatarManager() 0 3 1
A getRootFolder() 0 3 1
C getUserFolder() 5 43 7
A getAppFolder() 5 11 2
A getUserManager() 0 3 1
A getGroupManager() 0 3 1
A getUserSession() 0 3 1
A getSession() 0 3 1
A setSession() 0 3 1
A getNavigationManager() 0 3 1
A getConfig() 0 3 1
A getSystemConfig() 0 3 1
A getAppConfig() 0 3 1
A getL10N() 0 3 1
A getURLGenerator() 0 3 1
A getHelper() 0 3 1
A getCache() 0 3 1
A getMemCacheFactory() 0 3 1
A getDatabaseConnection() 0 3 1
A getActivityManager() 0 3 1
A getJobList() 0 3 1
A getLogger() 0 3 1
A getRouter() 0 3 1
A getSearch() 0 3 1
A getSecureRandom() 0 3 1
A getCrypto() 0 3 1
A getHasher() 0 3 1
A getDb() 0 3 1
A getHTTPHelper() 0 3 1
A getCertificateManager() 0 11 3
A createEventSource() 0 3 1
A getEventLogger() 0 3 1
A getQueryLogger() 0 3 1
A getTempManager() 0 3 1
A getAppManager() 0 3 1
A getWebRoot() 0 3 1
A getDateTimeZone() 0 3 1
A getDateTimeFormatter() 0 3 1
A getMountProviderCollection() 0 3 1
A getIniWrapper() 0 3 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Server often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Server, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace OC;
4
5
use bantu\IniGetWrapper\IniGetWrapper;
6
use OC\AppFramework\Http\Request;
7
use OC\AppFramework\Db\Db;
8
use OC\AppFramework\Utility\SimpleContainer;
9
use OC\Cache\UserCache;
10
use OC\Diagnostics\NullQueryLogger;
11
use OC\Diagnostics\EventLogger;
12
use OC\Diagnostics\QueryLogger;
13
use OC\Files\Config\StorageManager;
14
use OC\Security\CertificateManager;
15
use OC\Files\Node\Root;
16
use OC\Files\View;
17
use OC\Security\Crypto;
18
use OC\Security\Hasher;
19
use OC\Security\SecureRandom;
20
use OC\Diagnostics\NullEventLogger;
21
use OCP\IServerContainer;
22
use OCP\ISession;
23
use OC\Tagging\TagMapper;
24
25
/**
26
 * Class Server
27
 *
28
 * @package OC
29
 *
30
 * TODO: hookup all manager classes
31
 */
32
class Server extends SimpleContainer implements IServerContainer {
33
	/** @var string */
34
	private $webRoot;
35
36
	/**
37
	 * @param string $webRoot
38
	 */
39
	function __construct($webRoot) {
40
		parent::__construct();
41
		$this->webRoot = $webRoot;
42
43
		$this->registerService('ContactsManager', function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
44
			return new ContactsManager();
45
		});
46
		$this->registerService('Request', function (Server $c) {
47
			if (isset($c['urlParams'])) {
48
				$urlParams = $c['urlParams'];
49
			} else {
50
				$urlParams = array();
51
			}
52
53
			if ($c->getSession()->exists('requesttoken')) {
54
				$requestToken = $c->getSession()->get('requesttoken');
55
			} else {
56
				$requestToken = false;
57
			}
58
59
			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
60
				&& in_array('fakeinput', stream_get_wrappers())
61
			) {
62
				$stream = 'fakeinput://data';
63
			} else {
64
				$stream = 'php://input';
65
			}
66
67
			return new Request(
68
				array(
69
					'get' => $_GET,
70
					'post' => $_POST,
71
					'files' => $_FILES,
72
					'server' => $_SERVER,
73
					'env' => $_ENV,
74
					'cookies' => $_COOKIE,
75
					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
76
						? $_SERVER['REQUEST_METHOD']
77
						: null,
78
					'urlParams' => $urlParams,
79
					'requesttoken' => $requestToken,
80
				), $stream
81
			);
82
		});
83
		$this->registerService('PreviewManager', function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
84
			return new PreviewManager();
85
		});
86
		$this->registerService('TagMapper', function(Server $c) {
87
			return new TagMapper($c->getDb());
88
		});
89
		$this->registerService('TagManager', function (Server $c) {
90
			$tagMapper = $c->query('TagMapper');
91
			return new TagManager($tagMapper, $c->getUserSession());
92
		});
93
		$this->registerService('RootFolder', function (Server $c) {
94
			// TODO: get user and user manager from container as well
95
			$user = \OC_User::getUser();
96
			/** @var $c SimpleContainer */
97
			$userManager = $c->query('UserManager');
98
			$user = $userManager->get($user);
99
			$manager = \OC\Files\Filesystem::getMountManager();
100
			$view = new View();
101
			return new Root($manager, $view, $user);
102
		});
103
		$this->registerService('UserManager', function (Server $c) {
104
			$config = $c->getConfig();
105
			return new \OC\User\Manager($config);
106
		});
107
		$this->registerService('GroupManager', function (Server $c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
108
			$groupManager = new \OC\Group\Manager($this->getUserManager());
109
			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
110
				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
111
			});
112
			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
113
				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
114
			});
115
			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
116
				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
117
			});
118
			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
119
				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
120
			});
121
			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
122
				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
123
			});
124
			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
125
				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
126
				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
127
				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
128
			});
129
			return $groupManager;
130
		});
131
		$this->registerService('UserSession', function (Server $c) {
132
			$manager = $c->getUserManager();
133
			$userSession = new \OC\User\Session($manager, new \OC\Session\Memory(''));
134
			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
135
				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
136
			});
137
			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
138
				/** @var $user \OC\User\User */
139
				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
140
			});
141
			$userSession->listen('\OC\User', 'preDelete', function ($user) {
142
				/** @var $user \OC\User\User */
143
				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
144
			});
145
			$userSession->listen('\OC\User', 'postDelete', function ($user) {
146
				/** @var $user \OC\User\User */
147
				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
148
			});
149 View Code Duplication
			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
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...
150
				/** @var $user \OC\User\User */
151
				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
152
			});
153 View Code Duplication
			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
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...
154
				/** @var $user \OC\User\User */
155
				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
156
			});
157
			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
158
				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
159
			});
160
			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
161
				/** @var $user \OC\User\User */
162
				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
163
			});
164
			$userSession->listen('\OC\User', 'logout', function () {
165
				\OC_Hook::emit('OC_User', 'logout', array());
166
			});
167
			return $userSession;
168
		});
169
		$this->registerService('NavigationManager', function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
170
			return new \OC\NavigationManager();
171
		});
172
		$this->registerService('AllConfig', function (Server $c) {
173
			return new \OC\AllConfig(
174
				$c->getSystemConfig()
175
			);
176
		});
177
		$this->registerService('SystemConfig', function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
178
			return new \OC\SystemConfig();
179
		});
180
		$this->registerService('AppConfig', function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
181
			return new \OC\AppConfig(\OC_DB::getConnection());
0 ignored issues
show
Compatibility introduced by
\OC_DB::getConnection() of type object<OCP\IDBConnection> is not a sub-type of object<OC\DB\Connection>. It seems like you assume a concrete implementation of the interface OCP\IDBConnection to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
182
		});
183
		$this->registerService('L10NFactory', function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
184
			return new \OC\L10N\Factory();
185
		});
186
		$this->registerService('URLGenerator', function (Server $c) {
187
			$config = $c->getConfig();
188
			return new \OC\URLGenerator($config);
189
		});
190
		$this->registerService('AppHelper', function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
191
			return new \OC\AppHelper();
192
		});
193
		$this->registerService('UserCache', function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
194
			return new UserCache();
195
		});
196
		$this->registerService('MemCacheFactory', function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
197
			$instanceId = \OC_Util::getInstanceId();
198
			return new \OC\Memcache\Factory($instanceId);
199
		});
200
		$this->registerService('ActivityManager', function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
201
			return new ActivityManager();
202
		});
203
		$this->registerService('AvatarManager', function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
204
			return new AvatarManager();
205
		});
206
		$this->registerService('Logger', function (Server $c) {
207
			$logClass = $c->query('AllConfig')->getSystemValue('log_type', 'owncloud');
208
			$logger = 'OC_Log_' . ucfirst($logClass);
209
			call_user_func(array($logger, 'init'));
210
211
			return new Log($logger);
212
		});
213
		$this->registerService('JobList', function (Server $c) {
214
			$config = $c->getConfig();
215
			return new \OC\BackgroundJob\JobList($c->getDatabaseConnection(), $config);
216
		});
217
		$this->registerService('Router', function (Server $c) {
218
			$cacheFactory = $c->getMemCacheFactory();
219
			if ($cacheFactory->isAvailable()) {
220
				$router = new \OC\Route\CachingRouter($cacheFactory->create('route'));
221
			} else {
222
				$router = new \OC\Route\Router();
223
			}
224
			return $router;
225
		});
226
		$this->registerService('Search', function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
227
			return new Search();
228
		});
229
		$this->registerService('SecureRandom', function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
230
			return new SecureRandom();
231
		});
232
		$this->registerService('Crypto', function (Server $c) {
233
			return new Crypto($c->getConfig(), $c->getSecureRandom());
234
		});
235
		$this->registerService('Hasher', function (Server $c) {
236
			return new Hasher($c->getConfig());
237
		});
238
		$this->registerService('DatabaseConnection', function (Server $c) {
239
			$factory = new \OC\DB\ConnectionFactory();
240
			$systemConfig = $c->getSystemConfig();
241
			$type = $systemConfig->getValue('dbtype', 'sqlite');
242
			if (!$factory->isValidType($type)) {
243
				throw new \OC\DatabaseException('Invalid database type');
244
			}
245
			$connectionParams = $factory->createConnectionParams($systemConfig);
246
			$connection = $factory->getConnection($type, $connectionParams);
247
			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
248
			return $connection;
249
		});
250
		$this->registerService('Db', function (Server $c) {
251
			return new Db($c->getDatabaseConnection());
252
		});
253
		$this->registerService('HTTPHelper', function (Server $c) {
254
			$config = $c->getConfig();
255
			$user = $c->getUserSession()->getUser();
256
			$uid = $user ? $user->getUID() : null;
257
			return new HTTPHelper($config, new \OC\Security\CertificateManager($uid, new \OC\Files\View()));
258
		});
259
		$this->registerService('EventLogger', function (Server $c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
260
			if (defined('DEBUG') and DEBUG) {
261
				return new EventLogger();
262
			} else {
263
				return new NullEventLogger();
264
			}
265
		});
266
		$this->registerService('QueryLogger', function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
267
			if (defined('DEBUG') and DEBUG) {
268
				return new QueryLogger();
269
			} else {
270
				return new NullQueryLogger();
271
			}
272
		});
273
		$this->registerService('TempManager', function (Server $c) {
274
			return new TempManager(get_temp_dir(), $c->getLogger());
275
		});
276
		$this->registerService('AppManager', function(Server $c) {
277
			$userSession = $c->getUserSession();
278
			$appConfig = $c->getAppConfig();
279
			$groupManager = $c->getGroupManager();
280
			return new \OC\App\AppManager($userSession, $appConfig, $groupManager);
281
		});
282
		$this->registerService('DateTimeZone', function(Server $c) {
283
			return new DateTimeZone(
284
				$c->getConfig(),
285
				$c->getSession()
286
			);
287
		});
288
		$this->registerService('DateTimeFormatter', function(Server $c) {
289
			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
290
291
			return new DateTimeFormatter(
292
				$c->getDateTimeZone()->getTimeZone(),
293
				$c->getL10N('lib', $language)
294
			);
295
		});
296
		$this->registerService('MountConfigManager', function () {
297
			$loader = \OC\Files\Filesystem::getLoader();
298
			return new \OC\Files\Config\MountProviderCollection($loader);
299
		});
300
		$this->registerService('IniWrapper', function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c 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...
301
			return new IniGetWrapper();
302
		});
303
	}
304
305
	/**
306
	 * @return \OCP\Contacts\IManager
307
	 */
308
	function getContactsManager() {
309
		return $this->query('ContactsManager');
310
	}
311
312
	/**
313
	 * The current request object holding all information about the request
314
	 * currently being processed is returned from this method.
315
	 * In case the current execution was not initiated by a web request null is returned
316
	 *
317
	 * @return \OCP\IRequest|null
318
	 */
319
	function getRequest() {
320
		return $this->query('Request');
321
	}
322
323
	/**
324
	 * Returns the preview manager which can create preview images for a given file
325
	 *
326
	 * @return \OCP\IPreview
327
	 */
328
	function getPreviewManager() {
329
		return $this->query('PreviewManager');
330
	}
331
332
	/**
333
	 * Returns the tag manager which can get and set tags for different object types
334
	 *
335
	 * @see \OCP\ITagManager::load()
336
	 * @return \OCP\ITagManager
337
	 */
338
	function getTagManager() {
339
		return $this->query('TagManager');
340
	}
341
342
	/**
343
	 * Returns the avatar manager, used for avatar functionality
344
	 *
345
	 * @return \OCP\IAvatarManager
346
	 */
347
	function getAvatarManager() {
348
		return $this->query('AvatarManager');
349
	}
350
351
	/**
352
	 * Returns the root folder of ownCloud's data directory
353
	 *
354
	 * @return \OCP\Files\Folder
355
	 */
356
	function getRootFolder() {
357
		return $this->query('RootFolder');
358
	}
359
360
	/**
361
	 * Returns a view to ownCloud's files folder
362
	 *
363
	 * @param string $userId user ID
364
	 * @return \OCP\Files\Folder
365
	 */
366
	function getUserFolder($userId = null) {
367
		if ($userId === null) {
368
			$user = $this->getUserSession()->getUser();
369
			if (!$user) {
370
				return null;
371
			}
372
			$userId = $user->getUID();
373
		} else {
374
			$user = $this->getUserManager()->get($userId);
375
		}
376
		\OC\Files\Filesystem::initMountPoints($userId);
377
		$dir = '/' . $userId;
378
		$root = $this->getRootFolder();
379
		$folder = null;
0 ignored issues
show
Unused Code introduced by
$folder is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
380
381 View Code Duplication
		if (!$root->nodeExists($dir)) {
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...
382
			$folder = $root->newFolder($dir);
383
		} else {
384
			$folder = $root->get($dir);
385
		}
386
387
		$dir = '/files';
388
		if (!$folder->nodeExists($dir)) {
389
			$folder = $folder->newFolder($dir);
390
391
			if (\OCP\App::isEnabled('files_encryption')) {
392
				// disable encryption proxy to prevent recursive calls
393
				$proxyStatus = \OC_FileProxy::$enabled;
394
				\OC_FileProxy::$enabled = false;
395
			}
396
397
			\OC_Util::copySkeleton($user, $folder);
0 ignored issues
show
Bug introduced by
It seems like $user can be null; however, copySkeleton() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
398
399
			if (\OCP\App::isEnabled('files_encryption')) {
400
				// re-enable proxy - our work is done
401
				\OC_FileProxy::$enabled = $proxyStatus;
0 ignored issues
show
Bug introduced by
The variable $proxyStatus does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
402
			}
403
		} else {
404
			$folder = $folder->get($dir);
405
		}
406
407
		return $folder;
408
	}
409
410
	/**
411
	 * Returns an app-specific view in ownClouds data directory
412
	 *
413
	 * @return \OCP\Files\Folder
414
	 */
415
	function getAppFolder() {
416
		$dir = '/' . \OC_App::getCurrentApp();
417
		$root = $this->getRootFolder();
418
		$folder = null;
0 ignored issues
show
Unused Code introduced by
$folder is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
419 View Code Duplication
		if (!$root->nodeExists($dir)) {
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...
420
			$folder = $root->newFolder($dir);
421
		} else {
422
			$folder = $root->get($dir);
423
		}
424
		return $folder;
425
	}
426
427
	/**
428
	 * @return \OC\User\Manager
429
	 */
430
	function getUserManager() {
431
		return $this->query('UserManager');
432
	}
433
434
	/**
435
	 * @return \OC\Group\Manager
436
	 */
437
	function getGroupManager() {
438
		return $this->query('GroupManager');
439
	}
440
441
	/**
442
	 * @return \OC\User\Session
443
	 */
444
	function getUserSession() {
445
		return $this->query('UserSession');
446
	}
447
448
	/**
449
	 * @return \OCP\ISession
450
	 */
451
	function getSession() {
452
		return $this->query('UserSession')->getSession();
453
	}
454
455
	/**
456
	 * @param \OCP\ISession $session
457
	 */
458
	function setSession(\OCP\ISession $session) {
459
		return $this->query('UserSession')->setSession($session);
460
	}
461
462
	/**
463
	 * @return \OC\NavigationManager
464
	 */
465
	function getNavigationManager() {
466
		return $this->query('NavigationManager');
467
	}
468
469
	/**
470
	 * @return \OCP\IConfig
471
	 */
472
	function getConfig() {
473
		return $this->query('AllConfig');
474
	}
475
476
	/**
477
	 * For internal use only
478
	 *
479
	 * @return \OC\SystemConfig
480
	 */
481
	function getSystemConfig() {
482
		return $this->query('SystemConfig');
483
	}
484
485
	/**
486
	 * Returns the app config manager
487
	 *
488
	 * @return \OCP\IAppConfig
489
	 */
490
	function getAppConfig() {
491
		return $this->query('AppConfig');
492
	}
493
494
	/**
495
	 * get an L10N instance
496
	 *
497
	 * @param string $app appid
498
	 * @param string $lang
499
	 * @return \OC_L10N
500
	 */
501
	function getL10N($app, $lang = null) {
502
		return $this->query('L10NFactory')->get($app, $lang);
503
	}
504
505
	/**
506
	 * @return \OCP\IURLGenerator
507
	 */
508
	function getURLGenerator() {
509
		return $this->query('URLGenerator');
510
	}
511
512
	/**
513
	 * @return \OCP\IHelper
514
	 */
515
	function getHelper() {
516
		return $this->query('AppHelper');
517
	}
518
519
	/**
520
	 * Returns an ICache instance
521
	 *
522
	 * @return \OCP\ICache
523
	 */
524
	function getCache() {
525
		return $this->query('UserCache');
526
	}
527
528
	/**
529
	 * Returns an \OCP\CacheFactory instance
530
	 *
531
	 * @return \OCP\ICacheFactory
532
	 */
533
	function getMemCacheFactory() {
534
		return $this->query('MemCacheFactory');
535
	}
536
537
	/**
538
	 * Returns the current session
539
	 *
540
	 * @return \OCP\IDBConnection
541
	 */
542
	function getDatabaseConnection() {
543
		return $this->query('DatabaseConnection');
544
	}
545
546
	/**
547
	 * Returns the activity manager
548
	 *
549
	 * @return \OCP\Activity\IManager
550
	 */
551
	function getActivityManager() {
552
		return $this->query('ActivityManager');
553
	}
554
555
	/**
556
	 * Returns an job list for controlling background jobs
557
	 *
558
	 * @return \OCP\BackgroundJob\IJobList
559
	 */
560
	function getJobList() {
561
		return $this->query('JobList');
562
	}
563
564
	/**
565
	 * Returns a logger instance
566
	 *
567
	 * @return \OCP\ILogger
568
	 */
569
	function getLogger() {
570
		return $this->query('Logger');
571
	}
572
573
	/**
574
	 * Returns a router for generating and matching urls
575
	 *
576
	 * @return \OCP\Route\IRouter
577
	 */
578
	function getRouter() {
579
		return $this->query('Router');
580
	}
581
582
	/**
583
	 * Returns a search instance
584
	 *
585
	 * @return \OCP\ISearch
586
	 */
587
	function getSearch() {
588
		return $this->query('Search');
589
	}
590
591
	/**
592
	 * Returns a SecureRandom instance
593
	 *
594
	 * @return \OCP\Security\ISecureRandom
595
	 */
596
	function getSecureRandom() {
597
		return $this->query('SecureRandom');
598
	}
599
600
	/**
601
	 * Returns a Crypto instance
602
	 *
603
	 * @return \OCP\Security\ICrypto
604
	 */
605
	function getCrypto() {
606
		return $this->query('Crypto');
607
	}
608
609
	/**
610
	 * Returns a Hasher instance
611
	 *
612
	 * @return \OCP\Security\IHasher
613
	 */
614
	function getHasher() {
615
		return $this->query('Hasher');
616
	}
617
618
	/**
619
	 * Returns an instance of the db facade
620
	 *
621
	 * @return \OCP\IDb
622
	 */
623
	function getDb() {
624
		return $this->query('Db');
625
	}
626
627
	/**
628
	 * Returns an instance of the HTTP helper class
629
	 *
630
	 * @return \OC\HTTPHelper
631
	 */
632
	function getHTTPHelper() {
633
		return $this->query('HTTPHelper');
634
	}
635
636
	/**
637
	 * Get the certificate manager for the user
638
	 *
639
	 * @param string $uid (optional) if not specified the current loggedin user is used
640
	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
641
	 */
642
	function getCertificateManager($uid = null) {
643
		if (is_null($uid)) {
644
			$userSession = $this->getUserSession();
645
			$user = $userSession->getUser();
646
			if (is_null($user)) {
647
				return null;
648
			}
649
			$uid = $user->getUID();
650
		}
651
		return new CertificateManager($uid, new \OC\Files\View());
652
	}
653
654
	/**
655
	 * Create a new event source
656
	 *
657
	 * @return \OCP\IEventSource
658
	 */
659
	function createEventSource() {
660
		return new \OC_EventSource();
661
	}
662
663
	/**
664
	 * Get the active event logger
665
	 *
666
	 * The returned logger only logs data when debug mode is enabled
667
	 *
668
	 * @return \OCP\Diagnostics\IEventLogger
669
	 */
670
	function getEventLogger() {
671
		return $this->query('EventLogger');
672
	}
673
674
	/**
675
	 * Get the active query logger
676
	 *
677
	 * The returned logger only logs data when debug mode is enabled
678
	 *
679
	 * @return \OCP\Diagnostics\IQueryLogger
680
	 */
681
	function getQueryLogger() {
682
		return $this->query('QueryLogger');
683
	}
684
685
	/**
686
	 * Get the manager for temporary files and folders
687
	 *
688
	 * @return \OCP\ITempManager
689
	 */
690
	function getTempManager() {
691
		return $this->query('TempManager');
692
	}
693
694
	/**
695
	 * Get the app manager
696
	 *
697
	 * @return \OCP\App\IAppManager
698
	 */
699
	function getAppManager() {
700
		return $this->query('AppManager');
701
	}
702
703
	/**
704
	 * Get the webroot
705
	 *
706
	 * @return string
707
	 */
708
	function getWebRoot() {
709
		return $this->webRoot;
710
	}
711
712
	/**
713
	 * @return \OCP\IDateTimeZone
714
	 */
715
	public function getDateTimeZone() {
716
		return $this->query('DateTimeZone');
717
	}
718
719
	/**
720
	 * @return \OCP\IDateTimeFormatter
721
	 */
722
	public function getDateTimeFormatter() {
723
		return $this->query('DateTimeFormatter');
724
	}
725
726
	/**
727
	 * @return \OCP\Files\Config\IMountProviderCollection
728
	 */
729
	function getMountProviderCollection(){
730
		return $this->query('MountConfigManager');
731
	}
732
733
	/**
734
	 * Get the IniWrapper
735
	 *
736
	 * @return IniGetWrapper
737
	 */
738
	public function getIniWrapper() {
739
		return $this->query('IniWrapper');
740
	}
741
}
742