Completed
Pull Request — master (#4454)
by Jan-Christoph
15:21
created
lib/private/Installer.php 3 patches
Spacing   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
 	 */
109 109
 	public function installApp($appId) {
110 110
 		$app = \OC_App::findAppInDirectories($appId);
111
-		if($app === false) {
111
+		if ($app === false) {
112 112
 			throw new \Exception('App not found in any app directory');
113 113
 		}
114 114
 
@@ -116,7 +116,7 @@  discard block
 block discarded – undo
116 116
 		$info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
117 117
 
118 118
 		//install the database
119
-		if(is_file($basedir.'/appinfo/database.xml')) {
119
+		if (is_file($basedir.'/appinfo/database.xml')) {
120 120
 			if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
121 121
 				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
122 122
 			} else {
@@ -128,8 +128,8 @@  discard block
 block discarded – undo
128 128
 		\OC_App::setupBackgroundJobs($info['background-jobs']);
129 129
 
130 130
 		//run appinfo/install.php
131
-		if((!isset($data['noinstall']) or $data['noinstall']==false)) {
132
-			self::includeAppScript($basedir . '/appinfo/install.php');
131
+		if ((!isset($data['noinstall']) or $data['noinstall'] == false)) {
132
+			self::includeAppScript($basedir.'/appinfo/install.php');
133 133
 		}
134 134
 
135 135
 		$appData = OC_App::getAppInfo($appId);
@@ -140,10 +140,10 @@  discard block
 block discarded – undo
140 140
 		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
141 141
 
142 142
 		//set remote/public handlers
143
-		foreach($info['remote'] as $name=>$path) {
143
+		foreach ($info['remote'] as $name=>$path) {
144 144
 			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
145 145
 		}
146
-		foreach($info['public'] as $name=>$path) {
146
+		foreach ($info['public'] as $name=>$path) {
147 147
 			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
148 148
 		}
149 149
 
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
 	 *
160 160
 	 * Checks whether or not an app is installed, i.e. registered in apps table.
161 161
 	 */
162
-	public static function isInstalled( $app ) {
162
+	public static function isInstalled($app) {
163 163
 		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
164 164
 	}
165 165
 
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 	 * @return bool
171 171
 	 */
172 172
 	public function updateAppstoreApp($appId) {
173
-		if(self::isUpdateAvailable($appId, $this->appFetcher)) {
173
+		if (self::isUpdateAvailable($appId, $this->appFetcher)) {
174 174
 			try {
175 175
 				$this->downloadApp($appId);
176 176
 			} catch (\Exception $e) {
@@ -194,18 +194,18 @@  discard block
 block discarded – undo
194 194
 		$appId = strtolower($appId);
195 195
 
196 196
 		$apps = $this->appFetcher->get();
197
-		foreach($apps as $app) {
198
-			if($app['id'] === $appId) {
197
+		foreach ($apps as $app) {
198
+			if ($app['id'] === $appId) {
199 199
 				// Load the certificate
200 200
 				$certificate = new X509();
201
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
201
+				$certificate->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
202 202
 				$loadedCertificate = $certificate->loadX509($app['certificate']);
203 203
 
204 204
 				// Verify if the certificate has been revoked
205 205
 				$crl = new X509();
206
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
207
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
208
-				if($crl->validateSignature() !== true) {
206
+				$crl->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
207
+				$crl->loadCRL(file_get_contents(__DIR__.'/../../resources/codesigning/root.crl'));
208
+				if ($crl->validateSignature() !== true) {
209 209
 					throw new \Exception('Could not validate CRL signature');
210 210
 				}
211 211
 				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
 				}
221 221
 
222 222
 				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
223
-				if($certificate->validateSignature() !== true) {
223
+				if ($certificate->validateSignature() !== true) {
224 224
 					throw new \Exception(
225 225
 						sprintf(
226 226
 							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
 
232 232
 				// Verify if the certificate is issued for the requested app id
233 233
 				$certInfo = openssl_x509_parse($app['certificate']);
234
-				if(!isset($certInfo['subject']['CN'])) {
234
+				if (!isset($certInfo['subject']['CN'])) {
235 235
 					throw new \Exception(
236 236
 						sprintf(
237 237
 							'App with id %s has a cert with no CN',
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
 						)
240 240
 					);
241 241
 				}
242
-				if($certInfo['subject']['CN'] !== $appId) {
242
+				if ($certInfo['subject']['CN'] !== $appId) {
243 243
 					throw new \Exception(
244 244
 						sprintf(
245 245
 							'App with id %s has a cert issued to %s',
@@ -256,21 +256,21 @@  discard block
 block discarded – undo
256 256
 
257 257
 				// Check if the signature actually matches the downloaded content
258 258
 				$certificate = openssl_get_publickey($app['certificate']);
259
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
259
+				$verified = (bool) openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
260 260
 				openssl_free_key($certificate);
261 261
 
262
-				if($verified === true) {
262
+				if ($verified === true) {
263 263
 					// Seems to match, let's proceed
264 264
 					$extractDir = $this->tempManager->getTemporaryFolder();
265 265
 					$archive = new TAR($tempFile);
266 266
 
267
-					if($archive) {
267
+					if ($archive) {
268 268
 						$archive->extract($extractDir);
269 269
 						$allFiles = scandir($extractDir);
270 270
 						$folders = array_diff($allFiles, ['.', '..']);
271 271
 						$folders = array_values($folders);
272 272
 
273
-						if(count($folders) > 1) {
273
+						if (count($folders) > 1) {
274 274
 							throw new \Exception(
275 275
 								sprintf(
276 276
 									'Extracted app %s has more than 1 folder',
@@ -281,22 +281,22 @@  discard block
 block discarded – undo
281 281
 
282 282
 						// Check if appinfo/info.xml has the same app ID as well
283 283
 						$loadEntities = libxml_disable_entity_loader(false);
284
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
284
+						$xml = simplexml_load_file($extractDir.'/'.$folders[0].'/appinfo/info.xml');
285 285
 						libxml_disable_entity_loader($loadEntities);
286
-						if((string)$xml->id !== $appId) {
286
+						if ((string) $xml->id !== $appId) {
287 287
 							throw new \Exception(
288 288
 								sprintf(
289 289
 									'App for id %s has a wrong app ID in info.xml: %s',
290 290
 									$appId,
291
-									(string)$xml->id
291
+									(string) $xml->id
292 292
 								)
293 293
 							);
294 294
 						}
295 295
 
296 296
 						// Check if the version is lower than before
297 297
 						$currentVersion = OC_App::getAppVersion($appId);
298
-						$newVersion = (string)$xml->version;
299
-						if(version_compare($currentVersion, $newVersion) === 1) {
298
+						$newVersion = (string) $xml->version;
299
+						if (version_compare($currentVersion, $newVersion) === 1) {
300 300
 							throw new \Exception(
301 301
 								sprintf(
302 302
 									'App for id %s has version %s and tried to update to lower version %s',
@@ -307,12 +307,12 @@  discard block
 block discarded – undo
307 307
 							);
308 308
 						}
309 309
 
310
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
310
+						$baseDir = OC_App::getInstallPath().'/'.$appId;
311 311
 						// Remove old app with the ID if existent
312 312
 						OC_Helper::rmdirr($baseDir);
313 313
 						// Move to app folder
314
-						if(@mkdir($baseDir)) {
315
-							$extractDir .= '/' . $folders[0];
314
+						if (@mkdir($baseDir)) {
315
+							$extractDir .= '/'.$folders[0];
316 316
 							OC_Helper::copyr($extractDir, $baseDir);
317 317
 						}
318 318
 						OC_Helper::copyr($extractDir, $baseDir);
@@ -372,8 +372,8 @@  discard block
 block discarded – undo
372 372
 		}
373 373
 
374 374
 		$apps = $appFetcher->get();
375
-		foreach($apps as $app) {
376
-			if($app['id'] === $appId) {
375
+		foreach ($apps as $app) {
376
+			if ($app['id'] === $appId) {
377 377
 				$currentVersion = OC_App::getAppVersion($appId);
378 378
 				$newestVersion = $app['releases'][0]['version'];
379 379
 				if (version_compare($newestVersion, $currentVersion, '>')) {
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
 	 * The function will check if the app is already downloaded in the apps repository
396 396
 	 */
397 397
 	public function isDownloaded($name) {
398
-		foreach(\OC::$APPSROOTS as $dir) {
398
+		foreach (\OC::$APPSROOTS as $dir) {
399 399
 			$dirToTest  = $dir['path'];
400 400
 			$dirToTest .= '/';
401 401
 			$dirToTest .= $name;
@@ -423,11 +423,11 @@  discard block
 block discarded – undo
423 423
 	 * this has to be done by the function oc_app_uninstall().
424 424
 	 */
425 425
 	public function removeApp($appId) {
426
-		if($this->isDownloaded( $appId )) {
427
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
426
+		if ($this->isDownloaded($appId)) {
427
+			$appDir = OC_App::getInstallPath().'/'.$appId;
428 428
 			OC_Helper::rmdirr($appDir);
429 429
 			return true;
430
-		}else{
430
+		} else {
431 431
 			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
432 432
 
433 433
 			return false;
@@ -443,8 +443,8 @@  discard block
 block discarded – undo
443 443
 	 */
444 444
 	public function installAppBundle(Bundle $bundle) {
445 445
 		$appIds = $bundle->getAppIdentifiers();
446
-		foreach($appIds as $appId) {
447
-			if(!$this->isDownloaded($appId)) {
446
+		foreach ($appIds as $appId) {
447
+			if (!$this->isDownloaded($appId)) {
448 448
 				$this->downloadApp($appId);
449 449
 			}
450 450
 			$this->installApp($appId);
@@ -466,13 +466,13 @@  discard block
 block discarded – undo
466 466
 	 */
467 467
 	public static function installShippedApps($softErrors = false) {
468 468
 		$errors = [];
469
-		foreach(\OC::$APPSROOTS as $app_dir) {
470
-			if($dir = opendir( $app_dir['path'] )) {
471
-				while( false !== ( $filename = readdir( $dir ))) {
472
-					if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
473
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
474
-							if(!Installer::isInstalled($filename)) {
475
-								$info=OC_App::getAppInfo($filename);
469
+		foreach (\OC::$APPSROOTS as $app_dir) {
470
+			if ($dir = opendir($app_dir['path'])) {
471
+				while (false !== ($filename = readdir($dir))) {
472
+					if (substr($filename, 0, 1) != '.' and is_dir($app_dir['path']."/$filename")) {
473
+						if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
474
+							if (!Installer::isInstalled($filename)) {
475
+								$info = OC_App::getAppInfo($filename);
476 476
 								$enabled = isset($info['default_enable']);
477 477
 								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
478 478
 									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
 						}
496 496
 					}
497 497
 				}
498
-				closedir( $dir );
498
+				closedir($dir);
499 499
 			}
500 500
 		}
501 501
 
@@ -510,12 +510,12 @@  discard block
 block discarded – undo
510 510
 	public static function installShippedApp($app) {
511 511
 		//install the database
512 512
 		$appPath = OC_App::getAppPath($app);
513
-		if(is_file("$appPath/appinfo/database.xml")) {
513
+		if (is_file("$appPath/appinfo/database.xml")) {
514 514
 			try {
515 515
 				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
516 516
 			} catch (TableExistsException $e) {
517 517
 				throw new HintException(
518
-					'Failed to enable app ' . $app,
518
+					'Failed to enable app '.$app,
519 519
 					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer">support channels</a>.',
520 520
 					0, $e
521 521
 				);
@@ -542,16 +542,16 @@  discard block
 block discarded – undo
542 542
 		}
543 543
 
544 544
 		//set remote/public handlers
545
-		foreach($info['remote'] as $name=>$path) {
545
+		foreach ($info['remote'] as $name=>$path) {
546 546
 			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
547 547
 		}
548
-		foreach($info['public'] as $name=>$path) {
548
+		foreach ($info['public'] as $name=>$path) {
549 549
 			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
550 550
 		}
551 551
 
552 552
 		OC_App::setAppTypes($info['id']);
553 553
 
554
-		if(isset($info['settings']) && is_array($info['settings'])) {
554
+		if (isset($info['settings']) && is_array($info['settings'])) {
555 555
 			// requires that autoloading was registered for the app,
556 556
 			// as happens before running the install.php some lines above
557 557
 			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
 	 */
568 568
 	public static function checkCode($folder) {
569 569
 		// is the code checker enabled?
570
-		if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
570
+		if (!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
571 571
 			return true;
572 572
 		}
573 573
 
@@ -581,7 +581,7 @@  discard block
 block discarded – undo
581 581
 	 * @param string $script
582 582
 	 */
583 583
 	private static function includeAppScript($script) {
584
-		if ( file_exists($script) ){
584
+		if (file_exists($script)) {
585 585
 			include $script;
586 586
 		}
587 587
 	}
Please login to merge, or discard this patch.
Unused Use Statements   -2 removed lines patch added patch discarded remove patch
@@ -42,7 +42,6 @@  discard block
 block discarded – undo
42 42
 namespace OC;
43 43
 
44 44
 use Doctrine\DBAL\Exception\TableExistsException;
45
-use OC\App\AppManager;
46 45
 use OC\App\AppStore\Bundles\Bundle;
47 46
 use OC\App\AppStore\Fetcher\AppFetcher;
48 47
 use OC\App\CodeChecker\CodeChecker;
@@ -52,7 +51,6 @@  discard block
 block discarded – undo
52 51
 use OC_App;
53 52
 use OC_DB;
54 53
 use OC_Helper;
55
-use OCP\App\IAppManager;
56 54
 use OCP\Http\Client\IClientService;
57 55
 use OCP\IConfig;
58 56
 use OCP\ILogger;
Please login to merge, or discard this patch.
Indentation   +516 added lines, -516 removed lines patch added patch discarded remove patch
@@ -63,520 +63,520 @@
 block discarded – undo
63 63
  * This class provides the functionality needed to install, update and remove apps
64 64
  */
65 65
 class Installer {
66
-	/** @var AppFetcher */
67
-	private $appFetcher;
68
-	/** @var IClientService */
69
-	private $clientService;
70
-	/** @var ITempManager */
71
-	private $tempManager;
72
-	/** @var ILogger */
73
-	private $logger;
74
-	/** @var IConfig */
75
-	private $config;
76
-
77
-	/**
78
-	 * @param AppFetcher $appFetcher
79
-	 * @param IClientService $clientService
80
-	 * @param ITempManager $tempManager
81
-	 * @param ILogger $logger
82
-	 * @param IConfig $config
83
-	 */
84
-	public function __construct(AppFetcher $appFetcher,
85
-								IClientService $clientService,
86
-								ITempManager $tempManager,
87
-								ILogger $logger,
88
-								IConfig $config) {
89
-		$this->appFetcher = $appFetcher;
90
-		$this->clientService = $clientService;
91
-		$this->tempManager = $tempManager;
92
-		$this->logger = $logger;
93
-		$this->config = $config;
94
-	}
95
-
96
-	/**
97
-	 * Installs an app that is located in one of the app folders already
98
-	 *
99
-	 * @param string $appId App to install
100
-	 * @throws \Exception
101
-	 * @return integer
102
-	 */
103
-	public function installApp($appId) {
104
-		$app = \OC_App::findAppInDirectories($appId);
105
-		if($app === false) {
106
-			throw new \Exception('App not found in any app directory');
107
-		}
108
-
109
-		$basedir = $app['path'].'/'.$appId;
110
-		$info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
111
-
112
-		//install the database
113
-		if(is_file($basedir.'/appinfo/database.xml')) {
114
-			if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
115
-				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
116
-			} else {
117
-				OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
118
-			}
119
-		}
120
-
121
-		\OC_App::registerAutoloading($appId, $basedir);
122
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
123
-
124
-		//run appinfo/install.php
125
-		if((!isset($data['noinstall']) or $data['noinstall']==false)) {
126
-			self::includeAppScript($basedir . '/appinfo/install.php');
127
-		}
128
-
129
-		$appData = OC_App::getAppInfo($appId);
130
-		OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
131
-
132
-		//set the installed version
133
-		\OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
134
-		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
135
-
136
-		//set remote/public handlers
137
-		foreach($info['remote'] as $name=>$path) {
138
-			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
139
-		}
140
-		foreach($info['public'] as $name=>$path) {
141
-			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
142
-		}
143
-
144
-		OC_App::setAppTypes($info['id']);
145
-
146
-		return $info['id'];
147
-	}
148
-
149
-	/**
150
-	 * @brief checks whether or not an app is installed
151
-	 * @param string $app app
152
-	 * @returns bool
153
-	 *
154
-	 * Checks whether or not an app is installed, i.e. registered in apps table.
155
-	 */
156
-	public static function isInstalled( $app ) {
157
-		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
158
-	}
159
-
160
-	/**
161
-	 * Updates the specified app from the appstore
162
-	 *
163
-	 * @param string $appId
164
-	 * @return bool
165
-	 */
166
-	public function updateAppstoreApp($appId) {
167
-		if(self::isUpdateAvailable($appId, $this->appFetcher)) {
168
-			try {
169
-				$this->downloadApp($appId);
170
-			} catch (\Exception $e) {
171
-				$this->logger->error($e->getMessage(), ['app' => 'core']);
172
-				return false;
173
-			}
174
-			return OC_App::updateApp($appId);
175
-		}
176
-
177
-		return false;
178
-	}
179
-
180
-	/**
181
-	 * Downloads an app and puts it into the app directory
182
-	 *
183
-	 * @param string $appId
184
-	 *
185
-	 * @throws \Exception If the installation was not successful
186
-	 */
187
-	public function downloadApp($appId) {
188
-		$appId = strtolower($appId);
189
-
190
-		$apps = $this->appFetcher->get();
191
-		foreach($apps as $app) {
192
-			if($app['id'] === $appId) {
193
-				// Load the certificate
194
-				$certificate = new X509();
195
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
196
-				$loadedCertificate = $certificate->loadX509($app['certificate']);
197
-
198
-				// Verify if the certificate has been revoked
199
-				$crl = new X509();
200
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
201
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
202
-				if($crl->validateSignature() !== true) {
203
-					throw new \Exception('Could not validate CRL signature');
204
-				}
205
-				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
206
-				$revoked = $crl->getRevoked($csn);
207
-				if ($revoked !== false) {
208
-					throw new \Exception(
209
-						sprintf(
210
-							'Certificate "%s" has been revoked',
211
-							$csn
212
-						)
213
-					);
214
-				}
215
-
216
-				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
217
-				if($certificate->validateSignature() !== true) {
218
-					throw new \Exception(
219
-						sprintf(
220
-							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
221
-							$appId
222
-						)
223
-					);
224
-				}
225
-
226
-				// Verify if the certificate is issued for the requested app id
227
-				$certInfo = openssl_x509_parse($app['certificate']);
228
-				if(!isset($certInfo['subject']['CN'])) {
229
-					throw new \Exception(
230
-						sprintf(
231
-							'App with id %s has a cert with no CN',
232
-							$appId
233
-						)
234
-					);
235
-				}
236
-				if($certInfo['subject']['CN'] !== $appId) {
237
-					throw new \Exception(
238
-						sprintf(
239
-							'App with id %s has a cert issued to %s',
240
-							$appId,
241
-							$certInfo['subject']['CN']
242
-						)
243
-					);
244
-				}
245
-
246
-				// Download the release
247
-				$tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
248
-				$client = $this->clientService->newClient();
249
-				$client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
250
-
251
-				// Check if the signature actually matches the downloaded content
252
-				$certificate = openssl_get_publickey($app['certificate']);
253
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
254
-				openssl_free_key($certificate);
255
-
256
-				if($verified === true) {
257
-					// Seems to match, let's proceed
258
-					$extractDir = $this->tempManager->getTemporaryFolder();
259
-					$archive = new TAR($tempFile);
260
-
261
-					if($archive) {
262
-						$archive->extract($extractDir);
263
-						$allFiles = scandir($extractDir);
264
-						$folders = array_diff($allFiles, ['.', '..']);
265
-						$folders = array_values($folders);
266
-
267
-						if(count($folders) > 1) {
268
-							throw new \Exception(
269
-								sprintf(
270
-									'Extracted app %s has more than 1 folder',
271
-									$appId
272
-								)
273
-							);
274
-						}
275
-
276
-						// Check if appinfo/info.xml has the same app ID as well
277
-						$loadEntities = libxml_disable_entity_loader(false);
278
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
279
-						libxml_disable_entity_loader($loadEntities);
280
-						if((string)$xml->id !== $appId) {
281
-							throw new \Exception(
282
-								sprintf(
283
-									'App for id %s has a wrong app ID in info.xml: %s',
284
-									$appId,
285
-									(string)$xml->id
286
-								)
287
-							);
288
-						}
289
-
290
-						// Check if the version is lower than before
291
-						$currentVersion = OC_App::getAppVersion($appId);
292
-						$newVersion = (string)$xml->version;
293
-						if(version_compare($currentVersion, $newVersion) === 1) {
294
-							throw new \Exception(
295
-								sprintf(
296
-									'App for id %s has version %s and tried to update to lower version %s',
297
-									$appId,
298
-									$currentVersion,
299
-									$newVersion
300
-								)
301
-							);
302
-						}
303
-
304
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
305
-						// Remove old app with the ID if existent
306
-						OC_Helper::rmdirr($baseDir);
307
-						// Move to app folder
308
-						if(@mkdir($baseDir)) {
309
-							$extractDir .= '/' . $folders[0];
310
-							OC_Helper::copyr($extractDir, $baseDir);
311
-						}
312
-						OC_Helper::copyr($extractDir, $baseDir);
313
-						OC_Helper::rmdirr($extractDir);
314
-						return;
315
-					} else {
316
-						throw new \Exception(
317
-							sprintf(
318
-								'Could not extract app with ID %s to %s',
319
-								$appId,
320
-								$extractDir
321
-							)
322
-						);
323
-					}
324
-				} else {
325
-					// Signature does not match
326
-					throw new \Exception(
327
-						sprintf(
328
-							'App with id %s has invalid signature',
329
-							$appId
330
-						)
331
-					);
332
-				}
333
-			}
334
-		}
335
-
336
-		throw new \Exception(
337
-			sprintf(
338
-				'Could not download app %s',
339
-				$appId
340
-			)
341
-		);
342
-	}
343
-
344
-	/**
345
-	 * Check if an update for the app is available
346
-	 *
347
-	 * @param string $appId
348
-	 * @param AppFetcher $appFetcher
349
-	 * @return string|false false or the version number of the update
350
-	 */
351
-	public static function isUpdateAvailable($appId,
352
-									  AppFetcher $appFetcher) {
353
-		static $isInstanceReadyForUpdates = null;
354
-
355
-		if ($isInstanceReadyForUpdates === null) {
356
-			$installPath = OC_App::getInstallPath();
357
-			if ($installPath === false || $installPath === null) {
358
-				$isInstanceReadyForUpdates = false;
359
-			} else {
360
-				$isInstanceReadyForUpdates = true;
361
-			}
362
-		}
363
-
364
-		if ($isInstanceReadyForUpdates === false) {
365
-			return false;
366
-		}
367
-
368
-		$apps = $appFetcher->get();
369
-		foreach($apps as $app) {
370
-			if($app['id'] === $appId) {
371
-				$currentVersion = OC_App::getAppVersion($appId);
372
-				$newestVersion = $app['releases'][0]['version'];
373
-				if (version_compare($newestVersion, $currentVersion, '>')) {
374
-					return $newestVersion;
375
-				} else {
376
-					return false;
377
-				}
378
-			}
379
-		}
380
-
381
-		return false;
382
-	}
383
-
384
-	/**
385
-	 * Check if app is already downloaded
386
-	 * @param string $name name of the application to remove
387
-	 * @return boolean
388
-	 *
389
-	 * The function will check if the app is already downloaded in the apps repository
390
-	 */
391
-	public function isDownloaded($name) {
392
-		foreach(\OC::$APPSROOTS as $dir) {
393
-			$dirToTest  = $dir['path'];
394
-			$dirToTest .= '/';
395
-			$dirToTest .= $name;
396
-			$dirToTest .= '/';
397
-
398
-			if (is_dir($dirToTest)) {
399
-				return true;
400
-			}
401
-		}
402
-
403
-		return false;
404
-	}
405
-
406
-	/**
407
-	 * Removes an app
408
-	 * @param string $appId ID of the application to remove
409
-	 * @return boolean
410
-	 *
411
-	 *
412
-	 * This function works as follows
413
-	 *   -# call uninstall repair steps
414
-	 *   -# removing the files
415
-	 *
416
-	 * The function will not delete preferences, tables and the configuration,
417
-	 * this has to be done by the function oc_app_uninstall().
418
-	 */
419
-	public function removeApp($appId) {
420
-		if($this->isDownloaded( $appId )) {
421
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
422
-			OC_Helper::rmdirr($appDir);
423
-			return true;
424
-		}else{
425
-			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
426
-
427
-			return false;
428
-		}
429
-
430
-	}
431
-
432
-	/**
433
-	 * Installs the app within the bundle and marks the bundle as installed
434
-	 *
435
-	 * @param Bundle $bundle
436
-	 * @throws \Exception If app could not get installed
437
-	 */
438
-	public function installAppBundle(Bundle $bundle) {
439
-		$appIds = $bundle->getAppIdentifiers();
440
-		foreach($appIds as $appId) {
441
-			if(!$this->isDownloaded($appId)) {
442
-				$this->downloadApp($appId);
443
-			}
444
-			$this->installApp($appId);
445
-			$app = new OC_App();
446
-			$app->enable($appId);
447
-		}
448
-		$bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
449
-		$bundles[] = $bundle->getIdentifier();
450
-		$this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
451
-	}
452
-
453
-	/**
454
-	 * Installs shipped apps
455
-	 *
456
-	 * This function installs all apps found in the 'apps' directory that should be enabled by default;
457
-	 * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
458
-	 *                         working ownCloud at the end instead of an aborted update.
459
-	 * @return array Array of error messages (appid => Exception)
460
-	 */
461
-	public static function installShippedApps($softErrors = false) {
462
-		$errors = [];
463
-		foreach(\OC::$APPSROOTS as $app_dir) {
464
-			if($dir = opendir( $app_dir['path'] )) {
465
-				while( false !== ( $filename = readdir( $dir ))) {
466
-					if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
467
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
468
-							if(!Installer::isInstalled($filename)) {
469
-								$info=OC_App::getAppInfo($filename);
470
-								$enabled = isset($info['default_enable']);
471
-								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
472
-									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
473
-									if ($softErrors) {
474
-										try {
475
-											Installer::installShippedApp($filename);
476
-										} catch (HintException $e) {
477
-											if ($e->getPrevious() instanceof TableExistsException) {
478
-												$errors[$filename] = $e;
479
-												continue;
480
-											}
481
-											throw $e;
482
-										}
483
-									} else {
484
-										Installer::installShippedApp($filename);
485
-									}
486
-									\OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
487
-								}
488
-							}
489
-						}
490
-					}
491
-				}
492
-				closedir( $dir );
493
-			}
494
-		}
495
-
496
-		return $errors;
497
-	}
498
-
499
-	/**
500
-	 * install an app already placed in the app folder
501
-	 * @param string $app id of the app to install
502
-	 * @return integer
503
-	 */
504
-	public static function installShippedApp($app) {
505
-		//install the database
506
-		$appPath = OC_App::getAppPath($app);
507
-		if(is_file("$appPath/appinfo/database.xml")) {
508
-			try {
509
-				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
510
-			} catch (TableExistsException $e) {
511
-				throw new HintException(
512
-					'Failed to enable app ' . $app,
513
-					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer">support channels</a>.',
514
-					0, $e
515
-				);
516
-			}
517
-		}
518
-
519
-		//run appinfo/install.php
520
-		\OC_App::registerAutoloading($app, $appPath);
521
-		self::includeAppScript("$appPath/appinfo/install.php");
522
-
523
-		$info = OC_App::getAppInfo($app);
524
-		if (is_null($info)) {
525
-			return false;
526
-		}
527
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
528
-
529
-		OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
530
-
531
-		$config = \OC::$server->getConfig();
532
-
533
-		$config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
534
-		if (array_key_exists('ocsid', $info)) {
535
-			$config->setAppValue($app, 'ocsid', $info['ocsid']);
536
-		}
537
-
538
-		//set remote/public handlers
539
-		foreach($info['remote'] as $name=>$path) {
540
-			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
541
-		}
542
-		foreach($info['public'] as $name=>$path) {
543
-			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
544
-		}
545
-
546
-		OC_App::setAppTypes($info['id']);
547
-
548
-		if(isset($info['settings']) && is_array($info['settings'])) {
549
-			// requires that autoloading was registered for the app,
550
-			// as happens before running the install.php some lines above
551
-			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
552
-		}
553
-
554
-		return $info['id'];
555
-	}
556
-
557
-	/**
558
-	 * check the code of an app with some static code checks
559
-	 * @param string $folder the folder of the app to check
560
-	 * @return boolean true for app is o.k. and false for app is not o.k.
561
-	 */
562
-	public static function checkCode($folder) {
563
-		// is the code checker enabled?
564
-		if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
565
-			return true;
566
-		}
567
-
568
-		$codeChecker = new CodeChecker(new PrivateCheck(new EmptyCheck()));
569
-		$errors = $codeChecker->analyseFolder(basename($folder), $folder);
570
-
571
-		return empty($errors);
572
-	}
573
-
574
-	/**
575
-	 * @param string $script
576
-	 */
577
-	private static function includeAppScript($script) {
578
-		if ( file_exists($script) ){
579
-			include $script;
580
-		}
581
-	}
66
+    /** @var AppFetcher */
67
+    private $appFetcher;
68
+    /** @var IClientService */
69
+    private $clientService;
70
+    /** @var ITempManager */
71
+    private $tempManager;
72
+    /** @var ILogger */
73
+    private $logger;
74
+    /** @var IConfig */
75
+    private $config;
76
+
77
+    /**
78
+     * @param AppFetcher $appFetcher
79
+     * @param IClientService $clientService
80
+     * @param ITempManager $tempManager
81
+     * @param ILogger $logger
82
+     * @param IConfig $config
83
+     */
84
+    public function __construct(AppFetcher $appFetcher,
85
+                                IClientService $clientService,
86
+                                ITempManager $tempManager,
87
+                                ILogger $logger,
88
+                                IConfig $config) {
89
+        $this->appFetcher = $appFetcher;
90
+        $this->clientService = $clientService;
91
+        $this->tempManager = $tempManager;
92
+        $this->logger = $logger;
93
+        $this->config = $config;
94
+    }
95
+
96
+    /**
97
+     * Installs an app that is located in one of the app folders already
98
+     *
99
+     * @param string $appId App to install
100
+     * @throws \Exception
101
+     * @return integer
102
+     */
103
+    public function installApp($appId) {
104
+        $app = \OC_App::findAppInDirectories($appId);
105
+        if($app === false) {
106
+            throw new \Exception('App not found in any app directory');
107
+        }
108
+
109
+        $basedir = $app['path'].'/'.$appId;
110
+        $info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
111
+
112
+        //install the database
113
+        if(is_file($basedir.'/appinfo/database.xml')) {
114
+            if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
115
+                OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
116
+            } else {
117
+                OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
118
+            }
119
+        }
120
+
121
+        \OC_App::registerAutoloading($appId, $basedir);
122
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
123
+
124
+        //run appinfo/install.php
125
+        if((!isset($data['noinstall']) or $data['noinstall']==false)) {
126
+            self::includeAppScript($basedir . '/appinfo/install.php');
127
+        }
128
+
129
+        $appData = OC_App::getAppInfo($appId);
130
+        OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
131
+
132
+        //set the installed version
133
+        \OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
134
+        \OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
135
+
136
+        //set remote/public handlers
137
+        foreach($info['remote'] as $name=>$path) {
138
+            \OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
139
+        }
140
+        foreach($info['public'] as $name=>$path) {
141
+            \OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
142
+        }
143
+
144
+        OC_App::setAppTypes($info['id']);
145
+
146
+        return $info['id'];
147
+    }
148
+
149
+    /**
150
+     * @brief checks whether or not an app is installed
151
+     * @param string $app app
152
+     * @returns bool
153
+     *
154
+     * Checks whether or not an app is installed, i.e. registered in apps table.
155
+     */
156
+    public static function isInstalled( $app ) {
157
+        return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
158
+    }
159
+
160
+    /**
161
+     * Updates the specified app from the appstore
162
+     *
163
+     * @param string $appId
164
+     * @return bool
165
+     */
166
+    public function updateAppstoreApp($appId) {
167
+        if(self::isUpdateAvailable($appId, $this->appFetcher)) {
168
+            try {
169
+                $this->downloadApp($appId);
170
+            } catch (\Exception $e) {
171
+                $this->logger->error($e->getMessage(), ['app' => 'core']);
172
+                return false;
173
+            }
174
+            return OC_App::updateApp($appId);
175
+        }
176
+
177
+        return false;
178
+    }
179
+
180
+    /**
181
+     * Downloads an app and puts it into the app directory
182
+     *
183
+     * @param string $appId
184
+     *
185
+     * @throws \Exception If the installation was not successful
186
+     */
187
+    public function downloadApp($appId) {
188
+        $appId = strtolower($appId);
189
+
190
+        $apps = $this->appFetcher->get();
191
+        foreach($apps as $app) {
192
+            if($app['id'] === $appId) {
193
+                // Load the certificate
194
+                $certificate = new X509();
195
+                $certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
196
+                $loadedCertificate = $certificate->loadX509($app['certificate']);
197
+
198
+                // Verify if the certificate has been revoked
199
+                $crl = new X509();
200
+                $crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
201
+                $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
202
+                if($crl->validateSignature() !== true) {
203
+                    throw new \Exception('Could not validate CRL signature');
204
+                }
205
+                $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
206
+                $revoked = $crl->getRevoked($csn);
207
+                if ($revoked !== false) {
208
+                    throw new \Exception(
209
+                        sprintf(
210
+                            'Certificate "%s" has been revoked',
211
+                            $csn
212
+                        )
213
+                    );
214
+                }
215
+
216
+                // Verify if the certificate has been issued by the Nextcloud Code Authority CA
217
+                if($certificate->validateSignature() !== true) {
218
+                    throw new \Exception(
219
+                        sprintf(
220
+                            'App with id %s has a certificate not issued by a trusted Code Signing Authority',
221
+                            $appId
222
+                        )
223
+                    );
224
+                }
225
+
226
+                // Verify if the certificate is issued for the requested app id
227
+                $certInfo = openssl_x509_parse($app['certificate']);
228
+                if(!isset($certInfo['subject']['CN'])) {
229
+                    throw new \Exception(
230
+                        sprintf(
231
+                            'App with id %s has a cert with no CN',
232
+                            $appId
233
+                        )
234
+                    );
235
+                }
236
+                if($certInfo['subject']['CN'] !== $appId) {
237
+                    throw new \Exception(
238
+                        sprintf(
239
+                            'App with id %s has a cert issued to %s',
240
+                            $appId,
241
+                            $certInfo['subject']['CN']
242
+                        )
243
+                    );
244
+                }
245
+
246
+                // Download the release
247
+                $tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
248
+                $client = $this->clientService->newClient();
249
+                $client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
250
+
251
+                // Check if the signature actually matches the downloaded content
252
+                $certificate = openssl_get_publickey($app['certificate']);
253
+                $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
254
+                openssl_free_key($certificate);
255
+
256
+                if($verified === true) {
257
+                    // Seems to match, let's proceed
258
+                    $extractDir = $this->tempManager->getTemporaryFolder();
259
+                    $archive = new TAR($tempFile);
260
+
261
+                    if($archive) {
262
+                        $archive->extract($extractDir);
263
+                        $allFiles = scandir($extractDir);
264
+                        $folders = array_diff($allFiles, ['.', '..']);
265
+                        $folders = array_values($folders);
266
+
267
+                        if(count($folders) > 1) {
268
+                            throw new \Exception(
269
+                                sprintf(
270
+                                    'Extracted app %s has more than 1 folder',
271
+                                    $appId
272
+                                )
273
+                            );
274
+                        }
275
+
276
+                        // Check if appinfo/info.xml has the same app ID as well
277
+                        $loadEntities = libxml_disable_entity_loader(false);
278
+                        $xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
279
+                        libxml_disable_entity_loader($loadEntities);
280
+                        if((string)$xml->id !== $appId) {
281
+                            throw new \Exception(
282
+                                sprintf(
283
+                                    'App for id %s has a wrong app ID in info.xml: %s',
284
+                                    $appId,
285
+                                    (string)$xml->id
286
+                                )
287
+                            );
288
+                        }
289
+
290
+                        // Check if the version is lower than before
291
+                        $currentVersion = OC_App::getAppVersion($appId);
292
+                        $newVersion = (string)$xml->version;
293
+                        if(version_compare($currentVersion, $newVersion) === 1) {
294
+                            throw new \Exception(
295
+                                sprintf(
296
+                                    'App for id %s has version %s and tried to update to lower version %s',
297
+                                    $appId,
298
+                                    $currentVersion,
299
+                                    $newVersion
300
+                                )
301
+                            );
302
+                        }
303
+
304
+                        $baseDir = OC_App::getInstallPath() . '/' . $appId;
305
+                        // Remove old app with the ID if existent
306
+                        OC_Helper::rmdirr($baseDir);
307
+                        // Move to app folder
308
+                        if(@mkdir($baseDir)) {
309
+                            $extractDir .= '/' . $folders[0];
310
+                            OC_Helper::copyr($extractDir, $baseDir);
311
+                        }
312
+                        OC_Helper::copyr($extractDir, $baseDir);
313
+                        OC_Helper::rmdirr($extractDir);
314
+                        return;
315
+                    } else {
316
+                        throw new \Exception(
317
+                            sprintf(
318
+                                'Could not extract app with ID %s to %s',
319
+                                $appId,
320
+                                $extractDir
321
+                            )
322
+                        );
323
+                    }
324
+                } else {
325
+                    // Signature does not match
326
+                    throw new \Exception(
327
+                        sprintf(
328
+                            'App with id %s has invalid signature',
329
+                            $appId
330
+                        )
331
+                    );
332
+                }
333
+            }
334
+        }
335
+
336
+        throw new \Exception(
337
+            sprintf(
338
+                'Could not download app %s',
339
+                $appId
340
+            )
341
+        );
342
+    }
343
+
344
+    /**
345
+     * Check if an update for the app is available
346
+     *
347
+     * @param string $appId
348
+     * @param AppFetcher $appFetcher
349
+     * @return string|false false or the version number of the update
350
+     */
351
+    public static function isUpdateAvailable($appId,
352
+                                        AppFetcher $appFetcher) {
353
+        static $isInstanceReadyForUpdates = null;
354
+
355
+        if ($isInstanceReadyForUpdates === null) {
356
+            $installPath = OC_App::getInstallPath();
357
+            if ($installPath === false || $installPath === null) {
358
+                $isInstanceReadyForUpdates = false;
359
+            } else {
360
+                $isInstanceReadyForUpdates = true;
361
+            }
362
+        }
363
+
364
+        if ($isInstanceReadyForUpdates === false) {
365
+            return false;
366
+        }
367
+
368
+        $apps = $appFetcher->get();
369
+        foreach($apps as $app) {
370
+            if($app['id'] === $appId) {
371
+                $currentVersion = OC_App::getAppVersion($appId);
372
+                $newestVersion = $app['releases'][0]['version'];
373
+                if (version_compare($newestVersion, $currentVersion, '>')) {
374
+                    return $newestVersion;
375
+                } else {
376
+                    return false;
377
+                }
378
+            }
379
+        }
380
+
381
+        return false;
382
+    }
383
+
384
+    /**
385
+     * Check if app is already downloaded
386
+     * @param string $name name of the application to remove
387
+     * @return boolean
388
+     *
389
+     * The function will check if the app is already downloaded in the apps repository
390
+     */
391
+    public function isDownloaded($name) {
392
+        foreach(\OC::$APPSROOTS as $dir) {
393
+            $dirToTest  = $dir['path'];
394
+            $dirToTest .= '/';
395
+            $dirToTest .= $name;
396
+            $dirToTest .= '/';
397
+
398
+            if (is_dir($dirToTest)) {
399
+                return true;
400
+            }
401
+        }
402
+
403
+        return false;
404
+    }
405
+
406
+    /**
407
+     * Removes an app
408
+     * @param string $appId ID of the application to remove
409
+     * @return boolean
410
+     *
411
+     *
412
+     * This function works as follows
413
+     *   -# call uninstall repair steps
414
+     *   -# removing the files
415
+     *
416
+     * The function will not delete preferences, tables and the configuration,
417
+     * this has to be done by the function oc_app_uninstall().
418
+     */
419
+    public function removeApp($appId) {
420
+        if($this->isDownloaded( $appId )) {
421
+            $appDir = OC_App::getInstallPath() . '/' . $appId;
422
+            OC_Helper::rmdirr($appDir);
423
+            return true;
424
+        }else{
425
+            \OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
426
+
427
+            return false;
428
+        }
429
+
430
+    }
431
+
432
+    /**
433
+     * Installs the app within the bundle and marks the bundle as installed
434
+     *
435
+     * @param Bundle $bundle
436
+     * @throws \Exception If app could not get installed
437
+     */
438
+    public function installAppBundle(Bundle $bundle) {
439
+        $appIds = $bundle->getAppIdentifiers();
440
+        foreach($appIds as $appId) {
441
+            if(!$this->isDownloaded($appId)) {
442
+                $this->downloadApp($appId);
443
+            }
444
+            $this->installApp($appId);
445
+            $app = new OC_App();
446
+            $app->enable($appId);
447
+        }
448
+        $bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
449
+        $bundles[] = $bundle->getIdentifier();
450
+        $this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
451
+    }
452
+
453
+    /**
454
+     * Installs shipped apps
455
+     *
456
+     * This function installs all apps found in the 'apps' directory that should be enabled by default;
457
+     * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
458
+     *                         working ownCloud at the end instead of an aborted update.
459
+     * @return array Array of error messages (appid => Exception)
460
+     */
461
+    public static function installShippedApps($softErrors = false) {
462
+        $errors = [];
463
+        foreach(\OC::$APPSROOTS as $app_dir) {
464
+            if($dir = opendir( $app_dir['path'] )) {
465
+                while( false !== ( $filename = readdir( $dir ))) {
466
+                    if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
467
+                        if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
468
+                            if(!Installer::isInstalled($filename)) {
469
+                                $info=OC_App::getAppInfo($filename);
470
+                                $enabled = isset($info['default_enable']);
471
+                                if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
472
+                                      && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
473
+                                    if ($softErrors) {
474
+                                        try {
475
+                                            Installer::installShippedApp($filename);
476
+                                        } catch (HintException $e) {
477
+                                            if ($e->getPrevious() instanceof TableExistsException) {
478
+                                                $errors[$filename] = $e;
479
+                                                continue;
480
+                                            }
481
+                                            throw $e;
482
+                                        }
483
+                                    } else {
484
+                                        Installer::installShippedApp($filename);
485
+                                    }
486
+                                    \OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
487
+                                }
488
+                            }
489
+                        }
490
+                    }
491
+                }
492
+                closedir( $dir );
493
+            }
494
+        }
495
+
496
+        return $errors;
497
+    }
498
+
499
+    /**
500
+     * install an app already placed in the app folder
501
+     * @param string $app id of the app to install
502
+     * @return integer
503
+     */
504
+    public static function installShippedApp($app) {
505
+        //install the database
506
+        $appPath = OC_App::getAppPath($app);
507
+        if(is_file("$appPath/appinfo/database.xml")) {
508
+            try {
509
+                OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
510
+            } catch (TableExistsException $e) {
511
+                throw new HintException(
512
+                    'Failed to enable app ' . $app,
513
+                    'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer">support channels</a>.',
514
+                    0, $e
515
+                );
516
+            }
517
+        }
518
+
519
+        //run appinfo/install.php
520
+        \OC_App::registerAutoloading($app, $appPath);
521
+        self::includeAppScript("$appPath/appinfo/install.php");
522
+
523
+        $info = OC_App::getAppInfo($app);
524
+        if (is_null($info)) {
525
+            return false;
526
+        }
527
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
528
+
529
+        OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
530
+
531
+        $config = \OC::$server->getConfig();
532
+
533
+        $config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
534
+        if (array_key_exists('ocsid', $info)) {
535
+            $config->setAppValue($app, 'ocsid', $info['ocsid']);
536
+        }
537
+
538
+        //set remote/public handlers
539
+        foreach($info['remote'] as $name=>$path) {
540
+            $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
541
+        }
542
+        foreach($info['public'] as $name=>$path) {
543
+            $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
544
+        }
545
+
546
+        OC_App::setAppTypes($info['id']);
547
+
548
+        if(isset($info['settings']) && is_array($info['settings'])) {
549
+            // requires that autoloading was registered for the app,
550
+            // as happens before running the install.php some lines above
551
+            \OC::$server->getSettingsManager()->setupSettings($info['settings']);
552
+        }
553
+
554
+        return $info['id'];
555
+    }
556
+
557
+    /**
558
+     * check the code of an app with some static code checks
559
+     * @param string $folder the folder of the app to check
560
+     * @return boolean true for app is o.k. and false for app is not o.k.
561
+     */
562
+    public static function checkCode($folder) {
563
+        // is the code checker enabled?
564
+        if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
565
+            return true;
566
+        }
567
+
568
+        $codeChecker = new CodeChecker(new PrivateCheck(new EmptyCheck()));
569
+        $errors = $codeChecker->analyseFolder(basename($folder), $folder);
570
+
571
+        return empty($errors);
572
+    }
573
+
574
+    /**
575
+     * @param string $script
576
+     */
577
+    private static function includeAppScript($script) {
578
+        if ( file_exists($script) ){
579
+            include $script;
580
+        }
581
+    }
582 582
 }
Please login to merge, or discard this patch.
lib/private/Repair.php 1 patch
Indentation   +172 added lines, -172 removed lines patch added patch discarded remove patch
@@ -51,176 +51,176 @@
 block discarded – undo
51 51
 use Symfony\Component\EventDispatcher\GenericEvent;
52 52
 
53 53
 class Repair implements IOutput{
54
-	/* @var IRepairStep[] */
55
-	private $repairSteps;
56
-	/** @var EventDispatcher */
57
-	private $dispatcher;
58
-	/** @var string */
59
-	private $currentStep;
60
-
61
-	/**
62
-	 * Creates a new repair step runner
63
-	 *
64
-	 * @param IRepairStep[] $repairSteps array of RepairStep instances
65
-	 * @param EventDispatcher $dispatcher
66
-	 */
67
-	public function __construct($repairSteps = [], EventDispatcher $dispatcher = null) {
68
-		$this->repairSteps = $repairSteps;
69
-		$this->dispatcher = $dispatcher;
70
-	}
71
-
72
-	/**
73
-	 * Run a series of repair steps for common problems
74
-	 */
75
-	public function run() {
76
-		if (count($this->repairSteps) === 0) {
77
-			$this->emit('\OC\Repair', 'info', array('No repair steps available'));
78
-			return;
79
-		}
80
-		// run each repair step
81
-		foreach ($this->repairSteps as $step) {
82
-			$this->currentStep = $step->getName();
83
-			$this->emit('\OC\Repair', 'step', [$this->currentStep]);
84
-			$step->run($this);
85
-		}
86
-	}
87
-
88
-	/**
89
-	 * Add repair step
90
-	 *
91
-	 * @param IRepairStep|string $repairStep repair step
92
-	 * @throws \Exception
93
-	 */
94
-	public function addStep($repairStep) {
95
-		if (is_string($repairStep)) {
96
-			try {
97
-				$s = \OC::$server->query($repairStep);
98
-			} catch (QueryException $e) {
99
-				if (class_exists($repairStep)) {
100
-					$s = new $repairStep();
101
-				} else {
102
-					throw new \Exception("Repair step '$repairStep' is unknown");
103
-				}
104
-			}
105
-
106
-			if ($s instanceof IRepairStep) {
107
-				$this->repairSteps[] = $s;
108
-			} else {
109
-				throw new \Exception("Repair step '$repairStep' is not of type \\OCP\\Migration\\IRepairStep");
110
-			}
111
-		} else {
112
-			$this->repairSteps[] = $repairStep;
113
-		}
114
-	}
115
-
116
-	/**
117
-	 * Returns the default repair steps to be run on the
118
-	 * command line or after an upgrade.
119
-	 *
120
-	 * @return IRepairStep[]
121
-	 */
122
-	public static function getRepairSteps() {
123
-		return [
124
-			new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), \OC::$server->getDatabaseConnection(), false),
125
-			new RepairMimeTypes(\OC::$server->getConfig()),
126
-			new CleanTags(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager()),
127
-			new RepairInvalidShares(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
128
-			new RemoveRootShares(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager(), \OC::$server->getLazyRootFolder()),
129
-			new MoveUpdaterStepFile(\OC::$server->getConfig()),
130
-			new MoveAvatars(
131
-				\OC::$server->getJobList(),
132
-				\OC::$server->getConfig()
133
-			),
134
-			new CleanPreviews(
135
-				\OC::$server->getJobList(),
136
-				\OC::$server->getUserManager(),
137
-				\OC::$server->getConfig()
138
-			),
139
-			new FixMountStorages(\OC::$server->getDatabaseConnection()),
140
-			new UpdateLanguageCodes(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()),
141
-			new InstallCoreBundle(
142
-				\OC::$server->query(BundleFetcher::class),
143
-				\OC::$server->getConfig(),
144
-				\OC::$server->query(Installer::class)
145
-			)
146
-		];
147
-	}
148
-
149
-	/**
150
-	 * Returns expensive repair steps to be run on the
151
-	 * command line with a special option.
152
-	 *
153
-	 * @return IRepairStep[]
154
-	 */
155
-	public static function getExpensiveRepairSteps() {
156
-		return [
157
-			new OldGroupMembershipShares(\OC::$server->getDatabaseConnection(), \OC::$server->getGroupManager()),
158
-		];
159
-	}
160
-
161
-	/**
162
-	 * Returns the repair steps to be run before an
163
-	 * upgrade.
164
-	 *
165
-	 * @return IRepairStep[]
166
-	 */
167
-	public static function getBeforeUpgradeRepairSteps() {
168
-		$connection = \OC::$server->getDatabaseConnection();
169
-		$steps = [
170
-			new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), $connection, true),
171
-			new SqliteAutoincrement($connection),
172
-		];
173
-
174
-		return $steps;
175
-	}
176
-
177
-	/**
178
-	 * @param string $scope
179
-	 * @param string $method
180
-	 * @param array $arguments
181
-	 */
182
-	public function emit($scope, $method, array $arguments = []) {
183
-		if (!is_null($this->dispatcher)) {
184
-			$this->dispatcher->dispatch("$scope::$method",
185
-				new GenericEvent("$scope::$method", $arguments));
186
-		}
187
-	}
188
-
189
-	public function info($string) {
190
-		// for now just emit as we did in the past
191
-		$this->emit('\OC\Repair', 'info', array($string));
192
-	}
193
-
194
-	/**
195
-	 * @param string $message
196
-	 */
197
-	public function warning($message) {
198
-		// for now just emit as we did in the past
199
-		$this->emit('\OC\Repair', 'warning', [$message]);
200
-	}
201
-
202
-	/**
203
-	 * @param int $max
204
-	 */
205
-	public function startProgress($max = 0) {
206
-		// for now just emit as we did in the past
207
-		$this->emit('\OC\Repair', 'startProgress', [$max, $this->currentStep]);
208
-	}
209
-
210
-	/**
211
-	 * @param int $step
212
-	 * @param string $description
213
-	 */
214
-	public function advance($step = 1, $description = '') {
215
-		// for now just emit as we did in the past
216
-		$this->emit('\OC\Repair', 'advance', [$step, $description]);
217
-	}
218
-
219
-	/**
220
-	 * @param int $max
221
-	 */
222
-	public function finishProgress() {
223
-		// for now just emit as we did in the past
224
-		$this->emit('\OC\Repair', 'finishProgress', []);
225
-	}
54
+    /* @var IRepairStep[] */
55
+    private $repairSteps;
56
+    /** @var EventDispatcher */
57
+    private $dispatcher;
58
+    /** @var string */
59
+    private $currentStep;
60
+
61
+    /**
62
+     * Creates a new repair step runner
63
+     *
64
+     * @param IRepairStep[] $repairSteps array of RepairStep instances
65
+     * @param EventDispatcher $dispatcher
66
+     */
67
+    public function __construct($repairSteps = [], EventDispatcher $dispatcher = null) {
68
+        $this->repairSteps = $repairSteps;
69
+        $this->dispatcher = $dispatcher;
70
+    }
71
+
72
+    /**
73
+     * Run a series of repair steps for common problems
74
+     */
75
+    public function run() {
76
+        if (count($this->repairSteps) === 0) {
77
+            $this->emit('\OC\Repair', 'info', array('No repair steps available'));
78
+            return;
79
+        }
80
+        // run each repair step
81
+        foreach ($this->repairSteps as $step) {
82
+            $this->currentStep = $step->getName();
83
+            $this->emit('\OC\Repair', 'step', [$this->currentStep]);
84
+            $step->run($this);
85
+        }
86
+    }
87
+
88
+    /**
89
+     * Add repair step
90
+     *
91
+     * @param IRepairStep|string $repairStep repair step
92
+     * @throws \Exception
93
+     */
94
+    public function addStep($repairStep) {
95
+        if (is_string($repairStep)) {
96
+            try {
97
+                $s = \OC::$server->query($repairStep);
98
+            } catch (QueryException $e) {
99
+                if (class_exists($repairStep)) {
100
+                    $s = new $repairStep();
101
+                } else {
102
+                    throw new \Exception("Repair step '$repairStep' is unknown");
103
+                }
104
+            }
105
+
106
+            if ($s instanceof IRepairStep) {
107
+                $this->repairSteps[] = $s;
108
+            } else {
109
+                throw new \Exception("Repair step '$repairStep' is not of type \\OCP\\Migration\\IRepairStep");
110
+            }
111
+        } else {
112
+            $this->repairSteps[] = $repairStep;
113
+        }
114
+    }
115
+
116
+    /**
117
+     * Returns the default repair steps to be run on the
118
+     * command line or after an upgrade.
119
+     *
120
+     * @return IRepairStep[]
121
+     */
122
+    public static function getRepairSteps() {
123
+        return [
124
+            new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), \OC::$server->getDatabaseConnection(), false),
125
+            new RepairMimeTypes(\OC::$server->getConfig()),
126
+            new CleanTags(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager()),
127
+            new RepairInvalidShares(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
128
+            new RemoveRootShares(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager(), \OC::$server->getLazyRootFolder()),
129
+            new MoveUpdaterStepFile(\OC::$server->getConfig()),
130
+            new MoveAvatars(
131
+                \OC::$server->getJobList(),
132
+                \OC::$server->getConfig()
133
+            ),
134
+            new CleanPreviews(
135
+                \OC::$server->getJobList(),
136
+                \OC::$server->getUserManager(),
137
+                \OC::$server->getConfig()
138
+            ),
139
+            new FixMountStorages(\OC::$server->getDatabaseConnection()),
140
+            new UpdateLanguageCodes(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()),
141
+            new InstallCoreBundle(
142
+                \OC::$server->query(BundleFetcher::class),
143
+                \OC::$server->getConfig(),
144
+                \OC::$server->query(Installer::class)
145
+            )
146
+        ];
147
+    }
148
+
149
+    /**
150
+     * Returns expensive repair steps to be run on the
151
+     * command line with a special option.
152
+     *
153
+     * @return IRepairStep[]
154
+     */
155
+    public static function getExpensiveRepairSteps() {
156
+        return [
157
+            new OldGroupMembershipShares(\OC::$server->getDatabaseConnection(), \OC::$server->getGroupManager()),
158
+        ];
159
+    }
160
+
161
+    /**
162
+     * Returns the repair steps to be run before an
163
+     * upgrade.
164
+     *
165
+     * @return IRepairStep[]
166
+     */
167
+    public static function getBeforeUpgradeRepairSteps() {
168
+        $connection = \OC::$server->getDatabaseConnection();
169
+        $steps = [
170
+            new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), $connection, true),
171
+            new SqliteAutoincrement($connection),
172
+        ];
173
+
174
+        return $steps;
175
+    }
176
+
177
+    /**
178
+     * @param string $scope
179
+     * @param string $method
180
+     * @param array $arguments
181
+     */
182
+    public function emit($scope, $method, array $arguments = []) {
183
+        if (!is_null($this->dispatcher)) {
184
+            $this->dispatcher->dispatch("$scope::$method",
185
+                new GenericEvent("$scope::$method", $arguments));
186
+        }
187
+    }
188
+
189
+    public function info($string) {
190
+        // for now just emit as we did in the past
191
+        $this->emit('\OC\Repair', 'info', array($string));
192
+    }
193
+
194
+    /**
195
+     * @param string $message
196
+     */
197
+    public function warning($message) {
198
+        // for now just emit as we did in the past
199
+        $this->emit('\OC\Repair', 'warning', [$message]);
200
+    }
201
+
202
+    /**
203
+     * @param int $max
204
+     */
205
+    public function startProgress($max = 0) {
206
+        // for now just emit as we did in the past
207
+        $this->emit('\OC\Repair', 'startProgress', [$max, $this->currentStep]);
208
+    }
209
+
210
+    /**
211
+     * @param int $step
212
+     * @param string $description
213
+     */
214
+    public function advance($step = 1, $description = '') {
215
+        // for now just emit as we did in the past
216
+        $this->emit('\OC\Repair', 'advance', [$step, $description]);
217
+    }
218
+
219
+    /**
220
+     * @param int $max
221
+     */
222
+    public function finishProgress() {
223
+        // for now just emit as we did in the past
224
+        $this->emit('\OC\Repair', 'finishProgress', []);
225
+    }
226 226
 }
Please login to merge, or discard this patch.
lib/private/App/AppStore/Bundles/BundleFetcher.php 2 patches
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -24,56 +24,56 @@
 block discarded – undo
24 24
 use OCP\IL10N;
25 25
 
26 26
 class BundleFetcher {
27
-	/** @var IL10N */
28
-	private $l10n;
27
+    /** @var IL10N */
28
+    private $l10n;
29 29
 
30
-	/**
31
-	 * @param IL10N $l10n
32
-	 */
33
-	public function __construct(IL10N $l10n) {
34
-		$this->l10n = $l10n;
35
-	}
30
+    /**
31
+     * @param IL10N $l10n
32
+     */
33
+    public function __construct(IL10N $l10n) {
34
+        $this->l10n = $l10n;
35
+    }
36 36
 
37
-	/**
38
-	 * @return Bundle[]
39
-	 */
40
-	public function getBundles() {
41
-		return [
42
-			new EnterpriseBundle($this->l10n),
43
-			new GroupwareBundle($this->l10n),
44
-		];
45
-	}
37
+    /**
38
+     * @return Bundle[]
39
+     */
40
+    public function getBundles() {
41
+        return [
42
+            new EnterpriseBundle($this->l10n),
43
+            new GroupwareBundle($this->l10n),
44
+        ];
45
+    }
46 46
 
47
-	/**
48
-	 * Bundles that should be installed by default after installation
49
-	 *
50
-	 * @return Bundle[]
51
-	 */
52
-	public function getDefaultInstallationBundle() {
53
-		return [
54
-			new CoreBundle($this->l10n),
55
-		];
56
-	}
47
+    /**
48
+     * Bundles that should be installed by default after installation
49
+     *
50
+     * @return Bundle[]
51
+     */
52
+    public function getDefaultInstallationBundle() {
53
+        return [
54
+            new CoreBundle($this->l10n),
55
+        ];
56
+    }
57 57
 
58
-	/**
59
-	 * Get the bundle with the specified identifier
60
-	 *
61
-	 * @param string $identifier
62
-	 * @return Bundle
63
-	 * @throws \BadMethodCallException If the bundle does not exist
64
-	 */
65
-	public function getBundleByIdentifier($identifier) {
66
-		/** @var Bundle[] $bundles */
67
-		$bundles = array_merge(
68
-			$this->getBundles(),
69
-			$this->getDefaultInstallationBundle()
70
-		);
71
-		foreach($bundles as $bundle) {
72
-			if($bundle->getIdentifier() === $identifier) {
73
-				return $bundle;
74
-			}
75
-		}
58
+    /**
59
+     * Get the bundle with the specified identifier
60
+     *
61
+     * @param string $identifier
62
+     * @return Bundle
63
+     * @throws \BadMethodCallException If the bundle does not exist
64
+     */
65
+    public function getBundleByIdentifier($identifier) {
66
+        /** @var Bundle[] $bundles */
67
+        $bundles = array_merge(
68
+            $this->getBundles(),
69
+            $this->getDefaultInstallationBundle()
70
+        );
71
+        foreach($bundles as $bundle) {
72
+            if($bundle->getIdentifier() === $identifier) {
73
+                return $bundle;
74
+            }
75
+        }
76 76
 
77
-		throw new \BadMethodCallException('Bundle with specified identifier does not exist');
78
-	}
77
+        throw new \BadMethodCallException('Bundle with specified identifier does not exist');
78
+    }
79 79
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -68,8 +68,8 @@
 block discarded – undo
68 68
 			$this->getBundles(),
69 69
 			$this->getDefaultInstallationBundle()
70 70
 		);
71
-		foreach($bundles as $bundle) {
72
-			if($bundle->getIdentifier() === $identifier) {
71
+		foreach ($bundles as $bundle) {
72
+			if ($bundle->getIdentifier() === $identifier) {
73 73
 				return $bundle;
74 74
 			}
75 75
 		}
Please login to merge, or discard this patch.
lib/private/Setup.php 2 patches
Indentation   +480 added lines, -480 removed lines patch added patch discarded remove patch
@@ -48,484 +48,484 @@
 block discarded – undo
48 48
 use OCP\Security\ISecureRandom;
49 49
 
50 50
 class Setup {
51
-	/** @var SystemConfig */
52
-	protected $config;
53
-	/** @var IniGetWrapper */
54
-	protected $iniWrapper;
55
-	/** @var IL10N */
56
-	protected $l10n;
57
-	/** @var Defaults */
58
-	protected $defaults;
59
-	/** @var ILogger */
60
-	protected $logger;
61
-	/** @var ISecureRandom */
62
-	protected $random;
63
-
64
-	/**
65
-	 * @param SystemConfig $config
66
-	 * @param IniGetWrapper $iniWrapper
67
-	 * @param IL10N $l10n
68
-	 * @param Defaults $defaults
69
-	 * @param ILogger $logger
70
-	 * @param ISecureRandom $random
71
-	 */
72
-	public function __construct(SystemConfig $config,
73
-						 IniGetWrapper $iniWrapper,
74
-						 IL10N $l10n,
75
-						 Defaults $defaults,
76
-						 ILogger $logger,
77
-						 ISecureRandom $random
78
-		) {
79
-		$this->config = $config;
80
-		$this->iniWrapper = $iniWrapper;
81
-		$this->l10n = $l10n;
82
-		$this->defaults = $defaults;
83
-		$this->logger = $logger;
84
-		$this->random = $random;
85
-	}
86
-
87
-	static $dbSetupClasses = [
88
-		'mysql' => \OC\Setup\MySQL::class,
89
-		'pgsql' => \OC\Setup\PostgreSQL::class,
90
-		'oci'   => \OC\Setup\OCI::class,
91
-		'sqlite' => \OC\Setup\Sqlite::class,
92
-		'sqlite3' => \OC\Setup\Sqlite::class,
93
-	];
94
-
95
-	/**
96
-	 * Wrapper around the "class_exists" PHP function to be able to mock it
97
-	 * @param string $name
98
-	 * @return bool
99
-	 */
100
-	protected function class_exists($name) {
101
-		return class_exists($name);
102
-	}
103
-
104
-	/**
105
-	 * Wrapper around the "is_callable" PHP function to be able to mock it
106
-	 * @param string $name
107
-	 * @return bool
108
-	 */
109
-	protected function is_callable($name) {
110
-		return is_callable($name);
111
-	}
112
-
113
-	/**
114
-	 * Wrapper around \PDO::getAvailableDrivers
115
-	 *
116
-	 * @return array
117
-	 */
118
-	protected function getAvailableDbDriversForPdo() {
119
-		return \PDO::getAvailableDrivers();
120
-	}
121
-
122
-	/**
123
-	 * Get the available and supported databases of this instance
124
-	 *
125
-	 * @param bool $allowAllDatabases
126
-	 * @return array
127
-	 * @throws Exception
128
-	 */
129
-	public function getSupportedDatabases($allowAllDatabases = false) {
130
-		$availableDatabases = array(
131
-			'sqlite' =>  array(
132
-				'type' => 'pdo',
133
-				'call' => 'sqlite',
134
-				'name' => 'SQLite'
135
-			),
136
-			'mysql' => array(
137
-				'type' => 'pdo',
138
-				'call' => 'mysql',
139
-				'name' => 'MySQL/MariaDB'
140
-			),
141
-			'pgsql' => array(
142
-				'type' => 'pdo',
143
-				'call' => 'pgsql',
144
-				'name' => 'PostgreSQL'
145
-			),
146
-			'oci' => array(
147
-				'type' => 'function',
148
-				'call' => 'oci_connect',
149
-				'name' => 'Oracle'
150
-			)
151
-		);
152
-		if ($allowAllDatabases) {
153
-			$configuredDatabases = array_keys($availableDatabases);
154
-		} else {
155
-			$configuredDatabases = $this->config->getValue('supportedDatabases',
156
-				array('sqlite', 'mysql', 'pgsql'));
157
-		}
158
-		if(!is_array($configuredDatabases)) {
159
-			throw new Exception('Supported databases are not properly configured.');
160
-		}
161
-
162
-		$supportedDatabases = array();
163
-
164
-		foreach($configuredDatabases as $database) {
165
-			if(array_key_exists($database, $availableDatabases)) {
166
-				$working = false;
167
-				$type = $availableDatabases[$database]['type'];
168
-				$call = $availableDatabases[$database]['call'];
169
-
170
-				if ($type === 'function') {
171
-					$working = $this->is_callable($call);
172
-				} elseif($type === 'pdo') {
173
-					$working = in_array($call, $this->getAvailableDbDriversForPdo(), TRUE);
174
-				}
175
-				if($working) {
176
-					$supportedDatabases[$database] = $availableDatabases[$database]['name'];
177
-				}
178
-			}
179
-		}
180
-
181
-		return $supportedDatabases;
182
-	}
183
-
184
-	/**
185
-	 * Gathers system information like database type and does
186
-	 * a few system checks.
187
-	 *
188
-	 * @return array of system info, including an "errors" value
189
-	 * in case of errors/warnings
190
-	 */
191
-	public function getSystemInfo($allowAllDatabases = false) {
192
-		$databases = $this->getSupportedDatabases($allowAllDatabases);
193
-
194
-		$dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT.'/data');
195
-
196
-		$errors = array();
197
-
198
-		// Create data directory to test whether the .htaccess works
199
-		// Notice that this is not necessarily the same data directory as the one
200
-		// that will effectively be used.
201
-		if(!file_exists($dataDir)) {
202
-			@mkdir($dataDir);
203
-		}
204
-		$htAccessWorking = true;
205
-		if (is_dir($dataDir) && is_writable($dataDir)) {
206
-			// Protect data directory here, so we can test if the protection is working
207
-			\OC\Setup::protectDataDirectory();
208
-
209
-			try {
210
-				$util = new \OC_Util();
211
-				$htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig());
212
-			} catch (\OC\HintException $e) {
213
-				$errors[] = array(
214
-					'error' => $e->getMessage(),
215
-					'hint' => $e->getHint()
216
-				);
217
-				$htAccessWorking = false;
218
-			}
219
-		}
220
-
221
-		if (\OC_Util::runningOnMac()) {
222
-			$errors[] = array(
223
-				'error' => $this->l10n->t(
224
-					'Mac OS X is not supported and %s will not work properly on this platform. ' .
225
-					'Use it at your own risk! ',
226
-					$this->defaults->getName()
227
-				),
228
-				'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.')
229
-			);
230
-		}
231
-
232
-		if($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
233
-			$errors[] = array(
234
-				'error' => $this->l10n->t(
235
-					'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
236
-					'This will lead to problems with files over 4 GB and is highly discouraged.',
237
-					$this->defaults->getName()
238
-				),
239
-				'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.')
240
-			);
241
-		}
242
-
243
-		return array(
244
-			'hasSQLite' => isset($databases['sqlite']),
245
-			'hasMySQL' => isset($databases['mysql']),
246
-			'hasPostgreSQL' => isset($databases['pgsql']),
247
-			'hasOracle' => isset($databases['oci']),
248
-			'databases' => $databases,
249
-			'directory' => $dataDir,
250
-			'htaccessWorking' => $htAccessWorking,
251
-			'errors' => $errors,
252
-		);
253
-	}
254
-
255
-	/**
256
-	 * @param $options
257
-	 * @return array
258
-	 */
259
-	public function install($options) {
260
-		$l = $this->l10n;
261
-
262
-		$error = array();
263
-		$dbType = $options['dbtype'];
264
-
265
-		if(empty($options['adminlogin'])) {
266
-			$error[] = $l->t('Set an admin username.');
267
-		}
268
-		if(empty($options['adminpass'])) {
269
-			$error[] = $l->t('Set an admin password.');
270
-		}
271
-		if(empty($options['directory'])) {
272
-			$options['directory'] = \OC::$SERVERROOT."/data";
273
-		}
274
-
275
-		if (!isset(self::$dbSetupClasses[$dbType])) {
276
-			$dbType = 'sqlite';
277
-		}
278
-
279
-		$username = htmlspecialchars_decode($options['adminlogin']);
280
-		$password = htmlspecialchars_decode($options['adminpass']);
281
-		$dataDir = htmlspecialchars_decode($options['directory']);
282
-
283
-		$class = self::$dbSetupClasses[$dbType];
284
-		/** @var \OC\Setup\AbstractDatabase $dbSetup */
285
-		$dbSetup = new $class($l, 'db_structure.xml', $this->config,
286
-			$this->logger, $this->random);
287
-		$error = array_merge($error, $dbSetup->validate($options));
288
-
289
-		// validate the data directory
290
-		if (
291
-			(!is_dir($dataDir) and !mkdir($dataDir)) or
292
-			!is_writable($dataDir)
293
-		) {
294
-			$error[] = $l->t("Can't create or write into the data directory %s", array($dataDir));
295
-		}
296
-
297
-		if(count($error) != 0) {
298
-			return $error;
299
-		}
300
-
301
-		$request = \OC::$server->getRequest();
302
-
303
-		//no errors, good
304
-		if(isset($options['trusted_domains'])
305
-		    && is_array($options['trusted_domains'])) {
306
-			$trustedDomains = $options['trusted_domains'];
307
-		} else {
308
-			$trustedDomains = [$request->getInsecureServerHost()];
309
-		}
310
-
311
-		//use sqlite3 when available, otherwise sqlite2 will be used.
312
-		if($dbType=='sqlite' and class_exists('SQLite3')) {
313
-			$dbType='sqlite3';
314
-		}
315
-
316
-		//generate a random salt that is used to salt the local user passwords
317
-		$salt = $this->random->generate(30);
318
-		// generate a secret
319
-		$secret = $this->random->generate(48);
320
-
321
-		//write the config file
322
-		$this->config->setValues([
323
-			'passwordsalt'		=> $salt,
324
-			'secret'			=> $secret,
325
-			'trusted_domains'	=> $trustedDomains,
326
-			'datadirectory'		=> $dataDir,
327
-			'overwrite.cli.url'	=> $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT,
328
-			'dbtype'			=> $dbType,
329
-			'version'			=> implode('.', \OCP\Util::getVersion()),
330
-		]);
331
-
332
-		try {
333
-			$dbSetup->initialize($options);
334
-			$dbSetup->setupDatabase($username);
335
-		} catch (\OC\DatabaseSetupException $e) {
336
-			$error[] = array(
337
-				'error' => $e->getMessage(),
338
-				'hint' => $e->getHint()
339
-			);
340
-			return($error);
341
-		} catch (Exception $e) {
342
-			$error[] = array(
343
-				'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
344
-				'hint' => ''
345
-			);
346
-			return($error);
347
-		}
348
-
349
-		//create the user and group
350
-		$user =  null;
351
-		try {
352
-			$user = \OC::$server->getUserManager()->createUser($username, $password);
353
-			if (!$user) {
354
-				$error[] = "User <$username> could not be created.";
355
-			}
356
-		} catch(Exception $exception) {
357
-			$error[] = $exception->getMessage();
358
-		}
359
-
360
-		if(count($error) == 0) {
361
-			$config = \OC::$server->getConfig();
362
-			$config->setAppValue('core', 'installedat', microtime(true));
363
-			$config->setAppValue('core', 'lastupdatedat', microtime(true));
364
-			$config->setAppValue('core', 'vendor', $this->getVendor());
365
-
366
-			$group =\OC::$server->getGroupManager()->createGroup('admin');
367
-			$group->addUser($user);
368
-
369
-			// Install shipped apps and specified app bundles
370
-			Installer::installShippedApps();
371
-			$installer = new Installer(
372
-				\OC::$server->getAppFetcher(),
373
-				\OC::$server->getHTTPClientService(),
374
-				\OC::$server->getTempManager(),
375
-				\OC::$server->getLogger(),
376
-				\OC::$server->getConfig()
377
-			);
378
-			$bundleFetcher = new BundleFetcher(\OC::$server->getL10N('lib'));
379
-			$defaultInstallationBundles = $bundleFetcher->getDefaultInstallationBundle();
380
-			foreach($defaultInstallationBundles as $bundle) {
381
-				try {
382
-					$installer->installAppBundle($bundle);
383
-				} catch (Exception $e) {}
384
-			}
385
-
386
-			// create empty file in data dir, so we can later find
387
-			// out that this is indeed an ownCloud data directory
388
-			file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/.ocdata', '');
389
-
390
-			// Update .htaccess files
391
-			Setup::updateHtaccess();
392
-			Setup::protectDataDirectory();
393
-
394
-			self::installBackgroundJobs();
395
-
396
-			//and we are done
397
-			$config->setSystemValue('installed', true);
398
-
399
-			// Create a session token for the newly created user
400
-			// The token provider requires a working db, so it's not injected on setup
401
-			/* @var $userSession User\Session */
402
-			$userSession = \OC::$server->getUserSession();
403
-			$defaultTokenProvider = \OC::$server->query('OC\Authentication\Token\DefaultTokenProvider');
404
-			$userSession->setTokenProvider($defaultTokenProvider);
405
-			$userSession->login($username, $password);
406
-			$userSession->createSessionToken($request, $userSession->getUser()->getUID(), $username, $password);
407
-		}
408
-
409
-		return $error;
410
-	}
411
-
412
-	public static function installBackgroundJobs() {
413
-		\OC::$server->getJobList()->add('\OC\Authentication\Token\DefaultTokenCleanupJob');
414
-	}
415
-
416
-	/**
417
-	 * @return string Absolute path to htaccess
418
-	 */
419
-	private function pathToHtaccess() {
420
-		return \OC::$SERVERROOT.'/.htaccess';
421
-	}
422
-
423
-	/**
424
-	 * Append the correct ErrorDocument path for Apache hosts
425
-	 * @return bool True when success, False otherwise
426
-	 */
427
-	public static function updateHtaccess() {
428
-		$config = \OC::$server->getSystemConfig();
429
-
430
-		// For CLI read the value from overwrite.cli.url
431
-		if(\OC::$CLI) {
432
-			$webRoot = $config->getValue('overwrite.cli.url', '');
433
-			if($webRoot === '') {
434
-				return false;
435
-			}
436
-			$webRoot = parse_url($webRoot, PHP_URL_PATH);
437
-			$webRoot = rtrim($webRoot, '/');
438
-		} else {
439
-			$webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
440
-		}
441
-
442
-		$setupHelper = new \OC\Setup($config, \OC::$server->getIniWrapper(),
443
-			\OC::$server->getL10N('lib'), \OC::$server->query(Defaults::class), \OC::$server->getLogger(),
444
-			\OC::$server->getSecureRandom());
445
-
446
-		$htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
447
-		$content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
448
-		$htaccessContent = explode($content, $htaccessContent, 2)[0];
449
-
450
-		//custom 403 error page
451
-		$content.= "\nErrorDocument 403 ".$webRoot."/core/templates/403.php";
452
-
453
-		//custom 404 error page
454
-		$content.= "\nErrorDocument 404 ".$webRoot."/core/templates/404.php";
455
-
456
-		// Add rewrite rules if the RewriteBase is configured
457
-		$rewriteBase = $config->getValue('htaccess.RewriteBase', '');
458
-		if($rewriteBase !== '') {
459
-			$content .= "\n<IfModule mod_rewrite.c>";
460
-			$content .= "\n  Options -MultiViews";
461
-			$content .= "\n  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
462
-			$content .= "\n  RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
463
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff|ico|jpg|jpeg)$";
464
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/favicon.ico$";
465
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/remote.php";
466
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/public.php";
467
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/cron.php";
468
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/core/ajax/update.php";
469
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/status.php";
470
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v1.php";
471
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v2.php";
472
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/robots.txt";
473
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/updater/";
474
-			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs-provider/";
475
-			$content .= "\n  RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge/.*";
476
-			$content .= "\n  RewriteRule . index.php [PT,E=PATH_INFO:$1]";
477
-			$content .= "\n  RewriteBase " . $rewriteBase;
478
-			$content .= "\n  <IfModule mod_env.c>";
479
-			$content .= "\n    SetEnv front_controller_active true";
480
-			$content .= "\n    <IfModule mod_dir.c>";
481
-			$content .= "\n      DirectorySlash off";
482
-			$content .= "\n    </IfModule>";
483
-			$content .= "\n  </IfModule>";
484
-			$content .= "\n</IfModule>";
485
-		}
486
-
487
-		if ($content !== '') {
488
-			//suppress errors in case we don't have permissions for it
489
-			return (bool) @file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent.$content . "\n");
490
-		}
491
-
492
-		return false;
493
-	}
494
-
495
-	public static function protectDataDirectory() {
496
-		//Require all denied
497
-		$now =  date('Y-m-d H:i:s');
498
-		$content = "# Generated by Nextcloud on $now\n";
499
-		$content.= "# line below if for Apache 2.4\n";
500
-		$content.= "<ifModule mod_authz_core.c>\n";
501
-		$content.= "Require all denied\n";
502
-		$content.= "</ifModule>\n\n";
503
-		$content.= "# line below if for Apache 2.2\n";
504
-		$content.= "<ifModule !mod_authz_core.c>\n";
505
-		$content.= "deny from all\n";
506
-		$content.= "Satisfy All\n";
507
-		$content.= "</ifModule>\n\n";
508
-		$content.= "# section for Apache 2.2 and 2.4\n";
509
-		$content.= "<ifModule mod_autoindex.c>\n";
510
-		$content.= "IndexIgnore *\n";
511
-		$content.= "</ifModule>\n";
512
-
513
-		$baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
514
-		file_put_contents($baseDir . '/.htaccess', $content);
515
-		file_put_contents($baseDir . '/index.html', '');
516
-	}
517
-
518
-	/**
519
-	 * Return vendor from which this version was published
520
-	 *
521
-	 * @return string Get the vendor
522
-	 *
523
-	 * Copy of \OC\Updater::getVendor()
524
-	 */
525
-	private function getVendor() {
526
-		// this should really be a JSON file
527
-		require \OC::$SERVERROOT . '/version.php';
528
-		/** @var string $vendor */
529
-		return (string) $vendor;
530
-	}
51
+    /** @var SystemConfig */
52
+    protected $config;
53
+    /** @var IniGetWrapper */
54
+    protected $iniWrapper;
55
+    /** @var IL10N */
56
+    protected $l10n;
57
+    /** @var Defaults */
58
+    protected $defaults;
59
+    /** @var ILogger */
60
+    protected $logger;
61
+    /** @var ISecureRandom */
62
+    protected $random;
63
+
64
+    /**
65
+     * @param SystemConfig $config
66
+     * @param IniGetWrapper $iniWrapper
67
+     * @param IL10N $l10n
68
+     * @param Defaults $defaults
69
+     * @param ILogger $logger
70
+     * @param ISecureRandom $random
71
+     */
72
+    public function __construct(SystemConfig $config,
73
+                            IniGetWrapper $iniWrapper,
74
+                            IL10N $l10n,
75
+                            Defaults $defaults,
76
+                            ILogger $logger,
77
+                            ISecureRandom $random
78
+        ) {
79
+        $this->config = $config;
80
+        $this->iniWrapper = $iniWrapper;
81
+        $this->l10n = $l10n;
82
+        $this->defaults = $defaults;
83
+        $this->logger = $logger;
84
+        $this->random = $random;
85
+    }
86
+
87
+    static $dbSetupClasses = [
88
+        'mysql' => \OC\Setup\MySQL::class,
89
+        'pgsql' => \OC\Setup\PostgreSQL::class,
90
+        'oci'   => \OC\Setup\OCI::class,
91
+        'sqlite' => \OC\Setup\Sqlite::class,
92
+        'sqlite3' => \OC\Setup\Sqlite::class,
93
+    ];
94
+
95
+    /**
96
+     * Wrapper around the "class_exists" PHP function to be able to mock it
97
+     * @param string $name
98
+     * @return bool
99
+     */
100
+    protected function class_exists($name) {
101
+        return class_exists($name);
102
+    }
103
+
104
+    /**
105
+     * Wrapper around the "is_callable" PHP function to be able to mock it
106
+     * @param string $name
107
+     * @return bool
108
+     */
109
+    protected function is_callable($name) {
110
+        return is_callable($name);
111
+    }
112
+
113
+    /**
114
+     * Wrapper around \PDO::getAvailableDrivers
115
+     *
116
+     * @return array
117
+     */
118
+    protected function getAvailableDbDriversForPdo() {
119
+        return \PDO::getAvailableDrivers();
120
+    }
121
+
122
+    /**
123
+     * Get the available and supported databases of this instance
124
+     *
125
+     * @param bool $allowAllDatabases
126
+     * @return array
127
+     * @throws Exception
128
+     */
129
+    public function getSupportedDatabases($allowAllDatabases = false) {
130
+        $availableDatabases = array(
131
+            'sqlite' =>  array(
132
+                'type' => 'pdo',
133
+                'call' => 'sqlite',
134
+                'name' => 'SQLite'
135
+            ),
136
+            'mysql' => array(
137
+                'type' => 'pdo',
138
+                'call' => 'mysql',
139
+                'name' => 'MySQL/MariaDB'
140
+            ),
141
+            'pgsql' => array(
142
+                'type' => 'pdo',
143
+                'call' => 'pgsql',
144
+                'name' => 'PostgreSQL'
145
+            ),
146
+            'oci' => array(
147
+                'type' => 'function',
148
+                'call' => 'oci_connect',
149
+                'name' => 'Oracle'
150
+            )
151
+        );
152
+        if ($allowAllDatabases) {
153
+            $configuredDatabases = array_keys($availableDatabases);
154
+        } else {
155
+            $configuredDatabases = $this->config->getValue('supportedDatabases',
156
+                array('sqlite', 'mysql', 'pgsql'));
157
+        }
158
+        if(!is_array($configuredDatabases)) {
159
+            throw new Exception('Supported databases are not properly configured.');
160
+        }
161
+
162
+        $supportedDatabases = array();
163
+
164
+        foreach($configuredDatabases as $database) {
165
+            if(array_key_exists($database, $availableDatabases)) {
166
+                $working = false;
167
+                $type = $availableDatabases[$database]['type'];
168
+                $call = $availableDatabases[$database]['call'];
169
+
170
+                if ($type === 'function') {
171
+                    $working = $this->is_callable($call);
172
+                } elseif($type === 'pdo') {
173
+                    $working = in_array($call, $this->getAvailableDbDriversForPdo(), TRUE);
174
+                }
175
+                if($working) {
176
+                    $supportedDatabases[$database] = $availableDatabases[$database]['name'];
177
+                }
178
+            }
179
+        }
180
+
181
+        return $supportedDatabases;
182
+    }
183
+
184
+    /**
185
+     * Gathers system information like database type and does
186
+     * a few system checks.
187
+     *
188
+     * @return array of system info, including an "errors" value
189
+     * in case of errors/warnings
190
+     */
191
+    public function getSystemInfo($allowAllDatabases = false) {
192
+        $databases = $this->getSupportedDatabases($allowAllDatabases);
193
+
194
+        $dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT.'/data');
195
+
196
+        $errors = array();
197
+
198
+        // Create data directory to test whether the .htaccess works
199
+        // Notice that this is not necessarily the same data directory as the one
200
+        // that will effectively be used.
201
+        if(!file_exists($dataDir)) {
202
+            @mkdir($dataDir);
203
+        }
204
+        $htAccessWorking = true;
205
+        if (is_dir($dataDir) && is_writable($dataDir)) {
206
+            // Protect data directory here, so we can test if the protection is working
207
+            \OC\Setup::protectDataDirectory();
208
+
209
+            try {
210
+                $util = new \OC_Util();
211
+                $htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig());
212
+            } catch (\OC\HintException $e) {
213
+                $errors[] = array(
214
+                    'error' => $e->getMessage(),
215
+                    'hint' => $e->getHint()
216
+                );
217
+                $htAccessWorking = false;
218
+            }
219
+        }
220
+
221
+        if (\OC_Util::runningOnMac()) {
222
+            $errors[] = array(
223
+                'error' => $this->l10n->t(
224
+                    'Mac OS X is not supported and %s will not work properly on this platform. ' .
225
+                    'Use it at your own risk! ',
226
+                    $this->defaults->getName()
227
+                ),
228
+                'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.')
229
+            );
230
+        }
231
+
232
+        if($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
233
+            $errors[] = array(
234
+                'error' => $this->l10n->t(
235
+                    'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
236
+                    'This will lead to problems with files over 4 GB and is highly discouraged.',
237
+                    $this->defaults->getName()
238
+                ),
239
+                'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.')
240
+            );
241
+        }
242
+
243
+        return array(
244
+            'hasSQLite' => isset($databases['sqlite']),
245
+            'hasMySQL' => isset($databases['mysql']),
246
+            'hasPostgreSQL' => isset($databases['pgsql']),
247
+            'hasOracle' => isset($databases['oci']),
248
+            'databases' => $databases,
249
+            'directory' => $dataDir,
250
+            'htaccessWorking' => $htAccessWorking,
251
+            'errors' => $errors,
252
+        );
253
+    }
254
+
255
+    /**
256
+     * @param $options
257
+     * @return array
258
+     */
259
+    public function install($options) {
260
+        $l = $this->l10n;
261
+
262
+        $error = array();
263
+        $dbType = $options['dbtype'];
264
+
265
+        if(empty($options['adminlogin'])) {
266
+            $error[] = $l->t('Set an admin username.');
267
+        }
268
+        if(empty($options['adminpass'])) {
269
+            $error[] = $l->t('Set an admin password.');
270
+        }
271
+        if(empty($options['directory'])) {
272
+            $options['directory'] = \OC::$SERVERROOT."/data";
273
+        }
274
+
275
+        if (!isset(self::$dbSetupClasses[$dbType])) {
276
+            $dbType = 'sqlite';
277
+        }
278
+
279
+        $username = htmlspecialchars_decode($options['adminlogin']);
280
+        $password = htmlspecialchars_decode($options['adminpass']);
281
+        $dataDir = htmlspecialchars_decode($options['directory']);
282
+
283
+        $class = self::$dbSetupClasses[$dbType];
284
+        /** @var \OC\Setup\AbstractDatabase $dbSetup */
285
+        $dbSetup = new $class($l, 'db_structure.xml', $this->config,
286
+            $this->logger, $this->random);
287
+        $error = array_merge($error, $dbSetup->validate($options));
288
+
289
+        // validate the data directory
290
+        if (
291
+            (!is_dir($dataDir) and !mkdir($dataDir)) or
292
+            !is_writable($dataDir)
293
+        ) {
294
+            $error[] = $l->t("Can't create or write into the data directory %s", array($dataDir));
295
+        }
296
+
297
+        if(count($error) != 0) {
298
+            return $error;
299
+        }
300
+
301
+        $request = \OC::$server->getRequest();
302
+
303
+        //no errors, good
304
+        if(isset($options['trusted_domains'])
305
+            && is_array($options['trusted_domains'])) {
306
+            $trustedDomains = $options['trusted_domains'];
307
+        } else {
308
+            $trustedDomains = [$request->getInsecureServerHost()];
309
+        }
310
+
311
+        //use sqlite3 when available, otherwise sqlite2 will be used.
312
+        if($dbType=='sqlite' and class_exists('SQLite3')) {
313
+            $dbType='sqlite3';
314
+        }
315
+
316
+        //generate a random salt that is used to salt the local user passwords
317
+        $salt = $this->random->generate(30);
318
+        // generate a secret
319
+        $secret = $this->random->generate(48);
320
+
321
+        //write the config file
322
+        $this->config->setValues([
323
+            'passwordsalt'		=> $salt,
324
+            'secret'			=> $secret,
325
+            'trusted_domains'	=> $trustedDomains,
326
+            'datadirectory'		=> $dataDir,
327
+            'overwrite.cli.url'	=> $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT,
328
+            'dbtype'			=> $dbType,
329
+            'version'			=> implode('.', \OCP\Util::getVersion()),
330
+        ]);
331
+
332
+        try {
333
+            $dbSetup->initialize($options);
334
+            $dbSetup->setupDatabase($username);
335
+        } catch (\OC\DatabaseSetupException $e) {
336
+            $error[] = array(
337
+                'error' => $e->getMessage(),
338
+                'hint' => $e->getHint()
339
+            );
340
+            return($error);
341
+        } catch (Exception $e) {
342
+            $error[] = array(
343
+                'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
344
+                'hint' => ''
345
+            );
346
+            return($error);
347
+        }
348
+
349
+        //create the user and group
350
+        $user =  null;
351
+        try {
352
+            $user = \OC::$server->getUserManager()->createUser($username, $password);
353
+            if (!$user) {
354
+                $error[] = "User <$username> could not be created.";
355
+            }
356
+        } catch(Exception $exception) {
357
+            $error[] = $exception->getMessage();
358
+        }
359
+
360
+        if(count($error) == 0) {
361
+            $config = \OC::$server->getConfig();
362
+            $config->setAppValue('core', 'installedat', microtime(true));
363
+            $config->setAppValue('core', 'lastupdatedat', microtime(true));
364
+            $config->setAppValue('core', 'vendor', $this->getVendor());
365
+
366
+            $group =\OC::$server->getGroupManager()->createGroup('admin');
367
+            $group->addUser($user);
368
+
369
+            // Install shipped apps and specified app bundles
370
+            Installer::installShippedApps();
371
+            $installer = new Installer(
372
+                \OC::$server->getAppFetcher(),
373
+                \OC::$server->getHTTPClientService(),
374
+                \OC::$server->getTempManager(),
375
+                \OC::$server->getLogger(),
376
+                \OC::$server->getConfig()
377
+            );
378
+            $bundleFetcher = new BundleFetcher(\OC::$server->getL10N('lib'));
379
+            $defaultInstallationBundles = $bundleFetcher->getDefaultInstallationBundle();
380
+            foreach($defaultInstallationBundles as $bundle) {
381
+                try {
382
+                    $installer->installAppBundle($bundle);
383
+                } catch (Exception $e) {}
384
+            }
385
+
386
+            // create empty file in data dir, so we can later find
387
+            // out that this is indeed an ownCloud data directory
388
+            file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/.ocdata', '');
389
+
390
+            // Update .htaccess files
391
+            Setup::updateHtaccess();
392
+            Setup::protectDataDirectory();
393
+
394
+            self::installBackgroundJobs();
395
+
396
+            //and we are done
397
+            $config->setSystemValue('installed', true);
398
+
399
+            // Create a session token for the newly created user
400
+            // The token provider requires a working db, so it's not injected on setup
401
+            /* @var $userSession User\Session */
402
+            $userSession = \OC::$server->getUserSession();
403
+            $defaultTokenProvider = \OC::$server->query('OC\Authentication\Token\DefaultTokenProvider');
404
+            $userSession->setTokenProvider($defaultTokenProvider);
405
+            $userSession->login($username, $password);
406
+            $userSession->createSessionToken($request, $userSession->getUser()->getUID(), $username, $password);
407
+        }
408
+
409
+        return $error;
410
+    }
411
+
412
+    public static function installBackgroundJobs() {
413
+        \OC::$server->getJobList()->add('\OC\Authentication\Token\DefaultTokenCleanupJob');
414
+    }
415
+
416
+    /**
417
+     * @return string Absolute path to htaccess
418
+     */
419
+    private function pathToHtaccess() {
420
+        return \OC::$SERVERROOT.'/.htaccess';
421
+    }
422
+
423
+    /**
424
+     * Append the correct ErrorDocument path for Apache hosts
425
+     * @return bool True when success, False otherwise
426
+     */
427
+    public static function updateHtaccess() {
428
+        $config = \OC::$server->getSystemConfig();
429
+
430
+        // For CLI read the value from overwrite.cli.url
431
+        if(\OC::$CLI) {
432
+            $webRoot = $config->getValue('overwrite.cli.url', '');
433
+            if($webRoot === '') {
434
+                return false;
435
+            }
436
+            $webRoot = parse_url($webRoot, PHP_URL_PATH);
437
+            $webRoot = rtrim($webRoot, '/');
438
+        } else {
439
+            $webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
440
+        }
441
+
442
+        $setupHelper = new \OC\Setup($config, \OC::$server->getIniWrapper(),
443
+            \OC::$server->getL10N('lib'), \OC::$server->query(Defaults::class), \OC::$server->getLogger(),
444
+            \OC::$server->getSecureRandom());
445
+
446
+        $htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
447
+        $content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
448
+        $htaccessContent = explode($content, $htaccessContent, 2)[0];
449
+
450
+        //custom 403 error page
451
+        $content.= "\nErrorDocument 403 ".$webRoot."/core/templates/403.php";
452
+
453
+        //custom 404 error page
454
+        $content.= "\nErrorDocument 404 ".$webRoot."/core/templates/404.php";
455
+
456
+        // Add rewrite rules if the RewriteBase is configured
457
+        $rewriteBase = $config->getValue('htaccess.RewriteBase', '');
458
+        if($rewriteBase !== '') {
459
+            $content .= "\n<IfModule mod_rewrite.c>";
460
+            $content .= "\n  Options -MultiViews";
461
+            $content .= "\n  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
462
+            $content .= "\n  RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
463
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff|ico|jpg|jpeg)$";
464
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !core/img/favicon.ico$";
465
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/remote.php";
466
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/public.php";
467
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/cron.php";
468
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/core/ajax/update.php";
469
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/status.php";
470
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v1.php";
471
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs/v2.php";
472
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/robots.txt";
473
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/updater/";
474
+            $content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs-provider/";
475
+            $content .= "\n  RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge/.*";
476
+            $content .= "\n  RewriteRule . index.php [PT,E=PATH_INFO:$1]";
477
+            $content .= "\n  RewriteBase " . $rewriteBase;
478
+            $content .= "\n  <IfModule mod_env.c>";
479
+            $content .= "\n    SetEnv front_controller_active true";
480
+            $content .= "\n    <IfModule mod_dir.c>";
481
+            $content .= "\n      DirectorySlash off";
482
+            $content .= "\n    </IfModule>";
483
+            $content .= "\n  </IfModule>";
484
+            $content .= "\n</IfModule>";
485
+        }
486
+
487
+        if ($content !== '') {
488
+            //suppress errors in case we don't have permissions for it
489
+            return (bool) @file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent.$content . "\n");
490
+        }
491
+
492
+        return false;
493
+    }
494
+
495
+    public static function protectDataDirectory() {
496
+        //Require all denied
497
+        $now =  date('Y-m-d H:i:s');
498
+        $content = "# Generated by Nextcloud on $now\n";
499
+        $content.= "# line below if for Apache 2.4\n";
500
+        $content.= "<ifModule mod_authz_core.c>\n";
501
+        $content.= "Require all denied\n";
502
+        $content.= "</ifModule>\n\n";
503
+        $content.= "# line below if for Apache 2.2\n";
504
+        $content.= "<ifModule !mod_authz_core.c>\n";
505
+        $content.= "deny from all\n";
506
+        $content.= "Satisfy All\n";
507
+        $content.= "</ifModule>\n\n";
508
+        $content.= "# section for Apache 2.2 and 2.4\n";
509
+        $content.= "<ifModule mod_autoindex.c>\n";
510
+        $content.= "IndexIgnore *\n";
511
+        $content.= "</ifModule>\n";
512
+
513
+        $baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
514
+        file_put_contents($baseDir . '/.htaccess', $content);
515
+        file_put_contents($baseDir . '/index.html', '');
516
+    }
517
+
518
+    /**
519
+     * Return vendor from which this version was published
520
+     *
521
+     * @return string Get the vendor
522
+     *
523
+     * Copy of \OC\Updater::getVendor()
524
+     */
525
+    private function getVendor() {
526
+        // this should really be a JSON file
527
+        require \OC::$SERVERROOT . '/version.php';
528
+        /** @var string $vendor */
529
+        return (string) $vendor;
530
+    }
531 531
 }
Please login to merge, or discard this patch.
Spacing   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -155,24 +155,24 @@  discard block
 block discarded – undo
155 155
 			$configuredDatabases = $this->config->getValue('supportedDatabases',
156 156
 				array('sqlite', 'mysql', 'pgsql'));
157 157
 		}
158
-		if(!is_array($configuredDatabases)) {
158
+		if (!is_array($configuredDatabases)) {
159 159
 			throw new Exception('Supported databases are not properly configured.');
160 160
 		}
161 161
 
162 162
 		$supportedDatabases = array();
163 163
 
164
-		foreach($configuredDatabases as $database) {
165
-			if(array_key_exists($database, $availableDatabases)) {
164
+		foreach ($configuredDatabases as $database) {
165
+			if (array_key_exists($database, $availableDatabases)) {
166 166
 				$working = false;
167 167
 				$type = $availableDatabases[$database]['type'];
168 168
 				$call = $availableDatabases[$database]['call'];
169 169
 
170 170
 				if ($type === 'function') {
171 171
 					$working = $this->is_callable($call);
172
-				} elseif($type === 'pdo') {
172
+				} elseif ($type === 'pdo') {
173 173
 					$working = in_array($call, $this->getAvailableDbDriversForPdo(), TRUE);
174 174
 				}
175
-				if($working) {
175
+				if ($working) {
176 176
 					$supportedDatabases[$database] = $availableDatabases[$database]['name'];
177 177
 				}
178 178
 			}
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 		// Create data directory to test whether the .htaccess works
199 199
 		// Notice that this is not necessarily the same data directory as the one
200 200
 		// that will effectively be used.
201
-		if(!file_exists($dataDir)) {
201
+		if (!file_exists($dataDir)) {
202 202
 			@mkdir($dataDir);
203 203
 		}
204 204
 		$htAccessWorking = true;
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
 		if (\OC_Util::runningOnMac()) {
222 222
 			$errors[] = array(
223 223
 				'error' => $this->l10n->t(
224
-					'Mac OS X is not supported and %s will not work properly on this platform. ' .
224
+					'Mac OS X is not supported and %s will not work properly on this platform. '.
225 225
 					'Use it at your own risk! ',
226 226
 					$this->defaults->getName()
227 227
 				),
@@ -229,10 +229,10 @@  discard block
 block discarded – undo
229 229
 			);
230 230
 		}
231 231
 
232
-		if($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
232
+		if ($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
233 233
 			$errors[] = array(
234 234
 				'error' => $this->l10n->t(
235
-					'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
235
+					'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. '.
236 236
 					'This will lead to problems with files over 4 GB and is highly discouraged.',
237 237
 					$this->defaults->getName()
238 238
 				),
@@ -262,13 +262,13 @@  discard block
 block discarded – undo
262 262
 		$error = array();
263 263
 		$dbType = $options['dbtype'];
264 264
 
265
-		if(empty($options['adminlogin'])) {
265
+		if (empty($options['adminlogin'])) {
266 266
 			$error[] = $l->t('Set an admin username.');
267 267
 		}
268
-		if(empty($options['adminpass'])) {
268
+		if (empty($options['adminpass'])) {
269 269
 			$error[] = $l->t('Set an admin password.');
270 270
 		}
271
-		if(empty($options['directory'])) {
271
+		if (empty($options['directory'])) {
272 272
 			$options['directory'] = \OC::$SERVERROOT."/data";
273 273
 		}
274 274
 
@@ -294,14 +294,14 @@  discard block
 block discarded – undo
294 294
 			$error[] = $l->t("Can't create or write into the data directory %s", array($dataDir));
295 295
 		}
296 296
 
297
-		if(count($error) != 0) {
297
+		if (count($error) != 0) {
298 298
 			return $error;
299 299
 		}
300 300
 
301 301
 		$request = \OC::$server->getRequest();
302 302
 
303 303
 		//no errors, good
304
-		if(isset($options['trusted_domains'])
304
+		if (isset($options['trusted_domains'])
305 305
 		    && is_array($options['trusted_domains'])) {
306 306
 			$trustedDomains = $options['trusted_domains'];
307 307
 		} else {
@@ -309,8 +309,8 @@  discard block
 block discarded – undo
309 309
 		}
310 310
 
311 311
 		//use sqlite3 when available, otherwise sqlite2 will be used.
312
-		if($dbType=='sqlite' and class_exists('SQLite3')) {
313
-			$dbType='sqlite3';
312
+		if ($dbType == 'sqlite' and class_exists('SQLite3')) {
313
+			$dbType = 'sqlite3';
314 314
 		}
315 315
 
316 316
 		//generate a random salt that is used to salt the local user passwords
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
 			'secret'			=> $secret,
325 325
 			'trusted_domains'	=> $trustedDomains,
326 326
 			'datadirectory'		=> $dataDir,
327
-			'overwrite.cli.url'	=> $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT,
327
+			'overwrite.cli.url'	=> $request->getServerProtocol().'://'.$request->getInsecureServerHost().\OC::$WEBROOT,
328 328
 			'dbtype'			=> $dbType,
329 329
 			'version'			=> implode('.', \OCP\Util::getVersion()),
330 330
 		]);
@@ -340,30 +340,30 @@  discard block
 block discarded – undo
340 340
 			return($error);
341 341
 		} catch (Exception $e) {
342 342
 			$error[] = array(
343
-				'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
343
+				'error' => 'Error while trying to create admin user: '.$e->getMessage(),
344 344
 				'hint' => ''
345 345
 			);
346 346
 			return($error);
347 347
 		}
348 348
 
349 349
 		//create the user and group
350
-		$user =  null;
350
+		$user = null;
351 351
 		try {
352 352
 			$user = \OC::$server->getUserManager()->createUser($username, $password);
353 353
 			if (!$user) {
354 354
 				$error[] = "User <$username> could not be created.";
355 355
 			}
356
-		} catch(Exception $exception) {
356
+		} catch (Exception $exception) {
357 357
 			$error[] = $exception->getMessage();
358 358
 		}
359 359
 
360
-		if(count($error) == 0) {
360
+		if (count($error) == 0) {
361 361
 			$config = \OC::$server->getConfig();
362 362
 			$config->setAppValue('core', 'installedat', microtime(true));
363 363
 			$config->setAppValue('core', 'lastupdatedat', microtime(true));
364 364
 			$config->setAppValue('core', 'vendor', $this->getVendor());
365 365
 
366
-			$group =\OC::$server->getGroupManager()->createGroup('admin');
366
+			$group = \OC::$server->getGroupManager()->createGroup('admin');
367 367
 			$group->addUser($user);
368 368
 
369 369
 			// Install shipped apps and specified app bundles
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
 			);
378 378
 			$bundleFetcher = new BundleFetcher(\OC::$server->getL10N('lib'));
379 379
 			$defaultInstallationBundles = $bundleFetcher->getDefaultInstallationBundle();
380
-			foreach($defaultInstallationBundles as $bundle) {
380
+			foreach ($defaultInstallationBundles as $bundle) {
381 381
 				try {
382 382
 					$installer->installAppBundle($bundle);
383 383
 				} catch (Exception $e) {}
@@ -428,9 +428,9 @@  discard block
 block discarded – undo
428 428
 		$config = \OC::$server->getSystemConfig();
429 429
 
430 430
 		// For CLI read the value from overwrite.cli.url
431
-		if(\OC::$CLI) {
431
+		if (\OC::$CLI) {
432 432
 			$webRoot = $config->getValue('overwrite.cli.url', '');
433
-			if($webRoot === '') {
433
+			if ($webRoot === '') {
434 434
 				return false;
435 435
 			}
436 436
 			$webRoot = parse_url($webRoot, PHP_URL_PATH);
@@ -448,14 +448,14 @@  discard block
 block discarded – undo
448 448
 		$htaccessContent = explode($content, $htaccessContent, 2)[0];
449 449
 
450 450
 		//custom 403 error page
451
-		$content.= "\nErrorDocument 403 ".$webRoot."/core/templates/403.php";
451
+		$content .= "\nErrorDocument 403 ".$webRoot."/core/templates/403.php";
452 452
 
453 453
 		//custom 404 error page
454
-		$content.= "\nErrorDocument 404 ".$webRoot."/core/templates/404.php";
454
+		$content .= "\nErrorDocument 404 ".$webRoot."/core/templates/404.php";
455 455
 
456 456
 		// Add rewrite rules if the RewriteBase is configured
457 457
 		$rewriteBase = $config->getValue('htaccess.RewriteBase', '');
458
-		if($rewriteBase !== '') {
458
+		if ($rewriteBase !== '') {
459 459
 			$content .= "\n<IfModule mod_rewrite.c>";
460 460
 			$content .= "\n  Options -MultiViews";
461 461
 			$content .= "\n  RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
@@ -474,7 +474,7 @@  discard block
 block discarded – undo
474 474
 			$content .= "\n  RewriteCond %{REQUEST_FILENAME} !/ocs-provider/";
475 475
 			$content .= "\n  RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge/.*";
476 476
 			$content .= "\n  RewriteRule . index.php [PT,E=PATH_INFO:$1]";
477
-			$content .= "\n  RewriteBase " . $rewriteBase;
477
+			$content .= "\n  RewriteBase ".$rewriteBase;
478 478
 			$content .= "\n  <IfModule mod_env.c>";
479 479
 			$content .= "\n    SetEnv front_controller_active true";
480 480
 			$content .= "\n    <IfModule mod_dir.c>";
@@ -486,7 +486,7 @@  discard block
 block discarded – undo
486 486
 
487 487
 		if ($content !== '') {
488 488
 			//suppress errors in case we don't have permissions for it
489
-			return (bool) @file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent.$content . "\n");
489
+			return (bool) @file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent.$content."\n");
490 490
 		}
491 491
 
492 492
 		return false;
@@ -494,25 +494,25 @@  discard block
 block discarded – undo
494 494
 
495 495
 	public static function protectDataDirectory() {
496 496
 		//Require all denied
497
-		$now =  date('Y-m-d H:i:s');
497
+		$now = date('Y-m-d H:i:s');
498 498
 		$content = "# Generated by Nextcloud on $now\n";
499
-		$content.= "# line below if for Apache 2.4\n";
500
-		$content.= "<ifModule mod_authz_core.c>\n";
501
-		$content.= "Require all denied\n";
502
-		$content.= "</ifModule>\n\n";
503
-		$content.= "# line below if for Apache 2.2\n";
504
-		$content.= "<ifModule !mod_authz_core.c>\n";
505
-		$content.= "deny from all\n";
506
-		$content.= "Satisfy All\n";
507
-		$content.= "</ifModule>\n\n";
508
-		$content.= "# section for Apache 2.2 and 2.4\n";
509
-		$content.= "<ifModule mod_autoindex.c>\n";
510
-		$content.= "IndexIgnore *\n";
511
-		$content.= "</ifModule>\n";
512
-
513
-		$baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
514
-		file_put_contents($baseDir . '/.htaccess', $content);
515
-		file_put_contents($baseDir . '/index.html', '');
499
+		$content .= "# line below if for Apache 2.4\n";
500
+		$content .= "<ifModule mod_authz_core.c>\n";
501
+		$content .= "Require all denied\n";
502
+		$content .= "</ifModule>\n\n";
503
+		$content .= "# line below if for Apache 2.2\n";
504
+		$content .= "<ifModule !mod_authz_core.c>\n";
505
+		$content .= "deny from all\n";
506
+		$content .= "Satisfy All\n";
507
+		$content .= "</ifModule>\n\n";
508
+		$content .= "# section for Apache 2.2 and 2.4\n";
509
+		$content .= "<ifModule mod_autoindex.c>\n";
510
+		$content .= "IndexIgnore *\n";
511
+		$content .= "</ifModule>\n";
512
+
513
+		$baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data');
514
+		file_put_contents($baseDir.'/.htaccess', $content);
515
+		file_put_contents($baseDir.'/index.html', '');
516 516
 	}
517 517
 
518 518
 	/**
@@ -524,7 +524,7 @@  discard block
 block discarded – undo
524 524
 	 */
525 525
 	private function getVendor() {
526 526
 		// this should really be a JSON file
527
-		require \OC::$SERVERROOT . '/version.php';
527
+		require \OC::$SERVERROOT.'/version.php';
528 528
 		/** @var string $vendor */
529 529
 		return (string) $vendor;
530 530
 	}
Please login to merge, or discard this patch.
settings/ajax/enableapp.php 2 patches
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -30,27 +30,27 @@
 block discarded – undo
30 30
 
31 31
 $lastConfirm = (int) \OC::$server->getSession()->get('last-password-confirm');
32 32
 if ($lastConfirm < (time() - 30 * 60 + 15)) { // allow 15 seconds delay
33
-	$l = \OC::$server->getL10N('core');
34
-	OC_JSON::error(array( 'data' => array( 'message' => $l->t('Password confirmation is required'))));
35
-	exit();
33
+    $l = \OC::$server->getL10N('core');
34
+    OC_JSON::error(array( 'data' => array( 'message' => $l->t('Password confirmation is required'))));
35
+    exit();
36 36
 }
37 37
 
38 38
 $groups = isset($_POST['groups']) ? (array)$_POST['groups'] : null;
39 39
 $appIds = isset($_POST['appIds']) ? (array)$_POST['appIds'] : [];
40 40
 
41 41
 try {
42
-	$updateRequired = false;
43
-	foreach($appIds as $appId) {
44
-		$app = new OC_App();
45
-		$appId = OC_App::cleanAppId($appId);
46
-		$app->enable($appId, $groups);
47
-		if(\OC_App::shouldUpgrade($appId)) {
48
-			$updateRequired = true;
49
-		}
50
-	}
42
+    $updateRequired = false;
43
+    foreach($appIds as $appId) {
44
+        $app = new OC_App();
45
+        $appId = OC_App::cleanAppId($appId);
46
+        $app->enable($appId, $groups);
47
+        if(\OC_App::shouldUpgrade($appId)) {
48
+            $updateRequired = true;
49
+        }
50
+    }
51 51
 
52
-	OC_JSON::success(['data' => ['update_required' => $updateRequired]]);
52
+    OC_JSON::success(['data' => ['update_required' => $updateRequired]]);
53 53
 } catch (Exception $e) {
54
-	\OCP\Util::writeLog('core', $e->getMessage(), \OCP\Util::ERROR);
55
-	OC_JSON::error(array("data" => array("message" => $e->getMessage()) ));
54
+    \OCP\Util::writeLog('core', $e->getMessage(), \OCP\Util::ERROR);
55
+    OC_JSON::error(array("data" => array("message" => $e->getMessage()) ));
56 56
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -31,20 +31,20 @@  discard block
 block discarded – undo
31 31
 $lastConfirm = (int) \OC::$server->getSession()->get('last-password-confirm');
32 32
 if ($lastConfirm < (time() - 30 * 60 + 15)) { // allow 15 seconds delay
33 33
 	$l = \OC::$server->getL10N('core');
34
-	OC_JSON::error(array( 'data' => array( 'message' => $l->t('Password confirmation is required'))));
34
+	OC_JSON::error(array('data' => array('message' => $l->t('Password confirmation is required'))));
35 35
 	exit();
36 36
 }
37 37
 
38
-$groups = isset($_POST['groups']) ? (array)$_POST['groups'] : null;
39
-$appIds = isset($_POST['appIds']) ? (array)$_POST['appIds'] : [];
38
+$groups = isset($_POST['groups']) ? (array) $_POST['groups'] : null;
39
+$appIds = isset($_POST['appIds']) ? (array) $_POST['appIds'] : [];
40 40
 
41 41
 try {
42 42
 	$updateRequired = false;
43
-	foreach($appIds as $appId) {
43
+	foreach ($appIds as $appId) {
44 44
 		$app = new OC_App();
45 45
 		$appId = OC_App::cleanAppId($appId);
46 46
 		$app->enable($appId, $groups);
47
-		if(\OC_App::shouldUpgrade($appId)) {
47
+		if (\OC_App::shouldUpgrade($appId)) {
48 48
 			$updateRequired = true;
49 49
 		}
50 50
 	}
@@ -52,5 +52,5 @@  discard block
 block discarded – undo
52 52
 	OC_JSON::success(['data' => ['update_required' => $updateRequired]]);
53 53
 } catch (Exception $e) {
54 54
 	\OCP\Util::writeLog('core', $e->getMessage(), \OCP\Util::ERROR);
55
-	OC_JSON::error(array("data" => array("message" => $e->getMessage()) ));
55
+	OC_JSON::error(array("data" => array("message" => $e->getMessage())));
56 56
 }
Please login to merge, or discard this patch.
settings/ajax/updateapp.php 1 patch
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -28,10 +28,10 @@  discard block
 block discarded – undo
28 28
 OCP\JSON::callCheck();
29 29
 
30 30
 if (!array_key_exists('appid', $_POST)) {
31
-	OCP\JSON::error(array(
32
-		'message' => 'No AppId given!'
33
-	));
34
-	return;
31
+    OCP\JSON::error(array(
32
+        'message' => 'No AppId given!'
33
+    ));
34
+    return;
35 35
 }
36 36
 
37 37
 $appId = (string)$_POST['appid'];
@@ -40,24 +40,24 @@  discard block
 block discarded – undo
40 40
 $config = \OC::$server->getConfig();
41 41
 $config->setSystemValue('maintenance', true);
42 42
 try {
43
-	$installer = new \OC\Installer(
44
-		\OC::$server->getAppFetcher(),
45
-		\OC::$server->getHTTPClientService(),
46
-		\OC::$server->getTempManager(),
47
-		\OC::$server->getLogger(),
48
-		\OC::$server->getConfig()
49
-	);
50
-	$result = $installer->updateAppstoreApp($appId);
51
-	$config->setSystemValue('maintenance', false);
43
+    $installer = new \OC\Installer(
44
+        \OC::$server->getAppFetcher(),
45
+        \OC::$server->getHTTPClientService(),
46
+        \OC::$server->getTempManager(),
47
+        \OC::$server->getLogger(),
48
+        \OC::$server->getConfig()
49
+    );
50
+    $result = $installer->updateAppstoreApp($appId);
51
+    $config->setSystemValue('maintenance', false);
52 52
 } catch(Exception $ex) {
53
-	$config->setSystemValue('maintenance', false);
54
-	OC_JSON::error(array("data" => array( "message" => $ex->getMessage() )));
55
-	return;
53
+    $config->setSystemValue('maintenance', false);
54
+    OC_JSON::error(array("data" => array( "message" => $ex->getMessage() )));
55
+    return;
56 56
 }
57 57
 
58 58
 if($result !== false) {
59
-	OC_JSON::success(array('data' => array('appid' => $appId)));
59
+    OC_JSON::success(array('data' => array('appid' => $appId)));
60 60
 } else {
61
-	$l = \OC::$server->getL10N('settings');
62
-	OC_JSON::error(array("data" => array( "message" => $l->t("Couldn't update app.") )));
61
+    $l = \OC::$server->getL10N('settings');
62
+    OC_JSON::error(array("data" => array( "message" => $l->t("Couldn't update app.") )));
63 63
 }
Please login to merge, or discard this patch.
lib/private/Updater.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -431,7 +431,7 @@
 block discarded – undo
431 431
 	}
432 432
 
433 433
 	/**
434
-	 * @param array $disabledApps
434
+	 * @param string[] $disabledApps
435 435
 	 * @throws \Exception
436 436
 	 */
437 437
 	private function upgradeAppStoreApps(array $disabledApps) {
Please login to merge, or discard this patch.
Indentation   +559 added lines, -559 removed lines patch added patch discarded remove patch
@@ -51,565 +51,565 @@
 block discarded – undo
51 51
  */
52 52
 class Updater extends BasicEmitter {
53 53
 
54
-	/** @var ILogger $log */
55
-	private $log;
56
-
57
-	/** @var IConfig */
58
-	private $config;
59
-
60
-	/** @var Checker */
61
-	private $checker;
62
-
63
-	/** @var bool */
64
-	private $skip3rdPartyAppsDisable;
65
-
66
-	private $logLevelNames = [
67
-		0 => 'Debug',
68
-		1 => 'Info',
69
-		2 => 'Warning',
70
-		3 => 'Error',
71
-		4 => 'Fatal',
72
-	];
73
-
74
-	/**
75
-	 * @param IConfig $config
76
-	 * @param Checker $checker
77
-	 * @param ILogger $log
78
-	 */
79
-	public function __construct(IConfig $config,
80
-								Checker $checker,
81
-								ILogger $log = null) {
82
-		$this->log = $log;
83
-		$this->config = $config;
84
-		$this->checker = $checker;
85
-
86
-		// If at least PHP 7.0.0 is used we don't need to disable apps as we catch
87
-		// fatal errors and exceptions and disable the app just instead.
88
-		if(version_compare(phpversion(), '7.0.0', '>=')) {
89
-			$this->skip3rdPartyAppsDisable = true;
90
-		}
91
-	}
92
-
93
-	/**
94
-	 * Sets whether the update disables 3rd party apps.
95
-	 * This can be set to true to skip the disable.
96
-	 *
97
-	 * @param bool $flag false to not disable, true otherwise
98
-	 */
99
-	public function setSkip3rdPartyAppsDisable($flag) {
100
-		$this->skip3rdPartyAppsDisable = $flag;
101
-	}
102
-
103
-	/**
104
-	 * runs the update actions in maintenance mode, does not upgrade the source files
105
-	 * except the main .htaccess file
106
-	 *
107
-	 * @return bool true if the operation succeeded, false otherwise
108
-	 */
109
-	public function upgrade() {
110
-		$this->emitRepairEvents();
111
-		$this->logAllEvents();
112
-
113
-		$logLevel = $this->config->getSystemValue('loglevel', Util::WARN);
114
-		$this->emit('\OC\Updater', 'setDebugLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
115
-		$this->config->setSystemValue('loglevel', Util::DEBUG);
116
-
117
-		$wasMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false);
118
-
119
-		if(!$wasMaintenanceModeEnabled) {
120
-			$this->config->setSystemValue('maintenance', true);
121
-			$this->emit('\OC\Updater', 'maintenanceEnabled');
122
-		}
123
-
124
-		$installedVersion = $this->config->getSystemValue('version', '0.0.0');
125
-		$currentVersion = implode('.', \OCP\Util::getVersion());
126
-		$this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, array('app' => 'core'));
127
-
128
-		$success = true;
129
-		try {
130
-			$this->doUpgrade($currentVersion, $installedVersion);
131
-		} catch (HintException $exception) {
132
-			$this->log->logException($exception, ['app' => 'core']);
133
-			$this->emit('\OC\Updater', 'failure', array($exception->getMessage() . ': ' .$exception->getHint()));
134
-			$success = false;
135
-		} catch (\Exception $exception) {
136
-			$this->log->logException($exception, ['app' => 'core']);
137
-			$this->emit('\OC\Updater', 'failure', array(get_class($exception) . ': ' .$exception->getMessage()));
138
-			$success = false;
139
-		}
140
-
141
-		$this->emit('\OC\Updater', 'updateEnd', array($success));
142
-
143
-		if(!$wasMaintenanceModeEnabled && $success) {
144
-			$this->config->setSystemValue('maintenance', false);
145
-			$this->emit('\OC\Updater', 'maintenanceDisabled');
146
-		} else {
147
-			$this->emit('\OC\Updater', 'maintenanceActive');
148
-		}
149
-
150
-		$this->emit('\OC\Updater', 'resetLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
151
-		$this->config->setSystemValue('loglevel', $logLevel);
152
-		$this->config->setSystemValue('installed', true);
153
-
154
-		return $success;
155
-	}
156
-
157
-	/**
158
-	 * Return version from which this version is allowed to upgrade from
159
-	 *
160
-	 * @return array allowed previous versions per vendor
161
-	 */
162
-	private function getAllowedPreviousVersions() {
163
-		// this should really be a JSON file
164
-		require \OC::$SERVERROOT . '/version.php';
165
-		/** @var array $OC_VersionCanBeUpgradedFrom */
166
-		return $OC_VersionCanBeUpgradedFrom;
167
-	}
168
-
169
-	/**
170
-	 * Return vendor from which this version was published
171
-	 *
172
-	 * @return string Get the vendor
173
-	 */
174
-	private function getVendor() {
175
-		// this should really be a JSON file
176
-		require \OC::$SERVERROOT . '/version.php';
177
-		/** @var string $vendor */
178
-		return (string) $vendor;
179
-	}
180
-
181
-	/**
182
-	 * Whether an upgrade to a specified version is possible
183
-	 * @param string $oldVersion
184
-	 * @param string $newVersion
185
-	 * @param array $allowedPreviousVersions
186
-	 * @return bool
187
-	 */
188
-	public function isUpgradePossible($oldVersion, $newVersion, array $allowedPreviousVersions) {
189
-		$version = explode('.', $oldVersion);
190
-		$majorMinor = $version[0] . '.' . $version[1];
191
-
192
-		$currentVendor = $this->config->getAppValue('core', 'vendor', '');
193
-		if ($currentVendor === 'nextcloud') {
194
-			return isset($allowedPreviousVersions[$currentVendor][$majorMinor])
195
-				&& (version_compare($oldVersion, $newVersion, '<=') ||
196
-					$this->config->getSystemValue('debug', false));
197
-		}
198
-
199
-		// Check if the instance can be migrated
200
-		return isset($allowedPreviousVersions[$currentVendor][$majorMinor]);
201
-	}
202
-
203
-	/**
204
-	 * runs the update actions in maintenance mode, does not upgrade the source files
205
-	 * except the main .htaccess file
206
-	 *
207
-	 * @param string $currentVersion current version to upgrade to
208
-	 * @param string $installedVersion previous version from which to upgrade from
209
-	 *
210
-	 * @throws \Exception
211
-	 */
212
-	private function doUpgrade($currentVersion, $installedVersion) {
213
-		// Stop update if the update is over several major versions
214
-		$allowedPreviousVersions = $this->getAllowedPreviousVersions();
215
-		if (!$this->isUpgradePossible($installedVersion, $currentVersion, $allowedPreviousVersions)) {
216
-			throw new \Exception('Updates between multiple major versions and downgrades are unsupported.');
217
-		}
218
-
219
-		// Update .htaccess files
220
-		try {
221
-			Setup::updateHtaccess();
222
-			Setup::protectDataDirectory();
223
-		} catch (\Exception $e) {
224
-			throw new \Exception($e->getMessage());
225
-		}
226
-
227
-		// create empty file in data dir, so we can later find
228
-		// out that this is indeed an ownCloud data directory
229
-		// (in case it didn't exist before)
230
-		file_put_contents($this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
231
-
232
-		// pre-upgrade repairs
233
-		$repair = new Repair(Repair::getBeforeUpgradeRepairSteps(), \OC::$server->getEventDispatcher());
234
-		$repair->run();
235
-
236
-		$this->doCoreUpgrade();
237
-
238
-		try {
239
-			// TODO: replace with the new repair step mechanism https://github.com/owncloud/core/pull/24378
240
-			Setup::installBackgroundJobs();
241
-		} catch (\Exception $e) {
242
-			throw new \Exception($e->getMessage());
243
-		}
244
-
245
-		// update all shipped apps
246
-		$this->checkAppsRequirements();
247
-		$this->doAppUpgrade();
248
-
249
-		// upgrade appstore apps
250
-		$this->upgradeAppStoreApps(\OC::$server->getAppManager()->getInstalledApps());
251
-
252
-		// install new shipped apps on upgrade
253
-		OC_App::loadApps('authentication');
254
-		$errors = Installer::installShippedApps(true);
255
-		foreach ($errors as $appId => $exception) {
256
-			/** @var \Exception $exception */
257
-			$this->log->logException($exception, ['app' => $appId]);
258
-			$this->emit('\OC\Updater', 'failure', [$appId . ': ' . $exception->getMessage()]);
259
-		}
260
-
261
-		// post-upgrade repairs
262
-		$repair = new Repair(Repair::getRepairSteps(), \OC::$server->getEventDispatcher());
263
-		$repair->run();
264
-
265
-		//Invalidate update feed
266
-		$this->config->setAppValue('core', 'lastupdatedat', 0);
267
-
268
-		// Check for code integrity if not disabled
269
-		if(\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) {
270
-			$this->emit('\OC\Updater', 'startCheckCodeIntegrity');
271
-			$this->checker->runInstanceVerification();
272
-			$this->emit('\OC\Updater', 'finishedCheckCodeIntegrity');
273
-		}
274
-
275
-		// only set the final version if everything went well
276
-		$this->config->setSystemValue('version', implode('.', Util::getVersion()));
277
-		$this->config->setAppValue('core', 'vendor', $this->getVendor());
278
-	}
279
-
280
-	protected function doCoreUpgrade() {
281
-		$this->emit('\OC\Updater', 'dbUpgradeBefore');
282
-
283
-		// do the real upgrade
284
-		\OC_DB::updateDbFromStructure(\OC::$SERVERROOT . '/db_structure.xml');
285
-
286
-		$this->emit('\OC\Updater', 'dbUpgrade');
287
-	}
288
-
289
-	/**
290
-	 * @param string $version the oc version to check app compatibility with
291
-	 */
292
-	protected function checkAppUpgrade($version) {
293
-		$apps = \OC_App::getEnabledApps();
294
-		$this->emit('\OC\Updater', 'appUpgradeCheckBefore');
295
-
296
-		foreach ($apps as $appId) {
297
-			$info = \OC_App::getAppInfo($appId);
298
-			$compatible = \OC_App::isAppCompatible($version, $info);
299
-			$isShipped = \OC_App::isShipped($appId);
300
-
301
-			if ($compatible && $isShipped && \OC_App::shouldUpgrade($appId)) {
302
-				/**
303
-				 * FIXME: The preupdate check is performed before the database migration, otherwise database changes
304
-				 * are not possible anymore within it. - Consider this when touching the code.
305
-				 * @link https://github.com/owncloud/core/issues/10980
306
-				 * @see \OC_App::updateApp
307
-				 */
308
-				if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/preupdate.php')) {
309
-					$this->includePreUpdate($appId);
310
-				}
311
-				if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/database.xml')) {
312
-					$this->emit('\OC\Updater', 'appSimulateUpdate', array($appId));
313
-					\OC_DB::simulateUpdateDbFromStructure(\OC_App::getAppPath($appId) . '/appinfo/database.xml');
314
-				}
315
-			}
316
-		}
317
-
318
-		$this->emit('\OC\Updater', 'appUpgradeCheck');
319
-	}
320
-
321
-	/**
322
-	 * Includes the pre-update file. Done here to prevent namespace mixups.
323
-	 * @param string $appId
324
-	 */
325
-	private function includePreUpdate($appId) {
326
-		include \OC_App::getAppPath($appId) . '/appinfo/preupdate.php';
327
-	}
328
-
329
-	/**
330
-	 * upgrades all apps within a major ownCloud upgrade. Also loads "priority"
331
-	 * (types authentication, filesystem, logging, in that order) afterwards.
332
-	 *
333
-	 * @throws NeedsUpdateException
334
-	 */
335
-	protected function doAppUpgrade() {
336
-		$apps = \OC_App::getEnabledApps();
337
-		$priorityTypes = array('authentication', 'filesystem', 'logging');
338
-		$pseudoOtherType = 'other';
339
-		$stacks = array($pseudoOtherType => array());
340
-
341
-		foreach ($apps as $appId) {
342
-			$priorityType = false;
343
-			foreach ($priorityTypes as $type) {
344
-				if(!isset($stacks[$type])) {
345
-					$stacks[$type] = array();
346
-				}
347
-				if (\OC_App::isType($appId, $type)) {
348
-					$stacks[$type][] = $appId;
349
-					$priorityType = true;
350
-					break;
351
-				}
352
-			}
353
-			if (!$priorityType) {
354
-				$stacks[$pseudoOtherType][] = $appId;
355
-			}
356
-		}
357
-		foreach ($stacks as $type => $stack) {
358
-			foreach ($stack as $appId) {
359
-				if (\OC_App::shouldUpgrade($appId)) {
360
-					$this->emit('\OC\Updater', 'appUpgradeStarted', [$appId, \OC_App::getAppVersion($appId)]);
361
-					\OC_App::updateApp($appId);
362
-					$this->emit('\OC\Updater', 'appUpgrade', [$appId, \OC_App::getAppVersion($appId)]);
363
-				}
364
-				if($type !== $pseudoOtherType) {
365
-					// load authentication, filesystem and logging apps after
366
-					// upgrading them. Other apps my need to rely on modifying
367
-					// user and/or filesystem aspects.
368
-					\OC_App::loadApp($appId);
369
-				}
370
-			}
371
-		}
372
-	}
373
-
374
-	/**
375
-	 * check if the current enabled apps are compatible with the current
376
-	 * ownCloud version. disable them if not.
377
-	 * This is important if you upgrade ownCloud and have non ported 3rd
378
-	 * party apps installed.
379
-	 *
380
-	 * @return array
381
-	 * @throws \Exception
382
-	 */
383
-	private function checkAppsRequirements() {
384
-		$isCoreUpgrade = $this->isCodeUpgrade();
385
-		$apps = OC_App::getEnabledApps();
386
-		$version = Util::getVersion();
387
-		$disabledApps = [];
388
-		foreach ($apps as $app) {
389
-			// check if the app is compatible with this version of ownCloud
390
-			$info = OC_App::getAppInfo($app);
391
-			if(!OC_App::isAppCompatible($version, $info)) {
392
-				if (OC_App::isShipped($app)) {
393
-					throw new \UnexpectedValueException('The files of the app "' . $app . '" were not correctly replaced before running the update');
394
-				}
395
-				OC_App::disable($app);
396
-				$this->emit('\OC\Updater', 'incompatibleAppDisabled', array($app));
397
-			}
398
-			// no need to disable any app in case this is a non-core upgrade
399
-			if (!$isCoreUpgrade) {
400
-				continue;
401
-			}
402
-			// shipped apps will remain enabled
403
-			if (OC_App::isShipped($app)) {
404
-				continue;
405
-			}
406
-			// authentication and session apps will remain enabled as well
407
-			if (OC_App::isType($app, ['session', 'authentication'])) {
408
-				continue;
409
-			}
410
-
411
-			// disable any other 3rd party apps if not overriden
412
-			if(!$this->skip3rdPartyAppsDisable) {
413
-				\OC_App::disable($app);
414
-				$disabledApps[]= $app;
415
-				$this->emit('\OC\Updater', 'thirdPartyAppDisabled', array($app));
416
-			};
417
-		}
418
-		return $disabledApps;
419
-	}
420
-
421
-	/**
422
-	 * @return bool
423
-	 */
424
-	private function isCodeUpgrade() {
425
-		$installedVersion = $this->config->getSystemValue('version', '0.0.0');
426
-		$currentVersion = implode('.', Util::getVersion());
427
-		if (version_compare($currentVersion, $installedVersion, '>')) {
428
-			return true;
429
-		}
430
-		return false;
431
-	}
432
-
433
-	/**
434
-	 * @param array $disabledApps
435
-	 * @throws \Exception
436
-	 */
437
-	private function upgradeAppStoreApps(array $disabledApps) {
438
-		foreach($disabledApps as $app) {
439
-			try {
440
-				$installer = new Installer(
441
-					\OC::$server->getAppFetcher(),
442
-					\OC::$server->getHTTPClientService(),
443
-					\OC::$server->getTempManager(),
444
-					$this->log,
445
-					\OC::$server->getConfig()
446
-				);
447
-				if (Installer::isUpdateAvailable($app, \OC::$server->getAppFetcher())) {
448
-					$this->emit('\OC\Updater', 'upgradeAppStoreApp', [$app]);
449
-					$installer->updateAppstoreApp($app);
450
-				}
451
-			} catch (\Exception $ex) {
452
-				$this->log->logException($ex, ['app' => 'core']);
453
-			}
454
-		}
455
-	}
456
-
457
-	/**
458
-	 * Forward messages emitted by the repair routine
459
-	 */
460
-	private function emitRepairEvents() {
461
-		$dispatcher = \OC::$server->getEventDispatcher();
462
-		$dispatcher->addListener('\OC\Repair::warning', function ($event) {
463
-			if ($event instanceof GenericEvent) {
464
-				$this->emit('\OC\Updater', 'repairWarning', $event->getArguments());
465
-			}
466
-		});
467
-		$dispatcher->addListener('\OC\Repair::error', function ($event) {
468
-			if ($event instanceof GenericEvent) {
469
-				$this->emit('\OC\Updater', 'repairError', $event->getArguments());
470
-			}
471
-		});
472
-		$dispatcher->addListener('\OC\Repair::info', function ($event) {
473
-			if ($event instanceof GenericEvent) {
474
-				$this->emit('\OC\Updater', 'repairInfo', $event->getArguments());
475
-			}
476
-		});
477
-		$dispatcher->addListener('\OC\Repair::step', function ($event) {
478
-			if ($event instanceof GenericEvent) {
479
-				$this->emit('\OC\Updater', 'repairStep', $event->getArguments());
480
-			}
481
-		});
482
-	}
483
-
484
-	private function logAllEvents() {
485
-		$log = $this->log;
486
-
487
-		$dispatcher = \OC::$server->getEventDispatcher();
488
-		$dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($log) {
489
-			if (!$event instanceof GenericEvent) {
490
-				return;
491
-			}
492
-			$log->info('\OC\DB\Migrator::executeSql: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
493
-		});
494
-		$dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($log) {
495
-			if (!$event instanceof GenericEvent) {
496
-				return;
497
-			}
498
-			$log->info('\OC\DB\Migrator::checkTable: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
499
-		});
500
-
501
-		$repairListener = function($event) use ($log) {
502
-			if (!$event instanceof GenericEvent) {
503
-				return;
504
-			}
505
-			switch ($event->getSubject()) {
506
-				case '\OC\Repair::startProgress':
507
-					$log->info('\OC\Repair::startProgress: Starting ... ' . $event->getArgument(1) .  ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
508
-					break;
509
-				case '\OC\Repair::advance':
510
-					$desc = $event->getArgument(1);
511
-					if (empty($desc)) {
512
-						$desc = '';
513
-					}
514
-					$log->info('\OC\Repair::advance: ' . $desc . ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
515
-
516
-					break;
517
-				case '\OC\Repair::finishProgress':
518
-					$log->info('\OC\Repair::finishProgress', ['app' => 'updater']);
519
-					break;
520
-				case '\OC\Repair::step':
521
-					$log->info('\OC\Repair::step: Repair step: ' . $event->getArgument(0), ['app' => 'updater']);
522
-					break;
523
-				case '\OC\Repair::info':
524
-					$log->info('\OC\Repair::info: Repair info: ' . $event->getArgument(0), ['app' => 'updater']);
525
-					break;
526
-				case '\OC\Repair::warning':
527
-					$log->warning('\OC\Repair::warning: Repair warning: ' . $event->getArgument(0), ['app' => 'updater']);
528
-					break;
529
-				case '\OC\Repair::error':
530
-					$log->error('\OC\Repair::error: Repair error: ' . $event->getArgument(0), ['app' => 'updater']);
531
-					break;
532
-			}
533
-		};
534
-
535
-		$dispatcher->addListener('\OC\Repair::startProgress', $repairListener);
536
-		$dispatcher->addListener('\OC\Repair::advance', $repairListener);
537
-		$dispatcher->addListener('\OC\Repair::finishProgress', $repairListener);
538
-		$dispatcher->addListener('\OC\Repair::step', $repairListener);
539
-		$dispatcher->addListener('\OC\Repair::info', $repairListener);
540
-		$dispatcher->addListener('\OC\Repair::warning', $repairListener);
541
-		$dispatcher->addListener('\OC\Repair::error', $repairListener);
542
-
543
-
544
-		$this->listen('\OC\Updater', 'maintenanceEnabled', function () use($log) {
545
-			$log->info('\OC\Updater::maintenanceEnabled: Turned on maintenance mode', ['app' => 'updater']);
546
-		});
547
-		$this->listen('\OC\Updater', 'maintenanceDisabled', function () use($log) {
548
-			$log->info('\OC\Updater::maintenanceDisabled: Turned off maintenance mode', ['app' => 'updater']);
549
-		});
550
-		$this->listen('\OC\Updater', 'maintenanceActive', function () use($log) {
551
-			$log->info('\OC\Updater::maintenanceActive: Maintenance mode is kept active', ['app' => 'updater']);
552
-		});
553
-		$this->listen('\OC\Updater', 'updateEnd', function ($success) use($log) {
554
-			if ($success) {
555
-				$log->info('\OC\Updater::updateEnd: Update successful', ['app' => 'updater']);
556
-			} else {
557
-				$log->error('\OC\Updater::updateEnd: Update failed', ['app' => 'updater']);
558
-			}
559
-		});
560
-		$this->listen('\OC\Updater', 'dbUpgradeBefore', function () use($log) {
561
-			$log->info('\OC\Updater::dbUpgradeBefore: Updating database schema', ['app' => 'updater']);
562
-		});
563
-		$this->listen('\OC\Updater', 'dbUpgrade', function () use($log) {
564
-			$log->info('\OC\Updater::dbUpgrade: Updated database', ['app' => 'updater']);
565
-		});
566
-		$this->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($log) {
567
-			$log->info('\OC\Updater::dbSimulateUpgradeBefore: Checking whether the database schema can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
568
-		});
569
-		$this->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($log) {
570
-			$log->info('\OC\Updater::dbSimulateUpgrade: Checked database schema update', ['app' => 'updater']);
571
-		});
572
-		$this->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($log) {
573
-			$log->info('\OC\Updater::incompatibleAppDisabled: Disabled incompatible app: ' . $app, ['app' => 'updater']);
574
-		});
575
-		$this->listen('\OC\Updater', 'thirdPartyAppDisabled', function ($app) use ($log) {
576
-			$log->info('\OC\Updater::thirdPartyAppDisabled: Disabled 3rd-party app: ' . $app, ['app' => 'updater']);
577
-		});
578
-		$this->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($log) {
579
-			$log->info('\OC\Updater::upgradeAppStoreApp: Update 3rd-party app: ' . $app, ['app' => 'updater']);
580
-		});
581
-		$this->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($log) {
582
-			$log->info('\OC\Updater::appUpgradeCheckBefore: Checking updates of apps', ['app' => 'updater']);
583
-		});
584
-		$this->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($log) {
585
-			$log->info('\OC\Updater::appSimulateUpdate: Checking whether the database schema for <' . $app . '> can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
586
-		});
587
-		$this->listen('\OC\Updater', 'appUpgradeCheck', function () use ($log) {
588
-			$log->info('\OC\Updater::appUpgradeCheck: Checked database schema update for apps', ['app' => 'updater']);
589
-		});
590
-		$this->listen('\OC\Updater', 'appUpgradeStarted', function ($app) use ($log) {
591
-			$log->info('\OC\Updater::appUpgradeStarted: Updating <' . $app . '> ...', ['app' => 'updater']);
592
-		});
593
-		$this->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($log) {
594
-			$log->info('\OC\Updater::appUpgrade: Updated <' . $app . '> to ' . $version, ['app' => 'updater']);
595
-		});
596
-		$this->listen('\OC\Updater', 'failure', function ($message) use($log) {
597
-			$log->error('\OC\Updater::failure: ' . $message, ['app' => 'updater']);
598
-		});
599
-		$this->listen('\OC\Updater', 'setDebugLogLevel', function () use($log) {
600
-			$log->info('\OC\Updater::setDebugLogLevel: Set log level to debug', ['app' => 'updater']);
601
-		});
602
-		$this->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($log) {
603
-			$log->info('\OC\Updater::resetLogLevel: Reset log level to ' . $logLevelName . '(' . $logLevel . ')', ['app' => 'updater']);
604
-		});
605
-		$this->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($log) {
606
-			$log->info('\OC\Updater::startCheckCodeIntegrity: Starting code integrity check...', ['app' => 'updater']);
607
-		});
608
-		$this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($log) {
609
-			$log->info('\OC\Updater::finishedCheckCodeIntegrity: Finished code integrity check', ['app' => 'updater']);
610
-		});
611
-
612
-	}
54
+    /** @var ILogger $log */
55
+    private $log;
56
+
57
+    /** @var IConfig */
58
+    private $config;
59
+
60
+    /** @var Checker */
61
+    private $checker;
62
+
63
+    /** @var bool */
64
+    private $skip3rdPartyAppsDisable;
65
+
66
+    private $logLevelNames = [
67
+        0 => 'Debug',
68
+        1 => 'Info',
69
+        2 => 'Warning',
70
+        3 => 'Error',
71
+        4 => 'Fatal',
72
+    ];
73
+
74
+    /**
75
+     * @param IConfig $config
76
+     * @param Checker $checker
77
+     * @param ILogger $log
78
+     */
79
+    public function __construct(IConfig $config,
80
+                                Checker $checker,
81
+                                ILogger $log = null) {
82
+        $this->log = $log;
83
+        $this->config = $config;
84
+        $this->checker = $checker;
85
+
86
+        // If at least PHP 7.0.0 is used we don't need to disable apps as we catch
87
+        // fatal errors and exceptions and disable the app just instead.
88
+        if(version_compare(phpversion(), '7.0.0', '>=')) {
89
+            $this->skip3rdPartyAppsDisable = true;
90
+        }
91
+    }
92
+
93
+    /**
94
+     * Sets whether the update disables 3rd party apps.
95
+     * This can be set to true to skip the disable.
96
+     *
97
+     * @param bool $flag false to not disable, true otherwise
98
+     */
99
+    public function setSkip3rdPartyAppsDisable($flag) {
100
+        $this->skip3rdPartyAppsDisable = $flag;
101
+    }
102
+
103
+    /**
104
+     * runs the update actions in maintenance mode, does not upgrade the source files
105
+     * except the main .htaccess file
106
+     *
107
+     * @return bool true if the operation succeeded, false otherwise
108
+     */
109
+    public function upgrade() {
110
+        $this->emitRepairEvents();
111
+        $this->logAllEvents();
112
+
113
+        $logLevel = $this->config->getSystemValue('loglevel', Util::WARN);
114
+        $this->emit('\OC\Updater', 'setDebugLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
115
+        $this->config->setSystemValue('loglevel', Util::DEBUG);
116
+
117
+        $wasMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false);
118
+
119
+        if(!$wasMaintenanceModeEnabled) {
120
+            $this->config->setSystemValue('maintenance', true);
121
+            $this->emit('\OC\Updater', 'maintenanceEnabled');
122
+        }
123
+
124
+        $installedVersion = $this->config->getSystemValue('version', '0.0.0');
125
+        $currentVersion = implode('.', \OCP\Util::getVersion());
126
+        $this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, array('app' => 'core'));
127
+
128
+        $success = true;
129
+        try {
130
+            $this->doUpgrade($currentVersion, $installedVersion);
131
+        } catch (HintException $exception) {
132
+            $this->log->logException($exception, ['app' => 'core']);
133
+            $this->emit('\OC\Updater', 'failure', array($exception->getMessage() . ': ' .$exception->getHint()));
134
+            $success = false;
135
+        } catch (\Exception $exception) {
136
+            $this->log->logException($exception, ['app' => 'core']);
137
+            $this->emit('\OC\Updater', 'failure', array(get_class($exception) . ': ' .$exception->getMessage()));
138
+            $success = false;
139
+        }
140
+
141
+        $this->emit('\OC\Updater', 'updateEnd', array($success));
142
+
143
+        if(!$wasMaintenanceModeEnabled && $success) {
144
+            $this->config->setSystemValue('maintenance', false);
145
+            $this->emit('\OC\Updater', 'maintenanceDisabled');
146
+        } else {
147
+            $this->emit('\OC\Updater', 'maintenanceActive');
148
+        }
149
+
150
+        $this->emit('\OC\Updater', 'resetLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
151
+        $this->config->setSystemValue('loglevel', $logLevel);
152
+        $this->config->setSystemValue('installed', true);
153
+
154
+        return $success;
155
+    }
156
+
157
+    /**
158
+     * Return version from which this version is allowed to upgrade from
159
+     *
160
+     * @return array allowed previous versions per vendor
161
+     */
162
+    private function getAllowedPreviousVersions() {
163
+        // this should really be a JSON file
164
+        require \OC::$SERVERROOT . '/version.php';
165
+        /** @var array $OC_VersionCanBeUpgradedFrom */
166
+        return $OC_VersionCanBeUpgradedFrom;
167
+    }
168
+
169
+    /**
170
+     * Return vendor from which this version was published
171
+     *
172
+     * @return string Get the vendor
173
+     */
174
+    private function getVendor() {
175
+        // this should really be a JSON file
176
+        require \OC::$SERVERROOT . '/version.php';
177
+        /** @var string $vendor */
178
+        return (string) $vendor;
179
+    }
180
+
181
+    /**
182
+     * Whether an upgrade to a specified version is possible
183
+     * @param string $oldVersion
184
+     * @param string $newVersion
185
+     * @param array $allowedPreviousVersions
186
+     * @return bool
187
+     */
188
+    public function isUpgradePossible($oldVersion, $newVersion, array $allowedPreviousVersions) {
189
+        $version = explode('.', $oldVersion);
190
+        $majorMinor = $version[0] . '.' . $version[1];
191
+
192
+        $currentVendor = $this->config->getAppValue('core', 'vendor', '');
193
+        if ($currentVendor === 'nextcloud') {
194
+            return isset($allowedPreviousVersions[$currentVendor][$majorMinor])
195
+                && (version_compare($oldVersion, $newVersion, '<=') ||
196
+                    $this->config->getSystemValue('debug', false));
197
+        }
198
+
199
+        // Check if the instance can be migrated
200
+        return isset($allowedPreviousVersions[$currentVendor][$majorMinor]);
201
+    }
202
+
203
+    /**
204
+     * runs the update actions in maintenance mode, does not upgrade the source files
205
+     * except the main .htaccess file
206
+     *
207
+     * @param string $currentVersion current version to upgrade to
208
+     * @param string $installedVersion previous version from which to upgrade from
209
+     *
210
+     * @throws \Exception
211
+     */
212
+    private function doUpgrade($currentVersion, $installedVersion) {
213
+        // Stop update if the update is over several major versions
214
+        $allowedPreviousVersions = $this->getAllowedPreviousVersions();
215
+        if (!$this->isUpgradePossible($installedVersion, $currentVersion, $allowedPreviousVersions)) {
216
+            throw new \Exception('Updates between multiple major versions and downgrades are unsupported.');
217
+        }
218
+
219
+        // Update .htaccess files
220
+        try {
221
+            Setup::updateHtaccess();
222
+            Setup::protectDataDirectory();
223
+        } catch (\Exception $e) {
224
+            throw new \Exception($e->getMessage());
225
+        }
226
+
227
+        // create empty file in data dir, so we can later find
228
+        // out that this is indeed an ownCloud data directory
229
+        // (in case it didn't exist before)
230
+        file_put_contents($this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
231
+
232
+        // pre-upgrade repairs
233
+        $repair = new Repair(Repair::getBeforeUpgradeRepairSteps(), \OC::$server->getEventDispatcher());
234
+        $repair->run();
235
+
236
+        $this->doCoreUpgrade();
237
+
238
+        try {
239
+            // TODO: replace with the new repair step mechanism https://github.com/owncloud/core/pull/24378
240
+            Setup::installBackgroundJobs();
241
+        } catch (\Exception $e) {
242
+            throw new \Exception($e->getMessage());
243
+        }
244
+
245
+        // update all shipped apps
246
+        $this->checkAppsRequirements();
247
+        $this->doAppUpgrade();
248
+
249
+        // upgrade appstore apps
250
+        $this->upgradeAppStoreApps(\OC::$server->getAppManager()->getInstalledApps());
251
+
252
+        // install new shipped apps on upgrade
253
+        OC_App::loadApps('authentication');
254
+        $errors = Installer::installShippedApps(true);
255
+        foreach ($errors as $appId => $exception) {
256
+            /** @var \Exception $exception */
257
+            $this->log->logException($exception, ['app' => $appId]);
258
+            $this->emit('\OC\Updater', 'failure', [$appId . ': ' . $exception->getMessage()]);
259
+        }
260
+
261
+        // post-upgrade repairs
262
+        $repair = new Repair(Repair::getRepairSteps(), \OC::$server->getEventDispatcher());
263
+        $repair->run();
264
+
265
+        //Invalidate update feed
266
+        $this->config->setAppValue('core', 'lastupdatedat', 0);
267
+
268
+        // Check for code integrity if not disabled
269
+        if(\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) {
270
+            $this->emit('\OC\Updater', 'startCheckCodeIntegrity');
271
+            $this->checker->runInstanceVerification();
272
+            $this->emit('\OC\Updater', 'finishedCheckCodeIntegrity');
273
+        }
274
+
275
+        // only set the final version if everything went well
276
+        $this->config->setSystemValue('version', implode('.', Util::getVersion()));
277
+        $this->config->setAppValue('core', 'vendor', $this->getVendor());
278
+    }
279
+
280
+    protected function doCoreUpgrade() {
281
+        $this->emit('\OC\Updater', 'dbUpgradeBefore');
282
+
283
+        // do the real upgrade
284
+        \OC_DB::updateDbFromStructure(\OC::$SERVERROOT . '/db_structure.xml');
285
+
286
+        $this->emit('\OC\Updater', 'dbUpgrade');
287
+    }
288
+
289
+    /**
290
+     * @param string $version the oc version to check app compatibility with
291
+     */
292
+    protected function checkAppUpgrade($version) {
293
+        $apps = \OC_App::getEnabledApps();
294
+        $this->emit('\OC\Updater', 'appUpgradeCheckBefore');
295
+
296
+        foreach ($apps as $appId) {
297
+            $info = \OC_App::getAppInfo($appId);
298
+            $compatible = \OC_App::isAppCompatible($version, $info);
299
+            $isShipped = \OC_App::isShipped($appId);
300
+
301
+            if ($compatible && $isShipped && \OC_App::shouldUpgrade($appId)) {
302
+                /**
303
+                 * FIXME: The preupdate check is performed before the database migration, otherwise database changes
304
+                 * are not possible anymore within it. - Consider this when touching the code.
305
+                 * @link https://github.com/owncloud/core/issues/10980
306
+                 * @see \OC_App::updateApp
307
+                 */
308
+                if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/preupdate.php')) {
309
+                    $this->includePreUpdate($appId);
310
+                }
311
+                if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/database.xml')) {
312
+                    $this->emit('\OC\Updater', 'appSimulateUpdate', array($appId));
313
+                    \OC_DB::simulateUpdateDbFromStructure(\OC_App::getAppPath($appId) . '/appinfo/database.xml');
314
+                }
315
+            }
316
+        }
317
+
318
+        $this->emit('\OC\Updater', 'appUpgradeCheck');
319
+    }
320
+
321
+    /**
322
+     * Includes the pre-update file. Done here to prevent namespace mixups.
323
+     * @param string $appId
324
+     */
325
+    private function includePreUpdate($appId) {
326
+        include \OC_App::getAppPath($appId) . '/appinfo/preupdate.php';
327
+    }
328
+
329
+    /**
330
+     * upgrades all apps within a major ownCloud upgrade. Also loads "priority"
331
+     * (types authentication, filesystem, logging, in that order) afterwards.
332
+     *
333
+     * @throws NeedsUpdateException
334
+     */
335
+    protected function doAppUpgrade() {
336
+        $apps = \OC_App::getEnabledApps();
337
+        $priorityTypes = array('authentication', 'filesystem', 'logging');
338
+        $pseudoOtherType = 'other';
339
+        $stacks = array($pseudoOtherType => array());
340
+
341
+        foreach ($apps as $appId) {
342
+            $priorityType = false;
343
+            foreach ($priorityTypes as $type) {
344
+                if(!isset($stacks[$type])) {
345
+                    $stacks[$type] = array();
346
+                }
347
+                if (\OC_App::isType($appId, $type)) {
348
+                    $stacks[$type][] = $appId;
349
+                    $priorityType = true;
350
+                    break;
351
+                }
352
+            }
353
+            if (!$priorityType) {
354
+                $stacks[$pseudoOtherType][] = $appId;
355
+            }
356
+        }
357
+        foreach ($stacks as $type => $stack) {
358
+            foreach ($stack as $appId) {
359
+                if (\OC_App::shouldUpgrade($appId)) {
360
+                    $this->emit('\OC\Updater', 'appUpgradeStarted', [$appId, \OC_App::getAppVersion($appId)]);
361
+                    \OC_App::updateApp($appId);
362
+                    $this->emit('\OC\Updater', 'appUpgrade', [$appId, \OC_App::getAppVersion($appId)]);
363
+                }
364
+                if($type !== $pseudoOtherType) {
365
+                    // load authentication, filesystem and logging apps after
366
+                    // upgrading them. Other apps my need to rely on modifying
367
+                    // user and/or filesystem aspects.
368
+                    \OC_App::loadApp($appId);
369
+                }
370
+            }
371
+        }
372
+    }
373
+
374
+    /**
375
+     * check if the current enabled apps are compatible with the current
376
+     * ownCloud version. disable them if not.
377
+     * This is important if you upgrade ownCloud and have non ported 3rd
378
+     * party apps installed.
379
+     *
380
+     * @return array
381
+     * @throws \Exception
382
+     */
383
+    private function checkAppsRequirements() {
384
+        $isCoreUpgrade = $this->isCodeUpgrade();
385
+        $apps = OC_App::getEnabledApps();
386
+        $version = Util::getVersion();
387
+        $disabledApps = [];
388
+        foreach ($apps as $app) {
389
+            // check if the app is compatible with this version of ownCloud
390
+            $info = OC_App::getAppInfo($app);
391
+            if(!OC_App::isAppCompatible($version, $info)) {
392
+                if (OC_App::isShipped($app)) {
393
+                    throw new \UnexpectedValueException('The files of the app "' . $app . '" were not correctly replaced before running the update');
394
+                }
395
+                OC_App::disable($app);
396
+                $this->emit('\OC\Updater', 'incompatibleAppDisabled', array($app));
397
+            }
398
+            // no need to disable any app in case this is a non-core upgrade
399
+            if (!$isCoreUpgrade) {
400
+                continue;
401
+            }
402
+            // shipped apps will remain enabled
403
+            if (OC_App::isShipped($app)) {
404
+                continue;
405
+            }
406
+            // authentication and session apps will remain enabled as well
407
+            if (OC_App::isType($app, ['session', 'authentication'])) {
408
+                continue;
409
+            }
410
+
411
+            // disable any other 3rd party apps if not overriden
412
+            if(!$this->skip3rdPartyAppsDisable) {
413
+                \OC_App::disable($app);
414
+                $disabledApps[]= $app;
415
+                $this->emit('\OC\Updater', 'thirdPartyAppDisabled', array($app));
416
+            };
417
+        }
418
+        return $disabledApps;
419
+    }
420
+
421
+    /**
422
+     * @return bool
423
+     */
424
+    private function isCodeUpgrade() {
425
+        $installedVersion = $this->config->getSystemValue('version', '0.0.0');
426
+        $currentVersion = implode('.', Util::getVersion());
427
+        if (version_compare($currentVersion, $installedVersion, '>')) {
428
+            return true;
429
+        }
430
+        return false;
431
+    }
432
+
433
+    /**
434
+     * @param array $disabledApps
435
+     * @throws \Exception
436
+     */
437
+    private function upgradeAppStoreApps(array $disabledApps) {
438
+        foreach($disabledApps as $app) {
439
+            try {
440
+                $installer = new Installer(
441
+                    \OC::$server->getAppFetcher(),
442
+                    \OC::$server->getHTTPClientService(),
443
+                    \OC::$server->getTempManager(),
444
+                    $this->log,
445
+                    \OC::$server->getConfig()
446
+                );
447
+                if (Installer::isUpdateAvailable($app, \OC::$server->getAppFetcher())) {
448
+                    $this->emit('\OC\Updater', 'upgradeAppStoreApp', [$app]);
449
+                    $installer->updateAppstoreApp($app);
450
+                }
451
+            } catch (\Exception $ex) {
452
+                $this->log->logException($ex, ['app' => 'core']);
453
+            }
454
+        }
455
+    }
456
+
457
+    /**
458
+     * Forward messages emitted by the repair routine
459
+     */
460
+    private function emitRepairEvents() {
461
+        $dispatcher = \OC::$server->getEventDispatcher();
462
+        $dispatcher->addListener('\OC\Repair::warning', function ($event) {
463
+            if ($event instanceof GenericEvent) {
464
+                $this->emit('\OC\Updater', 'repairWarning', $event->getArguments());
465
+            }
466
+        });
467
+        $dispatcher->addListener('\OC\Repair::error', function ($event) {
468
+            if ($event instanceof GenericEvent) {
469
+                $this->emit('\OC\Updater', 'repairError', $event->getArguments());
470
+            }
471
+        });
472
+        $dispatcher->addListener('\OC\Repair::info', function ($event) {
473
+            if ($event instanceof GenericEvent) {
474
+                $this->emit('\OC\Updater', 'repairInfo', $event->getArguments());
475
+            }
476
+        });
477
+        $dispatcher->addListener('\OC\Repair::step', function ($event) {
478
+            if ($event instanceof GenericEvent) {
479
+                $this->emit('\OC\Updater', 'repairStep', $event->getArguments());
480
+            }
481
+        });
482
+    }
483
+
484
+    private function logAllEvents() {
485
+        $log = $this->log;
486
+
487
+        $dispatcher = \OC::$server->getEventDispatcher();
488
+        $dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($log) {
489
+            if (!$event instanceof GenericEvent) {
490
+                return;
491
+            }
492
+            $log->info('\OC\DB\Migrator::executeSql: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
493
+        });
494
+        $dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($log) {
495
+            if (!$event instanceof GenericEvent) {
496
+                return;
497
+            }
498
+            $log->info('\OC\DB\Migrator::checkTable: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
499
+        });
500
+
501
+        $repairListener = function($event) use ($log) {
502
+            if (!$event instanceof GenericEvent) {
503
+                return;
504
+            }
505
+            switch ($event->getSubject()) {
506
+                case '\OC\Repair::startProgress':
507
+                    $log->info('\OC\Repair::startProgress: Starting ... ' . $event->getArgument(1) .  ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
508
+                    break;
509
+                case '\OC\Repair::advance':
510
+                    $desc = $event->getArgument(1);
511
+                    if (empty($desc)) {
512
+                        $desc = '';
513
+                    }
514
+                    $log->info('\OC\Repair::advance: ' . $desc . ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
515
+
516
+                    break;
517
+                case '\OC\Repair::finishProgress':
518
+                    $log->info('\OC\Repair::finishProgress', ['app' => 'updater']);
519
+                    break;
520
+                case '\OC\Repair::step':
521
+                    $log->info('\OC\Repair::step: Repair step: ' . $event->getArgument(0), ['app' => 'updater']);
522
+                    break;
523
+                case '\OC\Repair::info':
524
+                    $log->info('\OC\Repair::info: Repair info: ' . $event->getArgument(0), ['app' => 'updater']);
525
+                    break;
526
+                case '\OC\Repair::warning':
527
+                    $log->warning('\OC\Repair::warning: Repair warning: ' . $event->getArgument(0), ['app' => 'updater']);
528
+                    break;
529
+                case '\OC\Repair::error':
530
+                    $log->error('\OC\Repair::error: Repair error: ' . $event->getArgument(0), ['app' => 'updater']);
531
+                    break;
532
+            }
533
+        };
534
+
535
+        $dispatcher->addListener('\OC\Repair::startProgress', $repairListener);
536
+        $dispatcher->addListener('\OC\Repair::advance', $repairListener);
537
+        $dispatcher->addListener('\OC\Repair::finishProgress', $repairListener);
538
+        $dispatcher->addListener('\OC\Repair::step', $repairListener);
539
+        $dispatcher->addListener('\OC\Repair::info', $repairListener);
540
+        $dispatcher->addListener('\OC\Repair::warning', $repairListener);
541
+        $dispatcher->addListener('\OC\Repair::error', $repairListener);
542
+
543
+
544
+        $this->listen('\OC\Updater', 'maintenanceEnabled', function () use($log) {
545
+            $log->info('\OC\Updater::maintenanceEnabled: Turned on maintenance mode', ['app' => 'updater']);
546
+        });
547
+        $this->listen('\OC\Updater', 'maintenanceDisabled', function () use($log) {
548
+            $log->info('\OC\Updater::maintenanceDisabled: Turned off maintenance mode', ['app' => 'updater']);
549
+        });
550
+        $this->listen('\OC\Updater', 'maintenanceActive', function () use($log) {
551
+            $log->info('\OC\Updater::maintenanceActive: Maintenance mode is kept active', ['app' => 'updater']);
552
+        });
553
+        $this->listen('\OC\Updater', 'updateEnd', function ($success) use($log) {
554
+            if ($success) {
555
+                $log->info('\OC\Updater::updateEnd: Update successful', ['app' => 'updater']);
556
+            } else {
557
+                $log->error('\OC\Updater::updateEnd: Update failed', ['app' => 'updater']);
558
+            }
559
+        });
560
+        $this->listen('\OC\Updater', 'dbUpgradeBefore', function () use($log) {
561
+            $log->info('\OC\Updater::dbUpgradeBefore: Updating database schema', ['app' => 'updater']);
562
+        });
563
+        $this->listen('\OC\Updater', 'dbUpgrade', function () use($log) {
564
+            $log->info('\OC\Updater::dbUpgrade: Updated database', ['app' => 'updater']);
565
+        });
566
+        $this->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($log) {
567
+            $log->info('\OC\Updater::dbSimulateUpgradeBefore: Checking whether the database schema can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
568
+        });
569
+        $this->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($log) {
570
+            $log->info('\OC\Updater::dbSimulateUpgrade: Checked database schema update', ['app' => 'updater']);
571
+        });
572
+        $this->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($log) {
573
+            $log->info('\OC\Updater::incompatibleAppDisabled: Disabled incompatible app: ' . $app, ['app' => 'updater']);
574
+        });
575
+        $this->listen('\OC\Updater', 'thirdPartyAppDisabled', function ($app) use ($log) {
576
+            $log->info('\OC\Updater::thirdPartyAppDisabled: Disabled 3rd-party app: ' . $app, ['app' => 'updater']);
577
+        });
578
+        $this->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($log) {
579
+            $log->info('\OC\Updater::upgradeAppStoreApp: Update 3rd-party app: ' . $app, ['app' => 'updater']);
580
+        });
581
+        $this->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($log) {
582
+            $log->info('\OC\Updater::appUpgradeCheckBefore: Checking updates of apps', ['app' => 'updater']);
583
+        });
584
+        $this->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($log) {
585
+            $log->info('\OC\Updater::appSimulateUpdate: Checking whether the database schema for <' . $app . '> can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
586
+        });
587
+        $this->listen('\OC\Updater', 'appUpgradeCheck', function () use ($log) {
588
+            $log->info('\OC\Updater::appUpgradeCheck: Checked database schema update for apps', ['app' => 'updater']);
589
+        });
590
+        $this->listen('\OC\Updater', 'appUpgradeStarted', function ($app) use ($log) {
591
+            $log->info('\OC\Updater::appUpgradeStarted: Updating <' . $app . '> ...', ['app' => 'updater']);
592
+        });
593
+        $this->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($log) {
594
+            $log->info('\OC\Updater::appUpgrade: Updated <' . $app . '> to ' . $version, ['app' => 'updater']);
595
+        });
596
+        $this->listen('\OC\Updater', 'failure', function ($message) use($log) {
597
+            $log->error('\OC\Updater::failure: ' . $message, ['app' => 'updater']);
598
+        });
599
+        $this->listen('\OC\Updater', 'setDebugLogLevel', function () use($log) {
600
+            $log->info('\OC\Updater::setDebugLogLevel: Set log level to debug', ['app' => 'updater']);
601
+        });
602
+        $this->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($log) {
603
+            $log->info('\OC\Updater::resetLogLevel: Reset log level to ' . $logLevelName . '(' . $logLevel . ')', ['app' => 'updater']);
604
+        });
605
+        $this->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($log) {
606
+            $log->info('\OC\Updater::startCheckCodeIntegrity: Starting code integrity check...', ['app' => 'updater']);
607
+        });
608
+        $this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($log) {
609
+            $log->info('\OC\Updater::finishedCheckCodeIntegrity: Finished code integrity check', ['app' => 'updater']);
610
+        });
611
+
612
+    }
613 613
 
614 614
 }
615 615
 
Please login to merge, or discard this patch.
lib/private/legacy/app.php 1 patch
Indentation   +1210 added lines, -1210 removed lines patch added patch discarded remove patch
@@ -60,1214 +60,1214 @@
 block discarded – undo
60 60
  * upgrading and removing apps.
61 61
  */
62 62
 class OC_App {
63
-	static private $appVersion = [];
64
-	static private $adminForms = array();
65
-	static private $personalForms = array();
66
-	static private $appInfo = array();
67
-	static private $appTypes = array();
68
-	static private $loadedApps = array();
69
-	static private $altLogin = array();
70
-	static private $alreadyRegistered = [];
71
-	const officialApp = 200;
72
-
73
-	/**
74
-	 * clean the appId
75
-	 *
76
-	 * @param string|boolean $app AppId that needs to be cleaned
77
-	 * @return string
78
-	 */
79
-	public static function cleanAppId($app) {
80
-		return str_replace(array('\0', '/', '\\', '..'), '', $app);
81
-	}
82
-
83
-	/**
84
-	 * Check if an app is loaded
85
-	 *
86
-	 * @param string $app
87
-	 * @return bool
88
-	 */
89
-	public static function isAppLoaded($app) {
90
-		return in_array($app, self::$loadedApps, true);
91
-	}
92
-
93
-	/**
94
-	 * loads all apps
95
-	 *
96
-	 * @param string[] | string | null $types
97
-	 * @return bool
98
-	 *
99
-	 * This function walks through the ownCloud directory and loads all apps
100
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
101
-	 * exists.
102
-	 *
103
-	 * if $types is set, only apps of those types will be loaded
104
-	 */
105
-	public static function loadApps($types = null) {
106
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
107
-			return false;
108
-		}
109
-		// Load the enabled apps here
110
-		$apps = self::getEnabledApps();
111
-
112
-		// Add each apps' folder as allowed class path
113
-		foreach($apps as $app) {
114
-			$path = self::getAppPath($app);
115
-			if($path !== false) {
116
-				self::registerAutoloading($app, $path);
117
-			}
118
-		}
119
-
120
-		// prevent app.php from printing output
121
-		ob_start();
122
-		foreach ($apps as $app) {
123
-			if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
124
-				self::loadApp($app);
125
-			}
126
-		}
127
-		ob_end_clean();
128
-
129
-		return true;
130
-	}
131
-
132
-	/**
133
-	 * load a single app
134
-	 *
135
-	 * @param string $app
136
-	 */
137
-	public static function loadApp($app) {
138
-		self::$loadedApps[] = $app;
139
-		$appPath = self::getAppPath($app);
140
-		if($appPath === false) {
141
-			return;
142
-		}
143
-
144
-		// in case someone calls loadApp() directly
145
-		self::registerAutoloading($app, $appPath);
146
-
147
-		if (is_file($appPath . '/appinfo/app.php')) {
148
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
149
-			self::requireAppFile($app);
150
-			if (self::isType($app, array('authentication'))) {
151
-				// since authentication apps affect the "is app enabled for group" check,
152
-				// the enabled apps cache needs to be cleared to make sure that the
153
-				// next time getEnableApps() is called it will also include apps that were
154
-				// enabled for groups
155
-				self::$enabledAppsCache = array();
156
-			}
157
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
158
-		}
159
-
160
-		$info = self::getAppInfo($app);
161
-		if (!empty($info['activity']['filters'])) {
162
-			foreach ($info['activity']['filters'] as $filter) {
163
-				\OC::$server->getActivityManager()->registerFilter($filter);
164
-			}
165
-		}
166
-		if (!empty($info['activity']['settings'])) {
167
-			foreach ($info['activity']['settings'] as $setting) {
168
-				\OC::$server->getActivityManager()->registerSetting($setting);
169
-			}
170
-		}
171
-		if (!empty($info['activity']['providers'])) {
172
-			foreach ($info['activity']['providers'] as $provider) {
173
-				\OC::$server->getActivityManager()->registerProvider($provider);
174
-			}
175
-		}
176
-	}
177
-
178
-	/**
179
-	 * @internal
180
-	 * @param string $app
181
-	 * @param string $path
182
-	 */
183
-	public static function registerAutoloading($app, $path) {
184
-		$key = $app . '-' . $path;
185
-		if(isset(self::$alreadyRegistered[$key])) {
186
-			return;
187
-		}
188
-		self::$alreadyRegistered[$key] = true;
189
-		// Register on PSR-4 composer autoloader
190
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
191
-		\OC::$server->registerNamespace($app, $appNamespace);
192
-		\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
193
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
194
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
195
-		}
196
-
197
-		// Register on legacy autoloader
198
-		\OC::$loader->addValidRoot($path);
199
-	}
200
-
201
-	/**
202
-	 * Load app.php from the given app
203
-	 *
204
-	 * @param string $app app name
205
-	 */
206
-	private static function requireAppFile($app) {
207
-		try {
208
-			// encapsulated here to avoid variable scope conflicts
209
-			require_once $app . '/appinfo/app.php';
210
-		} catch (Error $ex) {
211
-			\OC::$server->getLogger()->logException($ex);
212
-			$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
213
-			if (!in_array($app, $blacklist)) {
214
-				self::disable($app);
215
-			}
216
-		}
217
-	}
218
-
219
-	/**
220
-	 * check if an app is of a specific type
221
-	 *
222
-	 * @param string $app
223
-	 * @param string|array $types
224
-	 * @return bool
225
-	 */
226
-	public static function isType($app, $types) {
227
-		if (is_string($types)) {
228
-			$types = array($types);
229
-		}
230
-		$appTypes = self::getAppTypes($app);
231
-		foreach ($types as $type) {
232
-			if (array_search($type, $appTypes) !== false) {
233
-				return true;
234
-			}
235
-		}
236
-		return false;
237
-	}
238
-
239
-	/**
240
-	 * get the types of an app
241
-	 *
242
-	 * @param string $app
243
-	 * @return array
244
-	 */
245
-	private static function getAppTypes($app) {
246
-		//load the cache
247
-		if (count(self::$appTypes) == 0) {
248
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
249
-		}
250
-
251
-		if (isset(self::$appTypes[$app])) {
252
-			return explode(',', self::$appTypes[$app]);
253
-		} else {
254
-			return array();
255
-		}
256
-	}
257
-
258
-	/**
259
-	 * read app types from info.xml and cache them in the database
260
-	 */
261
-	public static function setAppTypes($app) {
262
-		$appData = self::getAppInfo($app);
263
-		if(!is_array($appData)) {
264
-			return;
265
-		}
266
-
267
-		if (isset($appData['types'])) {
268
-			$appTypes = implode(',', $appData['types']);
269
-		} else {
270
-			$appTypes = '';
271
-			$appData['types'] = [];
272
-		}
273
-
274
-		\OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
275
-
276
-		if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
277
-			$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
278
-			if ($enabled !== 'yes' && $enabled !== 'no') {
279
-				\OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
280
-			}
281
-		}
282
-	}
283
-
284
-	/**
285
-	 * check if app is shipped
286
-	 *
287
-	 * @param string $appId the id of the app to check
288
-	 * @return bool
289
-	 *
290
-	 * Check if an app that is installed is a shipped app or installed from the appstore.
291
-	 */
292
-	public static function isShipped($appId) {
293
-		return \OC::$server->getAppManager()->isShipped($appId);
294
-	}
295
-
296
-	/**
297
-	 * get all enabled apps
298
-	 */
299
-	protected static $enabledAppsCache = array();
300
-
301
-	/**
302
-	 * Returns apps enabled for the current user.
303
-	 *
304
-	 * @param bool $forceRefresh whether to refresh the cache
305
-	 * @param bool $all whether to return apps for all users, not only the
306
-	 * currently logged in one
307
-	 * @return string[]
308
-	 */
309
-	public static function getEnabledApps($forceRefresh = false, $all = false) {
310
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
311
-			return array();
312
-		}
313
-		// in incognito mode or when logged out, $user will be false,
314
-		// which is also the case during an upgrade
315
-		$appManager = \OC::$server->getAppManager();
316
-		if ($all) {
317
-			$user = null;
318
-		} else {
319
-			$user = \OC::$server->getUserSession()->getUser();
320
-		}
321
-
322
-		if (is_null($user)) {
323
-			$apps = $appManager->getInstalledApps();
324
-		} else {
325
-			$apps = $appManager->getEnabledAppsForUser($user);
326
-		}
327
-		$apps = array_filter($apps, function ($app) {
328
-			return $app !== 'files';//we add this manually
329
-		});
330
-		sort($apps);
331
-		array_unshift($apps, 'files');
332
-		return $apps;
333
-	}
334
-
335
-	/**
336
-	 * checks whether or not an app is enabled
337
-	 *
338
-	 * @param string $app app
339
-	 * @return bool
340
-	 *
341
-	 * This function checks whether or not an app is enabled.
342
-	 */
343
-	public static function isEnabled($app) {
344
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
345
-	}
346
-
347
-	/**
348
-	 * enables an app
349
-	 *
350
-	 * @param string $appId
351
-	 * @param array $groups (optional) when set, only these groups will have access to the app
352
-	 * @throws \Exception
353
-	 * @return void
354
-	 *
355
-	 * This function set an app as enabled in appconfig.
356
-	 */
357
-	public function enable($appId,
358
-						   $groups = null) {
359
-		self::$enabledAppsCache = []; // flush
360
-		$l = \OC::$server->getL10N('core');
361
-		$config = \OC::$server->getConfig();
362
-
363
-		// Check if app is already downloaded
364
-		$installer = new Installer(
365
-			\OC::$server->getAppFetcher(),
366
-			\OC::$server->getHTTPClientService(),
367
-			\OC::$server->getTempManager(),
368
-			\OC::$server->getLogger(),
369
-			\OC::$server->getConfig()
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
-			\OC::$server->getConfig()
433
-		);
434
-		return $installer->removeApp($app);
435
-	}
436
-
437
-	/**
438
-	 * This function set an app as disabled in appconfig.
439
-	 *
440
-	 * @param string $app app
441
-	 * @throws Exception
442
-	 */
443
-	public static function disable($app) {
444
-		// flush
445
-		self::$enabledAppsCache = array();
446
-
447
-		// run uninstall steps
448
-		$appData = OC_App::getAppInfo($app);
449
-		if (!is_null($appData)) {
450
-			OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
451
-		}
452
-
453
-		// emit disable hook - needed anymore ?
454
-		\OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
455
-
456
-		// finally disable it
457
-		$appManager = \OC::$server->getAppManager();
458
-		$appManager->disableApp($app);
459
-	}
460
-
461
-	// This is private as well. It simply works, so don't ask for more details
462
-	private static function proceedNavigation($list) {
463
-		usort($list, function($a, $b) {
464
-			if (isset($a['order']) && isset($b['order'])) {
465
-				return ($a['order'] < $b['order']) ? -1 : 1;
466
-			} else if (isset($a['order']) || isset($b['order'])) {
467
-				return isset($a['order']) ? -1 : 1;
468
-			} else {
469
-				return ($a['name'] < $b['name']) ? -1 : 1;
470
-			}
471
-		});
472
-
473
-		$activeApp = OC::$server->getNavigationManager()->getActiveEntry();
474
-		foreach ($list as $index => &$navEntry) {
475
-			if ($navEntry['id'] == $activeApp) {
476
-				$navEntry['active'] = true;
477
-			} else {
478
-				$navEntry['active'] = false;
479
-			}
480
-		}
481
-		unset($navEntry);
482
-
483
-		return $list;
484
-	}
485
-
486
-	/**
487
-	 * Get the path where to install apps
488
-	 *
489
-	 * @return string|false
490
-	 */
491
-	public static function getInstallPath() {
492
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
493
-			return false;
494
-		}
495
-
496
-		foreach (OC::$APPSROOTS as $dir) {
497
-			if (isset($dir['writable']) && $dir['writable'] === true) {
498
-				return $dir['path'];
499
-			}
500
-		}
501
-
502
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
503
-		return null;
504
-	}
505
-
506
-
507
-	/**
508
-	 * search for an app in all app-directories
509
-	 *
510
-	 * @param string $appId
511
-	 * @return false|string
512
-	 */
513
-	public static function findAppInDirectories($appId) {
514
-		$sanitizedAppId = self::cleanAppId($appId);
515
-		if($sanitizedAppId !== $appId) {
516
-			return false;
517
-		}
518
-		static $app_dir = array();
519
-
520
-		if (isset($app_dir[$appId])) {
521
-			return $app_dir[$appId];
522
-		}
523
-
524
-		$possibleApps = array();
525
-		foreach (OC::$APPSROOTS as $dir) {
526
-			if (file_exists($dir['path'] . '/' . $appId)) {
527
-				$possibleApps[] = $dir;
528
-			}
529
-		}
530
-
531
-		if (empty($possibleApps)) {
532
-			return false;
533
-		} elseif (count($possibleApps) === 1) {
534
-			$dir = array_shift($possibleApps);
535
-			$app_dir[$appId] = $dir;
536
-			return $dir;
537
-		} else {
538
-			$versionToLoad = array();
539
-			foreach ($possibleApps as $possibleApp) {
540
-				$version = self::getAppVersionByPath($possibleApp['path']);
541
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
542
-					$versionToLoad = array(
543
-						'dir' => $possibleApp,
544
-						'version' => $version,
545
-					);
546
-				}
547
-			}
548
-			$app_dir[$appId] = $versionToLoad['dir'];
549
-			return $versionToLoad['dir'];
550
-			//TODO - write test
551
-		}
552
-	}
553
-
554
-	/**
555
-	 * Get the directory for the given app.
556
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
557
-	 *
558
-	 * @param string $appId
559
-	 * @return string|false
560
-	 */
561
-	public static function getAppPath($appId) {
562
-		if ($appId === null || trim($appId) === '') {
563
-			return false;
564
-		}
565
-
566
-		if (($dir = self::findAppInDirectories($appId)) != false) {
567
-			return $dir['path'] . '/' . $appId;
568
-		}
569
-		return false;
570
-	}
571
-
572
-	/**
573
-	 * Get the path for the given app on the access
574
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
575
-	 *
576
-	 * @param string $appId
577
-	 * @return string|false
578
-	 */
579
-	public static function getAppWebPath($appId) {
580
-		if (($dir = self::findAppInDirectories($appId)) != false) {
581
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
582
-		}
583
-		return false;
584
-	}
585
-
586
-	/**
587
-	 * get the last version of the app from appinfo/info.xml
588
-	 *
589
-	 * @param string $appId
590
-	 * @param bool $useCache
591
-	 * @return string
592
-	 */
593
-	public static function getAppVersion($appId, $useCache = true) {
594
-		if($useCache && isset(self::$appVersion[$appId])) {
595
-			return self::$appVersion[$appId];
596
-		}
597
-
598
-		$file = self::getAppPath($appId);
599
-		self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
600
-		return self::$appVersion[$appId];
601
-	}
602
-
603
-	/**
604
-	 * get app's version based on it's path
605
-	 *
606
-	 * @param string $path
607
-	 * @return string
608
-	 */
609
-	public static function getAppVersionByPath($path) {
610
-		$infoFile = $path . '/appinfo/info.xml';
611
-		$appData = self::getAppInfo($infoFile, true);
612
-		return isset($appData['version']) ? $appData['version'] : '';
613
-	}
614
-
615
-
616
-	/**
617
-	 * Read all app metadata from the info.xml file
618
-	 *
619
-	 * @param string $appId id of the app or the path of the info.xml file
620
-	 * @param bool $path
621
-	 * @param string $lang
622
-	 * @return array|null
623
-	 * @note all data is read from info.xml, not just pre-defined fields
624
-	 */
625
-	public static function getAppInfo($appId, $path = false, $lang = null) {
626
-		if ($path) {
627
-			$file = $appId;
628
-		} else {
629
-			if ($lang === null && isset(self::$appInfo[$appId])) {
630
-				return self::$appInfo[$appId];
631
-			}
632
-			$appPath = self::getAppPath($appId);
633
-			if($appPath === false) {
634
-				return null;
635
-			}
636
-			$file = $appPath . '/appinfo/info.xml';
637
-		}
638
-
639
-		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->create('core.appinfo'));
640
-		$data = $parser->parse($file);
641
-
642
-		if (is_array($data)) {
643
-			$data = OC_App::parseAppInfo($data, $lang);
644
-		}
645
-		if(isset($data['ocsid'])) {
646
-			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
647
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
648
-				$data['ocsid'] = $storedId;
649
-			}
650
-		}
651
-
652
-		if ($lang === null) {
653
-			self::$appInfo[$appId] = $data;
654
-		}
655
-
656
-		return $data;
657
-	}
658
-
659
-	/**
660
-	 * Returns the navigation
661
-	 *
662
-	 * @return array
663
-	 *
664
-	 * This function returns an array containing all entries added. The
665
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
666
-	 * given for each app the following keys exist:
667
-	 *   - active: boolean, signals if the user is on this navigation entry
668
-	 */
669
-	public static function getNavigation() {
670
-		$entries = OC::$server->getNavigationManager()->getAll();
671
-		return self::proceedNavigation($entries);
672
-	}
673
-
674
-	/**
675
-	 * Returns the Settings Navigation
676
-	 *
677
-	 * @return string[]
678
-	 *
679
-	 * This function returns an array containing all settings pages added. The
680
-	 * entries are sorted by the key 'order' ascending.
681
-	 */
682
-	public static function getSettingsNavigation() {
683
-		$entries = OC::$server->getNavigationManager()->getAll('settings');
684
-		return self::proceedNavigation($entries);
685
-	}
686
-
687
-	/**
688
-	 * get the id of loaded app
689
-	 *
690
-	 * @return string
691
-	 */
692
-	public static function getCurrentApp() {
693
-		$request = \OC::$server->getRequest();
694
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
695
-		$topFolder = substr($script, 0, strpos($script, '/'));
696
-		if (empty($topFolder)) {
697
-			$path_info = $request->getPathInfo();
698
-			if ($path_info) {
699
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
700
-			}
701
-		}
702
-		if ($topFolder == 'apps') {
703
-			$length = strlen($topFolder);
704
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
705
-		} else {
706
-			return $topFolder;
707
-		}
708
-	}
709
-
710
-	/**
711
-	 * @param string $type
712
-	 * @return array
713
-	 */
714
-	public static function getForms($type) {
715
-		$forms = array();
716
-		switch ($type) {
717
-			case 'admin':
718
-				$source = self::$adminForms;
719
-				break;
720
-			case 'personal':
721
-				$source = self::$personalForms;
722
-				break;
723
-			default:
724
-				return array();
725
-		}
726
-		foreach ($source as $form) {
727
-			$forms[] = include $form;
728
-		}
729
-		return $forms;
730
-	}
731
-
732
-	/**
733
-	 * register an admin form to be shown
734
-	 *
735
-	 * @param string $app
736
-	 * @param string $page
737
-	 */
738
-	public static function registerAdmin($app, $page) {
739
-		self::$adminForms[] = $app . '/' . $page . '.php';
740
-	}
741
-
742
-	/**
743
-	 * register a personal form to be shown
744
-	 * @param string $app
745
-	 * @param string $page
746
-	 */
747
-	public static function registerPersonal($app, $page) {
748
-		self::$personalForms[] = $app . '/' . $page . '.php';
749
-	}
750
-
751
-	/**
752
-	 * @param array $entry
753
-	 */
754
-	public static function registerLogIn(array $entry) {
755
-		self::$altLogin[] = $entry;
756
-	}
757
-
758
-	/**
759
-	 * @return array
760
-	 */
761
-	public static function getAlternativeLogIns() {
762
-		return self::$altLogin;
763
-	}
764
-
765
-	/**
766
-	 * get a list of all apps in the apps folder
767
-	 *
768
-	 * @return array an array of app names (string IDs)
769
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
770
-	 */
771
-	public static function getAllApps() {
772
-
773
-		$apps = array();
774
-
775
-		foreach (OC::$APPSROOTS as $apps_dir) {
776
-			if (!is_readable($apps_dir['path'])) {
777
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
778
-				continue;
779
-			}
780
-			$dh = opendir($apps_dir['path']);
781
-
782
-			if (is_resource($dh)) {
783
-				while (($file = readdir($dh)) !== false) {
784
-
785
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
786
-
787
-						$apps[] = $file;
788
-					}
789
-				}
790
-			}
791
-		}
792
-
793
-		return $apps;
794
-	}
795
-
796
-	/**
797
-	 * List all apps, this is used in apps.php
798
-	 *
799
-	 * @return array
800
-	 */
801
-	public function listAllApps() {
802
-		$installedApps = OC_App::getAllApps();
803
-
804
-		//we don't want to show configuration for these
805
-		$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
806
-		$appList = array();
807
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
808
-		$urlGenerator = \OC::$server->getURLGenerator();
809
-
810
-		foreach ($installedApps as $app) {
811
-			if (array_search($app, $blacklist) === false) {
812
-
813
-				$info = OC_App::getAppInfo($app, false, $langCode);
814
-				if (!is_array($info)) {
815
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
816
-					continue;
817
-				}
818
-
819
-				if (!isset($info['name'])) {
820
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
821
-					continue;
822
-				}
823
-
824
-				$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
825
-				$info['groups'] = null;
826
-				if ($enabled === 'yes') {
827
-					$active = true;
828
-				} else if ($enabled === 'no') {
829
-					$active = false;
830
-				} else {
831
-					$active = true;
832
-					$info['groups'] = $enabled;
833
-				}
834
-
835
-				$info['active'] = $active;
836
-
837
-				if (self::isShipped($app)) {
838
-					$info['internal'] = true;
839
-					$info['level'] = self::officialApp;
840
-					$info['removable'] = false;
841
-				} else {
842
-					$info['internal'] = false;
843
-					$info['removable'] = true;
844
-				}
845
-
846
-				$appPath = self::getAppPath($app);
847
-				if($appPath !== false) {
848
-					$appIcon = $appPath . '/img/' . $app . '.svg';
849
-					if (file_exists($appIcon)) {
850
-						$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app . '.svg');
851
-						$info['previewAsIcon'] = true;
852
-					} else {
853
-						$appIcon = $appPath . '/img/app.svg';
854
-						if (file_exists($appIcon)) {
855
-							$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, 'app.svg');
856
-							$info['previewAsIcon'] = true;
857
-						}
858
-					}
859
-				}
860
-				// fix documentation
861
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
862
-					foreach ($info['documentation'] as $key => $url) {
863
-						// If it is not an absolute URL we assume it is a key
864
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
865
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
866
-							$url = $urlGenerator->linkToDocs($url);
867
-						}
868
-
869
-						$info['documentation'][$key] = $url;
870
-					}
871
-				}
872
-
873
-				$info['version'] = OC_App::getAppVersion($app);
874
-				$appList[] = $info;
875
-			}
876
-		}
877
-
878
-		return $appList;
879
-	}
880
-
881
-	/**
882
-	 * Returns the internal app ID or false
883
-	 * @param string $ocsID
884
-	 * @return string|false
885
-	 */
886
-	public static function getInternalAppIdByOcs($ocsID) {
887
-		if(is_numeric($ocsID)) {
888
-			$idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
889
-			if(array_search($ocsID, $idArray)) {
890
-				return array_search($ocsID, $idArray);
891
-			}
892
-		}
893
-		return false;
894
-	}
895
-
896
-	public static function shouldUpgrade($app) {
897
-		$versions = self::getAppVersions();
898
-		$currentVersion = OC_App::getAppVersion($app);
899
-		if ($currentVersion && isset($versions[$app])) {
900
-			$installedVersion = $versions[$app];
901
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
902
-				return true;
903
-			}
904
-		}
905
-		return false;
906
-	}
907
-
908
-	/**
909
-	 * Adjust the number of version parts of $version1 to match
910
-	 * the number of version parts of $version2.
911
-	 *
912
-	 * @param string $version1 version to adjust
913
-	 * @param string $version2 version to take the number of parts from
914
-	 * @return string shortened $version1
915
-	 */
916
-	private static function adjustVersionParts($version1, $version2) {
917
-		$version1 = explode('.', $version1);
918
-		$version2 = explode('.', $version2);
919
-		// reduce $version1 to match the number of parts in $version2
920
-		while (count($version1) > count($version2)) {
921
-			array_pop($version1);
922
-		}
923
-		// if $version1 does not have enough parts, add some
924
-		while (count($version1) < count($version2)) {
925
-			$version1[] = '0';
926
-		}
927
-		return implode('.', $version1);
928
-	}
929
-
930
-	/**
931
-	 * Check whether the current ownCloud version matches the given
932
-	 * application's version requirements.
933
-	 *
934
-	 * The comparison is made based on the number of parts that the
935
-	 * app info version has. For example for ownCloud 6.0.3 if the
936
-	 * app info version is expecting version 6.0, the comparison is
937
-	 * made on the first two parts of the ownCloud version.
938
-	 * This means that it's possible to specify "requiremin" => 6
939
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
940
-	 *
941
-	 * @param string $ocVersion ownCloud version to check against
942
-	 * @param array $appInfo app info (from xml)
943
-	 *
944
-	 * @return boolean true if compatible, otherwise false
945
-	 */
946
-	public static function isAppCompatible($ocVersion, $appInfo) {
947
-		$requireMin = '';
948
-		$requireMax = '';
949
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
950
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
951
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
952
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
953
-		} else if (isset($appInfo['requiremin'])) {
954
-			$requireMin = $appInfo['requiremin'];
955
-		} else if (isset($appInfo['require'])) {
956
-			$requireMin = $appInfo['require'];
957
-		}
958
-
959
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
960
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
961
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
962
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
963
-		} else if (isset($appInfo['requiremax'])) {
964
-			$requireMax = $appInfo['requiremax'];
965
-		}
966
-
967
-		if (is_array($ocVersion)) {
968
-			$ocVersion = implode('.', $ocVersion);
969
-		}
970
-
971
-		if (!empty($requireMin)
972
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
973
-		) {
974
-
975
-			return false;
976
-		}
977
-
978
-		if (!empty($requireMax)
979
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
980
-		) {
981
-			return false;
982
-		}
983
-
984
-		return true;
985
-	}
986
-
987
-	/**
988
-	 * get the installed version of all apps
989
-	 */
990
-	public static function getAppVersions() {
991
-		static $versions;
992
-
993
-		if(!$versions) {
994
-			$appConfig = \OC::$server->getAppConfig();
995
-			$versions = $appConfig->getValues(false, 'installed_version');
996
-		}
997
-		return $versions;
998
-	}
999
-
1000
-	/**
1001
-	 * @param string $app
1002
-	 * @param \OCP\IConfig $config
1003
-	 * @param \OCP\IL10N $l
1004
-	 * @return bool
1005
-	 *
1006
-	 * @throws Exception if app is not compatible with this version of ownCloud
1007
-	 * @throws Exception if no app-name was specified
1008
-	 */
1009
-	public function installApp($app,
1010
-							   \OCP\IConfig $config,
1011
-							   \OCP\IL10N $l) {
1012
-		if ($app !== false) {
1013
-			// check if the app is compatible with this version of ownCloud
1014
-			$info = self::getAppInfo($app);
1015
-			if(!is_array($info)) {
1016
-				throw new \Exception(
1017
-					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1018
-						[$info['name']]
1019
-					)
1020
-				);
1021
-			}
1022
-
1023
-			$version = \OCP\Util::getVersion();
1024
-			if (!self::isAppCompatible($version, $info)) {
1025
-				throw new \Exception(
1026
-					$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1027
-						array($info['name'])
1028
-					)
1029
-				);
1030
-			}
1031
-
1032
-			// check for required dependencies
1033
-			self::checkAppDependencies($config, $l, $info);
1034
-
1035
-			$config->setAppValue($app, 'enabled', 'yes');
1036
-			if (isset($appData['id'])) {
1037
-				$config->setAppValue($app, 'ocsid', $appData['id']);
1038
-			}
1039
-
1040
-			if(isset($info['settings']) && is_array($info['settings'])) {
1041
-				$appPath = self::getAppPath($app);
1042
-				self::registerAutoloading($app, $appPath);
1043
-				\OC::$server->getSettingsManager()->setupSettings($info['settings']);
1044
-			}
1045
-
1046
-			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1047
-		} else {
1048
-			if(empty($appName) ) {
1049
-				throw new \Exception($l->t("No app name specified"));
1050
-			} else {
1051
-				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1052
-			}
1053
-		}
1054
-
1055
-		return $app;
1056
-	}
1057
-
1058
-	/**
1059
-	 * update the database for the app and call the update script
1060
-	 *
1061
-	 * @param string $appId
1062
-	 * @return bool
1063
-	 */
1064
-	public static function updateApp($appId) {
1065
-		$appPath = self::getAppPath($appId);
1066
-		if($appPath === false) {
1067
-			return false;
1068
-		}
1069
-		$appData = self::getAppInfo($appId);
1070
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1071
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1072
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1073
-		}
1074
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1075
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1076
-		unset(self::$appVersion[$appId]);
1077
-		// run upgrade code
1078
-		if (file_exists($appPath . '/appinfo/update.php')) {
1079
-			self::loadApp($appId);
1080
-			include $appPath . '/appinfo/update.php';
1081
-		}
1082
-		self::setupBackgroundJobs($appData['background-jobs']);
1083
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
1084
-			$appPath = self::getAppPath($appId);
1085
-			self::registerAutoloading($appId, $appPath);
1086
-			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1087
-		}
1088
-
1089
-		//set remote/public handlers
1090
-		if (array_key_exists('ocsid', $appData)) {
1091
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1092
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1093
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1094
-		}
1095
-		foreach ($appData['remote'] as $name => $path) {
1096
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1097
-		}
1098
-		foreach ($appData['public'] as $name => $path) {
1099
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1100
-		}
1101
-
1102
-		self::setAppTypes($appId);
1103
-
1104
-		$version = \OC_App::getAppVersion($appId);
1105
-		\OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1106
-
1107
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1108
-			ManagerEvent::EVENT_APP_UPDATE, $appId
1109
-		));
1110
-
1111
-		return true;
1112
-	}
1113
-
1114
-	/**
1115
-	 * @param string $appId
1116
-	 * @param string[] $steps
1117
-	 * @throws \OC\NeedsUpdateException
1118
-	 */
1119
-	public static function executeRepairSteps($appId, array $steps) {
1120
-		if (empty($steps)) {
1121
-			return;
1122
-		}
1123
-		// load the app
1124
-		self::loadApp($appId);
1125
-
1126
-		$dispatcher = OC::$server->getEventDispatcher();
1127
-
1128
-		// load the steps
1129
-		$r = new Repair([], $dispatcher);
1130
-		foreach ($steps as $step) {
1131
-			try {
1132
-				$r->addStep($step);
1133
-			} catch (Exception $ex) {
1134
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1135
-				\OC::$server->getLogger()->logException($ex);
1136
-			}
1137
-		}
1138
-		// run the steps
1139
-		$r->run();
1140
-	}
1141
-
1142
-	public static function setupBackgroundJobs(array $jobs) {
1143
-		$queue = \OC::$server->getJobList();
1144
-		foreach ($jobs as $job) {
1145
-			$queue->add($job);
1146
-		}
1147
-	}
1148
-
1149
-	/**
1150
-	 * @param string $appId
1151
-	 * @param string[] $steps
1152
-	 */
1153
-	private static function setupLiveMigrations($appId, array $steps) {
1154
-		$queue = \OC::$server->getJobList();
1155
-		foreach ($steps as $step) {
1156
-			$queue->add('OC\Migration\BackgroundRepair', [
1157
-				'app' => $appId,
1158
-				'step' => $step]);
1159
-		}
1160
-	}
1161
-
1162
-	/**
1163
-	 * @param string $appId
1164
-	 * @return \OC\Files\View|false
1165
-	 */
1166
-	public static function getStorage($appId) {
1167
-		if (OC_App::isEnabled($appId)) { //sanity check
1168
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1169
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1170
-				if (!$view->file_exists($appId)) {
1171
-					$view->mkdir($appId);
1172
-				}
1173
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1174
-			} else {
1175
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1176
-				return false;
1177
-			}
1178
-		} else {
1179
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1180
-			return false;
1181
-		}
1182
-	}
1183
-
1184
-	protected static function findBestL10NOption($options, $lang) {
1185
-		$fallback = $similarLangFallback = $englishFallback = false;
1186
-
1187
-		$lang = strtolower($lang);
1188
-		$similarLang = $lang;
1189
-		if (strpos($similarLang, '_')) {
1190
-			// For "de_DE" we want to find "de" and the other way around
1191
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1192
-		}
1193
-
1194
-		foreach ($options as $option) {
1195
-			if (is_array($option)) {
1196
-				if ($fallback === false) {
1197
-					$fallback = $option['@value'];
1198
-				}
1199
-
1200
-				if (!isset($option['@attributes']['lang'])) {
1201
-					continue;
1202
-				}
1203
-
1204
-				$attributeLang = strtolower($option['@attributes']['lang']);
1205
-				if ($attributeLang === $lang) {
1206
-					return $option['@value'];
1207
-				}
1208
-
1209
-				if ($attributeLang === $similarLang) {
1210
-					$similarLangFallback = $option['@value'];
1211
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1212
-					if ($similarLangFallback === false) {
1213
-						$similarLangFallback =  $option['@value'];
1214
-					}
1215
-				}
1216
-			} else {
1217
-				$englishFallback = $option;
1218
-			}
1219
-		}
1220
-
1221
-		if ($similarLangFallback !== false) {
1222
-			return $similarLangFallback;
1223
-		} else if ($englishFallback !== false) {
1224
-			return $englishFallback;
1225
-		}
1226
-		return (string) $fallback;
1227
-	}
1228
-
1229
-	/**
1230
-	 * parses the app data array and enhanced the 'description' value
1231
-	 *
1232
-	 * @param array $data the app data
1233
-	 * @param string $lang
1234
-	 * @return array improved app data
1235
-	 */
1236
-	public static function parseAppInfo(array $data, $lang = null) {
1237
-
1238
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1239
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1240
-		}
1241
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1242
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1243
-		}
1244
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1245
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1246
-		} else if (isset($data['description']) && is_string($data['description'])) {
1247
-			$data['description'] = trim($data['description']);
1248
-		} else  {
1249
-			$data['description'] = '';
1250
-		}
1251
-
1252
-		return $data;
1253
-	}
1254
-
1255
-	/**
1256
-	 * @param \OCP\IConfig $config
1257
-	 * @param \OCP\IL10N $l
1258
-	 * @param array $info
1259
-	 * @throws \Exception
1260
-	 */
1261
-	protected static function checkAppDependencies($config, $l, $info) {
1262
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1263
-		$missing = $dependencyAnalyzer->analyze($info);
1264
-		if (!empty($missing)) {
1265
-			$missingMsg = join(PHP_EOL, $missing);
1266
-			throw new \Exception(
1267
-				$l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1268
-					[$info['name'], $missingMsg]
1269
-				)
1270
-			);
1271
-		}
1272
-	}
63
+    static private $appVersion = [];
64
+    static private $adminForms = array();
65
+    static private $personalForms = array();
66
+    static private $appInfo = array();
67
+    static private $appTypes = array();
68
+    static private $loadedApps = array();
69
+    static private $altLogin = array();
70
+    static private $alreadyRegistered = [];
71
+    const officialApp = 200;
72
+
73
+    /**
74
+     * clean the appId
75
+     *
76
+     * @param string|boolean $app AppId that needs to be cleaned
77
+     * @return string
78
+     */
79
+    public static function cleanAppId($app) {
80
+        return str_replace(array('\0', '/', '\\', '..'), '', $app);
81
+    }
82
+
83
+    /**
84
+     * Check if an app is loaded
85
+     *
86
+     * @param string $app
87
+     * @return bool
88
+     */
89
+    public static function isAppLoaded($app) {
90
+        return in_array($app, self::$loadedApps, true);
91
+    }
92
+
93
+    /**
94
+     * loads all apps
95
+     *
96
+     * @param string[] | string | null $types
97
+     * @return bool
98
+     *
99
+     * This function walks through the ownCloud directory and loads all apps
100
+     * it can find. A directory contains an app if the file /appinfo/info.xml
101
+     * exists.
102
+     *
103
+     * if $types is set, only apps of those types will be loaded
104
+     */
105
+    public static function loadApps($types = null) {
106
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
107
+            return false;
108
+        }
109
+        // Load the enabled apps here
110
+        $apps = self::getEnabledApps();
111
+
112
+        // Add each apps' folder as allowed class path
113
+        foreach($apps as $app) {
114
+            $path = self::getAppPath($app);
115
+            if($path !== false) {
116
+                self::registerAutoloading($app, $path);
117
+            }
118
+        }
119
+
120
+        // prevent app.php from printing output
121
+        ob_start();
122
+        foreach ($apps as $app) {
123
+            if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
124
+                self::loadApp($app);
125
+            }
126
+        }
127
+        ob_end_clean();
128
+
129
+        return true;
130
+    }
131
+
132
+    /**
133
+     * load a single app
134
+     *
135
+     * @param string $app
136
+     */
137
+    public static function loadApp($app) {
138
+        self::$loadedApps[] = $app;
139
+        $appPath = self::getAppPath($app);
140
+        if($appPath === false) {
141
+            return;
142
+        }
143
+
144
+        // in case someone calls loadApp() directly
145
+        self::registerAutoloading($app, $appPath);
146
+
147
+        if (is_file($appPath . '/appinfo/app.php')) {
148
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
149
+            self::requireAppFile($app);
150
+            if (self::isType($app, array('authentication'))) {
151
+                // since authentication apps affect the "is app enabled for group" check,
152
+                // the enabled apps cache needs to be cleared to make sure that the
153
+                // next time getEnableApps() is called it will also include apps that were
154
+                // enabled for groups
155
+                self::$enabledAppsCache = array();
156
+            }
157
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
158
+        }
159
+
160
+        $info = self::getAppInfo($app);
161
+        if (!empty($info['activity']['filters'])) {
162
+            foreach ($info['activity']['filters'] as $filter) {
163
+                \OC::$server->getActivityManager()->registerFilter($filter);
164
+            }
165
+        }
166
+        if (!empty($info['activity']['settings'])) {
167
+            foreach ($info['activity']['settings'] as $setting) {
168
+                \OC::$server->getActivityManager()->registerSetting($setting);
169
+            }
170
+        }
171
+        if (!empty($info['activity']['providers'])) {
172
+            foreach ($info['activity']['providers'] as $provider) {
173
+                \OC::$server->getActivityManager()->registerProvider($provider);
174
+            }
175
+        }
176
+    }
177
+
178
+    /**
179
+     * @internal
180
+     * @param string $app
181
+     * @param string $path
182
+     */
183
+    public static function registerAutoloading($app, $path) {
184
+        $key = $app . '-' . $path;
185
+        if(isset(self::$alreadyRegistered[$key])) {
186
+            return;
187
+        }
188
+        self::$alreadyRegistered[$key] = true;
189
+        // Register on PSR-4 composer autoloader
190
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
191
+        \OC::$server->registerNamespace($app, $appNamespace);
192
+        \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
193
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
194
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
195
+        }
196
+
197
+        // Register on legacy autoloader
198
+        \OC::$loader->addValidRoot($path);
199
+    }
200
+
201
+    /**
202
+     * Load app.php from the given app
203
+     *
204
+     * @param string $app app name
205
+     */
206
+    private static function requireAppFile($app) {
207
+        try {
208
+            // encapsulated here to avoid variable scope conflicts
209
+            require_once $app . '/appinfo/app.php';
210
+        } catch (Error $ex) {
211
+            \OC::$server->getLogger()->logException($ex);
212
+            $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
213
+            if (!in_array($app, $blacklist)) {
214
+                self::disable($app);
215
+            }
216
+        }
217
+    }
218
+
219
+    /**
220
+     * check if an app is of a specific type
221
+     *
222
+     * @param string $app
223
+     * @param string|array $types
224
+     * @return bool
225
+     */
226
+    public static function isType($app, $types) {
227
+        if (is_string($types)) {
228
+            $types = array($types);
229
+        }
230
+        $appTypes = self::getAppTypes($app);
231
+        foreach ($types as $type) {
232
+            if (array_search($type, $appTypes) !== false) {
233
+                return true;
234
+            }
235
+        }
236
+        return false;
237
+    }
238
+
239
+    /**
240
+     * get the types of an app
241
+     *
242
+     * @param string $app
243
+     * @return array
244
+     */
245
+    private static function getAppTypes($app) {
246
+        //load the cache
247
+        if (count(self::$appTypes) == 0) {
248
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
249
+        }
250
+
251
+        if (isset(self::$appTypes[$app])) {
252
+            return explode(',', self::$appTypes[$app]);
253
+        } else {
254
+            return array();
255
+        }
256
+    }
257
+
258
+    /**
259
+     * read app types from info.xml and cache them in the database
260
+     */
261
+    public static function setAppTypes($app) {
262
+        $appData = self::getAppInfo($app);
263
+        if(!is_array($appData)) {
264
+            return;
265
+        }
266
+
267
+        if (isset($appData['types'])) {
268
+            $appTypes = implode(',', $appData['types']);
269
+        } else {
270
+            $appTypes = '';
271
+            $appData['types'] = [];
272
+        }
273
+
274
+        \OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
275
+
276
+        if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
277
+            $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
278
+            if ($enabled !== 'yes' && $enabled !== 'no') {
279
+                \OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
280
+            }
281
+        }
282
+    }
283
+
284
+    /**
285
+     * check if app is shipped
286
+     *
287
+     * @param string $appId the id of the app to check
288
+     * @return bool
289
+     *
290
+     * Check if an app that is installed is a shipped app or installed from the appstore.
291
+     */
292
+    public static function isShipped($appId) {
293
+        return \OC::$server->getAppManager()->isShipped($appId);
294
+    }
295
+
296
+    /**
297
+     * get all enabled apps
298
+     */
299
+    protected static $enabledAppsCache = array();
300
+
301
+    /**
302
+     * Returns apps enabled for the current user.
303
+     *
304
+     * @param bool $forceRefresh whether to refresh the cache
305
+     * @param bool $all whether to return apps for all users, not only the
306
+     * currently logged in one
307
+     * @return string[]
308
+     */
309
+    public static function getEnabledApps($forceRefresh = false, $all = false) {
310
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
311
+            return array();
312
+        }
313
+        // in incognito mode or when logged out, $user will be false,
314
+        // which is also the case during an upgrade
315
+        $appManager = \OC::$server->getAppManager();
316
+        if ($all) {
317
+            $user = null;
318
+        } else {
319
+            $user = \OC::$server->getUserSession()->getUser();
320
+        }
321
+
322
+        if (is_null($user)) {
323
+            $apps = $appManager->getInstalledApps();
324
+        } else {
325
+            $apps = $appManager->getEnabledAppsForUser($user);
326
+        }
327
+        $apps = array_filter($apps, function ($app) {
328
+            return $app !== 'files';//we add this manually
329
+        });
330
+        sort($apps);
331
+        array_unshift($apps, 'files');
332
+        return $apps;
333
+    }
334
+
335
+    /**
336
+     * checks whether or not an app is enabled
337
+     *
338
+     * @param string $app app
339
+     * @return bool
340
+     *
341
+     * This function checks whether or not an app is enabled.
342
+     */
343
+    public static function isEnabled($app) {
344
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
345
+    }
346
+
347
+    /**
348
+     * enables an app
349
+     *
350
+     * @param string $appId
351
+     * @param array $groups (optional) when set, only these groups will have access to the app
352
+     * @throws \Exception
353
+     * @return void
354
+     *
355
+     * This function set an app as enabled in appconfig.
356
+     */
357
+    public function enable($appId,
358
+                            $groups = null) {
359
+        self::$enabledAppsCache = []; // flush
360
+        $l = \OC::$server->getL10N('core');
361
+        $config = \OC::$server->getConfig();
362
+
363
+        // Check if app is already downloaded
364
+        $installer = new Installer(
365
+            \OC::$server->getAppFetcher(),
366
+            \OC::$server->getHTTPClientService(),
367
+            \OC::$server->getTempManager(),
368
+            \OC::$server->getLogger(),
369
+            \OC::$server->getConfig()
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
+            \OC::$server->getConfig()
433
+        );
434
+        return $installer->removeApp($app);
435
+    }
436
+
437
+    /**
438
+     * This function set an app as disabled in appconfig.
439
+     *
440
+     * @param string $app app
441
+     * @throws Exception
442
+     */
443
+    public static function disable($app) {
444
+        // flush
445
+        self::$enabledAppsCache = array();
446
+
447
+        // run uninstall steps
448
+        $appData = OC_App::getAppInfo($app);
449
+        if (!is_null($appData)) {
450
+            OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
451
+        }
452
+
453
+        // emit disable hook - needed anymore ?
454
+        \OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
455
+
456
+        // finally disable it
457
+        $appManager = \OC::$server->getAppManager();
458
+        $appManager->disableApp($app);
459
+    }
460
+
461
+    // This is private as well. It simply works, so don't ask for more details
462
+    private static function proceedNavigation($list) {
463
+        usort($list, function($a, $b) {
464
+            if (isset($a['order']) && isset($b['order'])) {
465
+                return ($a['order'] < $b['order']) ? -1 : 1;
466
+            } else if (isset($a['order']) || isset($b['order'])) {
467
+                return isset($a['order']) ? -1 : 1;
468
+            } else {
469
+                return ($a['name'] < $b['name']) ? -1 : 1;
470
+            }
471
+        });
472
+
473
+        $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
474
+        foreach ($list as $index => &$navEntry) {
475
+            if ($navEntry['id'] == $activeApp) {
476
+                $navEntry['active'] = true;
477
+            } else {
478
+                $navEntry['active'] = false;
479
+            }
480
+        }
481
+        unset($navEntry);
482
+
483
+        return $list;
484
+    }
485
+
486
+    /**
487
+     * Get the path where to install apps
488
+     *
489
+     * @return string|false
490
+     */
491
+    public static function getInstallPath() {
492
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
493
+            return false;
494
+        }
495
+
496
+        foreach (OC::$APPSROOTS as $dir) {
497
+            if (isset($dir['writable']) && $dir['writable'] === true) {
498
+                return $dir['path'];
499
+            }
500
+        }
501
+
502
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
503
+        return null;
504
+    }
505
+
506
+
507
+    /**
508
+     * search for an app in all app-directories
509
+     *
510
+     * @param string $appId
511
+     * @return false|string
512
+     */
513
+    public static function findAppInDirectories($appId) {
514
+        $sanitizedAppId = self::cleanAppId($appId);
515
+        if($sanitizedAppId !== $appId) {
516
+            return false;
517
+        }
518
+        static $app_dir = array();
519
+
520
+        if (isset($app_dir[$appId])) {
521
+            return $app_dir[$appId];
522
+        }
523
+
524
+        $possibleApps = array();
525
+        foreach (OC::$APPSROOTS as $dir) {
526
+            if (file_exists($dir['path'] . '/' . $appId)) {
527
+                $possibleApps[] = $dir;
528
+            }
529
+        }
530
+
531
+        if (empty($possibleApps)) {
532
+            return false;
533
+        } elseif (count($possibleApps) === 1) {
534
+            $dir = array_shift($possibleApps);
535
+            $app_dir[$appId] = $dir;
536
+            return $dir;
537
+        } else {
538
+            $versionToLoad = array();
539
+            foreach ($possibleApps as $possibleApp) {
540
+                $version = self::getAppVersionByPath($possibleApp['path']);
541
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
542
+                    $versionToLoad = array(
543
+                        'dir' => $possibleApp,
544
+                        'version' => $version,
545
+                    );
546
+                }
547
+            }
548
+            $app_dir[$appId] = $versionToLoad['dir'];
549
+            return $versionToLoad['dir'];
550
+            //TODO - write test
551
+        }
552
+    }
553
+
554
+    /**
555
+     * Get the directory for the given app.
556
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
557
+     *
558
+     * @param string $appId
559
+     * @return string|false
560
+     */
561
+    public static function getAppPath($appId) {
562
+        if ($appId === null || trim($appId) === '') {
563
+            return false;
564
+        }
565
+
566
+        if (($dir = self::findAppInDirectories($appId)) != false) {
567
+            return $dir['path'] . '/' . $appId;
568
+        }
569
+        return false;
570
+    }
571
+
572
+    /**
573
+     * Get the path for the given app on the access
574
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
575
+     *
576
+     * @param string $appId
577
+     * @return string|false
578
+     */
579
+    public static function getAppWebPath($appId) {
580
+        if (($dir = self::findAppInDirectories($appId)) != false) {
581
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
582
+        }
583
+        return false;
584
+    }
585
+
586
+    /**
587
+     * get the last version of the app from appinfo/info.xml
588
+     *
589
+     * @param string $appId
590
+     * @param bool $useCache
591
+     * @return string
592
+     */
593
+    public static function getAppVersion($appId, $useCache = true) {
594
+        if($useCache && isset(self::$appVersion[$appId])) {
595
+            return self::$appVersion[$appId];
596
+        }
597
+
598
+        $file = self::getAppPath($appId);
599
+        self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
600
+        return self::$appVersion[$appId];
601
+    }
602
+
603
+    /**
604
+     * get app's version based on it's path
605
+     *
606
+     * @param string $path
607
+     * @return string
608
+     */
609
+    public static function getAppVersionByPath($path) {
610
+        $infoFile = $path . '/appinfo/info.xml';
611
+        $appData = self::getAppInfo($infoFile, true);
612
+        return isset($appData['version']) ? $appData['version'] : '';
613
+    }
614
+
615
+
616
+    /**
617
+     * Read all app metadata from the info.xml file
618
+     *
619
+     * @param string $appId id of the app or the path of the info.xml file
620
+     * @param bool $path
621
+     * @param string $lang
622
+     * @return array|null
623
+     * @note all data is read from info.xml, not just pre-defined fields
624
+     */
625
+    public static function getAppInfo($appId, $path = false, $lang = null) {
626
+        if ($path) {
627
+            $file = $appId;
628
+        } else {
629
+            if ($lang === null && isset(self::$appInfo[$appId])) {
630
+                return self::$appInfo[$appId];
631
+            }
632
+            $appPath = self::getAppPath($appId);
633
+            if($appPath === false) {
634
+                return null;
635
+            }
636
+            $file = $appPath . '/appinfo/info.xml';
637
+        }
638
+
639
+        $parser = new InfoParser(\OC::$server->getMemCacheFactory()->create('core.appinfo'));
640
+        $data = $parser->parse($file);
641
+
642
+        if (is_array($data)) {
643
+            $data = OC_App::parseAppInfo($data, $lang);
644
+        }
645
+        if(isset($data['ocsid'])) {
646
+            $storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
647
+            if($storedId !== '' && $storedId !== $data['ocsid']) {
648
+                $data['ocsid'] = $storedId;
649
+            }
650
+        }
651
+
652
+        if ($lang === null) {
653
+            self::$appInfo[$appId] = $data;
654
+        }
655
+
656
+        return $data;
657
+    }
658
+
659
+    /**
660
+     * Returns the navigation
661
+     *
662
+     * @return array
663
+     *
664
+     * This function returns an array containing all entries added. The
665
+     * entries are sorted by the key 'order' ascending. Additional to the keys
666
+     * given for each app the following keys exist:
667
+     *   - active: boolean, signals if the user is on this navigation entry
668
+     */
669
+    public static function getNavigation() {
670
+        $entries = OC::$server->getNavigationManager()->getAll();
671
+        return self::proceedNavigation($entries);
672
+    }
673
+
674
+    /**
675
+     * Returns the Settings Navigation
676
+     *
677
+     * @return string[]
678
+     *
679
+     * This function returns an array containing all settings pages added. The
680
+     * entries are sorted by the key 'order' ascending.
681
+     */
682
+    public static function getSettingsNavigation() {
683
+        $entries = OC::$server->getNavigationManager()->getAll('settings');
684
+        return self::proceedNavigation($entries);
685
+    }
686
+
687
+    /**
688
+     * get the id of loaded app
689
+     *
690
+     * @return string
691
+     */
692
+    public static function getCurrentApp() {
693
+        $request = \OC::$server->getRequest();
694
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
695
+        $topFolder = substr($script, 0, strpos($script, '/'));
696
+        if (empty($topFolder)) {
697
+            $path_info = $request->getPathInfo();
698
+            if ($path_info) {
699
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
700
+            }
701
+        }
702
+        if ($topFolder == 'apps') {
703
+            $length = strlen($topFolder);
704
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
705
+        } else {
706
+            return $topFolder;
707
+        }
708
+    }
709
+
710
+    /**
711
+     * @param string $type
712
+     * @return array
713
+     */
714
+    public static function getForms($type) {
715
+        $forms = array();
716
+        switch ($type) {
717
+            case 'admin':
718
+                $source = self::$adminForms;
719
+                break;
720
+            case 'personal':
721
+                $source = self::$personalForms;
722
+                break;
723
+            default:
724
+                return array();
725
+        }
726
+        foreach ($source as $form) {
727
+            $forms[] = include $form;
728
+        }
729
+        return $forms;
730
+    }
731
+
732
+    /**
733
+     * register an admin form to be shown
734
+     *
735
+     * @param string $app
736
+     * @param string $page
737
+     */
738
+    public static function registerAdmin($app, $page) {
739
+        self::$adminForms[] = $app . '/' . $page . '.php';
740
+    }
741
+
742
+    /**
743
+     * register a personal form to be shown
744
+     * @param string $app
745
+     * @param string $page
746
+     */
747
+    public static function registerPersonal($app, $page) {
748
+        self::$personalForms[] = $app . '/' . $page . '.php';
749
+    }
750
+
751
+    /**
752
+     * @param array $entry
753
+     */
754
+    public static function registerLogIn(array $entry) {
755
+        self::$altLogin[] = $entry;
756
+    }
757
+
758
+    /**
759
+     * @return array
760
+     */
761
+    public static function getAlternativeLogIns() {
762
+        return self::$altLogin;
763
+    }
764
+
765
+    /**
766
+     * get a list of all apps in the apps folder
767
+     *
768
+     * @return array an array of app names (string IDs)
769
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
770
+     */
771
+    public static function getAllApps() {
772
+
773
+        $apps = array();
774
+
775
+        foreach (OC::$APPSROOTS as $apps_dir) {
776
+            if (!is_readable($apps_dir['path'])) {
777
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
778
+                continue;
779
+            }
780
+            $dh = opendir($apps_dir['path']);
781
+
782
+            if (is_resource($dh)) {
783
+                while (($file = readdir($dh)) !== false) {
784
+
785
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
786
+
787
+                        $apps[] = $file;
788
+                    }
789
+                }
790
+            }
791
+        }
792
+
793
+        return $apps;
794
+    }
795
+
796
+    /**
797
+     * List all apps, this is used in apps.php
798
+     *
799
+     * @return array
800
+     */
801
+    public function listAllApps() {
802
+        $installedApps = OC_App::getAllApps();
803
+
804
+        //we don't want to show configuration for these
805
+        $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
806
+        $appList = array();
807
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
808
+        $urlGenerator = \OC::$server->getURLGenerator();
809
+
810
+        foreach ($installedApps as $app) {
811
+            if (array_search($app, $blacklist) === false) {
812
+
813
+                $info = OC_App::getAppInfo($app, false, $langCode);
814
+                if (!is_array($info)) {
815
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
816
+                    continue;
817
+                }
818
+
819
+                if (!isset($info['name'])) {
820
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
821
+                    continue;
822
+                }
823
+
824
+                $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
825
+                $info['groups'] = null;
826
+                if ($enabled === 'yes') {
827
+                    $active = true;
828
+                } else if ($enabled === 'no') {
829
+                    $active = false;
830
+                } else {
831
+                    $active = true;
832
+                    $info['groups'] = $enabled;
833
+                }
834
+
835
+                $info['active'] = $active;
836
+
837
+                if (self::isShipped($app)) {
838
+                    $info['internal'] = true;
839
+                    $info['level'] = self::officialApp;
840
+                    $info['removable'] = false;
841
+                } else {
842
+                    $info['internal'] = false;
843
+                    $info['removable'] = true;
844
+                }
845
+
846
+                $appPath = self::getAppPath($app);
847
+                if($appPath !== false) {
848
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
849
+                    if (file_exists($appIcon)) {
850
+                        $info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app . '.svg');
851
+                        $info['previewAsIcon'] = true;
852
+                    } else {
853
+                        $appIcon = $appPath . '/img/app.svg';
854
+                        if (file_exists($appIcon)) {
855
+                            $info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, 'app.svg');
856
+                            $info['previewAsIcon'] = true;
857
+                        }
858
+                    }
859
+                }
860
+                // fix documentation
861
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
862
+                    foreach ($info['documentation'] as $key => $url) {
863
+                        // If it is not an absolute URL we assume it is a key
864
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
865
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
866
+                            $url = $urlGenerator->linkToDocs($url);
867
+                        }
868
+
869
+                        $info['documentation'][$key] = $url;
870
+                    }
871
+                }
872
+
873
+                $info['version'] = OC_App::getAppVersion($app);
874
+                $appList[] = $info;
875
+            }
876
+        }
877
+
878
+        return $appList;
879
+    }
880
+
881
+    /**
882
+     * Returns the internal app ID or false
883
+     * @param string $ocsID
884
+     * @return string|false
885
+     */
886
+    public static function getInternalAppIdByOcs($ocsID) {
887
+        if(is_numeric($ocsID)) {
888
+            $idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
889
+            if(array_search($ocsID, $idArray)) {
890
+                return array_search($ocsID, $idArray);
891
+            }
892
+        }
893
+        return false;
894
+    }
895
+
896
+    public static function shouldUpgrade($app) {
897
+        $versions = self::getAppVersions();
898
+        $currentVersion = OC_App::getAppVersion($app);
899
+        if ($currentVersion && isset($versions[$app])) {
900
+            $installedVersion = $versions[$app];
901
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
902
+                return true;
903
+            }
904
+        }
905
+        return false;
906
+    }
907
+
908
+    /**
909
+     * Adjust the number of version parts of $version1 to match
910
+     * the number of version parts of $version2.
911
+     *
912
+     * @param string $version1 version to adjust
913
+     * @param string $version2 version to take the number of parts from
914
+     * @return string shortened $version1
915
+     */
916
+    private static function adjustVersionParts($version1, $version2) {
917
+        $version1 = explode('.', $version1);
918
+        $version2 = explode('.', $version2);
919
+        // reduce $version1 to match the number of parts in $version2
920
+        while (count($version1) > count($version2)) {
921
+            array_pop($version1);
922
+        }
923
+        // if $version1 does not have enough parts, add some
924
+        while (count($version1) < count($version2)) {
925
+            $version1[] = '0';
926
+        }
927
+        return implode('.', $version1);
928
+    }
929
+
930
+    /**
931
+     * Check whether the current ownCloud version matches the given
932
+     * application's version requirements.
933
+     *
934
+     * The comparison is made based on the number of parts that the
935
+     * app info version has. For example for ownCloud 6.0.3 if the
936
+     * app info version is expecting version 6.0, the comparison is
937
+     * made on the first two parts of the ownCloud version.
938
+     * This means that it's possible to specify "requiremin" => 6
939
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
940
+     *
941
+     * @param string $ocVersion ownCloud version to check against
942
+     * @param array $appInfo app info (from xml)
943
+     *
944
+     * @return boolean true if compatible, otherwise false
945
+     */
946
+    public static function isAppCompatible($ocVersion, $appInfo) {
947
+        $requireMin = '';
948
+        $requireMax = '';
949
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
950
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
951
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
952
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
953
+        } else if (isset($appInfo['requiremin'])) {
954
+            $requireMin = $appInfo['requiremin'];
955
+        } else if (isset($appInfo['require'])) {
956
+            $requireMin = $appInfo['require'];
957
+        }
958
+
959
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
960
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
961
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
962
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
963
+        } else if (isset($appInfo['requiremax'])) {
964
+            $requireMax = $appInfo['requiremax'];
965
+        }
966
+
967
+        if (is_array($ocVersion)) {
968
+            $ocVersion = implode('.', $ocVersion);
969
+        }
970
+
971
+        if (!empty($requireMin)
972
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
973
+        ) {
974
+
975
+            return false;
976
+        }
977
+
978
+        if (!empty($requireMax)
979
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
980
+        ) {
981
+            return false;
982
+        }
983
+
984
+        return true;
985
+    }
986
+
987
+    /**
988
+     * get the installed version of all apps
989
+     */
990
+    public static function getAppVersions() {
991
+        static $versions;
992
+
993
+        if(!$versions) {
994
+            $appConfig = \OC::$server->getAppConfig();
995
+            $versions = $appConfig->getValues(false, 'installed_version');
996
+        }
997
+        return $versions;
998
+    }
999
+
1000
+    /**
1001
+     * @param string $app
1002
+     * @param \OCP\IConfig $config
1003
+     * @param \OCP\IL10N $l
1004
+     * @return bool
1005
+     *
1006
+     * @throws Exception if app is not compatible with this version of ownCloud
1007
+     * @throws Exception if no app-name was specified
1008
+     */
1009
+    public function installApp($app,
1010
+                                \OCP\IConfig $config,
1011
+                                \OCP\IL10N $l) {
1012
+        if ($app !== false) {
1013
+            // check if the app is compatible with this version of ownCloud
1014
+            $info = self::getAppInfo($app);
1015
+            if(!is_array($info)) {
1016
+                throw new \Exception(
1017
+                    $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1018
+                        [$info['name']]
1019
+                    )
1020
+                );
1021
+            }
1022
+
1023
+            $version = \OCP\Util::getVersion();
1024
+            if (!self::isAppCompatible($version, $info)) {
1025
+                throw new \Exception(
1026
+                    $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1027
+                        array($info['name'])
1028
+                    )
1029
+                );
1030
+            }
1031
+
1032
+            // check for required dependencies
1033
+            self::checkAppDependencies($config, $l, $info);
1034
+
1035
+            $config->setAppValue($app, 'enabled', 'yes');
1036
+            if (isset($appData['id'])) {
1037
+                $config->setAppValue($app, 'ocsid', $appData['id']);
1038
+            }
1039
+
1040
+            if(isset($info['settings']) && is_array($info['settings'])) {
1041
+                $appPath = self::getAppPath($app);
1042
+                self::registerAutoloading($app, $appPath);
1043
+                \OC::$server->getSettingsManager()->setupSettings($info['settings']);
1044
+            }
1045
+
1046
+            \OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1047
+        } else {
1048
+            if(empty($appName) ) {
1049
+                throw new \Exception($l->t("No app name specified"));
1050
+            } else {
1051
+                throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1052
+            }
1053
+        }
1054
+
1055
+        return $app;
1056
+    }
1057
+
1058
+    /**
1059
+     * update the database for the app and call the update script
1060
+     *
1061
+     * @param string $appId
1062
+     * @return bool
1063
+     */
1064
+    public static function updateApp($appId) {
1065
+        $appPath = self::getAppPath($appId);
1066
+        if($appPath === false) {
1067
+            return false;
1068
+        }
1069
+        $appData = self::getAppInfo($appId);
1070
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1071
+        if (file_exists($appPath . '/appinfo/database.xml')) {
1072
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1073
+        }
1074
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1075
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1076
+        unset(self::$appVersion[$appId]);
1077
+        // run upgrade code
1078
+        if (file_exists($appPath . '/appinfo/update.php')) {
1079
+            self::loadApp($appId);
1080
+            include $appPath . '/appinfo/update.php';
1081
+        }
1082
+        self::setupBackgroundJobs($appData['background-jobs']);
1083
+        if(isset($appData['settings']) && is_array($appData['settings'])) {
1084
+            $appPath = self::getAppPath($appId);
1085
+            self::registerAutoloading($appId, $appPath);
1086
+            \OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1087
+        }
1088
+
1089
+        //set remote/public handlers
1090
+        if (array_key_exists('ocsid', $appData)) {
1091
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1092
+        } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1093
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1094
+        }
1095
+        foreach ($appData['remote'] as $name => $path) {
1096
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1097
+        }
1098
+        foreach ($appData['public'] as $name => $path) {
1099
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1100
+        }
1101
+
1102
+        self::setAppTypes($appId);
1103
+
1104
+        $version = \OC_App::getAppVersion($appId);
1105
+        \OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1106
+
1107
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1108
+            ManagerEvent::EVENT_APP_UPDATE, $appId
1109
+        ));
1110
+
1111
+        return true;
1112
+    }
1113
+
1114
+    /**
1115
+     * @param string $appId
1116
+     * @param string[] $steps
1117
+     * @throws \OC\NeedsUpdateException
1118
+     */
1119
+    public static function executeRepairSteps($appId, array $steps) {
1120
+        if (empty($steps)) {
1121
+            return;
1122
+        }
1123
+        // load the app
1124
+        self::loadApp($appId);
1125
+
1126
+        $dispatcher = OC::$server->getEventDispatcher();
1127
+
1128
+        // load the steps
1129
+        $r = new Repair([], $dispatcher);
1130
+        foreach ($steps as $step) {
1131
+            try {
1132
+                $r->addStep($step);
1133
+            } catch (Exception $ex) {
1134
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1135
+                \OC::$server->getLogger()->logException($ex);
1136
+            }
1137
+        }
1138
+        // run the steps
1139
+        $r->run();
1140
+    }
1141
+
1142
+    public static function setupBackgroundJobs(array $jobs) {
1143
+        $queue = \OC::$server->getJobList();
1144
+        foreach ($jobs as $job) {
1145
+            $queue->add($job);
1146
+        }
1147
+    }
1148
+
1149
+    /**
1150
+     * @param string $appId
1151
+     * @param string[] $steps
1152
+     */
1153
+    private static function setupLiveMigrations($appId, array $steps) {
1154
+        $queue = \OC::$server->getJobList();
1155
+        foreach ($steps as $step) {
1156
+            $queue->add('OC\Migration\BackgroundRepair', [
1157
+                'app' => $appId,
1158
+                'step' => $step]);
1159
+        }
1160
+    }
1161
+
1162
+    /**
1163
+     * @param string $appId
1164
+     * @return \OC\Files\View|false
1165
+     */
1166
+    public static function getStorage($appId) {
1167
+        if (OC_App::isEnabled($appId)) { //sanity check
1168
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1169
+                $view = new \OC\Files\View('/' . OC_User::getUser());
1170
+                if (!$view->file_exists($appId)) {
1171
+                    $view->mkdir($appId);
1172
+                }
1173
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1174
+            } else {
1175
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1176
+                return false;
1177
+            }
1178
+        } else {
1179
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1180
+            return false;
1181
+        }
1182
+    }
1183
+
1184
+    protected static function findBestL10NOption($options, $lang) {
1185
+        $fallback = $similarLangFallback = $englishFallback = false;
1186
+
1187
+        $lang = strtolower($lang);
1188
+        $similarLang = $lang;
1189
+        if (strpos($similarLang, '_')) {
1190
+            // For "de_DE" we want to find "de" and the other way around
1191
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1192
+        }
1193
+
1194
+        foreach ($options as $option) {
1195
+            if (is_array($option)) {
1196
+                if ($fallback === false) {
1197
+                    $fallback = $option['@value'];
1198
+                }
1199
+
1200
+                if (!isset($option['@attributes']['lang'])) {
1201
+                    continue;
1202
+                }
1203
+
1204
+                $attributeLang = strtolower($option['@attributes']['lang']);
1205
+                if ($attributeLang === $lang) {
1206
+                    return $option['@value'];
1207
+                }
1208
+
1209
+                if ($attributeLang === $similarLang) {
1210
+                    $similarLangFallback = $option['@value'];
1211
+                } else if (strpos($attributeLang, $similarLang . '_') === 0) {
1212
+                    if ($similarLangFallback === false) {
1213
+                        $similarLangFallback =  $option['@value'];
1214
+                    }
1215
+                }
1216
+            } else {
1217
+                $englishFallback = $option;
1218
+            }
1219
+        }
1220
+
1221
+        if ($similarLangFallback !== false) {
1222
+            return $similarLangFallback;
1223
+        } else if ($englishFallback !== false) {
1224
+            return $englishFallback;
1225
+        }
1226
+        return (string) $fallback;
1227
+    }
1228
+
1229
+    /**
1230
+     * parses the app data array and enhanced the 'description' value
1231
+     *
1232
+     * @param array $data the app data
1233
+     * @param string $lang
1234
+     * @return array improved app data
1235
+     */
1236
+    public static function parseAppInfo(array $data, $lang = null) {
1237
+
1238
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1239
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1240
+        }
1241
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1242
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1243
+        }
1244
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1245
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1246
+        } else if (isset($data['description']) && is_string($data['description'])) {
1247
+            $data['description'] = trim($data['description']);
1248
+        } else  {
1249
+            $data['description'] = '';
1250
+        }
1251
+
1252
+        return $data;
1253
+    }
1254
+
1255
+    /**
1256
+     * @param \OCP\IConfig $config
1257
+     * @param \OCP\IL10N $l
1258
+     * @param array $info
1259
+     * @throws \Exception
1260
+     */
1261
+    protected static function checkAppDependencies($config, $l, $info) {
1262
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1263
+        $missing = $dependencyAnalyzer->analyze($info);
1264
+        if (!empty($missing)) {
1265
+            $missingMsg = join(PHP_EOL, $missing);
1266
+            throw new \Exception(
1267
+                $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1268
+                    [$info['name'], $missingMsg]
1269
+                )
1270
+            );
1271
+        }
1272
+    }
1273 1273
 }
