Completed
Push — master ( ec3f5a...0b5e18 )
by Blizzz
26:23 queued 12:08
created
lib/public/IContainer.php 1 patch
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -47,58 +47,58 @@
 block discarded – undo
47 47
  */
48 48
 interface IContainer {
49 49
 
50
-	/**
51
-	 * If a parameter is not registered in the container try to instantiate it
52
-	 * by using reflection to find out how to build the class
53
-	 * @param string $name the class name to resolve
54
-	 * @return \stdClass
55
-	 * @since 8.2.0
56
-	 * @throws QueryException if the class could not be found or instantiated
57
-	 */
58
-	public function resolve($name);
50
+    /**
51
+     * If a parameter is not registered in the container try to instantiate it
52
+     * by using reflection to find out how to build the class
53
+     * @param string $name the class name to resolve
54
+     * @return \stdClass
55
+     * @since 8.2.0
56
+     * @throws QueryException if the class could not be found or instantiated
57
+     */
58
+    public function resolve($name);
59 59
 
60
-	/**
61
-	 * Look up a service for a given name in the container.
62
-	 *
63
-	 * @param string $name
64
-	 * @return mixed
65
-	 * @throws QueryException if the query could not be resolved
66
-	 * @since 6.0.0
67
-	 */
68
-	public function query($name);
60
+    /**
61
+     * Look up a service for a given name in the container.
62
+     *
63
+     * @param string $name
64
+     * @return mixed
65
+     * @throws QueryException if the query could not be resolved
66
+     * @since 6.0.0
67
+     */
68
+    public function query($name);
69 69
 
70
-	/**
71
-	 * A value is stored in the container with it's corresponding name
72
-	 *
73
-	 * @param string $name
74
-	 * @param mixed $value
75
-	 * @return void
76
-	 * @since 6.0.0
77
-	 */
78
-	public function registerParameter($name, $value);
70
+    /**
71
+     * A value is stored in the container with it's corresponding name
72
+     *
73
+     * @param string $name
74
+     * @param mixed $value
75
+     * @return void
76
+     * @since 6.0.0
77
+     */
78
+    public function registerParameter($name, $value);
79 79
 
80
-	/**
81
-	 * A service is registered in the container where a closure is passed in which will actually
82
-	 * create the service on demand.
83
-	 * In case the parameter $shared is set to true (the default usage) the once created service will remain in
84
-	 * memory and be reused on subsequent calls.
85
-	 * In case the parameter is false the service will be recreated on every call.
86
-	 *
87
-	 * @param string $name
88
-	 * @param \Closure $closure
89
-	 * @param bool $shared
90
-	 * @return void
91
-	 * @since 6.0.0
92
-	 */
93
-	public function registerService($name, Closure $closure, $shared = true);
80
+    /**
81
+     * A service is registered in the container where a closure is passed in which will actually
82
+     * create the service on demand.
83
+     * In case the parameter $shared is set to true (the default usage) the once created service will remain in
84
+     * memory and be reused on subsequent calls.
85
+     * In case the parameter is false the service will be recreated on every call.
86
+     *
87
+     * @param string $name
88
+     * @param \Closure $closure
89
+     * @param bool $shared
90
+     * @return void
91
+     * @since 6.0.0
92
+     */
93
+    public function registerService($name, Closure $closure, $shared = true);
94 94
 
95
-	/**
96
-	 * Shortcut for returning a service from a service under a different key,
97
-	 * e.g. to tell the container to return a class when queried for an
98
-	 * interface
99
-	 * @param string $alias the alias that should be registered
100
-	 * @param string $target the target that should be resolved instead
101
-	 * @since 8.2.0
102
-	 */
103
-	public function registerAlias($alias, $target);
95
+    /**
96
+     * Shortcut for returning a service from a service under a different key,
97
+     * e.g. to tell the container to return a class when queried for an
98
+     * interface
99
+     * @param string $alias the alias that should be registered
100
+     * @param string $target the target that should be resolved instead
101
+     * @since 8.2.0
102
+     */
103
+    public function registerAlias($alias, $target);
104 104
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/DependencyInjection/DIContainer.php 2 patches
Indentation   +349 added lines, -349 removed lines patch added patch discarded remove patch
@@ -61,353 +61,353 @@
 block discarded – undo
61 61
 
62 62
 class DIContainer extends SimpleContainer implements IAppContainer {
63 63
 
64
-	/**
65
-	 * @var array
66
-	 */
67
-	private $middleWares = array();
68
-
69
-	/** @var ServerContainer */
70
-	private $server;
71
-
72
-	/**
73
-	 * Put your class dependencies in here
74
-	 * @param string $appName the name of the app
75
-	 * @param array $urlParams
76
-	 * @param ServerContainer $server
77
-	 */
78
-	public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
79
-		parent::__construct();
80
-		$this['AppName'] = $appName;
81
-		$this['urlParams'] = $urlParams;
82
-
83
-		/** @var \OC\ServerContainer $server */
84
-		if ($server === null) {
85
-			$server = \OC::$server;
86
-		}
87
-		$this->server = $server;
88
-		$this->server->registerAppContainer($appName, $this);
89
-
90
-		// aliases
91
-		$this->registerAlias('appName', 'AppName');
92
-		$this->registerAlias('webRoot', 'WebRoot');
93
-		$this->registerAlias('userId', 'UserId');
94
-
95
-		/**
96
-		 * Core services
97
-		 */
98
-		$this->registerService(IOutput::class, function($c){
99
-			return new Output($this->getServer()->getWebRoot());
100
-		});
101
-
102
-		$this->registerService(Folder::class, function() {
103
-			return $this->getServer()->getUserFolder();
104
-		});
105
-
106
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
107
-			return $this->getServer()->getAppDataDir($c->query('AppName'));
108
-		});
109
-
110
-		$this->registerService(IL10N::class, function($c) {
111
-			return $this->getServer()->getL10N($c->query('AppName'));
112
-		});
113
-
114
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
115
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
116
-
117
-		$this->registerService(IRequest::class, function() {
118
-			return $this->getServer()->query(IRequest::class);
119
-		});
120
-		$this->registerAlias('Request', IRequest::class);
121
-
122
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
123
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
124
-
125
-		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
126
-
127
-		$this->registerService(IServerContainer::class, function ($c) {
128
-			return $this->getServer();
129
-		});
130
-		$this->registerAlias('ServerContainer', IServerContainer::class);
131
-
132
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
133
-			return $c->query('OCA\WorkflowEngine\Manager');
134
-		});
135
-
136
-		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
137
-			return $c;
138
-		});
139
-
140
-		// commonly used attributes
141
-		$this->registerService('UserId', function ($c) {
142
-			return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
143
-		});
144
-
145
-		$this->registerService('WebRoot', function ($c) {
146
-			return $c->query('ServerContainer')->getWebRoot();
147
-		});
148
-
149
-		$this->registerService('fromMailAddress', function() {
150
-			return Util::getDefaultEmailAddress('no-reply');
151
-		});
152
-
153
-		$this->registerService('OC_Defaults', function ($c) {
154
-			return $c->getServer()->getThemingDefaults();
155
-		});
156
-
157
-		$this->registerService('OCP\Encryption\IManager', function ($c) {
158
-			return $this->getServer()->getEncryptionManager();
159
-		});
160
-
161
-		$this->registerService(IValidator::class, function($c) {
162
-			return $c->query(Validator::class);
163
-		});
164
-
165
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
166
-			return new \OC\Security\IdentityProof\Manager(
167
-				$this->getServer()->getAppDataDir('identityproof'),
168
-				$this->getServer()->getCrypto()
169
-			);
170
-		});
171
-
172
-
173
-		/**
174
-		 * App Framework APIs
175
-		 */
176
-		$this->registerService('API', function($c){
177
-			$c->query('OCP\\ILogger')->debug(
178
-				'Accessing the API class is deprecated! Use the appropriate ' .
179
-				'services instead!'
180
-			);
181
-			return new API($c['AppName']);
182
-		});
183
-
184
-		$this->registerService('Protocol', function($c){
185
-			/** @var \OC\Server $server */
186
-			$server = $c->query('ServerContainer');
187
-			$protocol = $server->getRequest()->getHttpProtocol();
188
-			return new Http($_SERVER, $protocol);
189
-		});
190
-
191
-		$this->registerService('Dispatcher', function($c) {
192
-			return new Dispatcher(
193
-				$c['Protocol'],
194
-				$c['MiddlewareDispatcher'],
195
-				$c['ControllerMethodReflector'],
196
-				$c['Request']
197
-			);
198
-		});
199
-
200
-		/**
201
-		 * App Framework default arguments
202
-		 */
203
-		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
204
-		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
205
-		$this->registerParameter('corsMaxAge', 1728000);
206
-
207
-		/**
208
-		 * Middleware
209
-		 */
210
-		$app = $this;
211
-		$this->registerService('SecurityMiddleware', function($c) use ($app){
212
-			/** @var \OC\Server $server */
213
-			$server = $app->getServer();
214
-
215
-			return new SecurityMiddleware(
216
-				$c['Request'],
217
-				$c['ControllerMethodReflector'],
218
-				$server->getNavigationManager(),
219
-				$server->getURLGenerator(),
220
-				$server->getLogger(),
221
-				$server->getSession(),
222
-				$c['AppName'],
223
-				$app->isLoggedIn(),
224
-				$app->isAdminUser(),
225
-				$server->getContentSecurityPolicyManager(),
226
-				$server->getCsrfTokenManager(),
227
-				$server->getContentSecurityPolicyNonceManager(),
228
-				$server->getBruteForceThrottler()
229
-			);
230
-
231
-		});
232
-
233
-		$this->registerService('CORSMiddleware', function($c) {
234
-			return new CORSMiddleware(
235
-				$c['Request'],
236
-				$c['ControllerMethodReflector'],
237
-				$c->query(IUserSession::class),
238
-				$c->getServer()->getBruteForceThrottler()
239
-			);
240
-		});
241
-
242
-		$this->registerService('SessionMiddleware', function($c) use ($app) {
243
-			return new SessionMiddleware(
244
-				$c['Request'],
245
-				$c['ControllerMethodReflector'],
246
-				$app->getServer()->getSession()
247
-			);
248
-		});
249
-
250
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
251
-			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
252
-			$userSession = $app->getServer()->getUserSession();
253
-			$session = $app->getServer()->getSession();
254
-			$urlGenerator = $app->getServer()->getURLGenerator();
255
-			$reflector = $c['ControllerMethodReflector'];
256
-			$request = $app->getServer()->getRequest();
257
-			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
258
-		});
259
-
260
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
261
-			return new OCSMiddleware(
262
-				$c['Request']
263
-			);
264
-		});
265
-
266
-		$middleWares = &$this->middleWares;
267
-		$this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
268
-			$dispatcher = new MiddlewareDispatcher();
269
-			$dispatcher->registerMiddleware($c['CORSMiddleware']);
270
-			$dispatcher->registerMiddleware($c['OCSMiddleware']);
271
-			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
272
-			$dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
273
-
274
-			foreach($middleWares as $middleWare) {
275
-				$dispatcher->registerMiddleware($c[$middleWare]);
276
-			}
277
-
278
-			$dispatcher->registerMiddleware($c['SessionMiddleware']);
279
-			return $dispatcher;
280
-		});
281
-
282
-	}
283
-
284
-
285
-	/**
286
-	 * @deprecated implements only deprecated methods
287
-	 * @return IApi
288
-	 */
289
-	function getCoreApi()
290
-	{
291
-		return $this->query('API');
292
-	}
293
-
294
-	/**
295
-	 * @return \OCP\IServerContainer
296
-	 */
297
-	function getServer()
298
-	{
299
-		return $this->server;
300
-	}
301
-
302
-	/**
303
-	 * @param string $middleWare
304
-	 * @return boolean|null
305
-	 */
306
-	function registerMiddleWare($middleWare) {
307
-		array_push($this->middleWares, $middleWare);
308
-	}
309
-
310
-	/**
311
-	 * used to return the appname of the set application
312
-	 * @return string the name of your application
313
-	 */
314
-	function getAppName() {
315
-		return $this->query('AppName');
316
-	}
317
-
318
-	/**
319
-	 * @deprecated use IUserSession->isLoggedIn()
320
-	 * @return boolean
321
-	 */
322
-	function isLoggedIn() {
323
-		return \OC::$server->getUserSession()->isLoggedIn();
324
-	}
325
-
326
-	/**
327
-	 * @deprecated use IGroupManager->isAdmin($userId)
328
-	 * @return boolean
329
-	 */
330
-	function isAdminUser() {
331
-		$uid = $this->getUserId();
332
-		return \OC_User::isAdminUser($uid);
333
-	}
334
-
335
-	private function getUserId() {
336
-		return $this->getServer()->getSession()->get('user_id');
337
-	}
338
-
339
-	/**
340
-	 * @deprecated use the ILogger instead
341
-	 * @param string $message
342
-	 * @param string $level
343
-	 * @return mixed
344
-	 */
345
-	function log($message, $level) {
346
-		switch($level){
347
-			case 'debug':
348
-				$level = \OCP\Util::DEBUG;
349
-				break;
350
-			case 'info':
351
-				$level = \OCP\Util::INFO;
352
-				break;
353
-			case 'warn':
354
-				$level = \OCP\Util::WARN;
355
-				break;
356
-			case 'fatal':
357
-				$level = \OCP\Util::FATAL;
358
-				break;
359
-			default:
360
-				$level = \OCP\Util::ERROR;
361
-				break;
362
-		}
363
-		\OCP\Util::writeLog($this->getAppName(), $message, $level);
364
-	}
365
-
366
-	/**
367
-	 * Register a capability
368
-	 *
369
-	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
370
-	 */
371
-	public function registerCapability($serviceName) {
372
-		$this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
373
-			return $this->query($serviceName);
374
-		});
375
-	}
376
-
377
-	/**
378
-	 * @param string $name
379
-	 * @return mixed
380
-	 * @throws QueryException if the query could not be resolved
381
-	 */
382
-	public function query($name) {
383
-		try {
384
-			return $this->queryNoFallback($name);
385
-		} catch (QueryException $e) {
386
-			return $this->getServer()->query($name);
387
-		}
388
-	}
389
-
390
-	/**
391
-	 * @param string $name
392
-	 * @return mixed
393
-	 * @throws QueryException if the query could not be resolved
394
-	 */
395
-	public function queryNoFallback($name) {
396
-		$name = $this->sanitizeName($name);
397
-
398
-		if ($this->offsetExists($name)) {
399
-			return parent::query($name);
400
-		} else {
401
-			if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
402
-				return parent::query($name);
403
-			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
404
-				return parent::query($name);
405
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
406
-				return parent::query($name);
407
-			}
408
-		}
409
-
410
-		throw new QueryException('Could not resolve ' . $name . '!' .
411
-			' Class can not be instantiated');
412
-	}
64
+    /**
65
+     * @var array
66
+     */
67
+    private $middleWares = array();
68
+
69
+    /** @var ServerContainer */
70
+    private $server;
71
+
72
+    /**
73
+     * Put your class dependencies in here
74
+     * @param string $appName the name of the app
75
+     * @param array $urlParams
76
+     * @param ServerContainer $server
77
+     */
78
+    public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
79
+        parent::__construct();
80
+        $this['AppName'] = $appName;
81
+        $this['urlParams'] = $urlParams;
82
+
83
+        /** @var \OC\ServerContainer $server */
84
+        if ($server === null) {
85
+            $server = \OC::$server;
86
+        }
87
+        $this->server = $server;
88
+        $this->server->registerAppContainer($appName, $this);
89
+
90
+        // aliases
91
+        $this->registerAlias('appName', 'AppName');
92
+        $this->registerAlias('webRoot', 'WebRoot');
93
+        $this->registerAlias('userId', 'UserId');
94
+
95
+        /**
96
+         * Core services
97
+         */
98
+        $this->registerService(IOutput::class, function($c){
99
+            return new Output($this->getServer()->getWebRoot());
100
+        });
101
+
102
+        $this->registerService(Folder::class, function() {
103
+            return $this->getServer()->getUserFolder();
104
+        });
105
+
106
+        $this->registerService(IAppData::class, function (SimpleContainer $c) {
107
+            return $this->getServer()->getAppDataDir($c->query('AppName'));
108
+        });
109
+
110
+        $this->registerService(IL10N::class, function($c) {
111
+            return $this->getServer()->getL10N($c->query('AppName'));
112
+        });
113
+
114
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
115
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
116
+
117
+        $this->registerService(IRequest::class, function() {
118
+            return $this->getServer()->query(IRequest::class);
119
+        });
120
+        $this->registerAlias('Request', IRequest::class);
121
+
122
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
123
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
124
+
125
+        $this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
126
+
127
+        $this->registerService(IServerContainer::class, function ($c) {
128
+            return $this->getServer();
129
+        });
130
+        $this->registerAlias('ServerContainer', IServerContainer::class);
131
+
132
+        $this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
133
+            return $c->query('OCA\WorkflowEngine\Manager');
134
+        });
135
+
136
+        $this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
137
+            return $c;
138
+        });
139
+
140
+        // commonly used attributes
141
+        $this->registerService('UserId', function ($c) {
142
+            return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
143
+        });
144
+
145
+        $this->registerService('WebRoot', function ($c) {
146
+            return $c->query('ServerContainer')->getWebRoot();
147
+        });
148
+
149
+        $this->registerService('fromMailAddress', function() {
150
+            return Util::getDefaultEmailAddress('no-reply');
151
+        });
152
+
153
+        $this->registerService('OC_Defaults', function ($c) {
154
+            return $c->getServer()->getThemingDefaults();
155
+        });
156
+
157
+        $this->registerService('OCP\Encryption\IManager', function ($c) {
158
+            return $this->getServer()->getEncryptionManager();
159
+        });
160
+
161
+        $this->registerService(IValidator::class, function($c) {
162
+            return $c->query(Validator::class);
163
+        });
164
+
165
+        $this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
166
+            return new \OC\Security\IdentityProof\Manager(
167
+                $this->getServer()->getAppDataDir('identityproof'),
168
+                $this->getServer()->getCrypto()
169
+            );
170
+        });
171
+
172
+
173
+        /**
174
+         * App Framework APIs
175
+         */
176
+        $this->registerService('API', function($c){
177
+            $c->query('OCP\\ILogger')->debug(
178
+                'Accessing the API class is deprecated! Use the appropriate ' .
179
+                'services instead!'
180
+            );
181
+            return new API($c['AppName']);
182
+        });
183
+
184
+        $this->registerService('Protocol', function($c){
185
+            /** @var \OC\Server $server */
186
+            $server = $c->query('ServerContainer');
187
+            $protocol = $server->getRequest()->getHttpProtocol();
188
+            return new Http($_SERVER, $protocol);
189
+        });
190
+
191
+        $this->registerService('Dispatcher', function($c) {
192
+            return new Dispatcher(
193
+                $c['Protocol'],
194
+                $c['MiddlewareDispatcher'],
195
+                $c['ControllerMethodReflector'],
196
+                $c['Request']
197
+            );
198
+        });
199
+
200
+        /**
201
+         * App Framework default arguments
202
+         */
203
+        $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
204
+        $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
205
+        $this->registerParameter('corsMaxAge', 1728000);
206
+
207
+        /**
208
+         * Middleware
209
+         */
210
+        $app = $this;
211
+        $this->registerService('SecurityMiddleware', function($c) use ($app){
212
+            /** @var \OC\Server $server */
213
+            $server = $app->getServer();
214
+
215
+            return new SecurityMiddleware(
216
+                $c['Request'],
217
+                $c['ControllerMethodReflector'],
218
+                $server->getNavigationManager(),
219
+                $server->getURLGenerator(),
220
+                $server->getLogger(),
221
+                $server->getSession(),
222
+                $c['AppName'],
223
+                $app->isLoggedIn(),
224
+                $app->isAdminUser(),
225
+                $server->getContentSecurityPolicyManager(),
226
+                $server->getCsrfTokenManager(),
227
+                $server->getContentSecurityPolicyNonceManager(),
228
+                $server->getBruteForceThrottler()
229
+            );
230
+
231
+        });
232
+
233
+        $this->registerService('CORSMiddleware', function($c) {
234
+            return new CORSMiddleware(
235
+                $c['Request'],
236
+                $c['ControllerMethodReflector'],
237
+                $c->query(IUserSession::class),
238
+                $c->getServer()->getBruteForceThrottler()
239
+            );
240
+        });
241
+
242
+        $this->registerService('SessionMiddleware', function($c) use ($app) {
243
+            return new SessionMiddleware(
244
+                $c['Request'],
245
+                $c['ControllerMethodReflector'],
246
+                $app->getServer()->getSession()
247
+            );
248
+        });
249
+
250
+        $this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
251
+            $twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
252
+            $userSession = $app->getServer()->getUserSession();
253
+            $session = $app->getServer()->getSession();
254
+            $urlGenerator = $app->getServer()->getURLGenerator();
255
+            $reflector = $c['ControllerMethodReflector'];
256
+            $request = $app->getServer()->getRequest();
257
+            return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
258
+        });
259
+
260
+        $this->registerService('OCSMiddleware', function (SimpleContainer $c) {
261
+            return new OCSMiddleware(
262
+                $c['Request']
263
+            );
264
+        });
265
+
266
+        $middleWares = &$this->middleWares;
267
+        $this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
268
+            $dispatcher = new MiddlewareDispatcher();
269
+            $dispatcher->registerMiddleware($c['CORSMiddleware']);
270
+            $dispatcher->registerMiddleware($c['OCSMiddleware']);
271
+            $dispatcher->registerMiddleware($c['SecurityMiddleware']);
272
+            $dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
273
+
274
+            foreach($middleWares as $middleWare) {
275
+                $dispatcher->registerMiddleware($c[$middleWare]);
276
+            }
277
+
278
+            $dispatcher->registerMiddleware($c['SessionMiddleware']);
279
+            return $dispatcher;
280
+        });
281
+
282
+    }
283
+
284
+
285
+    /**
286
+     * @deprecated implements only deprecated methods
287
+     * @return IApi
288
+     */
289
+    function getCoreApi()
290
+    {
291
+        return $this->query('API');
292
+    }
293
+
294
+    /**
295
+     * @return \OCP\IServerContainer
296
+     */
297
+    function getServer()
298
+    {
299
+        return $this->server;
300
+    }
301
+
302
+    /**
303
+     * @param string $middleWare
304
+     * @return boolean|null
305
+     */
306
+    function registerMiddleWare($middleWare) {
307
+        array_push($this->middleWares, $middleWare);
308
+    }
309
+
310
+    /**
311
+     * used to return the appname of the set application
312
+     * @return string the name of your application
313
+     */
314
+    function getAppName() {
315
+        return $this->query('AppName');
316
+    }
317
+
318
+    /**
319
+     * @deprecated use IUserSession->isLoggedIn()
320
+     * @return boolean
321
+     */
322
+    function isLoggedIn() {
323
+        return \OC::$server->getUserSession()->isLoggedIn();
324
+    }
325
+
326
+    /**
327
+     * @deprecated use IGroupManager->isAdmin($userId)
328
+     * @return boolean
329
+     */
330
+    function isAdminUser() {
331
+        $uid = $this->getUserId();
332
+        return \OC_User::isAdminUser($uid);
333
+    }
334
+
335
+    private function getUserId() {
336
+        return $this->getServer()->getSession()->get('user_id');
337
+    }
338
+
339
+    /**
340
+     * @deprecated use the ILogger instead
341
+     * @param string $message
342
+     * @param string $level
343
+     * @return mixed
344
+     */
345
+    function log($message, $level) {
346
+        switch($level){
347
+            case 'debug':
348
+                $level = \OCP\Util::DEBUG;
349
+                break;
350
+            case 'info':
351
+                $level = \OCP\Util::INFO;
352
+                break;
353
+            case 'warn':
354
+                $level = \OCP\Util::WARN;
355
+                break;
356
+            case 'fatal':
357
+                $level = \OCP\Util::FATAL;
358
+                break;
359
+            default:
360
+                $level = \OCP\Util::ERROR;
361
+                break;
362
+        }
363
+        \OCP\Util::writeLog($this->getAppName(), $message, $level);
364
+    }
365
+
366
+    /**
367
+     * Register a capability
368
+     *
369
+     * @param string $serviceName e.g. 'OCA\Files\Capabilities'
370
+     */
371
+    public function registerCapability($serviceName) {
372
+        $this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
373
+            return $this->query($serviceName);
374
+        });
375
+    }
376
+
377
+    /**
378
+     * @param string $name
379
+     * @return mixed
380
+     * @throws QueryException if the query could not be resolved
381
+     */
382
+    public function query($name) {
383
+        try {
384
+            return $this->queryNoFallback($name);
385
+        } catch (QueryException $e) {
386
+            return $this->getServer()->query($name);
387
+        }
388
+    }
389
+
390
+    /**
391
+     * @param string $name
392
+     * @return mixed
393
+     * @throws QueryException if the query could not be resolved
394
+     */
395
+    public function queryNoFallback($name) {
396
+        $name = $this->sanitizeName($name);
397
+
398
+        if ($this->offsetExists($name)) {
399
+            return parent::query($name);
400
+        } else {
401
+            if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
402
+                return parent::query($name);
403
+            } else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
404
+                return parent::query($name);
405
+            } else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
406
+                return parent::query($name);
407
+            }
408
+        }
409
+
410
+        throw new QueryException('Could not resolve ' . $name . '!' .
411
+            ' Class can not be instantiated');
412
+    }
413 413
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
 	 * @param array $urlParams
76 76
 	 * @param ServerContainer $server
77 77
 	 */
78
-	public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
78
+	public function __construct($appName, $urlParams = array(), ServerContainer $server = null) {
79 79
 		parent::__construct();
80 80
 		$this['AppName'] = $appName;
81 81
 		$this['urlParams'] = $urlParams;
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 		/**
96 96
 		 * Core services
97 97
 		 */
98
-		$this->registerService(IOutput::class, function($c){
98
+		$this->registerService(IOutput::class, function($c) {
99 99
 			return new Output($this->getServer()->getWebRoot());
100 100
 		});
101 101
 
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
 			return $this->getServer()->getUserFolder();
104 104
 		});
105 105
 
106
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
106
+		$this->registerService(IAppData::class, function(SimpleContainer $c) {
107 107
 			return $this->getServer()->getAppDataDir($c->query('AppName'));
108 108
 		});
109 109
 
@@ -124,25 +124,25 @@  discard block
 block discarded – undo
124 124
 
125 125
 		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
126 126
 
127
-		$this->registerService(IServerContainer::class, function ($c) {
127
+		$this->registerService(IServerContainer::class, function($c) {
128 128
 			return $this->getServer();
129 129
 		});
130 130
 		$this->registerAlias('ServerContainer', IServerContainer::class);
131 131
 
132
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
132
+		$this->registerService(\OCP\WorkflowEngine\IManager::class, function($c) {
133 133
 			return $c->query('OCA\WorkflowEngine\Manager');
134 134
 		});
135 135
 
136
-		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
136
+		$this->registerService(\OCP\AppFramework\IAppContainer::class, function($c) {
137 137
 			return $c;
138 138
 		});
139 139
 
140 140
 		// commonly used attributes
141
-		$this->registerService('UserId', function ($c) {
141
+		$this->registerService('UserId', function($c) {
142 142
 			return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
143 143
 		});
144 144
 
145
-		$this->registerService('WebRoot', function ($c) {
145
+		$this->registerService('WebRoot', function($c) {
146 146
 			return $c->query('ServerContainer')->getWebRoot();
147 147
 		});
148 148
 
@@ -150,11 +150,11 @@  discard block
 block discarded – undo
150 150
 			return Util::getDefaultEmailAddress('no-reply');
151 151
 		});
152 152
 
153
-		$this->registerService('OC_Defaults', function ($c) {
153
+		$this->registerService('OC_Defaults', function($c) {
154 154
 			return $c->getServer()->getThemingDefaults();
155 155
 		});
156 156
 
157
-		$this->registerService('OCP\Encryption\IManager', function ($c) {
157
+		$this->registerService('OCP\Encryption\IManager', function($c) {
158 158
 			return $this->getServer()->getEncryptionManager();
159 159
 		});
160 160
 
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 			return $c->query(Validator::class);
163 163
 		});
164 164
 
165
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
165
+		$this->registerService(\OC\Security\IdentityProof\Manager::class, function($c) {
166 166
 			return new \OC\Security\IdentityProof\Manager(
167 167
 				$this->getServer()->getAppDataDir('identityproof'),
168 168
 				$this->getServer()->getCrypto()
@@ -173,15 +173,15 @@  discard block
 block discarded – undo
173 173
 		/**
174 174
 		 * App Framework APIs
175 175
 		 */
176
-		$this->registerService('API', function($c){
176
+		$this->registerService('API', function($c) {
177 177
 			$c->query('OCP\\ILogger')->debug(
178
-				'Accessing the API class is deprecated! Use the appropriate ' .
178
+				'Accessing the API class is deprecated! Use the appropriate '.
179 179
 				'services instead!'
180 180
 			);
181 181
 			return new API($c['AppName']);
182 182
 		});
183 183
 
184
-		$this->registerService('Protocol', function($c){
184
+		$this->registerService('Protocol', function($c) {
185 185
 			/** @var \OC\Server $server */
186 186
 			$server = $c->query('ServerContainer');
187 187
 			$protocol = $server->getRequest()->getHttpProtocol();
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
 			);
248 248
 		});
249 249
 
250
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
250
+		$this->registerService('TwoFactorMiddleware', function(SimpleContainer $c) use ($app) {
251 251
 			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
252 252
 			$userSession = $app->getServer()->getUserSession();
253 253
 			$session = $app->getServer()->getSession();
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
 			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
258 258
 		});
259 259
 
260
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
260
+		$this->registerService('OCSMiddleware', function(SimpleContainer $c) {
261 261
 			return new OCSMiddleware(
262 262
 				$c['Request']
263 263
 			);
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
 			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
272 272
 			$dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
273 273
 
274
-			foreach($middleWares as $middleWare) {
274
+			foreach ($middleWares as $middleWare) {
275 275
 				$dispatcher->registerMiddleware($c[$middleWare]);
276 276
 			}
277 277
 
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
 	 * @return mixed
344 344
 	 */
345 345
 	function log($message, $level) {
346
-		switch($level){
346
+		switch ($level) {
347 347
 			case 'debug':
348 348
 				$level = \OCP\Util::DEBUG;
349 349
 				break;
@@ -402,12 +402,12 @@  discard block
 block discarded – undo
402 402
 				return parent::query($name);
403 403
 			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
404 404
 				return parent::query($name);
405
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
405
+			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']).'\\') === 0) {
406 406
 				return parent::query($name);
407 407
 			}
408 408
 		}
409 409
 
410
-		throw new QueryException('Could not resolve ' . $name . '!' .
410
+		throw new QueryException('Could not resolve '.$name.'!'.
411 411
 			' Class can not be instantiated');
412 412
 	}
413 413
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/App.php 2 patches
Indentation   +133 added lines, -133 removed lines patch added patch discarded remove patch
@@ -42,143 +42,143 @@
 block discarded – undo
42 42
  */
43 43
 class App {
44 44
 
45
-	/** @var string[] */
46
-	private static $nameSpaceCache = [];
47
-
48
-	/**
49
-	 * Turns an app id into a namespace by either reading the appinfo.xml's
50
-	 * namespace tag or uppercasing the appid's first letter
51
-	 * @param string $appId the app id
52
-	 * @param string $topNamespace the namespace which should be prepended to
53
-	 * the transformed app id, defaults to OCA\
54
-	 * @return string the starting namespace for the app
55
-	 */
56
-	public static function buildAppNamespace($appId, $topNamespace='OCA\\') {
57
-		// Hit the cache!
58
-		if (isset(self::$nameSpaceCache[$appId])) {
59
-			return $topNamespace . self::$nameSpaceCache[$appId];
60
-		}
61
-
62
-		$appInfo = \OC_App::getAppInfo($appId);
63
-		if (isset($appInfo['namespace'])) {
64
-			self::$nameSpaceCache[$appId] = trim($appInfo['namespace']);
65
-		} else {
66
-			// if the tag is not found, fall back to uppercasing the first letter
67
-			self::$nameSpaceCache[$appId] = ucfirst($appId);
68
-		}
69
-
70
-		return $topNamespace . self::$nameSpaceCache[$appId];
71
-	}
72
-
73
-
74
-	/**
75
-	 * Shortcut for calling a controller method and printing the result
76
-	 * @param string $controllerName the name of the controller under which it is
77
-	 *                               stored in the DI container
78
-	 * @param string $methodName the method that you want to call
79
-	 * @param DIContainer $container an instance of a pimple container.
80
-	 * @param array $urlParams list of URL parameters (optional)
81
-	 */
82
-	public static function main($controllerName, $methodName, DIContainer $container, array $urlParams = null) {
83
-		if (!is_null($urlParams)) {
84
-			$container['OCP\\IRequest']->setUrlParameters($urlParams);
85
-		} else if (isset($container['urlParams']) && !is_null($container['urlParams'])) {
86
-			$container['OCP\\IRequest']->setUrlParameters($container['urlParams']);
87
-		}
88
-		$appName = $container['AppName'];
89
-
90
-		// first try $controllerName then go for \OCA\AppName\Controller\$controllerName
91
-		try {
92
-			$controller = $container->query($controllerName);
93
-		} catch(QueryException $e) {
94
-			if ($appName === 'core') {
95
-				$appNameSpace = 'OC\\Core';
96
-			} else if ($appName === 'settings') {
97
-				$appNameSpace = 'OC\\Settings';
98
-			} else {
99
-				$appNameSpace = self::buildAppNamespace($appName);
100
-			}
101
-			$controllerName = $appNameSpace . '\\Controller\\' . $controllerName;
102
-			$controller = $container->query($controllerName);
103
-		}
104
-
105
-		// initialize the dispatcher and run all the middleware before the controller
106
-		/** @var Dispatcher $dispatcher */
107
-		$dispatcher = $container['Dispatcher'];
108
-
109
-		list(
110
-			$httpHeaders,
111
-			$responseHeaders,
112
-			$responseCookies,
113
-			$output,
114
-			$response
115
-		) = $dispatcher->dispatch($controller, $methodName);
116
-
117
-		$io = $container['OCP\\AppFramework\\Http\\IOutput'];
118
-
119
-		if(!is_null($httpHeaders)) {
120
-			$io->setHeader($httpHeaders);
121
-		}
122
-
123
-		foreach($responseHeaders as $name => $value) {
124
-			$io->setHeader($name . ': ' . $value);
125
-		}
126
-
127
-		foreach($responseCookies as $name => $value) {
128
-			$expireDate = null;
129
-			if($value['expireDate'] instanceof \DateTime) {
130
-				$expireDate = $value['expireDate']->getTimestamp();
131
-			}
132
-			$io->setCookie(
133
-				$name,
134
-				$value['value'],
135
-				$expireDate,
136
-				$container->getServer()->getWebRoot(),
137
-				null,
138
-				$container->getServer()->getRequest()->getServerProtocol() === 'https',
139
-				true
140
-			);
141
-		}
142
-
143
-		/*
45
+    /** @var string[] */
46
+    private static $nameSpaceCache = [];
47
+
48
+    /**
49
+     * Turns an app id into a namespace by either reading the appinfo.xml's
50
+     * namespace tag or uppercasing the appid's first letter
51
+     * @param string $appId the app id
52
+     * @param string $topNamespace the namespace which should be prepended to
53
+     * the transformed app id, defaults to OCA\
54
+     * @return string the starting namespace for the app
55
+     */
56
+    public static function buildAppNamespace($appId, $topNamespace='OCA\\') {
57
+        // Hit the cache!
58
+        if (isset(self::$nameSpaceCache[$appId])) {
59
+            return $topNamespace . self::$nameSpaceCache[$appId];
60
+        }
61
+
62
+        $appInfo = \OC_App::getAppInfo($appId);
63
+        if (isset($appInfo['namespace'])) {
64
+            self::$nameSpaceCache[$appId] = trim($appInfo['namespace']);
65
+        } else {
66
+            // if the tag is not found, fall back to uppercasing the first letter
67
+            self::$nameSpaceCache[$appId] = ucfirst($appId);
68
+        }
69
+
70
+        return $topNamespace . self::$nameSpaceCache[$appId];
71
+    }
72
+
73
+
74
+    /**
75
+     * Shortcut for calling a controller method and printing the result
76
+     * @param string $controllerName the name of the controller under which it is
77
+     *                               stored in the DI container
78
+     * @param string $methodName the method that you want to call
79
+     * @param DIContainer $container an instance of a pimple container.
80
+     * @param array $urlParams list of URL parameters (optional)
81
+     */
82
+    public static function main($controllerName, $methodName, DIContainer $container, array $urlParams = null) {
83
+        if (!is_null($urlParams)) {
84
+            $container['OCP\\IRequest']->setUrlParameters($urlParams);
85
+        } else if (isset($container['urlParams']) && !is_null($container['urlParams'])) {
86
+            $container['OCP\\IRequest']->setUrlParameters($container['urlParams']);
87
+        }
88
+        $appName = $container['AppName'];
89
+
90
+        // first try $controllerName then go for \OCA\AppName\Controller\$controllerName
91
+        try {
92
+            $controller = $container->query($controllerName);
93
+        } catch(QueryException $e) {
94
+            if ($appName === 'core') {
95
+                $appNameSpace = 'OC\\Core';
96
+            } else if ($appName === 'settings') {
97
+                $appNameSpace = 'OC\\Settings';
98
+            } else {
99
+                $appNameSpace = self::buildAppNamespace($appName);
100
+            }
101
+            $controllerName = $appNameSpace . '\\Controller\\' . $controllerName;
102
+            $controller = $container->query($controllerName);
103
+        }
104
+
105
+        // initialize the dispatcher and run all the middleware before the controller
106
+        /** @var Dispatcher $dispatcher */
107
+        $dispatcher = $container['Dispatcher'];
108
+
109
+        list(
110
+            $httpHeaders,
111
+            $responseHeaders,
112
+            $responseCookies,
113
+            $output,
114
+            $response
115
+        ) = $dispatcher->dispatch($controller, $methodName);
116
+
117
+        $io = $container['OCP\\AppFramework\\Http\\IOutput'];
118
+
119
+        if(!is_null($httpHeaders)) {
120
+            $io->setHeader($httpHeaders);
121
+        }
122
+
123
+        foreach($responseHeaders as $name => $value) {
124
+            $io->setHeader($name . ': ' . $value);
125
+        }
126
+
127
+        foreach($responseCookies as $name => $value) {
128
+            $expireDate = null;
129
+            if($value['expireDate'] instanceof \DateTime) {
130
+                $expireDate = $value['expireDate']->getTimestamp();
131
+            }
132
+            $io->setCookie(
133
+                $name,
134
+                $value['value'],
135
+                $expireDate,
136
+                $container->getServer()->getWebRoot(),
137
+                null,
138
+                $container->getServer()->getRequest()->getServerProtocol() === 'https',
139
+                true
140
+            );
141
+        }
142
+
143
+        /*
144 144
 		 * Status 204 does not have a body and no Content Length
145 145
 		 * Status 304 does not have a body and does not need a Content Length
146 146
 		 * https://tools.ietf.org/html/rfc7230#section-3.3
147 147
 		 * https://tools.ietf.org/html/rfc7230#section-3.3.2
148 148
 		 */
149
-		if ($httpHeaders !== Http::STATUS_NO_CONTENT && $httpHeaders !== Http::STATUS_NOT_MODIFIED) {
150
-			if ($response instanceof ICallbackResponse) {
151
-				$response->callback($io);
152
-			} else if (!is_null($output)) {
153
-				$io->setHeader('Content-Length: ' . strlen($output));
154
-				$io->setOutput($output);
155
-			}
156
-		}
157
-
158
-	}
159
-
160
-	/**
161
-	 * Shortcut for calling a controller method and printing the result.
162
-	 * Similar to App:main except that no headers will be sent.
163
-	 * This should be used for example when registering sections via
164
-	 * \OC\AppFramework\Core\API::registerAdmin()
165
-	 *
166
-	 * @param string $controllerName the name of the controller under which it is
167
-	 *                               stored in the DI container
168
-	 * @param string $methodName the method that you want to call
169
-	 * @param array $urlParams an array with variables extracted from the routes
170
-	 * @param DIContainer $container an instance of a pimple container.
171
-	 */
172
-	public static function part($controllerName, $methodName, array $urlParams,
173
-								DIContainer $container){
174
-
175
-		$container['urlParams'] = $urlParams;
176
-		$controller = $container[$controllerName];
177
-
178
-		$dispatcher = $container['Dispatcher'];
179
-
180
-		list(, , $output) =  $dispatcher->dispatch($controller, $methodName);
181
-		return $output;
182
-	}
149
+        if ($httpHeaders !== Http::STATUS_NO_CONTENT && $httpHeaders !== Http::STATUS_NOT_MODIFIED) {
150
+            if ($response instanceof ICallbackResponse) {
151
+                $response->callback($io);
152
+            } else if (!is_null($output)) {
153
+                $io->setHeader('Content-Length: ' . strlen($output));
154
+                $io->setOutput($output);
155
+            }
156
+        }
157
+
158
+    }
159
+
160
+    /**
161
+     * Shortcut for calling a controller method and printing the result.
162
+     * Similar to App:main except that no headers will be sent.
163
+     * This should be used for example when registering sections via
164
+     * \OC\AppFramework\Core\API::registerAdmin()
165
+     *
166
+     * @param string $controllerName the name of the controller under which it is
167
+     *                               stored in the DI container
168
+     * @param string $methodName the method that you want to call
169
+     * @param array $urlParams an array with variables extracted from the routes
170
+     * @param DIContainer $container an instance of a pimple container.
171
+     */
172
+    public static function part($controllerName, $methodName, array $urlParams,
173
+                                DIContainer $container){
174
+
175
+        $container['urlParams'] = $urlParams;
176
+        $controller = $container[$controllerName];
177
+
178
+        $dispatcher = $container['Dispatcher'];
179
+
180
+        list(, , $output) =  $dispatcher->dispatch($controller, $methodName);
181
+        return $output;
182
+    }
183 183
 
184 184
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -53,10 +53,10 @@  discard block
 block discarded – undo
53 53
 	 * the transformed app id, defaults to OCA\
54 54
 	 * @return string the starting namespace for the app
55 55
 	 */
56
-	public static function buildAppNamespace($appId, $topNamespace='OCA\\') {
56
+	public static function buildAppNamespace($appId, $topNamespace = 'OCA\\') {
57 57
 		// Hit the cache!
58 58
 		if (isset(self::$nameSpaceCache[$appId])) {
59
-			return $topNamespace . self::$nameSpaceCache[$appId];
59
+			return $topNamespace.self::$nameSpaceCache[$appId];
60 60
 		}
61 61
 
62 62
 		$appInfo = \OC_App::getAppInfo($appId);
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
 			self::$nameSpaceCache[$appId] = ucfirst($appId);
68 68
 		}
69 69
 
70
-		return $topNamespace . self::$nameSpaceCache[$appId];
70
+		return $topNamespace.self::$nameSpaceCache[$appId];
71 71
 	}
72 72
 
73 73
 
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 		// first try $controllerName then go for \OCA\AppName\Controller\$controllerName
91 91
 		try {
92 92
 			$controller = $container->query($controllerName);
93
-		} catch(QueryException $e) {
93
+		} catch (QueryException $e) {
94 94
 			if ($appName === 'core') {
95 95
 				$appNameSpace = 'OC\\Core';
96 96
 			} else if ($appName === 'settings') {
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 			} else {
99 99
 				$appNameSpace = self::buildAppNamespace($appName);
100 100
 			}
101
-			$controllerName = $appNameSpace . '\\Controller\\' . $controllerName;
101
+			$controllerName = $appNameSpace.'\\Controller\\'.$controllerName;
102 102
 			$controller = $container->query($controllerName);
103 103
 		}
104 104
 
@@ -116,17 +116,17 @@  discard block
 block discarded – undo
116 116
 
117 117
 		$io = $container['OCP\\AppFramework\\Http\\IOutput'];
118 118
 
119
-		if(!is_null($httpHeaders)) {
119
+		if (!is_null($httpHeaders)) {
120 120
 			$io->setHeader($httpHeaders);
121 121
 		}
122 122
 
123
-		foreach($responseHeaders as $name => $value) {
124
-			$io->setHeader($name . ': ' . $value);
123
+		foreach ($responseHeaders as $name => $value) {
124
+			$io->setHeader($name.': '.$value);
125 125
 		}
126 126
 
127
-		foreach($responseCookies as $name => $value) {
127
+		foreach ($responseCookies as $name => $value) {
128 128
 			$expireDate = null;
129
-			if($value['expireDate'] instanceof \DateTime) {
129
+			if ($value['expireDate'] instanceof \DateTime) {
130 130
 				$expireDate = $value['expireDate']->getTimestamp();
131 131
 			}
132 132
 			$io->setCookie(
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 			if ($response instanceof ICallbackResponse) {
151 151
 				$response->callback($io);
152 152
 			} else if (!is_null($output)) {
153
-				$io->setHeader('Content-Length: ' . strlen($output));
153
+				$io->setHeader('Content-Length: '.strlen($output));
154 154
 				$io->setOutput($output);
155 155
 			}
156 156
 		}
@@ -170,14 +170,14 @@  discard block
 block discarded – undo
170 170
 	 * @param DIContainer $container an instance of a pimple container.
171 171
 	 */
172 172
 	public static function part($controllerName, $methodName, array $urlParams,
173
-								DIContainer $container){
173
+								DIContainer $container) {
174 174
 
175 175
 		$container['urlParams'] = $urlParams;
176 176
 		$controller = $container[$controllerName];
177 177
 
178 178
 		$dispatcher = $container['Dispatcher'];
179 179
 
180
-		list(, , $output) =  $dispatcher->dispatch($controller, $methodName);
180
+		list(,, $output) = $dispatcher->dispatch($controller, $methodName);
181 181
 		return $output;
182 182
 	}
183 183
 
Please login to merge, or discard this patch.
lib/private/legacy/app.php 2 patches
Indentation   +1334 added lines, -1334 removed lines patch added patch discarded remove patch
@@ -61,1338 +61,1338 @@
 block discarded – undo
61 61
  * upgrading and removing apps.
62 62
  */
63 63
 class OC_App {
64
-	static private $appVersion = [];
65
-	static private $adminForms = array();
66
-	static private $personalForms = array();
67
-	static private $appInfo = array();
68
-	static private $appTypes = array();
69
-	static private $loadedApps = array();
70
-	static private $altLogin = array();
71
-	static private $alreadyRegistered = [];
72
-	const officialApp = 200;
73
-
74
-	/**
75
-	 * clean the appId
76
-	 *
77
-	 * @param string|boolean $app AppId that needs to be cleaned
78
-	 * @return string
79
-	 */
80
-	public static function cleanAppId($app) {
81
-		return str_replace(array('\0', '/', '\\', '..'), '', $app);
82
-	}
83
-
84
-	/**
85
-	 * Check if an app is loaded
86
-	 *
87
-	 * @param string $app
88
-	 * @return bool
89
-	 */
90
-	public static function isAppLoaded($app) {
91
-		return in_array($app, self::$loadedApps, true);
92
-	}
93
-
94
-	/**
95
-	 * loads all apps
96
-	 *
97
-	 * @param string[] | string | null $types
98
-	 * @return bool
99
-	 *
100
-	 * This function walks through the ownCloud directory and loads all apps
101
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
102
-	 * exists.
103
-	 *
104
-	 * if $types is set, only apps of those types will be loaded
105
-	 */
106
-	public static function loadApps($types = null) {
107
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
108
-			return false;
109
-		}
110
-		// Load the enabled apps here
111
-		$apps = self::getEnabledApps();
112
-
113
-		// Add each apps' folder as allowed class path
114
-		foreach($apps as $app) {
115
-			$path = self::getAppPath($app);
116
-			if($path !== false) {
117
-				self::registerAutoloading($app, $path);
118
-			}
119
-		}
120
-
121
-		// prevent app.php from printing output
122
-		ob_start();
123
-		foreach ($apps as $app) {
124
-			if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
125
-				self::loadApp($app);
126
-			}
127
-		}
128
-		ob_end_clean();
129
-
130
-		return true;
131
-	}
132
-
133
-	/**
134
-	 * load a single app
135
-	 *
136
-	 * @param string $app
137
-	 */
138
-	public static function loadApp($app) {
139
-		self::$loadedApps[] = $app;
140
-		$appPath = self::getAppPath($app);
141
-		if($appPath === false) {
142
-			return;
143
-		}
144
-
145
-		// in case someone calls loadApp() directly
146
-		self::registerAutoloading($app, $appPath);
147
-
148
-		if (is_file($appPath . '/appinfo/app.php')) {
149
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
-			self::requireAppFile($app);
151
-			if (self::isType($app, array('authentication'))) {
152
-				// since authentication apps affect the "is app enabled for group" check,
153
-				// the enabled apps cache needs to be cleared to make sure that the
154
-				// next time getEnableApps() is called it will also include apps that were
155
-				// enabled for groups
156
-				self::$enabledAppsCache = array();
157
-			}
158
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
159
-		}
160
-
161
-		$info = self::getAppInfo($app);
162
-		if (!empty($info['activity']['filters'])) {
163
-			foreach ($info['activity']['filters'] as $filter) {
164
-				\OC::$server->getActivityManager()->registerFilter($filter);
165
-			}
166
-		}
167
-		if (!empty($info['activity']['settings'])) {
168
-			foreach ($info['activity']['settings'] as $setting) {
169
-				\OC::$server->getActivityManager()->registerSetting($setting);
170
-			}
171
-		}
172
-		if (!empty($info['activity']['providers'])) {
173
-			foreach ($info['activity']['providers'] as $provider) {
174
-				\OC::$server->getActivityManager()->registerProvider($provider);
175
-			}
176
-		}
177
-	}
178
-
179
-	/**
180
-	 * @internal
181
-	 * @param string $app
182
-	 * @param string $path
183
-	 */
184
-	public static function registerAutoloading($app, $path) {
185
-		$key = $app . '-' . $path;
186
-		if(isset(self::$alreadyRegistered[$key])) {
187
-			return;
188
-		}
189
-		self::$alreadyRegistered[$key] = true;
190
-		// Register on PSR-4 composer autoloader
191
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
192
-		\OC::$server->registerNamespace($app, $appNamespace);
193
-		\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
194
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
195
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
196
-		}
197
-
198
-		// Register on legacy autoloader
199
-		\OC::$loader->addValidRoot($path);
200
-	}
201
-
202
-	/**
203
-	 * Load app.php from the given app
204
-	 *
205
-	 * @param string $app app name
206
-	 */
207
-	private static function requireAppFile($app) {
208
-		try {
209
-			// encapsulated here to avoid variable scope conflicts
210
-			require_once $app . '/appinfo/app.php';
211
-		} catch (Error $ex) {
212
-			\OC::$server->getLogger()->logException($ex);
213
-			$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
214
-			if (!in_array($app, $blacklist)) {
215
-				self::disable($app);
216
-			}
217
-		}
218
-	}
219
-
220
-	/**
221
-	 * check if an app is of a specific type
222
-	 *
223
-	 * @param string $app
224
-	 * @param string|array $types
225
-	 * @return bool
226
-	 */
227
-	public static function isType($app, $types) {
228
-		if (is_string($types)) {
229
-			$types = array($types);
230
-		}
231
-		$appTypes = self::getAppTypes($app);
232
-		foreach ($types as $type) {
233
-			if (array_search($type, $appTypes) !== false) {
234
-				return true;
235
-			}
236
-		}
237
-		return false;
238
-	}
239
-
240
-	/**
241
-	 * get the types of an app
242
-	 *
243
-	 * @param string $app
244
-	 * @return array
245
-	 */
246
-	private static function getAppTypes($app) {
247
-		//load the cache
248
-		if (count(self::$appTypes) == 0) {
249
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
250
-		}
251
-
252
-		if (isset(self::$appTypes[$app])) {
253
-			return explode(',', self::$appTypes[$app]);
254
-		} else {
255
-			return array();
256
-		}
257
-	}
258
-
259
-	/**
260
-	 * read app types from info.xml and cache them in the database
261
-	 */
262
-	public static function setAppTypes($app) {
263
-		$appData = self::getAppInfo($app);
264
-		if(!is_array($appData)) {
265
-			return;
266
-		}
267
-
268
-		if (isset($appData['types'])) {
269
-			$appTypes = implode(',', $appData['types']);
270
-		} else {
271
-			$appTypes = '';
272
-			$appData['types'] = [];
273
-		}
274
-
275
-		\OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
276
-
277
-		if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
278
-			$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
279
-			if ($enabled !== 'yes' && $enabled !== 'no') {
280
-				\OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
281
-			}
282
-		}
283
-	}
284
-
285
-	/**
286
-	 * check if app is shipped
287
-	 *
288
-	 * @param string $appId the id of the app to check
289
-	 * @return bool
290
-	 *
291
-	 * Check if an app that is installed is a shipped app or installed from the appstore.
292
-	 */
293
-	public static function isShipped($appId) {
294
-		return \OC::$server->getAppManager()->isShipped($appId);
295
-	}
296
-
297
-	/**
298
-	 * get all enabled apps
299
-	 */
300
-	protected static $enabledAppsCache = array();
301
-
302
-	/**
303
-	 * Returns apps enabled for the current user.
304
-	 *
305
-	 * @param bool $forceRefresh whether to refresh the cache
306
-	 * @param bool $all whether to return apps for all users, not only the
307
-	 * currently logged in one
308
-	 * @return string[]
309
-	 */
310
-	public static function getEnabledApps($forceRefresh = false, $all = false) {
311
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
312
-			return array();
313
-		}
314
-		// in incognito mode or when logged out, $user will be false,
315
-		// which is also the case during an upgrade
316
-		$appManager = \OC::$server->getAppManager();
317
-		if ($all) {
318
-			$user = null;
319
-		} else {
320
-			$user = \OC::$server->getUserSession()->getUser();
321
-		}
322
-
323
-		if (is_null($user)) {
324
-			$apps = $appManager->getInstalledApps();
325
-		} else {
326
-			$apps = $appManager->getEnabledAppsForUser($user);
327
-		}
328
-		$apps = array_filter($apps, function ($app) {
329
-			return $app !== 'files';//we add this manually
330
-		});
331
-		sort($apps);
332
-		array_unshift($apps, 'files');
333
-		return $apps;
334
-	}
335
-
336
-	/**
337
-	 * checks whether or not an app is enabled
338
-	 *
339
-	 * @param string $app app
340
-	 * @return bool
341
-	 *
342
-	 * This function checks whether or not an app is enabled.
343
-	 */
344
-	public static function isEnabled($app) {
345
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
346
-	}
347
-
348
-	/**
349
-	 * enables an app
350
-	 *
351
-	 * @param string $appId
352
-	 * @param array $groups (optional) when set, only these groups will have access to the app
353
-	 * @throws \Exception
354
-	 * @return void
355
-	 *
356
-	 * This function set an app as enabled in appconfig.
357
-	 */
358
-	public function enable($appId,
359
-						   $groups = null) {
360
-		self::$enabledAppsCache = []; // flush
361
-		$l = \OC::$server->getL10N('core');
362
-		$config = \OC::$server->getConfig();
363
-
364
-		// Check if app is already downloaded
365
-		$installer = new Installer(
366
-			\OC::$server->getAppFetcher(),
367
-			\OC::$server->getHTTPClientService(),
368
-			\OC::$server->getTempManager(),
369
-			\OC::$server->getLogger()
370
-		);
371
-		$isDownloaded = $installer->isDownloaded($appId);
372
-
373
-		if(!$isDownloaded) {
374
-			$installer->downloadApp($appId);
375
-		}
376
-
377
-		if (!Installer::isInstalled($appId)) {
378
-			$appId = self::installApp(
379
-				$appId,
380
-				$config,
381
-				$l
382
-			);
383
-			$appPath = self::getAppPath($appId);
384
-			self::registerAutoloading($appId, $appPath);
385
-			$installer->installApp($appId);
386
-		} else {
387
-			// check for required dependencies
388
-			$info = self::getAppInfo($appId);
389
-			self::checkAppDependencies($config, $l, $info);
390
-			$appPath = self::getAppPath($appId);
391
-			self::registerAutoloading($appId, $appPath);
392
-			$installer->installApp($appId);
393
-		}
394
-
395
-		$appManager = \OC::$server->getAppManager();
396
-		if (!is_null($groups)) {
397
-			$groupManager = \OC::$server->getGroupManager();
398
-			$groupsList = [];
399
-			foreach ($groups as $group) {
400
-				$groupItem = $groupManager->get($group);
401
-				if ($groupItem instanceof \OCP\IGroup) {
402
-					$groupsList[] = $groupManager->get($group);
403
-				}
404
-			}
405
-			$appManager->enableAppForGroups($appId, $groupsList);
406
-		} else {
407
-			$appManager->enableApp($appId);
408
-		}
409
-
410
-		$info = self::getAppInfo($appId);
411
-		if(isset($info['settings']) && is_array($info['settings'])) {
412
-			$appPath = self::getAppPath($appId);
413
-			self::registerAutoloading($appId, $appPath);
414
-			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
415
-		}
416
-	}
417
-
418
-	/**
419
-	 * @param string $app
420
-	 * @return bool
421
-	 */
422
-	public static function removeApp($app) {
423
-		if (self::isShipped($app)) {
424
-			return false;
425
-		}
426
-
427
-		$installer = new Installer(
428
-			\OC::$server->getAppFetcher(),
429
-			\OC::$server->getHTTPClientService(),
430
-			\OC::$server->getTempManager(),
431
-			\OC::$server->getLogger()
432
-		);
433
-		return $installer->removeApp($app);
434
-	}
435
-
436
-	/**
437
-	 * This function set an app as disabled in appconfig.
438
-	 *
439
-	 * @param string $app app
440
-	 * @throws Exception
441
-	 */
442
-	public static function disable($app) {
443
-		// flush
444
-		self::$enabledAppsCache = array();
445
-
446
-		// run uninstall steps
447
-		$appData = OC_App::getAppInfo($app);
448
-		if (!is_null($appData)) {
449
-			OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
450
-		}
451
-
452
-		// emit disable hook - needed anymore ?
453
-		\OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
454
-
455
-		// finally disable it
456
-		$appManager = \OC::$server->getAppManager();
457
-		$appManager->disableApp($app);
458
-	}
459
-
460
-	/**
461
-	 * Returns the Settings Navigation
462
-	 *
463
-	 * @return string[]
464
-	 *
465
-	 * This function returns an array containing all settings pages added. The
466
-	 * entries are sorted by the key 'order' ascending.
467
-	 */
468
-	public static function getSettingsNavigation() {
469
-		$l = \OC::$server->getL10N('lib');
470
-		$urlGenerator = \OC::$server->getURLGenerator();
471
-
472
-		$settings = array();
473
-		// by default, settings only contain the help menu
474
-		if (\OC::$server->getSystemConfig()->getValue('knowledgebaseenabled', true)) {
475
-			$settings = array(
476
-				array(
477
-					"id" => "help",
478
-					"order" => 4,
479
-					"href" => $urlGenerator->linkToRoute('settings_help'),
480
-					"name" => $l->t("Help"),
481
-					"icon" => $urlGenerator->imagePath("settings", "help.svg")
482
-				)
483
-			);
484
-		}
485
-
486
-		// if the user is logged-in
487
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
488
-			// personal menu
489
-			$settings[] = array(
490
-				"id" => "personal",
491
-				"order" => 1,
492
-				"href" => $urlGenerator->linkToRoute('settings_personal'),
493
-				"name" => $l->t("Personal"),
494
-				"icon" => $urlGenerator->imagePath("settings", "personal.svg")
495
-			);
496
-
497
-			//SubAdmins are also allowed to access user management
498
-			$userObject = \OC::$server->getUserSession()->getUser();
499
-			$isSubAdmin = false;
500
-			if($userObject !== null) {
501
-				$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
502
-			}
503
-			if ($isSubAdmin) {
504
-				// admin users menu
505
-				$settings[] = array(
506
-					"id" => "core_users",
507
-					"order" => 3,
508
-					"href" => $urlGenerator->linkToRoute('settings_users'),
509
-					"name" => $l->t("Users"),
510
-					"icon" => $urlGenerator->imagePath("settings", "users.svg")
511
-				);
512
-			}
513
-
514
-			// if the user is an admin
515
-			if (OC_User::isAdminUser(OC_User::getUser())) {
516
-				// admin settings
517
-				$settings[] = array(
518
-					"id" => "admin",
519
-					"order" => 2,
520
-					"href" => $urlGenerator->linkToRoute('settings.AdminSettings.index'),
521
-					"name" => $l->t("Admin"),
522
-					"icon" => $urlGenerator->imagePath("settings", "admin.svg")
523
-				);
524
-			}
525
-		}
526
-
527
-		$navigation = self::proceedNavigation($settings);
528
-		return $navigation;
529
-	}
530
-
531
-	// This is private as well. It simply works, so don't ask for more details
532
-	private static function proceedNavigation($list) {
533
-		$headerIconCount = 8;
534
-		if(OC_User::isAdminUser(OC_User::getUser())) {
535
-			$headerIconCount--;
536
-		}
537
-		usort($list, function($a, $b) {
538
-			if (isset($a['order']) && isset($b['order'])) {
539
-				return ($a['order'] < $b['order']) ? -1 : 1;
540
-			} else if (isset($a['order']) || isset($b['order'])) {
541
-				return isset($a['order']) ? -1 : 1;
542
-			} else {
543
-				return ($a['name'] < $b['name']) ? -1 : 1;
544
-			}
545
-		});
546
-
547
-		$activeAppIndex = -1;
548
-		$activeApp = OC::$server->getNavigationManager()->getActiveEntry();
549
-		foreach ($list as $index => &$navEntry) {
550
-			if ($navEntry['id'] == $activeApp) {
551
-				$navEntry['active'] = true;
552
-				$activeAppIndex = $index;
553
-			} else {
554
-				$navEntry['active'] = false;
555
-			}
556
-		}
557
-		unset($navEntry);
558
-
559
-		if($activeAppIndex > ($headerIconCount-1)) {
560
-			$active = $list[$activeAppIndex];
561
-			$lastInHeader = $list[$headerIconCount-1];
562
-			$list[$headerIconCount-1] = $active;
563
-			$list[$activeAppIndex] = $lastInHeader;
564
-		}
565
-
566
-		foreach ($list as $index => &$navEntry) {
567
-			$navEntry['showInHeader'] = false;
568
-			if($index < $headerIconCount) {
569
-				$navEntry['showInHeader'] = true;
570
-			}
571
-		}
572
-
573
-
574
-
575
-		return $list;
576
-	}
577
-
578
-	public static function proceedAppNavigation($entries) {
579
-		$headerIconCount = 8;
580
-		if(OC_User::isAdminUser(OC_User::getUser())) {
581
-			$headerIconCount--;
582
-		}
583
-		$activeAppIndex = -1;
584
-		$list = self::proceedNavigation($entries);
585
-
586
-		$activeApp = OC::$server->getNavigationManager()->getActiveEntry();
587
-		foreach ($list as $index => &$navEntry) {
588
-			if ($navEntry['id'] == $activeApp) {
589
-				$navEntry['active'] = true;
590
-				$activeAppIndex = $index;
591
-			} else {
592
-				$navEntry['active'] = false;
593
-			}
594
-		}
595
-		// move active item to last position
596
-		if($activeAppIndex > ($headerIconCount-1)) {
597
-			$active = $list[$activeAppIndex];
598
-			$lastInHeader = $list[$headerIconCount-1];
599
-			$list[$headerIconCount-1] = $active;
600
-			$list[$activeAppIndex] = $lastInHeader;
601
-		}
602
-		$list = array_slice($list, 0, $headerIconCount);
603
-
604
-		return $list;
605
-	}
606
-
607
-	/**
608
-	 * Get the path where to install apps
609
-	 *
610
-	 * @return string|false
611
-	 */
612
-	public static function getInstallPath() {
613
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
614
-			return false;
615
-		}
616
-
617
-		foreach (OC::$APPSROOTS as $dir) {
618
-			if (isset($dir['writable']) && $dir['writable'] === true) {
619
-				return $dir['path'];
620
-			}
621
-		}
622
-
623
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
624
-		return null;
625
-	}
626
-
627
-
628
-	/**
629
-	 * search for an app in all app-directories
630
-	 *
631
-	 * @param string $appId
632
-	 * @return false|string
633
-	 */
634
-	public static function findAppInDirectories($appId) {
635
-		$sanitizedAppId = self::cleanAppId($appId);
636
-		if($sanitizedAppId !== $appId) {
637
-			return false;
638
-		}
639
-		static $app_dir = array();
640
-
641
-		if (isset($app_dir[$appId])) {
642
-			return $app_dir[$appId];
643
-		}
644
-
645
-		$possibleApps = array();
646
-		foreach (OC::$APPSROOTS as $dir) {
647
-			if (file_exists($dir['path'] . '/' . $appId)) {
648
-				$possibleApps[] = $dir;
649
-			}
650
-		}
651
-
652
-		if (empty($possibleApps)) {
653
-			return false;
654
-		} elseif (count($possibleApps) === 1) {
655
-			$dir = array_shift($possibleApps);
656
-			$app_dir[$appId] = $dir;
657
-			return $dir;
658
-		} else {
659
-			$versionToLoad = array();
660
-			foreach ($possibleApps as $possibleApp) {
661
-				$version = self::getAppVersionByPath($possibleApp['path']);
662
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
663
-					$versionToLoad = array(
664
-						'dir' => $possibleApp,
665
-						'version' => $version,
666
-					);
667
-				}
668
-			}
669
-			$app_dir[$appId] = $versionToLoad['dir'];
670
-			return $versionToLoad['dir'];
671
-			//TODO - write test
672
-		}
673
-	}
674
-
675
-	/**
676
-	 * Get the directory for the given app.
677
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
678
-	 *
679
-	 * @param string $appId
680
-	 * @return string|false
681
-	 */
682
-	public static function getAppPath($appId) {
683
-		if ($appId === null || trim($appId) === '') {
684
-			return false;
685
-		}
686
-
687
-		if (($dir = self::findAppInDirectories($appId)) != false) {
688
-			return $dir['path'] . '/' . $appId;
689
-		}
690
-		return false;
691
-	}
692
-
693
-	/**
694
-	 * Get the path for the given app on the access
695
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
696
-	 *
697
-	 * @param string $appId
698
-	 * @return string|false
699
-	 */
700
-	public static function getAppWebPath($appId) {
701
-		if (($dir = self::findAppInDirectories($appId)) != false) {
702
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
703
-		}
704
-		return false;
705
-	}
706
-
707
-	/**
708
-	 * get the last version of the app from appinfo/info.xml
709
-	 *
710
-	 * @param string $appId
711
-	 * @param bool $useCache
712
-	 * @return string
713
-	 */
714
-	public static function getAppVersion($appId, $useCache = true) {
715
-		if($useCache && isset(self::$appVersion[$appId])) {
716
-			return self::$appVersion[$appId];
717
-		}
718
-
719
-		$file = self::getAppPath($appId);
720
-		self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
721
-		return self::$appVersion[$appId];
722
-	}
723
-
724
-	/**
725
-	 * get app's version based on it's path
726
-	 *
727
-	 * @param string $path
728
-	 * @return string
729
-	 */
730
-	public static function getAppVersionByPath($path) {
731
-		$infoFile = $path . '/appinfo/info.xml';
732
-		$appData = self::getAppInfo($infoFile, true);
733
-		return isset($appData['version']) ? $appData['version'] : '';
734
-	}
735
-
736
-
737
-	/**
738
-	 * Read all app metadata from the info.xml file
739
-	 *
740
-	 * @param string $appId id of the app or the path of the info.xml file
741
-	 * @param bool $path
742
-	 * @param string $lang
743
-	 * @return array|null
744
-	 * @note all data is read from info.xml, not just pre-defined fields
745
-	 */
746
-	public static function getAppInfo($appId, $path = false, $lang = null) {
747
-		if ($path) {
748
-			$file = $appId;
749
-		} else {
750
-			if ($lang === null && isset(self::$appInfo[$appId])) {
751
-				return self::$appInfo[$appId];
752
-			}
753
-			$appPath = self::getAppPath($appId);
754
-			if($appPath === false) {
755
-				return null;
756
-			}
757
-			$file = $appPath . '/appinfo/info.xml';
758
-		}
759
-
760
-		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->create('core.appinfo'));
761
-		$data = $parser->parse($file);
762
-
763
-		if (is_array($data)) {
764
-			$data = OC_App::parseAppInfo($data, $lang);
765
-		}
766
-		if(isset($data['ocsid'])) {
767
-			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
768
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
769
-				$data['ocsid'] = $storedId;
770
-			}
771
-		}
772
-
773
-		if ($lang === null) {
774
-			self::$appInfo[$appId] = $data;
775
-		}
776
-
777
-		return $data;
778
-	}
779
-
780
-	/**
781
-	 * Returns the navigation
782
-	 *
783
-	 * @return array
784
-	 *
785
-	 * This function returns an array containing all entries added. The
786
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
787
-	 * given for each app the following keys exist:
788
-	 *   - active: boolean, signals if the user is on this navigation entry
789
-	 */
790
-	public static function getNavigation() {
791
-		$entries = OC::$server->getNavigationManager()->getAll();
792
-		$navigation = self::proceedNavigation($entries);
793
-		return $navigation;
794
-	}
795
-
796
-	/**
797
-	 * Returns the navigation inside the header bar
798
-	 *
799
-	 * @return array
800
-	 *
801
-	 * This function returns an array containing all entries added. The
802
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
803
-	 * given for each app the following keys exist:
804
-	 *   - active: boolean, signals if the user is on this navigation entry
805
-	 */
806
-	public static function getHeaderNavigation() {
807
-		$entries = OC::$server->getNavigationManager()->getAll();
808
-		$navigation = self::proceedAppNavigation($entries);
809
-		return $navigation;
810
-	}
811
-
812
-	/**
813
-	 * get the id of loaded app
814
-	 *
815
-	 * @return string
816
-	 */
817
-	public static function getCurrentApp() {
818
-		$request = \OC::$server->getRequest();
819
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
820
-		$topFolder = substr($script, 0, strpos($script, '/'));
821
-		if (empty($topFolder)) {
822
-			$path_info = $request->getPathInfo();
823
-			if ($path_info) {
824
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
825
-			}
826
-		}
827
-		if ($topFolder == 'apps') {
828
-			$length = strlen($topFolder);
829
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
830
-		} else {
831
-			return $topFolder;
832
-		}
833
-	}
834
-
835
-	/**
836
-	 * @param string $type
837
-	 * @return array
838
-	 */
839
-	public static function getForms($type) {
840
-		$forms = array();
841
-		switch ($type) {
842
-			case 'admin':
843
-				$source = self::$adminForms;
844
-				break;
845
-			case 'personal':
846
-				$source = self::$personalForms;
847
-				break;
848
-			default:
849
-				return array();
850
-		}
851
-		foreach ($source as $form) {
852
-			$forms[] = include $form;
853
-		}
854
-		return $forms;
855
-	}
856
-
857
-	/**
858
-	 * register an admin form to be shown
859
-	 *
860
-	 * @param string $app
861
-	 * @param string $page
862
-	 */
863
-	public static function registerAdmin($app, $page) {
864
-		self::$adminForms[] = $app . '/' . $page . '.php';
865
-	}
866
-
867
-	/**
868
-	 * register a personal form to be shown
869
-	 * @param string $app
870
-	 * @param string $page
871
-	 */
872
-	public static function registerPersonal($app, $page) {
873
-		self::$personalForms[] = $app . '/' . $page . '.php';
874
-	}
875
-
876
-	/**
877
-	 * @param array $entry
878
-	 */
879
-	public static function registerLogIn(array $entry) {
880
-		self::$altLogin[] = $entry;
881
-	}
882
-
883
-	/**
884
-	 * @return array
885
-	 */
886
-	public static function getAlternativeLogIns() {
887
-		return self::$altLogin;
888
-	}
889
-
890
-	/**
891
-	 * get a list of all apps in the apps folder
892
-	 *
893
-	 * @return array an array of app names (string IDs)
894
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
895
-	 */
896
-	public static function getAllApps() {
897
-
898
-		$apps = array();
899
-
900
-		foreach (OC::$APPSROOTS as $apps_dir) {
901
-			if (!is_readable($apps_dir['path'])) {
902
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
903
-				continue;
904
-			}
905
-			$dh = opendir($apps_dir['path']);
906
-
907
-			if (is_resource($dh)) {
908
-				while (($file = readdir($dh)) !== false) {
909
-
910
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
911
-
912
-						$apps[] = $file;
913
-					}
914
-				}
915
-			}
916
-		}
917
-
918
-		return $apps;
919
-	}
920
-
921
-	/**
922
-	 * List all apps, this is used in apps.php
923
-	 *
924
-	 * @return array
925
-	 */
926
-	public function listAllApps() {
927
-		$installedApps = OC_App::getAllApps();
928
-
929
-		//we don't want to show configuration for these
930
-		$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
931
-		$appList = array();
932
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
933
-		$urlGenerator = \OC::$server->getURLGenerator();
934
-
935
-		foreach ($installedApps as $app) {
936
-			if (array_search($app, $blacklist) === false) {
937
-
938
-				$info = OC_App::getAppInfo($app, false, $langCode);
939
-				if (!is_array($info)) {
940
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
941
-					continue;
942
-				}
943
-
944
-				if (!isset($info['name'])) {
945
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
946
-					continue;
947
-				}
948
-
949
-				$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
950
-				$info['groups'] = null;
951
-				if ($enabled === 'yes') {
952
-					$active = true;
953
-				} else if ($enabled === 'no') {
954
-					$active = false;
955
-				} else {
956
-					$active = true;
957
-					$info['groups'] = $enabled;
958
-				}
959
-
960
-				$info['active'] = $active;
961
-
962
-				if (self::isShipped($app)) {
963
-					$info['internal'] = true;
964
-					$info['level'] = self::officialApp;
965
-					$info['removable'] = false;
966
-				} else {
967
-					$info['internal'] = false;
968
-					$info['removable'] = true;
969
-				}
970
-
971
-				$appPath = self::getAppPath($app);
972
-				if($appPath !== false) {
973
-					$appIcon = $appPath . '/img/' . $app . '.svg';
974
-					if (file_exists($appIcon)) {
975
-						$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app . '.svg');
976
-						$info['previewAsIcon'] = true;
977
-					} else {
978
-						$appIcon = $appPath . '/img/app.svg';
979
-						if (file_exists($appIcon)) {
980
-							$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, 'app.svg');
981
-							$info['previewAsIcon'] = true;
982
-						}
983
-					}
984
-				}
985
-				// fix documentation
986
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
987
-					foreach ($info['documentation'] as $key => $url) {
988
-						// If it is not an absolute URL we assume it is a key
989
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
990
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
991
-							$url = $urlGenerator->linkToDocs($url);
992
-						}
993
-
994
-						$info['documentation'][$key] = $url;
995
-					}
996
-				}
997
-
998
-				$info['version'] = OC_App::getAppVersion($app);
999
-				$appList[] = $info;
1000
-			}
1001
-		}
1002
-
1003
-		return $appList;
1004
-	}
1005
-
1006
-	/**
1007
-	 * Returns the internal app ID or false
1008
-	 * @param string $ocsID
1009
-	 * @return string|false
1010
-	 */
1011
-	public static function getInternalAppIdByOcs($ocsID) {
1012
-		if(is_numeric($ocsID)) {
1013
-			$idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
1014
-			if(array_search($ocsID, $idArray)) {
1015
-				return array_search($ocsID, $idArray);
1016
-			}
1017
-		}
1018
-		return false;
1019
-	}
1020
-
1021
-	public static function shouldUpgrade($app) {
1022
-		$versions = self::getAppVersions();
1023
-		$currentVersion = OC_App::getAppVersion($app);
1024
-		if ($currentVersion && isset($versions[$app])) {
1025
-			$installedVersion = $versions[$app];
1026
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
1027
-				return true;
1028
-			}
1029
-		}
1030
-		return false;
1031
-	}
1032
-
1033
-	/**
1034
-	 * Adjust the number of version parts of $version1 to match
1035
-	 * the number of version parts of $version2.
1036
-	 *
1037
-	 * @param string $version1 version to adjust
1038
-	 * @param string $version2 version to take the number of parts from
1039
-	 * @return string shortened $version1
1040
-	 */
1041
-	private static function adjustVersionParts($version1, $version2) {
1042
-		$version1 = explode('.', $version1);
1043
-		$version2 = explode('.', $version2);
1044
-		// reduce $version1 to match the number of parts in $version2
1045
-		while (count($version1) > count($version2)) {
1046
-			array_pop($version1);
1047
-		}
1048
-		// if $version1 does not have enough parts, add some
1049
-		while (count($version1) < count($version2)) {
1050
-			$version1[] = '0';
1051
-		}
1052
-		return implode('.', $version1);
1053
-	}
1054
-
1055
-	/**
1056
-	 * Check whether the current ownCloud version matches the given
1057
-	 * application's version requirements.
1058
-	 *
1059
-	 * The comparison is made based on the number of parts that the
1060
-	 * app info version has. For example for ownCloud 6.0.3 if the
1061
-	 * app info version is expecting version 6.0, the comparison is
1062
-	 * made on the first two parts of the ownCloud version.
1063
-	 * This means that it's possible to specify "requiremin" => 6
1064
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
1065
-	 *
1066
-	 * @param string $ocVersion ownCloud version to check against
1067
-	 * @param array $appInfo app info (from xml)
1068
-	 *
1069
-	 * @return boolean true if compatible, otherwise false
1070
-	 */
1071
-	public static function isAppCompatible($ocVersion, $appInfo) {
1072
-		$requireMin = '';
1073
-		$requireMax = '';
1074
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
1075
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
1076
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
1077
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
1078
-		} else if (isset($appInfo['requiremin'])) {
1079
-			$requireMin = $appInfo['requiremin'];
1080
-		} else if (isset($appInfo['require'])) {
1081
-			$requireMin = $appInfo['require'];
1082
-		}
1083
-
1084
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
1085
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
1086
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
1087
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
1088
-		} else if (isset($appInfo['requiremax'])) {
1089
-			$requireMax = $appInfo['requiremax'];
1090
-		}
1091
-
1092
-		if (is_array($ocVersion)) {
1093
-			$ocVersion = implode('.', $ocVersion);
1094
-		}
1095
-
1096
-		if (!empty($requireMin)
1097
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
1098
-		) {
1099
-
1100
-			return false;
1101
-		}
1102
-
1103
-		if (!empty($requireMax)
1104
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
1105
-		) {
1106
-			return false;
1107
-		}
1108
-
1109
-		return true;
1110
-	}
1111
-
1112
-	/**
1113
-	 * get the installed version of all apps
1114
-	 */
1115
-	public static function getAppVersions() {
1116
-		static $versions;
1117
-
1118
-		if(!$versions) {
1119
-			$appConfig = \OC::$server->getAppConfig();
1120
-			$versions = $appConfig->getValues(false, 'installed_version');
1121
-		}
1122
-		return $versions;
1123
-	}
1124
-
1125
-	/**
1126
-	 * @param string $app
1127
-	 * @param \OCP\IConfig $config
1128
-	 * @param \OCP\IL10N $l
1129
-	 * @return bool
1130
-	 *
1131
-	 * @throws Exception if app is not compatible with this version of ownCloud
1132
-	 * @throws Exception if no app-name was specified
1133
-	 */
1134
-	public function installApp($app,
1135
-							   \OCP\IConfig $config,
1136
-							   \OCP\IL10N $l) {
1137
-		if ($app !== false) {
1138
-			// check if the app is compatible with this version of ownCloud
1139
-			$info = self::getAppInfo($app);
1140
-			if(!is_array($info)) {
1141
-				throw new \Exception(
1142
-					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1143
-						[$info['name']]
1144
-					)
1145
-				);
1146
-			}
1147
-
1148
-			$version = \OCP\Util::getVersion();
1149
-			if (!self::isAppCompatible($version, $info)) {
1150
-				throw new \Exception(
1151
-					$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1152
-						array($info['name'])
1153
-					)
1154
-				);
1155
-			}
1156
-
1157
-			// check for required dependencies
1158
-			self::checkAppDependencies($config, $l, $info);
1159
-
1160
-			$config->setAppValue($app, 'enabled', 'yes');
1161
-			if (isset($appData['id'])) {
1162
-				$config->setAppValue($app, 'ocsid', $appData['id']);
1163
-			}
1164
-
1165
-			if(isset($info['settings']) && is_array($info['settings'])) {
1166
-				$appPath = self::getAppPath($app);
1167
-				self::registerAutoloading($app, $appPath);
1168
-				\OC::$server->getSettingsManager()->setupSettings($info['settings']);
1169
-			}
1170
-
1171
-			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1172
-		} else {
1173
-			if(empty($appName) ) {
1174
-				throw new \Exception($l->t("No app name specified"));
1175
-			} else {
1176
-				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1177
-			}
1178
-		}
1179
-
1180
-		return $app;
1181
-	}
1182
-
1183
-	/**
1184
-	 * update the database for the app and call the update script
1185
-	 *
1186
-	 * @param string $appId
1187
-	 * @return bool
1188
-	 */
1189
-	public static function updateApp($appId) {
1190
-		$appPath = self::getAppPath($appId);
1191
-		if($appPath === false) {
1192
-			return false;
1193
-		}
1194
-		$appData = self::getAppInfo($appId);
1195
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1196
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1197
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1198
-		}
1199
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1200
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1201
-		unset(self::$appVersion[$appId]);
1202
-		// run upgrade code
1203
-		if (file_exists($appPath . '/appinfo/update.php')) {
1204
-			self::loadApp($appId);
1205
-			include $appPath . '/appinfo/update.php';
1206
-		}
1207
-		self::setupBackgroundJobs($appData['background-jobs']);
1208
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
1209
-			$appPath = self::getAppPath($appId);
1210
-			self::registerAutoloading($appId, $appPath);
1211
-			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1212
-		}
1213
-
1214
-		//set remote/public handlers
1215
-		if (array_key_exists('ocsid', $appData)) {
1216
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1217
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1218
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1219
-		}
1220
-		foreach ($appData['remote'] as $name => $path) {
1221
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1222
-		}
1223
-		foreach ($appData['public'] as $name => $path) {
1224
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1225
-		}
1226
-
1227
-		self::setAppTypes($appId);
1228
-
1229
-		$version = \OC_App::getAppVersion($appId);
1230
-		\OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1231
-
1232
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1233
-			ManagerEvent::EVENT_APP_UPDATE, $appId
1234
-		));
1235
-
1236
-		return true;
1237
-	}
1238
-
1239
-	/**
1240
-	 * @param string $appId
1241
-	 * @param string[] $steps
1242
-	 * @throws \OC\NeedsUpdateException
1243
-	 */
1244
-	public static function executeRepairSteps($appId, array $steps) {
1245
-		if (empty($steps)) {
1246
-			return;
1247
-		}
1248
-		// load the app
1249
-		self::loadApp($appId);
1250
-
1251
-		$dispatcher = OC::$server->getEventDispatcher();
1252
-
1253
-		// load the steps
1254
-		$r = new Repair([], $dispatcher);
1255
-		foreach ($steps as $step) {
1256
-			try {
1257
-				$r->addStep($step);
1258
-			} catch (Exception $ex) {
1259
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1260
-				\OC::$server->getLogger()->logException($ex);
1261
-			}
1262
-		}
1263
-		// run the steps
1264
-		$r->run();
1265
-	}
1266
-
1267
-	public static function setupBackgroundJobs(array $jobs) {
1268
-		$queue = \OC::$server->getJobList();
1269
-		foreach ($jobs as $job) {
1270
-			$queue->add($job);
1271
-		}
1272
-	}
1273
-
1274
-	/**
1275
-	 * @param string $appId
1276
-	 * @param string[] $steps
1277
-	 */
1278
-	private static function setupLiveMigrations($appId, array $steps) {
1279
-		$queue = \OC::$server->getJobList();
1280
-		foreach ($steps as $step) {
1281
-			$queue->add('OC\Migration\BackgroundRepair', [
1282
-				'app' => $appId,
1283
-				'step' => $step]);
1284
-		}
1285
-	}
1286
-
1287
-	/**
1288
-	 * @param string $appId
1289
-	 * @return \OC\Files\View|false
1290
-	 */
1291
-	public static function getStorage($appId) {
1292
-		if (OC_App::isEnabled($appId)) { //sanity check
1293
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1294
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1295
-				if (!$view->file_exists($appId)) {
1296
-					$view->mkdir($appId);
1297
-				}
1298
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1299
-			} else {
1300
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1301
-				return false;
1302
-			}
1303
-		} else {
1304
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1305
-			return false;
1306
-		}
1307
-	}
1308
-
1309
-	protected static function findBestL10NOption($options, $lang) {
1310
-		$fallback = $similarLangFallback = $englishFallback = false;
1311
-
1312
-		$lang = strtolower($lang);
1313
-		$similarLang = $lang;
1314
-		if (strpos($similarLang, '_')) {
1315
-			// For "de_DE" we want to find "de" and the other way around
1316
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1317
-		}
1318
-
1319
-		foreach ($options as $option) {
1320
-			if (is_array($option)) {
1321
-				if ($fallback === false) {
1322
-					$fallback = $option['@value'];
1323
-				}
1324
-
1325
-				if (!isset($option['@attributes']['lang'])) {
1326
-					continue;
1327
-				}
1328
-
1329
-				$attributeLang = strtolower($option['@attributes']['lang']);
1330
-				if ($attributeLang === $lang) {
1331
-					return $option['@value'];
1332
-				}
1333
-
1334
-				if ($attributeLang === $similarLang) {
1335
-					$similarLangFallback = $option['@value'];
1336
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1337
-					if ($similarLangFallback === false) {
1338
-						$similarLangFallback =  $option['@value'];
1339
-					}
1340
-				}
1341
-			} else {
1342
-				$englishFallback = $option;
1343
-			}
1344
-		}
1345
-
1346
-		if ($similarLangFallback !== false) {
1347
-			return $similarLangFallback;
1348
-		} else if ($englishFallback !== false) {
1349
-			return $englishFallback;
1350
-		}
1351
-		return (string) $fallback;
1352
-	}
1353
-
1354
-	/**
1355
-	 * parses the app data array and enhanced the 'description' value
1356
-	 *
1357
-	 * @param array $data the app data
1358
-	 * @param string $lang
1359
-	 * @return array improved app data
1360
-	 */
1361
-	public static function parseAppInfo(array $data, $lang = null) {
1362
-
1363
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1364
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1365
-		}
1366
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1367
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1368
-		}
1369
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1370
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1371
-		} else if (isset($data['description']) && is_string($data['description'])) {
1372
-			$data['description'] = trim($data['description']);
1373
-		} else  {
1374
-			$data['description'] = '';
1375
-		}
1376
-
1377
-		return $data;
1378
-	}
1379
-
1380
-	/**
1381
-	 * @param \OCP\IConfig $config
1382
-	 * @param \OCP\IL10N $l
1383
-	 * @param array $info
1384
-	 * @throws \Exception
1385
-	 */
1386
-	protected static function checkAppDependencies($config, $l, $info) {
1387
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1388
-		$missing = $dependencyAnalyzer->analyze($info);
1389
-		if (!empty($missing)) {
1390
-			$missingMsg = join(PHP_EOL, $missing);
1391
-			throw new \Exception(
1392
-				$l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1393
-					[$info['name'], $missingMsg]
1394
-				)
1395
-			);
1396
-		}
1397
-	}
64
+    static private $appVersion = [];
65
+    static private $adminForms = array();
66
+    static private $personalForms = array();
67
+    static private $appInfo = array();
68
+    static private $appTypes = array();
69
+    static private $loadedApps = array();
70
+    static private $altLogin = array();
71
+    static private $alreadyRegistered = [];
72
+    const officialApp = 200;
73
+
74
+    /**
75
+     * clean the appId
76
+     *
77
+     * @param string|boolean $app AppId that needs to be cleaned
78
+     * @return string
79
+     */
80
+    public static function cleanAppId($app) {
81
+        return str_replace(array('\0', '/', '\\', '..'), '', $app);
82
+    }
83
+
84
+    /**
85
+     * Check if an app is loaded
86
+     *
87
+     * @param string $app
88
+     * @return bool
89
+     */
90
+    public static function isAppLoaded($app) {
91
+        return in_array($app, self::$loadedApps, true);
92
+    }
93
+
94
+    /**
95
+     * loads all apps
96
+     *
97
+     * @param string[] | string | null $types
98
+     * @return bool
99
+     *
100
+     * This function walks through the ownCloud directory and loads all apps
101
+     * it can find. A directory contains an app if the file /appinfo/info.xml
102
+     * exists.
103
+     *
104
+     * if $types is set, only apps of those types will be loaded
105
+     */
106
+    public static function loadApps($types = null) {
107
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
108
+            return false;
109
+        }
110
+        // Load the enabled apps here
111
+        $apps = self::getEnabledApps();
112
+
113
+        // Add each apps' folder as allowed class path
114
+        foreach($apps as $app) {
115
+            $path = self::getAppPath($app);
116
+            if($path !== false) {
117
+                self::registerAutoloading($app, $path);
118
+            }
119
+        }
120
+
121
+        // prevent app.php from printing output
122
+        ob_start();
123
+        foreach ($apps as $app) {
124
+            if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
125
+                self::loadApp($app);
126
+            }
127
+        }
128
+        ob_end_clean();
129
+
130
+        return true;
131
+    }
132
+
133
+    /**
134
+     * load a single app
135
+     *
136
+     * @param string $app
137
+     */
138
+    public static function loadApp($app) {
139
+        self::$loadedApps[] = $app;
140
+        $appPath = self::getAppPath($app);
141
+        if($appPath === false) {
142
+            return;
143
+        }
144
+
145
+        // in case someone calls loadApp() directly
146
+        self::registerAutoloading($app, $appPath);
147
+
148
+        if (is_file($appPath . '/appinfo/app.php')) {
149
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
+            self::requireAppFile($app);
151
+            if (self::isType($app, array('authentication'))) {
152
+                // since authentication apps affect the "is app enabled for group" check,
153
+                // the enabled apps cache needs to be cleared to make sure that the
154
+                // next time getEnableApps() is called it will also include apps that were
155
+                // enabled for groups
156
+                self::$enabledAppsCache = array();
157
+            }
158
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
159
+        }
160
+
161
+        $info = self::getAppInfo($app);
162
+        if (!empty($info['activity']['filters'])) {
163
+            foreach ($info['activity']['filters'] as $filter) {
164
+                \OC::$server->getActivityManager()->registerFilter($filter);
165
+            }
166
+        }
167
+        if (!empty($info['activity']['settings'])) {
168
+            foreach ($info['activity']['settings'] as $setting) {
169
+                \OC::$server->getActivityManager()->registerSetting($setting);
170
+            }
171
+        }
172
+        if (!empty($info['activity']['providers'])) {
173
+            foreach ($info['activity']['providers'] as $provider) {
174
+                \OC::$server->getActivityManager()->registerProvider($provider);
175
+            }
176
+        }
177
+    }
178
+
179
+    /**
180
+     * @internal
181
+     * @param string $app
182
+     * @param string $path
183
+     */
184
+    public static function registerAutoloading($app, $path) {
185
+        $key = $app . '-' . $path;
186
+        if(isset(self::$alreadyRegistered[$key])) {
187
+            return;
188
+        }
189
+        self::$alreadyRegistered[$key] = true;
190
+        // Register on PSR-4 composer autoloader
191
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
192
+        \OC::$server->registerNamespace($app, $appNamespace);
193
+        \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
194
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
195
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
196
+        }
197
+
198
+        // Register on legacy autoloader
199
+        \OC::$loader->addValidRoot($path);
200
+    }
201
+
202
+    /**
203
+     * Load app.php from the given app
204
+     *
205
+     * @param string $app app name
206
+     */
207
+    private static function requireAppFile($app) {
208
+        try {
209
+            // encapsulated here to avoid variable scope conflicts
210
+            require_once $app . '/appinfo/app.php';
211
+        } catch (Error $ex) {
212
+            \OC::$server->getLogger()->logException($ex);
213
+            $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
214
+            if (!in_array($app, $blacklist)) {
215
+                self::disable($app);
216
+            }
217
+        }
218
+    }
219
+
220
+    /**
221
+     * check if an app is of a specific type
222
+     *
223
+     * @param string $app
224
+     * @param string|array $types
225
+     * @return bool
226
+     */
227
+    public static function isType($app, $types) {
228
+        if (is_string($types)) {
229
+            $types = array($types);
230
+        }
231
+        $appTypes = self::getAppTypes($app);
232
+        foreach ($types as $type) {
233
+            if (array_search($type, $appTypes) !== false) {
234
+                return true;
235
+            }
236
+        }
237
+        return false;
238
+    }
239
+
240
+    /**
241
+     * get the types of an app
242
+     *
243
+     * @param string $app
244
+     * @return array
245
+     */
246
+    private static function getAppTypes($app) {
247
+        //load the cache
248
+        if (count(self::$appTypes) == 0) {
249
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
250
+        }
251
+
252
+        if (isset(self::$appTypes[$app])) {
253
+            return explode(',', self::$appTypes[$app]);
254
+        } else {
255
+            return array();
256
+        }
257
+    }
258
+
259
+    /**
260
+     * read app types from info.xml and cache them in the database
261
+     */
262
+    public static function setAppTypes($app) {
263
+        $appData = self::getAppInfo($app);
264
+        if(!is_array($appData)) {
265
+            return;
266
+        }
267
+
268
+        if (isset($appData['types'])) {
269
+            $appTypes = implode(',', $appData['types']);
270
+        } else {
271
+            $appTypes = '';
272
+            $appData['types'] = [];
273
+        }
274
+
275
+        \OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
276
+
277
+        if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
278
+            $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
279
+            if ($enabled !== 'yes' && $enabled !== 'no') {
280
+                \OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
281
+            }
282
+        }
283
+    }
284
+
285
+    /**
286
+     * check if app is shipped
287
+     *
288
+     * @param string $appId the id of the app to check
289
+     * @return bool
290
+     *
291
+     * Check if an app that is installed is a shipped app or installed from the appstore.
292
+     */
293
+    public static function isShipped($appId) {
294
+        return \OC::$server->getAppManager()->isShipped($appId);
295
+    }
296
+
297
+    /**
298
+     * get all enabled apps
299
+     */
300
+    protected static $enabledAppsCache = array();
301
+
302
+    /**
303
+     * Returns apps enabled for the current user.
304
+     *
305
+     * @param bool $forceRefresh whether to refresh the cache
306
+     * @param bool $all whether to return apps for all users, not only the
307
+     * currently logged in one
308
+     * @return string[]
309
+     */
310
+    public static function getEnabledApps($forceRefresh = false, $all = false) {
311
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
312
+            return array();
313
+        }
314
+        // in incognito mode or when logged out, $user will be false,
315
+        // which is also the case during an upgrade
316
+        $appManager = \OC::$server->getAppManager();
317
+        if ($all) {
318
+            $user = null;
319
+        } else {
320
+            $user = \OC::$server->getUserSession()->getUser();
321
+        }
322
+
323
+        if (is_null($user)) {
324
+            $apps = $appManager->getInstalledApps();
325
+        } else {
326
+            $apps = $appManager->getEnabledAppsForUser($user);
327
+        }
328
+        $apps = array_filter($apps, function ($app) {
329
+            return $app !== 'files';//we add this manually
330
+        });
331
+        sort($apps);
332
+        array_unshift($apps, 'files');
333
+        return $apps;
334
+    }
335
+
336
+    /**
337
+     * checks whether or not an app is enabled
338
+     *
339
+     * @param string $app app
340
+     * @return bool
341
+     *
342
+     * This function checks whether or not an app is enabled.
343
+     */
344
+    public static function isEnabled($app) {
345
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
346
+    }
347
+
348
+    /**
349
+     * enables an app
350
+     *
351
+     * @param string $appId
352
+     * @param array $groups (optional) when set, only these groups will have access to the app
353
+     * @throws \Exception
354
+     * @return void
355
+     *
356
+     * This function set an app as enabled in appconfig.
357
+     */
358
+    public function enable($appId,
359
+                            $groups = null) {
360
+        self::$enabledAppsCache = []; // flush
361
+        $l = \OC::$server->getL10N('core');
362
+        $config = \OC::$server->getConfig();
363
+
364
+        // Check if app is already downloaded
365
+        $installer = new Installer(
366
+            \OC::$server->getAppFetcher(),
367
+            \OC::$server->getHTTPClientService(),
368
+            \OC::$server->getTempManager(),
369
+            \OC::$server->getLogger()
370
+        );
371
+        $isDownloaded = $installer->isDownloaded($appId);
372
+
373
+        if(!$isDownloaded) {
374
+            $installer->downloadApp($appId);
375
+        }
376
+
377
+        if (!Installer::isInstalled($appId)) {
378
+            $appId = self::installApp(
379
+                $appId,
380
+                $config,
381
+                $l
382
+            );
383
+            $appPath = self::getAppPath($appId);
384
+            self::registerAutoloading($appId, $appPath);
385
+            $installer->installApp($appId);
386
+        } else {
387
+            // check for required dependencies
388
+            $info = self::getAppInfo($appId);
389
+            self::checkAppDependencies($config, $l, $info);
390
+            $appPath = self::getAppPath($appId);
391
+            self::registerAutoloading($appId, $appPath);
392
+            $installer->installApp($appId);
393
+        }
394
+
395
+        $appManager = \OC::$server->getAppManager();
396
+        if (!is_null($groups)) {
397
+            $groupManager = \OC::$server->getGroupManager();
398
+            $groupsList = [];
399
+            foreach ($groups as $group) {
400
+                $groupItem = $groupManager->get($group);
401
+                if ($groupItem instanceof \OCP\IGroup) {
402
+                    $groupsList[] = $groupManager->get($group);
403
+                }
404
+            }
405
+            $appManager->enableAppForGroups($appId, $groupsList);
406
+        } else {
407
+            $appManager->enableApp($appId);
408
+        }
409
+
410
+        $info = self::getAppInfo($appId);
411
+        if(isset($info['settings']) && is_array($info['settings'])) {
412
+            $appPath = self::getAppPath($appId);
413
+            self::registerAutoloading($appId, $appPath);
414
+            \OC::$server->getSettingsManager()->setupSettings($info['settings']);
415
+        }
416
+    }
417
+
418
+    /**
419
+     * @param string $app
420
+     * @return bool
421
+     */
422
+    public static function removeApp($app) {
423
+        if (self::isShipped($app)) {
424
+            return false;
425
+        }
426
+
427
+        $installer = new Installer(
428
+            \OC::$server->getAppFetcher(),
429
+            \OC::$server->getHTTPClientService(),
430
+            \OC::$server->getTempManager(),
431
+            \OC::$server->getLogger()
432
+        );
433
+        return $installer->removeApp($app);
434
+    }
435
+
436
+    /**
437
+     * This function set an app as disabled in appconfig.
438
+     *
439
+     * @param string $app app
440
+     * @throws Exception
441
+     */
442
+    public static function disable($app) {
443
+        // flush
444
+        self::$enabledAppsCache = array();
445
+
446
+        // run uninstall steps
447
+        $appData = OC_App::getAppInfo($app);
448
+        if (!is_null($appData)) {
449
+            OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
450
+        }
451
+
452
+        // emit disable hook - needed anymore ?
453
+        \OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
454
+
455
+        // finally disable it
456
+        $appManager = \OC::$server->getAppManager();
457
+        $appManager->disableApp($app);
458
+    }
459
+
460
+    /**
461
+     * Returns the Settings Navigation
462
+     *
463
+     * @return string[]
464
+     *
465
+     * This function returns an array containing all settings pages added. The
466
+     * entries are sorted by the key 'order' ascending.
467
+     */
468
+    public static function getSettingsNavigation() {
469
+        $l = \OC::$server->getL10N('lib');
470
+        $urlGenerator = \OC::$server->getURLGenerator();
471
+
472
+        $settings = array();
473
+        // by default, settings only contain the help menu
474
+        if (\OC::$server->getSystemConfig()->getValue('knowledgebaseenabled', true)) {
475
+            $settings = array(
476
+                array(
477
+                    "id" => "help",
478
+                    "order" => 4,
479
+                    "href" => $urlGenerator->linkToRoute('settings_help'),
480
+                    "name" => $l->t("Help"),
481
+                    "icon" => $urlGenerator->imagePath("settings", "help.svg")
482
+                )
483
+            );
484
+        }
485
+
486
+        // if the user is logged-in
487
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
488
+            // personal menu
489
+            $settings[] = array(
490
+                "id" => "personal",
491
+                "order" => 1,
492
+                "href" => $urlGenerator->linkToRoute('settings_personal'),
493
+                "name" => $l->t("Personal"),
494
+                "icon" => $urlGenerator->imagePath("settings", "personal.svg")
495
+            );
496
+
497
+            //SubAdmins are also allowed to access user management
498
+            $userObject = \OC::$server->getUserSession()->getUser();
499
+            $isSubAdmin = false;
500
+            if($userObject !== null) {
501
+                $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
502
+            }
503
+            if ($isSubAdmin) {
504
+                // admin users menu
505
+                $settings[] = array(
506
+                    "id" => "core_users",
507
+                    "order" => 3,
508
+                    "href" => $urlGenerator->linkToRoute('settings_users'),
509
+                    "name" => $l->t("Users"),
510
+                    "icon" => $urlGenerator->imagePath("settings", "users.svg")
511
+                );
512
+            }
513
+
514
+            // if the user is an admin
515
+            if (OC_User::isAdminUser(OC_User::getUser())) {
516
+                // admin settings
517
+                $settings[] = array(
518
+                    "id" => "admin",
519
+                    "order" => 2,
520
+                    "href" => $urlGenerator->linkToRoute('settings.AdminSettings.index'),
521
+                    "name" => $l->t("Admin"),
522
+                    "icon" => $urlGenerator->imagePath("settings", "admin.svg")
523
+                );
524
+            }
525
+        }
526
+
527
+        $navigation = self::proceedNavigation($settings);
528
+        return $navigation;
529
+    }
530
+
531
+    // This is private as well. It simply works, so don't ask for more details
532
+    private static function proceedNavigation($list) {
533
+        $headerIconCount = 8;
534
+        if(OC_User::isAdminUser(OC_User::getUser())) {
535
+            $headerIconCount--;
536
+        }
537
+        usort($list, function($a, $b) {
538
+            if (isset($a['order']) && isset($b['order'])) {
539
+                return ($a['order'] < $b['order']) ? -1 : 1;
540
+            } else if (isset($a['order']) || isset($b['order'])) {
541
+                return isset($a['order']) ? -1 : 1;
542
+            } else {
543
+                return ($a['name'] < $b['name']) ? -1 : 1;
544
+            }
545
+        });
546
+
547
+        $activeAppIndex = -1;
548
+        $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
549
+        foreach ($list as $index => &$navEntry) {
550
+            if ($navEntry['id'] == $activeApp) {
551
+                $navEntry['active'] = true;
552
+                $activeAppIndex = $index;
553
+            } else {
554
+                $navEntry['active'] = false;
555
+            }
556
+        }
557
+        unset($navEntry);
558
+
559
+        if($activeAppIndex > ($headerIconCount-1)) {
560
+            $active = $list[$activeAppIndex];
561
+            $lastInHeader = $list[$headerIconCount-1];
562
+            $list[$headerIconCount-1] = $active;
563
+            $list[$activeAppIndex] = $lastInHeader;
564
+        }
565
+
566
+        foreach ($list as $index => &$navEntry) {
567
+            $navEntry['showInHeader'] = false;
568
+            if($index < $headerIconCount) {
569
+                $navEntry['showInHeader'] = true;
570
+            }
571
+        }
572
+
573
+
574
+
575
+        return $list;
576
+    }
577
+
578
+    public static function proceedAppNavigation($entries) {
579
+        $headerIconCount = 8;
580
+        if(OC_User::isAdminUser(OC_User::getUser())) {
581
+            $headerIconCount--;
582
+        }
583
+        $activeAppIndex = -1;
584
+        $list = self::proceedNavigation($entries);
585
+
586
+        $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
587
+        foreach ($list as $index => &$navEntry) {
588
+            if ($navEntry['id'] == $activeApp) {
589
+                $navEntry['active'] = true;
590
+                $activeAppIndex = $index;
591
+            } else {
592
+                $navEntry['active'] = false;
593
+            }
594
+        }
595
+        // move active item to last position
596
+        if($activeAppIndex > ($headerIconCount-1)) {
597
+            $active = $list[$activeAppIndex];
598
+            $lastInHeader = $list[$headerIconCount-1];
599
+            $list[$headerIconCount-1] = $active;
600
+            $list[$activeAppIndex] = $lastInHeader;
601
+        }
602
+        $list = array_slice($list, 0, $headerIconCount);
603
+
604
+        return $list;
605
+    }
606
+
607
+    /**
608
+     * Get the path where to install apps
609
+     *
610
+     * @return string|false
611
+     */
612
+    public static function getInstallPath() {
613
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
614
+            return false;
615
+        }
616
+
617
+        foreach (OC::$APPSROOTS as $dir) {
618
+            if (isset($dir['writable']) && $dir['writable'] === true) {
619
+                return $dir['path'];
620
+            }
621
+        }
622
+
623
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
624
+        return null;
625
+    }
626
+
627
+
628
+    /**
629
+     * search for an app in all app-directories
630
+     *
631
+     * @param string $appId
632
+     * @return false|string
633
+     */
634
+    public static function findAppInDirectories($appId) {
635
+        $sanitizedAppId = self::cleanAppId($appId);
636
+        if($sanitizedAppId !== $appId) {
637
+            return false;
638
+        }
639
+        static $app_dir = array();
640
+
641
+        if (isset($app_dir[$appId])) {
642
+            return $app_dir[$appId];
643
+        }
644
+
645
+        $possibleApps = array();
646
+        foreach (OC::$APPSROOTS as $dir) {
647
+            if (file_exists($dir['path'] . '/' . $appId)) {
648
+                $possibleApps[] = $dir;
649
+            }
650
+        }
651
+
652
+        if (empty($possibleApps)) {
653
+            return false;
654
+        } elseif (count($possibleApps) === 1) {
655
+            $dir = array_shift($possibleApps);
656
+            $app_dir[$appId] = $dir;
657
+            return $dir;
658
+        } else {
659
+            $versionToLoad = array();
660
+            foreach ($possibleApps as $possibleApp) {
661
+                $version = self::getAppVersionByPath($possibleApp['path']);
662
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
663
+                    $versionToLoad = array(
664
+                        'dir' => $possibleApp,
665
+                        'version' => $version,
666
+                    );
667
+                }
668
+            }
669
+            $app_dir[$appId] = $versionToLoad['dir'];
670
+            return $versionToLoad['dir'];
671
+            //TODO - write test
672
+        }
673
+    }
674
+
675
+    /**
676
+     * Get the directory for the given app.
677
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
678
+     *
679
+     * @param string $appId
680
+     * @return string|false
681
+     */
682
+    public static function getAppPath($appId) {
683
+        if ($appId === null || trim($appId) === '') {
684
+            return false;
685
+        }
686
+
687
+        if (($dir = self::findAppInDirectories($appId)) != false) {
688
+            return $dir['path'] . '/' . $appId;
689
+        }
690
+        return false;
691
+    }
692
+
693
+    /**
694
+     * Get the path for the given app on the access
695
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
696
+     *
697
+     * @param string $appId
698
+     * @return string|false
699
+     */
700
+    public static function getAppWebPath($appId) {
701
+        if (($dir = self::findAppInDirectories($appId)) != false) {
702
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
703
+        }
704
+        return false;
705
+    }
706
+
707
+    /**
708
+     * get the last version of the app from appinfo/info.xml
709
+     *
710
+     * @param string $appId
711
+     * @param bool $useCache
712
+     * @return string
713
+     */
714
+    public static function getAppVersion($appId, $useCache = true) {
715
+        if($useCache && isset(self::$appVersion[$appId])) {
716
+            return self::$appVersion[$appId];
717
+        }
718
+
719
+        $file = self::getAppPath($appId);
720
+        self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
721
+        return self::$appVersion[$appId];
722
+    }
723
+
724
+    /**
725
+     * get app's version based on it's path
726
+     *
727
+     * @param string $path
728
+     * @return string
729
+     */
730
+    public static function getAppVersionByPath($path) {
731
+        $infoFile = $path . '/appinfo/info.xml';
732
+        $appData = self::getAppInfo($infoFile, true);
733
+        return isset($appData['version']) ? $appData['version'] : '';
734
+    }
735
+
736
+
737
+    /**
738
+     * Read all app metadata from the info.xml file
739
+     *
740
+     * @param string $appId id of the app or the path of the info.xml file
741
+     * @param bool $path
742
+     * @param string $lang
743
+     * @return array|null
744
+     * @note all data is read from info.xml, not just pre-defined fields
745
+     */
746
+    public static function getAppInfo($appId, $path = false, $lang = null) {
747
+        if ($path) {
748
+            $file = $appId;
749
+        } else {
750
+            if ($lang === null && isset(self::$appInfo[$appId])) {
751
+                return self::$appInfo[$appId];
752
+            }
753
+            $appPath = self::getAppPath($appId);
754
+            if($appPath === false) {
755
+                return null;
756
+            }
757
+            $file = $appPath . '/appinfo/info.xml';
758
+        }
759
+
760
+        $parser = new InfoParser(\OC::$server->getMemCacheFactory()->create('core.appinfo'));
761
+        $data = $parser->parse($file);
762
+
763
+        if (is_array($data)) {
764
+            $data = OC_App::parseAppInfo($data, $lang);
765
+        }
766
+        if(isset($data['ocsid'])) {
767
+            $storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
768
+            if($storedId !== '' && $storedId !== $data['ocsid']) {
769
+                $data['ocsid'] = $storedId;
770
+            }
771
+        }
772
+
773
+        if ($lang === null) {
774
+            self::$appInfo[$appId] = $data;
775
+        }
776
+
777
+        return $data;
778
+    }
779
+
780
+    /**
781
+     * Returns the navigation
782
+     *
783
+     * @return array
784
+     *
785
+     * This function returns an array containing all entries added. The
786
+     * entries are sorted by the key 'order' ascending. Additional to the keys
787
+     * given for each app the following keys exist:
788
+     *   - active: boolean, signals if the user is on this navigation entry
789
+     */
790
+    public static function getNavigation() {
791
+        $entries = OC::$server->getNavigationManager()->getAll();
792
+        $navigation = self::proceedNavigation($entries);
793
+        return $navigation;
794
+    }
795
+
796
+    /**
797
+     * Returns the navigation inside the header bar
798
+     *
799
+     * @return array
800
+     *
801
+     * This function returns an array containing all entries added. The
802
+     * entries are sorted by the key 'order' ascending. Additional to the keys
803
+     * given for each app the following keys exist:
804
+     *   - active: boolean, signals if the user is on this navigation entry
805
+     */
806
+    public static function getHeaderNavigation() {
807
+        $entries = OC::$server->getNavigationManager()->getAll();
808
+        $navigation = self::proceedAppNavigation($entries);
809
+        return $navigation;
810
+    }
811
+
812
+    /**
813
+     * get the id of loaded app
814
+     *
815
+     * @return string
816
+     */
817
+    public static function getCurrentApp() {
818
+        $request = \OC::$server->getRequest();
819
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
820
+        $topFolder = substr($script, 0, strpos($script, '/'));
821
+        if (empty($topFolder)) {
822
+            $path_info = $request->getPathInfo();
823
+            if ($path_info) {
824
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
825
+            }
826
+        }
827
+        if ($topFolder == 'apps') {
828
+            $length = strlen($topFolder);
829
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
830
+        } else {
831
+            return $topFolder;
832
+        }
833
+    }
834
+
835
+    /**
836
+     * @param string $type
837
+     * @return array
838
+     */
839
+    public static function getForms($type) {
840
+        $forms = array();
841
+        switch ($type) {
842
+            case 'admin':
843
+                $source = self::$adminForms;
844
+                break;
845
+            case 'personal':
846
+                $source = self::$personalForms;
847
+                break;
848
+            default:
849
+                return array();
850
+        }
851
+        foreach ($source as $form) {
852
+            $forms[] = include $form;
853
+        }
854
+        return $forms;
855
+    }
856
+
857
+    /**
858
+     * register an admin form to be shown
859
+     *
860
+     * @param string $app
861
+     * @param string $page
862
+     */
863
+    public static function registerAdmin($app, $page) {
864
+        self::$adminForms[] = $app . '/' . $page . '.php';
865
+    }
866
+
867
+    /**
868
+     * register a personal form to be shown
869
+     * @param string $app
870
+     * @param string $page
871
+     */
872
+    public static function registerPersonal($app, $page) {
873
+        self::$personalForms[] = $app . '/' . $page . '.php';
874
+    }
875
+
876
+    /**
877
+     * @param array $entry
878
+     */
879
+    public static function registerLogIn(array $entry) {
880
+        self::$altLogin[] = $entry;
881
+    }
882
+
883
+    /**
884
+     * @return array
885
+     */
886
+    public static function getAlternativeLogIns() {
887
+        return self::$altLogin;
888
+    }
889
+
890
+    /**
891
+     * get a list of all apps in the apps folder
892
+     *
893
+     * @return array an array of app names (string IDs)
894
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
895
+     */
896
+    public static function getAllApps() {
897
+
898
+        $apps = array();
899
+
900
+        foreach (OC::$APPSROOTS as $apps_dir) {
901
+            if (!is_readable($apps_dir['path'])) {
902
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
903
+                continue;
904
+            }
905
+            $dh = opendir($apps_dir['path']);
906
+
907
+            if (is_resource($dh)) {
908
+                while (($file = readdir($dh)) !== false) {
909
+
910
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
911
+
912
+                        $apps[] = $file;
913
+                    }
914
+                }
915
+            }
916
+        }
917
+
918
+        return $apps;
919
+    }
920
+
921
+    /**
922
+     * List all apps, this is used in apps.php
923
+     *
924
+     * @return array
925
+     */
926
+    public function listAllApps() {
927
+        $installedApps = OC_App::getAllApps();
928
+
929
+        //we don't want to show configuration for these
930
+        $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
931
+        $appList = array();
932
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
933
+        $urlGenerator = \OC::$server->getURLGenerator();
934
+
935
+        foreach ($installedApps as $app) {
936
+            if (array_search($app, $blacklist) === false) {
937
+
938
+                $info = OC_App::getAppInfo($app, false, $langCode);
939
+                if (!is_array($info)) {
940
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
941
+                    continue;
942
+                }
943
+
944
+                if (!isset($info['name'])) {
945
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
946
+                    continue;
947
+                }
948
+
949
+                $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
950
+                $info['groups'] = null;
951
+                if ($enabled === 'yes') {
952
+                    $active = true;
953
+                } else if ($enabled === 'no') {
954
+                    $active = false;
955
+                } else {
956
+                    $active = true;
957
+                    $info['groups'] = $enabled;
958
+                }
959
+
960
+                $info['active'] = $active;
961
+
962
+                if (self::isShipped($app)) {
963
+                    $info['internal'] = true;
964
+                    $info['level'] = self::officialApp;
965
+                    $info['removable'] = false;
966
+                } else {
967
+                    $info['internal'] = false;
968
+                    $info['removable'] = true;
969
+                }
970
+
971
+                $appPath = self::getAppPath($app);
972
+                if($appPath !== false) {
973
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
974
+                    if (file_exists($appIcon)) {
975
+                        $info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app . '.svg');
976
+                        $info['previewAsIcon'] = true;
977
+                    } else {
978
+                        $appIcon = $appPath . '/img/app.svg';
979
+                        if (file_exists($appIcon)) {
980
+                            $info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, 'app.svg');
981
+                            $info['previewAsIcon'] = true;
982
+                        }
983
+                    }
984
+                }
985
+                // fix documentation
986
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
987
+                    foreach ($info['documentation'] as $key => $url) {
988
+                        // If it is not an absolute URL we assume it is a key
989
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
990
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
991
+                            $url = $urlGenerator->linkToDocs($url);
992
+                        }
993
+
994
+                        $info['documentation'][$key] = $url;
995
+                    }
996
+                }
997
+
998
+                $info['version'] = OC_App::getAppVersion($app);
999
+                $appList[] = $info;
1000
+            }
1001
+        }
1002
+
1003
+        return $appList;
1004
+    }
1005
+
1006
+    /**
1007
+     * Returns the internal app ID or false
1008
+     * @param string $ocsID
1009
+     * @return string|false
1010
+     */
1011
+    public static function getInternalAppIdByOcs($ocsID) {
1012
+        if(is_numeric($ocsID)) {
1013
+            $idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
1014
+            if(array_search($ocsID, $idArray)) {
1015
+                return array_search($ocsID, $idArray);
1016
+            }
1017
+        }
1018
+        return false;
1019
+    }
1020
+
1021
+    public static function shouldUpgrade($app) {
1022
+        $versions = self::getAppVersions();
1023
+        $currentVersion = OC_App::getAppVersion($app);
1024
+        if ($currentVersion && isset($versions[$app])) {
1025
+            $installedVersion = $versions[$app];
1026
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
1027
+                return true;
1028
+            }
1029
+        }
1030
+        return false;
1031
+    }
1032
+
1033
+    /**
1034
+     * Adjust the number of version parts of $version1 to match
1035
+     * the number of version parts of $version2.
1036
+     *
1037
+     * @param string $version1 version to adjust
1038
+     * @param string $version2 version to take the number of parts from
1039
+     * @return string shortened $version1
1040
+     */
1041
+    private static function adjustVersionParts($version1, $version2) {
1042
+        $version1 = explode('.', $version1);
1043
+        $version2 = explode('.', $version2);
1044
+        // reduce $version1 to match the number of parts in $version2
1045
+        while (count($version1) > count($version2)) {
1046
+            array_pop($version1);
1047
+        }
1048
+        // if $version1 does not have enough parts, add some
1049
+        while (count($version1) < count($version2)) {
1050
+            $version1[] = '0';
1051
+        }
1052
+        return implode('.', $version1);
1053
+    }
1054
+
1055
+    /**
1056
+     * Check whether the current ownCloud version matches the given
1057
+     * application's version requirements.
1058
+     *
1059
+     * The comparison is made based on the number of parts that the
1060
+     * app info version has. For example for ownCloud 6.0.3 if the
1061
+     * app info version is expecting version 6.0, the comparison is
1062
+     * made on the first two parts of the ownCloud version.
1063
+     * This means that it's possible to specify "requiremin" => 6
1064
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
1065
+     *
1066
+     * @param string $ocVersion ownCloud version to check against
1067
+     * @param array $appInfo app info (from xml)
1068
+     *
1069
+     * @return boolean true if compatible, otherwise false
1070
+     */
1071
+    public static function isAppCompatible($ocVersion, $appInfo) {
1072
+        $requireMin = '';
1073
+        $requireMax = '';
1074
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
1075
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
1076
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
1077
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
1078
+        } else if (isset($appInfo['requiremin'])) {
1079
+            $requireMin = $appInfo['requiremin'];
1080
+        } else if (isset($appInfo['require'])) {
1081
+            $requireMin = $appInfo['require'];
1082
+        }
1083
+
1084
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
1085
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
1086
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
1087
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
1088
+        } else if (isset($appInfo['requiremax'])) {
1089
+            $requireMax = $appInfo['requiremax'];
1090
+        }
1091
+
1092
+        if (is_array($ocVersion)) {
1093
+            $ocVersion = implode('.', $ocVersion);
1094
+        }
1095
+
1096
+        if (!empty($requireMin)
1097
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
1098
+        ) {
1099
+
1100
+            return false;
1101
+        }
1102
+
1103
+        if (!empty($requireMax)
1104
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
1105
+        ) {
1106
+            return false;
1107
+        }
1108
+
1109
+        return true;
1110
+    }
1111
+
1112
+    /**
1113
+     * get the installed version of all apps
1114
+     */
1115
+    public static function getAppVersions() {
1116
+        static $versions;
1117
+
1118
+        if(!$versions) {
1119
+            $appConfig = \OC::$server->getAppConfig();
1120
+            $versions = $appConfig->getValues(false, 'installed_version');
1121
+        }
1122
+        return $versions;
1123
+    }
1124
+
1125
+    /**
1126
+     * @param string $app
1127
+     * @param \OCP\IConfig $config
1128
+     * @param \OCP\IL10N $l
1129
+     * @return bool
1130
+     *
1131
+     * @throws Exception if app is not compatible with this version of ownCloud
1132
+     * @throws Exception if no app-name was specified
1133
+     */
1134
+    public function installApp($app,
1135
+                                \OCP\IConfig $config,
1136
+                                \OCP\IL10N $l) {
1137
+        if ($app !== false) {
1138
+            // check if the app is compatible with this version of ownCloud
1139
+            $info = self::getAppInfo($app);
1140
+            if(!is_array($info)) {
1141
+                throw new \Exception(
1142
+                    $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1143
+                        [$info['name']]
1144
+                    )
1145
+                );
1146
+            }
1147
+
1148
+            $version = \OCP\Util::getVersion();
1149
+            if (!self::isAppCompatible($version, $info)) {
1150
+                throw new \Exception(
1151
+                    $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1152
+                        array($info['name'])
1153
+                    )
1154
+                );
1155
+            }
1156
+
1157
+            // check for required dependencies
1158
+            self::checkAppDependencies($config, $l, $info);
1159
+
1160
+            $config->setAppValue($app, 'enabled', 'yes');
1161
+            if (isset($appData['id'])) {
1162
+                $config->setAppValue($app, 'ocsid', $appData['id']);
1163
+            }
1164
+
1165
+            if(isset($info['settings']) && is_array($info['settings'])) {
1166
+                $appPath = self::getAppPath($app);
1167
+                self::registerAutoloading($app, $appPath);
1168
+                \OC::$server->getSettingsManager()->setupSettings($info['settings']);
1169
+            }
1170
+
1171
+            \OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1172
+        } else {
1173
+            if(empty($appName) ) {
1174
+                throw new \Exception($l->t("No app name specified"));
1175
+            } else {
1176
+                throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1177
+            }
1178
+        }
1179
+
1180
+        return $app;
1181
+    }
1182
+
1183
+    /**
1184
+     * update the database for the app and call the update script
1185
+     *
1186
+     * @param string $appId
1187
+     * @return bool
1188
+     */
1189
+    public static function updateApp($appId) {
1190
+        $appPath = self::getAppPath($appId);
1191
+        if($appPath === false) {
1192
+            return false;
1193
+        }
1194
+        $appData = self::getAppInfo($appId);
1195
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1196
+        if (file_exists($appPath . '/appinfo/database.xml')) {
1197
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1198
+        }
1199
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1200
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1201
+        unset(self::$appVersion[$appId]);
1202
+        // run upgrade code
1203
+        if (file_exists($appPath . '/appinfo/update.php')) {
1204
+            self::loadApp($appId);
1205
+            include $appPath . '/appinfo/update.php';
1206
+        }
1207
+        self::setupBackgroundJobs($appData['background-jobs']);
1208
+        if(isset($appData['settings']) && is_array($appData['settings'])) {
1209
+            $appPath = self::getAppPath($appId);
1210
+            self::registerAutoloading($appId, $appPath);
1211
+            \OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1212
+        }
1213
+
1214
+        //set remote/public handlers
1215
+        if (array_key_exists('ocsid', $appData)) {
1216
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1217
+        } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1218
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1219
+        }
1220
+        foreach ($appData['remote'] as $name => $path) {
1221
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1222
+        }
1223
+        foreach ($appData['public'] as $name => $path) {
1224
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1225
+        }
1226
+
1227
+        self::setAppTypes($appId);
1228
+
1229
+        $version = \OC_App::getAppVersion($appId);
1230
+        \OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1231
+
1232
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1233
+            ManagerEvent::EVENT_APP_UPDATE, $appId
1234
+        ));
1235
+
1236
+        return true;
1237
+    }
1238
+
1239
+    /**
1240
+     * @param string $appId
1241
+     * @param string[] $steps
1242
+     * @throws \OC\NeedsUpdateException
1243
+     */
1244
+    public static function executeRepairSteps($appId, array $steps) {
1245
+        if (empty($steps)) {
1246
+            return;
1247
+        }
1248
+        // load the app
1249
+        self::loadApp($appId);
1250
+
1251
+        $dispatcher = OC::$server->getEventDispatcher();
1252
+
1253
+        // load the steps
1254
+        $r = new Repair([], $dispatcher);
1255
+        foreach ($steps as $step) {
1256
+            try {
1257
+                $r->addStep($step);
1258
+            } catch (Exception $ex) {
1259
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1260
+                \OC::$server->getLogger()->logException($ex);
1261
+            }
1262
+        }
1263
+        // run the steps
1264
+        $r->run();
1265
+    }
1266
+
1267
+    public static function setupBackgroundJobs(array $jobs) {
1268
+        $queue = \OC::$server->getJobList();
1269
+        foreach ($jobs as $job) {
1270
+            $queue->add($job);
1271
+        }
1272
+    }
1273
+
1274
+    /**
1275
+     * @param string $appId
1276
+     * @param string[] $steps
1277
+     */
1278
+    private static function setupLiveMigrations($appId, array $steps) {
1279
+        $queue = \OC::$server->getJobList();
1280
+        foreach ($steps as $step) {
1281
+            $queue->add('OC\Migration\BackgroundRepair', [
1282
+                'app' => $appId,
1283
+                'step' => $step]);
1284
+        }
1285
+    }
1286
+
1287
+    /**
1288
+     * @param string $appId
1289
+     * @return \OC\Files\View|false
1290
+     */
1291
+    public static function getStorage($appId) {
1292
+        if (OC_App::isEnabled($appId)) { //sanity check
1293
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1294
+                $view = new \OC\Files\View('/' . OC_User::getUser());
1295
+                if (!$view->file_exists($appId)) {
1296
+                    $view->mkdir($appId);
1297
+                }
1298
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1299
+            } else {
1300
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1301
+                return false;
1302
+            }
1303
+        } else {
1304
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1305
+            return false;
1306
+        }
1307
+    }
1308
+
1309
+    protected static function findBestL10NOption($options, $lang) {
1310
+        $fallback = $similarLangFallback = $englishFallback = false;
1311
+
1312
+        $lang = strtolower($lang);
1313
+        $similarLang = $lang;
1314
+        if (strpos($similarLang, '_')) {
1315
+            // For "de_DE" we want to find "de" and the other way around
1316
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1317
+        }
1318
+
1319
+        foreach ($options as $option) {
1320
+            if (is_array($option)) {
1321
+                if ($fallback === false) {
1322
+                    $fallback = $option['@value'];
1323
+                }
1324
+
1325
+                if (!isset($option['@attributes']['lang'])) {
1326
+                    continue;
1327
+                }
1328
+
1329
+                $attributeLang = strtolower($option['@attributes']['lang']);
1330
+                if ($attributeLang === $lang) {
1331
+                    return $option['@value'];
1332
+                }
1333
+
1334
+                if ($attributeLang === $similarLang) {
1335
+                    $similarLangFallback = $option['@value'];
1336
+                } else if (strpos($attributeLang, $similarLang . '_') === 0) {
1337
+                    if ($similarLangFallback === false) {
1338
+                        $similarLangFallback =  $option['@value'];
1339
+                    }
1340
+                }
1341
+            } else {
1342
+                $englishFallback = $option;
1343
+            }
1344
+        }
1345
+
1346
+        if ($similarLangFallback !== false) {
1347
+            return $similarLangFallback;
1348
+        } else if ($englishFallback !== false) {
1349
+            return $englishFallback;
1350
+        }
1351
+        return (string) $fallback;
1352
+    }
1353
+
1354
+    /**
1355
+     * parses the app data array and enhanced the 'description' value
1356
+     *
1357
+     * @param array $data the app data
1358
+     * @param string $lang
1359
+     * @return array improved app data
1360
+     */
1361
+    public static function parseAppInfo(array $data, $lang = null) {
1362
+
1363
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1364
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1365
+        }
1366
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1367
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1368
+        }
1369
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1370
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1371
+        } else if (isset($data['description']) && is_string($data['description'])) {
1372
+            $data['description'] = trim($data['description']);
1373
+        } else  {
1374
+            $data['description'] = '';
1375
+        }
1376
+
1377
+        return $data;
1378
+    }
1379
+
1380
+    /**
1381
+     * @param \OCP\IConfig $config
1382
+     * @param \OCP\IL10N $l
1383
+     * @param array $info
1384
+     * @throws \Exception
1385
+     */
1386
+    protected static function checkAppDependencies($config, $l, $info) {
1387
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1388
+        $missing = $dependencyAnalyzer->analyze($info);
1389
+        if (!empty($missing)) {
1390
+            $missingMsg = join(PHP_EOL, $missing);
1391
+            throw new \Exception(
1392
+                $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1393
+                    [$info['name'], $missingMsg]
1394
+                )
1395
+            );
1396
+        }
1397
+    }
1398 1398
 }