Please login to merge, or discard this patch.
settings/ajax/disableapp.php 2 patches
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -26,19 +26,19 @@
 block discarded – undo
26 26
 
27 27
 $lastConfirm = (int) \OC::$server->getSession()->get('last-password-confirm');
28 28
 if ($lastConfirm < (time() - 30 * 60 + 15)) { // allow 15 seconds delay
29
-	$l = \OC::$server->getL10N('core');
30
-	OC_JSON::error(array( 'data' => array( 'message' => $l->t('Password confirmation is required'))));
31
-	exit();
29
+    $l = \OC::$server->getL10N('core');
30
+    OC_JSON::error(array( 'data' => array( 'message' => $l->t('Password confirmation is required'))));
31
+    exit();
32 32
 }
33 33
 
34 34
 if (!array_key_exists('appid', $_POST)) {
35
-	OC_JSON::error();
36
-	exit;
35
+    OC_JSON::error();
36
+    exit;
37 37
 }
38 38
 
39 39
 $appIds = (array)$_POST['appid'];
40 40
 foreach($appIds as $appId) {
41
-	$appId = OC_App::cleanAppId($appId);
42
-	OC_App::disable($appId);
41
+    $appId = OC_App::cleanAppId($appId);
42
+    OC_App::disable($appId);
43 43
 }
44 44
 OC_JSON::success();
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -27,7 +27,7 @@  discard block
 block discarded – undo
27 27
 $lastConfirm = (int) \OC::$server->getSession()->get('last-password-confirm');
28 28
 if ($lastConfirm < (time() - 30 * 60 + 15)) { // allow 15 seconds delay
29 29
 	$l = \OC::$server->getL10N('core');
30
-	OC_JSON::error(array( 'data' => array( 'message' => $l->t('Password confirmation is required'))));
30
+	OC_JSON::error(array('data' => array('message' => $l->t('Password confirmation is required'))));
31 31
 	exit();
32 32
 }
33 33
 
@@ -36,8 +36,8 @@  discard block
 block discarded – undo
36 36
 	exit;
37 37
 }
38 38
 
39
-$appIds = (array)$_POST['appid'];
40
-foreach($appIds as $appId) {
39
+$appIds = (array) $_POST['appid'];
40
+foreach ($appIds as $appId) {
41 41
 	$appId = OC_App::cleanAppId($appId);
42 42
 	OC_App::disable($appId);
43 43
 }
Please login to merge, or discard this patch.