Please login to merge, or discard this patch.
Spacing   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -111,9 +111,9 @@  discard block
 block discarded – undo
111 111
 		$apps = self::getEnabledApps();
112 112
 
113 113
 		// Add each apps' folder as allowed class path
114
-		foreach($apps as $app) {
114
+		foreach ($apps as $app) {
115 115
 			$path = self::getAppPath($app);
116
-			if($path !== false) {
116
+			if ($path !== false) {
117 117
 				self::registerAutoloading($app, $path);
118 118
 			}
119 119
 		}
@@ -138,15 +138,15 @@  discard block
 block discarded – undo
138 138
 	public static function loadApp($app) {
139 139
 		self::$loadedApps[] = $app;
140 140
 		$appPath = self::getAppPath($app);
141
-		if($appPath === false) {
141
+		if ($appPath === false) {
142 142
 			return;
143 143
 		}
144 144
 
145 145
 		// in case someone calls loadApp() directly
146 146
 		self::registerAutoloading($app, $appPath);
147 147
 
148
-		if (is_file($appPath . '/appinfo/app.php')) {
149
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
148
+		if (is_file($appPath.'/appinfo/app.php')) {
149
+			\OC::$server->getEventLogger()->start('load_app_'.$app, 'Load app: '.$app);
150 150
 			self::requireAppFile($app);
151 151
 			if (self::isType($app, array('authentication'))) {
152 152
 				// since authentication apps affect the "is app enabled for group" check,
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 				// enabled for groups
156 156
 				self::$enabledAppsCache = array();
157 157
 			}
158
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
158
+			\OC::$server->getEventLogger()->end('load_app_'.$app);
159 159
 		}
160 160
 
161 161
 		$info = self::getAppInfo($app);
@@ -182,17 +182,17 @@  discard block
 block discarded – undo
182 182
 	 * @param string $path
183 183
 	 */
184 184
 	public static function registerAutoloading($app, $path) {
185
-		$key = $app . '-' . $path;
186
-		if(isset(self::$alreadyRegistered[$key])) {
185
+		$key = $app.'-'.$path;
186
+		if (isset(self::$alreadyRegistered[$key])) {
187 187
 			return;
188 188
 		}
189 189
 		self::$alreadyRegistered[$key] = true;
190 190
 		// Register on PSR-4 composer autoloader
191 191
 		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
192 192
 		\OC::$server->registerNamespace($app, $appNamespace);
193
-		\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
193
+		\OC::$composerAutoloader->addPsr4($appNamespace.'\\', $path.'/lib/', true);
194 194
 		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
195
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
195
+			\OC::$composerAutoloader->addPsr4($appNamespace.'\\Tests\\', $path.'/tests/', true);
196 196
 		}
197 197
 
198 198
 		// Register on legacy autoloader
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 	private static function requireAppFile($app) {
208 208
 		try {
209 209
 			// encapsulated here to avoid variable scope conflicts
210
-			require_once $app . '/appinfo/app.php';
210
+			require_once $app.'/appinfo/app.php';
211 211
 		} catch (Error $ex) {
212 212
 			\OC::$server->getLogger()->logException($ex);
213 213
 			$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 	 */
262 262
 	public static function setAppTypes($app) {
263 263
 		$appData = self::getAppInfo($app);
264
-		if(!is_array($appData)) {
264
+		if (!is_array($appData)) {
265 265
 			return;
266 266
 		}
267 267
 
@@ -325,8 +325,8 @@  discard block
 block discarded – undo
325 325
 		} else {
326 326
 			$apps = $appManager->getEnabledAppsForUser($user);
327 327
 		}
328
-		$apps = array_filter($apps, function ($app) {
329
-			return $app !== 'files';//we add this manually
328
+		$apps = array_filter($apps, function($app) {
329
+			return $app !== 'files'; //we add this manually
330 330
 		});
331 331
 		sort($apps);
332 332
 		array_unshift($apps, 'files');
@@ -370,7 +370,7 @@  discard block
 block discarded – undo
370 370
 		);
371 371
 		$isDownloaded = $installer->isDownloaded($appId);
372 372
 
373
-		if(!$isDownloaded) {
373
+		if (!$isDownloaded) {
374 374
 			$installer->downloadApp($appId);
375 375
 		}
376 376
 
@@ -408,7 +408,7 @@  discard block
 block discarded – undo
408 408
 		}
409 409
 
410 410
 		$info = self::getAppInfo($appId);
411
-		if(isset($info['settings']) && is_array($info['settings'])) {
411
+		if (isset($info['settings']) && is_array($info['settings'])) {
412 412
 			$appPath = self::getAppPath($appId);
413 413
 			self::registerAutoloading($appId, $appPath);
414 414
 			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -497,7 +497,7 @@  discard block
 block discarded – undo
497 497
 			//SubAdmins are also allowed to access user management
498 498
 			$userObject = \OC::$server->getUserSession()->getUser();
499 499
 			$isSubAdmin = false;
500
-			if($userObject !== null) {
500
+			if ($userObject !== null) {
501 501
 				$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
502 502
 			}
503 503
 			if ($isSubAdmin) {
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 	// This is private as well. It simply works, so don't ask for more details
532 532
 	private static function proceedNavigation($list) {
533 533
 		$headerIconCount = 8;
534
-		if(OC_User::isAdminUser(OC_User::getUser())) {
534
+		if (OC_User::isAdminUser(OC_User::getUser())) {
535 535
 			$headerIconCount--;
536 536
 		}
537 537
 		usort($list, function($a, $b) {
@@ -556,16 +556,16 @@  discard block
 block discarded – undo
556 556
 		}
557 557
 		unset($navEntry);
558 558
 
559
-		if($activeAppIndex > ($headerIconCount-1)) {
559
+		if ($activeAppIndex > ($headerIconCount - 1)) {
560 560
 			$active = $list[$activeAppIndex];
561
-			$lastInHeader = $list[$headerIconCount-1];
562
-			$list[$headerIconCount-1] = $active;
561
+			$lastInHeader = $list[$headerIconCount - 1];
562
+			$list[$headerIconCount - 1] = $active;
563 563
 			$list[$activeAppIndex] = $lastInHeader;
564 564
 		}
565 565
 
566 566
 		foreach ($list as $index => &$navEntry) {
567 567
 			$navEntry['showInHeader'] = false;
568
-			if($index < $headerIconCount) {
568
+			if ($index < $headerIconCount) {
569 569
 				$navEntry['showInHeader'] = true;
570 570
 			}
571 571
 		}
@@ -577,7 +577,7 @@  discard block
 block discarded – undo
577 577
 
578 578
 	public static function proceedAppNavigation($entries) {
579 579
 		$headerIconCount = 8;
580
-		if(OC_User::isAdminUser(OC_User::getUser())) {
580
+		if (OC_User::isAdminUser(OC_User::getUser())) {
581 581
 			$headerIconCount--;
582 582
 		}
583 583
 		$activeAppIndex = -1;
@@ -593,10 +593,10 @@  discard block
 block discarded – undo
593 593
 			}
594 594
 		}
595 595
 		// move active item to last position
596
-		if($activeAppIndex > ($headerIconCount-1)) {
596
+		if ($activeAppIndex > ($headerIconCount - 1)) {
597 597
 			$active = $list[$activeAppIndex];
598
-			$lastInHeader = $list[$headerIconCount-1];
599
-			$list[$headerIconCount-1] = $active;
598
+			$lastInHeader = $list[$headerIconCount - 1];
599
+			$list[$headerIconCount - 1] = $active;
600 600
 			$list[$activeAppIndex] = $lastInHeader;
601 601
 		}
602 602
 		$list = array_slice($list, 0, $headerIconCount);
@@ -633,7 +633,7 @@  discard block
 block discarded – undo
633 633
 	 */
634 634
 	public static function findAppInDirectories($appId) {
635 635
 		$sanitizedAppId = self::cleanAppId($appId);
636
-		if($sanitizedAppId !== $appId) {
636
+		if ($sanitizedAppId !== $appId) {
637 637
 			return false;
638 638
 		}
639 639
 		static $app_dir = array();
@@ -644,7 +644,7 @@  discard block
 block discarded – undo
644 644
 
645 645
 		$possibleApps = array();
646 646
 		foreach (OC::$APPSROOTS as $dir) {
647
-			if (file_exists($dir['path'] . '/' . $appId)) {
647
+			if (file_exists($dir['path'].'/'.$appId)) {
648 648
 				$possibleApps[] = $dir;
649 649
 			}
650 650
 		}
@@ -685,7 +685,7 @@  discard block
 block discarded – undo
685 685
 		}
686 686
 
687 687
 		if (($dir = self::findAppInDirectories($appId)) != false) {
688
-			return $dir['path'] . '/' . $appId;
688
+			return $dir['path'].'/'.$appId;
689 689
 		}
690 690
 		return false;
691 691
 	}
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
 	 */
700 700
 	public static function getAppWebPath($appId) {
701 701
 		if (($dir = self::findAppInDirectories($appId)) != false) {
702
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
702
+			return OC::$WEBROOT.$dir['url'].'/'.$appId;
703 703
 		}
704 704
 		return false;
705 705
 	}
@@ -712,7 +712,7 @@  discard block
 block discarded – undo
712 712
 	 * @return string
713 713
 	 */
714 714
 	public static function getAppVersion($appId, $useCache = true) {
715
-		if($useCache && isset(self::$appVersion[$appId])) {
715
+		if ($useCache && isset(self::$appVersion[$appId])) {
716 716
 			return self::$appVersion[$appId];
717 717
 		}
718 718
 
@@ -728,7 +728,7 @@  discard block
 block discarded – undo
728 728
 	 * @return string
729 729
 	 */
730 730
 	public static function getAppVersionByPath($path) {
731
-		$infoFile = $path . '/appinfo/info.xml';
731
+		$infoFile = $path.'/appinfo/info.xml';
732 732
 		$appData = self::getAppInfo($infoFile, true);
733 733
 		return isset($appData['version']) ? $appData['version'] : '';
734 734
 	}
@@ -751,10 +751,10 @@  discard block
 block discarded – undo
751 751
 				return self::$appInfo[$appId];
752 752
 			}
753 753
 			$appPath = self::getAppPath($appId);
754
-			if($appPath === false) {
754
+			if ($appPath === false) {
755 755
 				return null;
756 756
 			}
757
-			$file = $appPath . '/appinfo/info.xml';
757
+			$file = $appPath.'/appinfo/info.xml';
758 758
 		}
759 759
 
760 760
 		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->create('core.appinfo'));
@@ -763,9 +763,9 @@  discard block
 block discarded – undo
763 763
 		if (is_array($data)) {
764 764
 			$data = OC_App::parseAppInfo($data, $lang);
765 765
 		}
766
-		if(isset($data['ocsid'])) {
766
+		if (isset($data['ocsid'])) {
767 767
 			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
768
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
768
+			if ($storedId !== '' && $storedId !== $data['ocsid']) {
769 769
 				$data['ocsid'] = $storedId;
770 770
 			}
771 771
 		}
@@ -861,7 +861,7 @@  discard block
 block discarded – undo
861 861
 	 * @param string $page
862 862
 	 */
863 863
 	public static function registerAdmin($app, $page) {
864
-		self::$adminForms[] = $app . '/' . $page . '.php';
864
+		self::$adminForms[] = $app.'/'.$page.'.php';
865 865
 	}
866 866
 
867 867
 	/**
@@ -870,7 +870,7 @@  discard block
 block discarded – undo
870 870
 	 * @param string $page
871 871
 	 */
872 872
 	public static function registerPersonal($app, $page) {
873
-		self::$personalForms[] = $app . '/' . $page . '.php';
873
+		self::$personalForms[] = $app.'/'.$page.'.php';
874 874
 	}
875 875
 
876 876
 	/**
@@ -899,7 +899,7 @@  discard block
 block discarded – undo
899 899
 
900 900
 		foreach (OC::$APPSROOTS as $apps_dir) {
901 901
 			if (!is_readable($apps_dir['path'])) {
902
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
902
+				\OCP\Util::writeLog('core', 'unable to read app folder : '.$apps_dir['path'], \OCP\Util::WARN);
903 903
 				continue;
904 904
 			}
905 905
 			$dh = opendir($apps_dir['path']);
@@ -907,7 +907,7 @@  discard block
 block discarded – undo
907 907
 			if (is_resource($dh)) {
908 908
 				while (($file = readdir($dh)) !== false) {
909 909
 
910
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
910
+					if ($file[0] != '.' and is_dir($apps_dir['path'].'/'.$file) and is_file($apps_dir['path'].'/'.$file.'/appinfo/info.xml')) {
911 911
 
912 912
 						$apps[] = $file;
913 913
 					}
@@ -937,12 +937,12 @@  discard block
 block discarded – undo
937 937
 
938 938
 				$info = OC_App::getAppInfo($app, false, $langCode);
939 939
 				if (!is_array($info)) {
940
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
940
+					\OCP\Util::writeLog('core', 'Could not read app info file for app "'.$app.'"', \OCP\Util::ERROR);
941 941
 					continue;
942 942
 				}
943 943
 
944 944
 				if (!isset($info['name'])) {
945
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
945
+					\OCP\Util::writeLog('core', 'App id "'.$app.'" has no name in appinfo', \OCP\Util::ERROR);
946 946
 					continue;
947 947
 				}
948 948
 
@@ -969,13 +969,13 @@  discard block
 block discarded – undo
969 969
 				}
970 970
 
971 971
 				$appPath = self::getAppPath($app);
972
-				if($appPath !== false) {
973
-					$appIcon = $appPath . '/img/' . $app . '.svg';
972
+				if ($appPath !== false) {
973
+					$appIcon = $appPath.'/img/'.$app.'.svg';
974 974
 					if (file_exists($appIcon)) {
975
-						$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app . '.svg');
975
+						$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app.'.svg');
976 976
 						$info['previewAsIcon'] = true;
977 977
 					} else {
978
-						$appIcon = $appPath . '/img/app.svg';
978
+						$appIcon = $appPath.'/img/app.svg';
979 979
 						if (file_exists($appIcon)) {
980 980
 							$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, 'app.svg');
981 981
 							$info['previewAsIcon'] = true;
@@ -1009,9 +1009,9 @@  discard block
 block discarded – undo
1009 1009
 	 * @return string|false
1010 1010
 	 */
1011 1011
 	public static function getInternalAppIdByOcs($ocsID) {
1012
-		if(is_numeric($ocsID)) {
1012
+		if (is_numeric($ocsID)) {
1013 1013
 			$idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
1014
-			if(array_search($ocsID, $idArray)) {
1014
+			if (array_search($ocsID, $idArray)) {
1015 1015
 				return array_search($ocsID, $idArray);
1016 1016
 			}
1017 1017
 		}
@@ -1115,7 +1115,7 @@  discard block
 block discarded – undo
1115 1115
 	public static function getAppVersions() {
1116 1116
 		static $versions;
1117 1117
 
1118
-		if(!$versions) {
1118
+		if (!$versions) {
1119 1119
 			$appConfig = \OC::$server->getAppConfig();
1120 1120
 			$versions = $appConfig->getValues(false, 'installed_version');
1121 1121
 		}
@@ -1137,7 +1137,7 @@  discard block
 block discarded – undo
1137 1137
 		if ($app !== false) {
1138 1138
 			// check if the app is compatible with this version of ownCloud
1139 1139
 			$info = self::getAppInfo($app);
1140
-			if(!is_array($info)) {
1140
+			if (!is_array($info)) {
1141 1141
 				throw new \Exception(
1142 1142
 					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1143 1143
 						[$info['name']]
@@ -1162,7 +1162,7 @@  discard block
 block discarded – undo
1162 1162
 				$config->setAppValue($app, 'ocsid', $appData['id']);
1163 1163
 			}
1164 1164
 
1165
-			if(isset($info['settings']) && is_array($info['settings'])) {
1165
+			if (isset($info['settings']) && is_array($info['settings'])) {
1166 1166
 				$appPath = self::getAppPath($app);
1167 1167
 				self::registerAutoloading($app, $appPath);
1168 1168
 				\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -1170,7 +1170,7 @@  discard block
 block discarded – undo
1170 1170
 
1171 1171
 			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1172 1172
 		} else {
1173
-			if(empty($appName) ) {
1173
+			if (empty($appName)) {
1174 1174
 				throw new \Exception($l->t("No app name specified"));
1175 1175
 			} else {
1176 1176
 				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
@@ -1188,24 +1188,24 @@  discard block
 block discarded – undo
1188 1188
 	 */
1189 1189
 	public static function updateApp($appId) {
1190 1190
 		$appPath = self::getAppPath($appId);
1191
-		if($appPath === false) {
1191
+		if ($appPath === false) {
1192 1192
 			return false;
1193 1193
 		}
1194 1194
 		$appData = self::getAppInfo($appId);
1195 1195
 		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1196
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1197
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1196
+		if (file_exists($appPath.'/appinfo/database.xml')) {
1197
+			OC_DB::updateDbFromStructure($appPath.'/appinfo/database.xml');
1198 1198
 		}
1199 1199
 		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1200 1200
 		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1201 1201
 		unset(self::$appVersion[$appId]);
1202 1202
 		// run upgrade code
1203
-		if (file_exists($appPath . '/appinfo/update.php')) {
1203
+		if (file_exists($appPath.'/appinfo/update.php')) {
1204 1204
 			self::loadApp($appId);
1205
-			include $appPath . '/appinfo/update.php';
1205
+			include $appPath.'/appinfo/update.php';
1206 1206
 		}
1207 1207
 		self::setupBackgroundJobs($appData['background-jobs']);
1208
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
1208
+		if (isset($appData['settings']) && is_array($appData['settings'])) {
1209 1209
 			$appPath = self::getAppPath($appId);
1210 1210
 			self::registerAutoloading($appId, $appPath);
1211 1211
 			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
@@ -1214,14 +1214,14 @@  discard block
 block discarded – undo
1214 1214
 		//set remote/public handlers
1215 1215
 		if (array_key_exists('ocsid', $appData)) {
1216 1216
 			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1217
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1217
+		} elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1218 1218
 			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1219 1219
 		}
1220 1220
 		foreach ($appData['remote'] as $name => $path) {
1221
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1221
+			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $appId.'/'.$path);
1222 1222
 		}
1223 1223
 		foreach ($appData['public'] as $name => $path) {
1224
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1224
+			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $appId.'/'.$path);
1225 1225
 		}
1226 1226
 
1227 1227
 		self::setAppTypes($appId);
@@ -1291,17 +1291,17 @@  discard block
 block discarded – undo
1291 1291
 	public static function getStorage($appId) {
1292 1292
 		if (OC_App::isEnabled($appId)) { //sanity check
1293 1293
 			if (\OC::$server->getUserSession()->isLoggedIn()) {
1294
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1294
+				$view = new \OC\Files\View('/'.OC_User::getUser());
1295 1295
 				if (!$view->file_exists($appId)) {
1296 1296
 					$view->mkdir($appId);
1297 1297
 				}
1298
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1298
+				return new \OC\Files\View('/'.OC_User::getUser().'/'.$appId);
1299 1299
 			} else {
1300
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1300
+				\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.', user not logged in', \OCP\Util::ERROR);
1301 1301
 				return false;
1302 1302
 			}
1303 1303
 		} else {
1304
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1304
+			\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.' not enabled', \OCP\Util::ERROR);
1305 1305
 			return false;
1306 1306
 		}
1307 1307
 	}
@@ -1333,9 +1333,9 @@  discard block
 block discarded – undo
1333 1333
 
1334 1334
 				if ($attributeLang === $similarLang) {
1335 1335
 					$similarLangFallback = $option['@value'];
1336
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1336
+				} else if (strpos($attributeLang, $similarLang.'_') === 0) {
1337 1337
 					if ($similarLangFallback === false) {
1338
-						$similarLangFallback =  $option['@value'];
1338
+						$similarLangFallback = $option['@value'];
1339 1339
 					}
1340 1340
 				}
1341 1341
 			} else {
@@ -1370,7 +1370,7 @@  discard block
 block discarded – undo
1370 1370
 			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1371 1371
 		} else if (isset($data['description']) && is_string($data['description'])) {
1372 1372
 			$data['description'] = trim($data['description']);
1373
-		} else  {
1373
+		} else {
1374 1374
 			$data['description'] = '';
1375 1375
 		}
1376 1376
 
Please login to merge, or discard this patch.
lib/private/ServerContainer.php 1 patch
Indentation   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -34,76 +34,76 @@
 block discarded – undo
34 34
  * @package OC
35 35
  */
36 36
 class ServerContainer extends SimpleContainer {
37
-	/** @var DIContainer[] */
38
-	protected $appContainers;
37
+    /** @var DIContainer[] */
38
+    protected $appContainers;
39 39
 
40
-	/** @var string[] */
41
-	protected $namespaces;
40
+    /** @var string[] */
41
+    protected $namespaces;
42 42
 
43
-	/**
44
-	 * ServerContainer constructor.
45
-	 */
46
-	public function __construct() {
47
-		parent::__construct();
48
-		$this->appContainers = [];
49
-		$this->namespaces = [];
50
-	}
43
+    /**
44
+     * ServerContainer constructor.
45
+     */
46
+    public function __construct() {
47
+        parent::__construct();
48
+        $this->appContainers = [];
49
+        $this->namespaces = [];
50
+    }
51 51
 
52
-	/**
53
-	 * @param string $appName
54
-	 * @param string $appNamespace
55
-	 */
56
-	public function registerNamespace($appName, $appNamespace) {
57
-		// Cut of OCA\ and lowercase
58
-		$appNamespace = strtolower(substr($appNamespace, strrpos($appNamespace, '\\') + 1));
59
-		$this->namespaces[$appNamespace] = $appName;
60
-	}
52
+    /**
53
+     * @param string $appName
54
+     * @param string $appNamespace
55
+     */
56
+    public function registerNamespace($appName, $appNamespace) {
57
+        // Cut of OCA\ and lowercase
58
+        $appNamespace = strtolower(substr($appNamespace, strrpos($appNamespace, '\\') + 1));
59
+        $this->namespaces[$appNamespace] = $appName;
60
+    }
61 61
 
62
-	/**
63
-	 * @param string $appName
64
-	 * @param DIContainer $container
65
-	 */
66
-	public function registerAppContainer($appName, DIContainer $container) {
67
-		$this->appContainers[strtolower(App::buildAppNamespace($appName, ''))] = $container;
68
-	}
62
+    /**
63
+     * @param string $appName
64
+     * @param DIContainer $container
65
+     */
66
+    public function registerAppContainer($appName, DIContainer $container) {
67
+        $this->appContainers[strtolower(App::buildAppNamespace($appName, ''))] = $container;
68
+    }
69 69
 
70
-	/**
71
-	 * @param string $namespace
72
-	 * @return DIContainer
73
-	 * @throws QueryException
74
-	 */
75
-	protected function getAppContainer($namespace) {
76
-		if (isset($this->appContainers[$namespace])) {
77
-			return $this->appContainers[$namespace];
78
-		}
70
+    /**
71
+     * @param string $namespace
72
+     * @return DIContainer
73
+     * @throws QueryException
74
+     */
75
+    protected function getAppContainer($namespace) {
76
+        if (isset($this->appContainers[$namespace])) {
77
+            return $this->appContainers[$namespace];
78
+        }
79 79
 
80
-		if (isset($this->namespaces[$namespace])) {
81
-			return new DIContainer($this->namespaces[$namespace]);
82
-		}
83
-		throw new QueryException();
84
-	}
80
+        if (isset($this->namespaces[$namespace])) {
81
+            return new DIContainer($this->namespaces[$namespace]);
82
+        }
83
+        throw new QueryException();
84
+    }
85 85
 
86
-	/**
87
-	 * @param string $name name of the service to query for
88
-	 * @return mixed registered service for the given $name
89
-	 * @throws QueryException if the query could not be resolved
90
-	 */
91
-	public function query($name) {
92
-		$name = $this->sanitizeName($name);
86
+    /**
87
+     * @param string $name name of the service to query for
88
+     * @return mixed registered service for the given $name
89
+     * @throws QueryException if the query could not be resolved
90
+     */
91
+    public function query($name) {
92
+        $name = $this->sanitizeName($name);
93 93
 
94
-		// In case the service starts with OCA\ we try to find the service in
95
-		// the apps container first.
96
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
97
-			$segments = explode('\\', $name);
98
-			try {
99
-				$appContainer = $this->getAppContainer(strtolower($segments[1]));
100
-				return $appContainer->queryNoFallback($name);
101
-			} catch (QueryException $e) {
102
-				// Didn't find the service or the respective app container,
103
-				// ignore it and fall back to the core container.
104
-			}
105
-		}
94
+        // In case the service starts with OCA\ we try to find the service in
95
+        // the apps container first.
96
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
97
+            $segments = explode('\\', $name);
98
+            try {
99
+                $appContainer = $this->getAppContainer(strtolower($segments[1]));
100
+                return $appContainer->queryNoFallback($name);
101
+            } catch (QueryException $e) {
102
+                // Didn't find the service or the respective app container,
103
+                // ignore it and fall back to the core container.
104
+            }
105
+        }
106 106
 
107
-		return parent::query($name);
108
-	}
107
+        return parent::query($name);
108
+    }
109 109
 }
Please login to merge, or discard this patch.