Completed
Pull Request — master (#7264)
by Morris
14:01
created
apps/updatenotification/lib/Notification/BackgroundJob.php 1 patch
Indentation   +228 added lines, -228 removed lines patch added patch discarded remove patch
@@ -36,232 +36,232 @@
 block discarded – undo
36 36
 
37 37
 class BackgroundJob extends TimedJob {
38 38
 
39
-	protected $connectionNotifications = [3, 7, 14, 30];
40
-
41
-	/** @var IConfig */
42
-	protected $config;
43
-
44
-	/** @var IManager */
45
-	protected $notificationManager;
46
-
47
-	/** @var IGroupManager */
48
-	protected $groupManager;
49
-
50
-	/** @var IAppManager */
51
-	protected $appManager;
52
-
53
-	/** @var IClientService */
54
-	protected $client;
55
-
56
-	/** @var Installer */
57
-	protected $installer;
58
-
59
-	/** @var string[] */
60
-	protected $users;
61
-
62
-	/**
63
-	 * NotificationBackgroundJob constructor.
64
-	 *
65
-	 * @param IConfig $config
66
-	 * @param IManager $notificationManager
67
-	 * @param IGroupManager $groupManager
68
-	 * @param IAppManager $appManager
69
-	 * @param IClientService $client
70
-	 * @param Installer $installer
71
-	 */
72
-	public function __construct(IConfig $config, IManager $notificationManager, IGroupManager $groupManager, IAppManager $appManager, IClientService $client, Installer $installer) {
73
-		// Run once a day
74
-		$this->setInterval(60 * 60 * 24);
75
-
76
-		$this->config = $config;
77
-		$this->notificationManager = $notificationManager;
78
-		$this->groupManager = $groupManager;
79
-		$this->appManager = $appManager;
80
-		$this->client = $client;
81
-		$this->installer = $installer;
82
-	}
83
-
84
-	protected function run($argument) {
85
-		$this->checkCoreUpdate();
86
-		$this->checkAppUpdates();
87
-	}
88
-
89
-	/**
90
-	 * Check for ownCloud update
91
-	 */
92
-	protected function checkCoreUpdate() {
93
-		if (in_array($this->getChannel(), ['daily', 'git'], true)) {
94
-			// "These aren't the update channels you're looking for." - Ben Obi-Wan Kenobi
95
-			return;
96
-		}
97
-
98
-		$updater = $this->createVersionCheck();
99
-
100
-		$status = $updater->check();
101
-		if ($status === false) {
102
-			$errors = 1 + (int) $this->config->getAppValue('updatenotification', 'update_check_errors', 0);
103
-			$this->config->setAppValue('updatenotification', 'update_check_errors', $errors);
104
-
105
-			if (in_array($errors, $this->connectionNotifications, true)) {
106
-				$this->sendErrorNotifications($errors);
107
-			}
108
-		} else if (is_array($status)) {
109
-			$this->config->setAppValue('updatenotification', 'update_check_errors', 0);
110
-			$this->clearErrorNotifications();
111
-
112
-			if (isset($status['version'])) {
113
-				$this->createNotifications('core', $status['version'], $status['versionstring']);
114
-			}
115
-		}
116
-	}
117
-
118
-	/**
119
-	 * Send a message to the admin when the update server could not be reached
120
-	 * @param int $numDays
121
-	 */
122
-	protected function sendErrorNotifications($numDays) {
123
-		$this->clearErrorNotifications();
124
-
125
-		$notification = $this->notificationManager->createNotification();
126
-		try {
127
-			$notification->setApp('updatenotification')
128
-				->setDateTime(new \DateTime())
129
-				->setObject('updatenotification', 'error')
130
-				->setSubject('connection_error', ['days' => $numDays]);
131
-
132
-			foreach ($this->getUsersToNotify() as $uid) {
133
-				$notification->setUser($uid);
134
-				$this->notificationManager->notify($notification);
135
-			}
136
-		} catch (\InvalidArgumentException $e) {
137
-			return;
138
-		}
139
-	}
140
-
141
-	/**
142
-	 * Remove error notifications again
143
-	 */
144
-	protected function clearErrorNotifications() {
145
-		$notification = $this->notificationManager->createNotification();
146
-		try {
147
-			$notification->setApp('updatenotification')
148
-				->setSubject('connection_error')
149
-				->setObject('updatenotification', 'error');
150
-		} catch (\InvalidArgumentException $e) {
151
-			return;
152
-		}
153
-		$this->notificationManager->markProcessed($notification);
154
-	}
155
-
156
-	/**
157
-	 * Check all installed apps for updates
158
-	 */
159
-	protected function checkAppUpdates() {
160
-		$apps = $this->appManager->getInstalledApps();
161
-		foreach ($apps as $app) {
162
-			$update = $this->isUpdateAvailable($app);
163
-			if ($update !== false) {
164
-				$this->createNotifications($app, $update);
165
-			}
166
-		}
167
-	}
168
-
169
-	/**
170
-	 * Create notifications for this app version
171
-	 *
172
-	 * @param string $app
173
-	 * @param string $version
174
-	 * @param string $visibleVersion
175
-	 */
176
-	protected function createNotifications($app, $version, $visibleVersion = '') {
177
-		$lastNotification = $this->config->getAppValue('updatenotification', $app, false);
178
-		if ($lastNotification === $version) {
179
-			// We already notified about this update
180
-			return;
181
-		} else if ($lastNotification !== false) {
182
-			// Delete old updates
183
-			$this->deleteOutdatedNotifications($app, $lastNotification);
184
-		}
185
-
186
-
187
-		$notification = $this->notificationManager->createNotification();
188
-		$notification->setApp('updatenotification')
189
-			->setDateTime(new \DateTime())
190
-			->setObject($app, $version);
191
-
192
-		if ($visibleVersion !== '') {
193
-			$notification->setSubject('update_available', ['version' => $visibleVersion]);
194
-		} else {
195
-			$notification->setSubject('update_available');
196
-		}
197
-
198
-		foreach ($this->getUsersToNotify() as $uid) {
199
-			$notification->setUser($uid);
200
-			$this->notificationManager->notify($notification);
201
-		}
202
-
203
-		$this->config->setAppValue('updatenotification', $app, $version);
204
-	}
205
-
206
-	/**
207
-	 * @return string[]
208
-	 */
209
-	protected function getUsersToNotify() {
210
-		if ($this->users !== null) {
211
-			return $this->users;
212
-		}
213
-
214
-		$notifyGroups = json_decode($this->config->getAppValue('updatenotification', 'notify_groups', '["admin"]'), true);
215
-		$this->users = [];
216
-		foreach ($notifyGroups as $group) {
217
-			$groupToNotify = $this->groupManager->get($group);
218
-			if ($groupToNotify instanceof IGroup) {
219
-				foreach ($groupToNotify->getUsers() as $user) {
220
-					$this->users[$user->getUID()] = true;
221
-				}
222
-			}
223
-		}
224
-
225
-		$this->users = array_keys($this->users);
226
-
227
-		return $this->users;
228
-	}
229
-
230
-	/**
231
-	 * Delete notifications for old updates
232
-	 *
233
-	 * @param string $app
234
-	 * @param string $version
235
-	 */
236
-	protected function deleteOutdatedNotifications($app, $version) {
237
-		$notification = $this->notificationManager->createNotification();
238
-		$notification->setApp('updatenotification')
239
-			->setObject($app, $version);
240
-		$this->notificationManager->markProcessed($notification);
241
-	}
242
-
243
-	/**
244
-	 * @return VersionCheck
245
-	 */
246
-	protected function createVersionCheck() {
247
-		return new VersionCheck(
248
-			$this->client,
249
-			$this->config
250
-		);
251
-	}
252
-
253
-	/**
254
-	 * @return string
255
-	 */
256
-	protected function getChannel() {
257
-		return \OC_Util::getChannel();
258
-	}
259
-
260
-	/**
261
-	 * @param string $app
262
-	 * @return string|false
263
-	 */
264
-	protected function isUpdateAvailable($app) {
265
-		return $this->installer->isUpdateAvailable($app);
266
-	}
39
+    protected $connectionNotifications = [3, 7, 14, 30];
40
+
41
+    /** @var IConfig */
42
+    protected $config;
43
+
44
+    /** @var IManager */
45
+    protected $notificationManager;
46
+
47
+    /** @var IGroupManager */
48
+    protected $groupManager;
49
+
50
+    /** @var IAppManager */
51
+    protected $appManager;
52
+
53
+    /** @var IClientService */
54
+    protected $client;
55
+
56
+    /** @var Installer */
57
+    protected $installer;
58
+
59
+    /** @var string[] */
60
+    protected $users;
61
+
62
+    /**
63
+     * NotificationBackgroundJob constructor.
64
+     *
65
+     * @param IConfig $config
66
+     * @param IManager $notificationManager
67
+     * @param IGroupManager $groupManager
68
+     * @param IAppManager $appManager
69
+     * @param IClientService $client
70
+     * @param Installer $installer
71
+     */
72
+    public function __construct(IConfig $config, IManager $notificationManager, IGroupManager $groupManager, IAppManager $appManager, IClientService $client, Installer $installer) {
73
+        // Run once a day
74
+        $this->setInterval(60 * 60 * 24);
75
+
76
+        $this->config = $config;
77
+        $this->notificationManager = $notificationManager;
78
+        $this->groupManager = $groupManager;
79
+        $this->appManager = $appManager;
80
+        $this->client = $client;
81
+        $this->installer = $installer;
82
+    }
83
+
84
+    protected function run($argument) {
85
+        $this->checkCoreUpdate();
86
+        $this->checkAppUpdates();
87
+    }
88
+
89
+    /**
90
+     * Check for ownCloud update
91
+     */
92
+    protected function checkCoreUpdate() {
93
+        if (in_array($this->getChannel(), ['daily', 'git'], true)) {
94
+            // "These aren't the update channels you're looking for." - Ben Obi-Wan Kenobi
95
+            return;
96
+        }
97
+
98
+        $updater = $this->createVersionCheck();
99
+
100
+        $status = $updater->check();
101
+        if ($status === false) {
102
+            $errors = 1 + (int) $this->config->getAppValue('updatenotification', 'update_check_errors', 0);
103
+            $this->config->setAppValue('updatenotification', 'update_check_errors', $errors);
104
+
105
+            if (in_array($errors, $this->connectionNotifications, true)) {
106
+                $this->sendErrorNotifications($errors);
107
+            }
108
+        } else if (is_array($status)) {
109
+            $this->config->setAppValue('updatenotification', 'update_check_errors', 0);
110
+            $this->clearErrorNotifications();
111
+
112
+            if (isset($status['version'])) {
113
+                $this->createNotifications('core', $status['version'], $status['versionstring']);
114
+            }
115
+        }
116
+    }
117
+
118
+    /**
119
+     * Send a message to the admin when the update server could not be reached
120
+     * @param int $numDays
121
+     */
122
+    protected function sendErrorNotifications($numDays) {
123
+        $this->clearErrorNotifications();
124
+
125
+        $notification = $this->notificationManager->createNotification();
126
+        try {
127
+            $notification->setApp('updatenotification')
128
+                ->setDateTime(new \DateTime())
129
+                ->setObject('updatenotification', 'error')
130
+                ->setSubject('connection_error', ['days' => $numDays]);
131
+
132
+            foreach ($this->getUsersToNotify() as $uid) {
133
+                $notification->setUser($uid);
134
+                $this->notificationManager->notify($notification);
135
+            }
136
+        } catch (\InvalidArgumentException $e) {
137
+            return;
138
+        }
139
+    }
140
+
141
+    /**
142
+     * Remove error notifications again
143
+     */
144
+    protected function clearErrorNotifications() {
145
+        $notification = $this->notificationManager->createNotification();
146
+        try {
147
+            $notification->setApp('updatenotification')
148
+                ->setSubject('connection_error')
149
+                ->setObject('updatenotification', 'error');
150
+        } catch (\InvalidArgumentException $e) {
151
+            return;
152
+        }
153
+        $this->notificationManager->markProcessed($notification);
154
+    }
155
+
156
+    /**
157
+     * Check all installed apps for updates
158
+     */
159
+    protected function checkAppUpdates() {
160
+        $apps = $this->appManager->getInstalledApps();
161
+        foreach ($apps as $app) {
162
+            $update = $this->isUpdateAvailable($app);
163
+            if ($update !== false) {
164
+                $this->createNotifications($app, $update);
165
+            }
166
+        }
167
+    }
168
+
169
+    /**
170
+     * Create notifications for this app version
171
+     *
172
+     * @param string $app
173
+     * @param string $version
174
+     * @param string $visibleVersion
175
+     */
176
+    protected function createNotifications($app, $version, $visibleVersion = '') {
177
+        $lastNotification = $this->config->getAppValue('updatenotification', $app, false);
178
+        if ($lastNotification === $version) {
179
+            // We already notified about this update
180
+            return;
181
+        } else if ($lastNotification !== false) {
182
+            // Delete old updates
183
+            $this->deleteOutdatedNotifications($app, $lastNotification);
184
+        }
185
+
186
+
187
+        $notification = $this->notificationManager->createNotification();
188
+        $notification->setApp('updatenotification')
189
+            ->setDateTime(new \DateTime())
190
+            ->setObject($app, $version);
191
+
192
+        if ($visibleVersion !== '') {
193
+            $notification->setSubject('update_available', ['version' => $visibleVersion]);
194
+        } else {
195
+            $notification->setSubject('update_available');
196
+        }
197
+
198
+        foreach ($this->getUsersToNotify() as $uid) {
199
+            $notification->setUser($uid);
200
+            $this->notificationManager->notify($notification);
201
+        }
202
+
203
+        $this->config->setAppValue('updatenotification', $app, $version);
204
+    }
205
+
206
+    /**
207
+     * @return string[]
208
+     */
209
+    protected function getUsersToNotify() {
210
+        if ($this->users !== null) {
211
+            return $this->users;
212
+        }
213
+
214
+        $notifyGroups = json_decode($this->config->getAppValue('updatenotification', 'notify_groups', '["admin"]'), true);
215
+        $this->users = [];
216
+        foreach ($notifyGroups as $group) {
217
+            $groupToNotify = $this->groupManager->get($group);
218
+            if ($groupToNotify instanceof IGroup) {
219
+                foreach ($groupToNotify->getUsers() as $user) {
220
+                    $this->users[$user->getUID()] = true;
221
+                }
222
+            }
223
+        }
224
+
225
+        $this->users = array_keys($this->users);
226
+
227
+        return $this->users;
228
+    }
229
+
230
+    /**
231
+     * Delete notifications for old updates
232
+     *
233
+     * @param string $app
234
+     * @param string $version
235
+     */
236
+    protected function deleteOutdatedNotifications($app, $version) {
237
+        $notification = $this->notificationManager->createNotification();
238
+        $notification->setApp('updatenotification')
239
+            ->setObject($app, $version);
240
+        $this->notificationManager->markProcessed($notification);
241
+    }
242
+
243
+    /**
244
+     * @return VersionCheck
245
+     */
246
+    protected function createVersionCheck() {
247
+        return new VersionCheck(
248
+            $this->client,
249
+            $this->config
250
+        );
251
+    }
252
+
253
+    /**
254
+     * @return string
255
+     */
256
+    protected function getChannel() {
257
+        return \OC_Util::getChannel();
258
+    }
259
+
260
+    /**
261
+     * @param string $app
262
+     * @return string|false
263
+     */
264
+    protected function isUpdateAvailable($app) {
265
+        return $this->installer->isUpdateAvailable($app);
266
+    }
267 267
 }
Please login to merge, or discard this patch.
settings/Controller/AppSettingsController.php 2 patches
Indentation   +411 added lines, -411 removed lines patch added patch discarded remove patch
@@ -53,415 +53,415 @@
 block discarded – undo
53 53
  * @package OC\Settings\Controller
54 54
  */
55 55
 class AppSettingsController extends Controller {
56
-	const CAT_ENABLED = 0;
57
-	const CAT_DISABLED = 1;
58
-	const CAT_ALL_INSTALLED = 2;
59
-	const CAT_APP_BUNDLES = 3;
60
-	const CAT_UPDATES = 4;
61
-
62
-	/** @var \OCP\IL10N */
63
-	private $l10n;
64
-	/** @var IConfig */
65
-	private $config;
66
-	/** @var INavigationManager */
67
-	private $navigationManager;
68
-	/** @var IAppManager */
69
-	private $appManager;
70
-	/** @var CategoryFetcher */
71
-	private $categoryFetcher;
72
-	/** @var AppFetcher */
73
-	private $appFetcher;
74
-	/** @var IFactory */
75
-	private $l10nFactory;
76
-	/** @var BundleFetcher */
77
-	private $bundleFetcher;
78
-	/** @var Installer */
79
-	private $installer;
80
-
81
-	/**
82
-	 * @param string $appName
83
-	 * @param IRequest $request
84
-	 * @param IL10N $l10n
85
-	 * @param IConfig $config
86
-	 * @param INavigationManager $navigationManager
87
-	 * @param IAppManager $appManager
88
-	 * @param CategoryFetcher $categoryFetcher
89
-	 * @param AppFetcher $appFetcher
90
-	 * @param IFactory $l10nFactory
91
-	 * @param BundleFetcher $bundleFetcher
92
-	 * @param Installer $installer
93
-	 */
94
-	public function __construct($appName,
95
-								IRequest $request,
96
-								IL10N $l10n,
97
-								IConfig $config,
98
-								INavigationManager $navigationManager,
99
-								IAppManager $appManager,
100
-								CategoryFetcher $categoryFetcher,
101
-								AppFetcher $appFetcher,
102
-								IFactory $l10nFactory,
103
-								BundleFetcher $bundleFetcher,
104
-								Installer $installer) {
105
-		parent::__construct($appName, $request);
106
-		$this->l10n = $l10n;
107
-		$this->config = $config;
108
-		$this->navigationManager = $navigationManager;
109
-		$this->appManager = $appManager;
110
-		$this->categoryFetcher = $categoryFetcher;
111
-		$this->appFetcher = $appFetcher;
112
-		$this->l10nFactory = $l10nFactory;
113
-		$this->bundleFetcher = $bundleFetcher;
114
-		$this->installer = $installer;
115
-	}
116
-
117
-	/**
118
-	 * @NoCSRFRequired
119
-	 *
120
-	 * @param string $category
121
-	 * @return TemplateResponse
122
-	 */
123
-	public function viewApps($category = '') {
124
-		if ($category === '') {
125
-			$category = 'installed';
126
-		}
127
-
128
-		$params = [];
129
-		$params['category'] = $category;
130
-		$params['appstoreEnabled'] = $this->config->getSystemValue('appstoreenabled', true) === true;
131
-		$this->navigationManager->setActiveEntry('core_apps');
132
-
133
-		$templateResponse = new TemplateResponse($this->appName, 'apps', $params, 'user');
134
-		$policy = new ContentSecurityPolicy();
135
-		$policy->addAllowedImageDomain('https://usercontent.apps.nextcloud.com');
136
-		$templateResponse->setContentSecurityPolicy($policy);
137
-
138
-		return $templateResponse;
139
-	}
140
-
141
-	private function getAllCategories() {
142
-		$currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2);
143
-
144
-		$updateCount = count($this->getAppsWithUpdates());
145
-		$formattedCategories = [
146
-			['id' => self::CAT_ALL_INSTALLED, 'ident' => 'installed', 'displayName' => (string)$this->l10n->t('Your apps')],
147
-			['id' => self::CAT_UPDATES, 'ident' => 'updates', 'displayName' => (string)$this->l10n->t('Updates'), 'counter' => $updateCount],
148
-			['id' => self::CAT_ENABLED, 'ident' => 'enabled', 'displayName' => (string)$this->l10n->t('Enabled apps')],
149
-			['id' => self::CAT_DISABLED, 'ident' => 'disabled', 'displayName' => (string)$this->l10n->t('Disabled apps')],
150
-			['id' => self::CAT_APP_BUNDLES, 'ident' => 'app-bundles', 'displayName' => (string)$this->l10n->t('App bundles')],
151
-		];
152
-		$categories = $this->categoryFetcher->get();
153
-		foreach($categories as $category) {
154
-			$formattedCategories[] = [
155
-				'id' => $category['id'],
156
-				'ident' => $category['id'],
157
-				'displayName' => isset($category['translations'][$currentLanguage]['name']) ? $category['translations'][$currentLanguage]['name'] : $category['translations']['en']['name'],
158
-			];
159
-		}
160
-
161
-		return $formattedCategories;
162
-	}
163
-
164
-	/**
165
-	 * Get all available categories
166
-	 *
167
-	 * @return JSONResponse
168
-	 */
169
-	public function listCategories() {
170
-		return new JSONResponse($this->getAllCategories());
171
-	}
172
-
173
-	/**
174
-	 * Get all apps for a category
175
-	 *
176
-	 * @param string $requestedCategory
177
-	 * @return array
178
-	 */
179
-	private function getAppsForCategory($requestedCategory) {
180
-		$versionParser = new VersionParser();
181
-		$formattedApps = [];
182
-		$apps = $this->appFetcher->get();
183
-		foreach($apps as $app) {
184
-			if (isset($app['isFeatured'])) {
185
-				$app['featured'] = $app['isFeatured'];
186
-			}
187
-
188
-			// Skip all apps not in the requested category
189
-			$isInCategory = false;
190
-			foreach($app['categories'] as $category) {
191
-				if($category === $requestedCategory) {
192
-					$isInCategory = true;
193
-				}
194
-			}
195
-			if(!$isInCategory) {
196
-				continue;
197
-			}
198
-
199
-			$nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']);
200
-			$nextCloudVersionDependencies = [];
201
-			if($nextCloudVersion->getMinimumVersion() !== '') {
202
-				$nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion();
203
-			}
204
-			if($nextCloudVersion->getMaximumVersion() !== '') {
205
-				$nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion();
206
-			}
207
-			$phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']);
208
-			$existsLocally = (\OC_App::getAppPath($app['id']) !== false) ? true : false;
209
-			$phpDependencies = [];
210
-			if($phpVersion->getMinimumVersion() !== '') {
211
-				$phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion();
212
-			}
213
-			if($phpVersion->getMaximumVersion() !== '') {
214
-				$phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion();
215
-			}
216
-			if(isset($app['releases'][0]['minIntSize'])) {
217
-				$phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize'];
218
-			}
219
-			$authors = '';
220
-			foreach($app['authors'] as $key => $author) {
221
-				$authors .= $author['name'];
222
-				if($key !== count($app['authors']) - 1) {
223
-					$authors .= ', ';
224
-				}
225
-			}
226
-
227
-			$currentLanguage = substr(\OC::$server->getL10NFactory()->findLanguage(), 0, 2);
228
-			$enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no');
229
-			$groups = null;
230
-			if($enabledValue !== 'no' && $enabledValue !== 'yes') {
231
-				$groups = $enabledValue;
232
-			}
233
-
234
-			$currentVersion = '';
235
-			if($this->appManager->isInstalled($app['id'])) {
236
-				$currentVersion = \OC_App::getAppVersion($app['id']);
237
-			} else {
238
-				$currentLanguage = $app['releases'][0]['version'];
239
-			}
240
-
241
-			$formattedApps[] = [
242
-				'id' => $app['id'],
243
-				'name' => isset($app['translations'][$currentLanguage]['name']) ? $app['translations'][$currentLanguage]['name'] : $app['translations']['en']['name'],
244
-				'description' => isset($app['translations'][$currentLanguage]['description']) ? $app['translations'][$currentLanguage]['description'] : $app['translations']['en']['description'],
245
-				'license' => $app['releases'][0]['licenses'],
246
-				'author' => $authors,
247
-				'shipped' => false,
248
-				'version' => $currentVersion,
249
-				'default_enable' => '',
250
-				'types' => [],
251
-				'documentation' => [
252
-					'admin' => $app['adminDocs'],
253
-					'user' => $app['userDocs'],
254
-					'developer' => $app['developerDocs']
255
-				],
256
-				'website' => $app['website'],
257
-				'bugs' => $app['issueTracker'],
258
-				'detailpage' => $app['website'],
259
-				'dependencies' => array_merge(
260
-					$nextCloudVersionDependencies,
261
-					$phpDependencies
262
-				),
263
-				'level' => ($app['featured'] === true) ? 200 : 100,
264
-				'missingMaxOwnCloudVersion' => false,
265
-				'missingMinOwnCloudVersion' => false,
266
-				'canInstall' => true,
267
-				'preview' => isset($app['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/'.base64_encode($app['screenshots'][0]['url']) : '',
268
-				'score' => $app['ratingOverall'],
269
-				'ratingNumOverall' => $app['ratingNumOverall'],
270
-				'ratingNumThresholdReached' => $app['ratingNumOverall'] > 5 ? true : false,
271
-				'removable' => $existsLocally,
272
-				'active' => $this->appManager->isEnabledForUser($app['id']),
273
-				'needsDownload' => !$existsLocally,
274
-				'groups' => $groups,
275
-				'fromAppStore' => true,
276
-			];
277
-
278
-
279
-			$newVersion = $this->installer->isUpdateAvailable($app['id']);
280
-			if($newVersion && $this->appManager->isInstalled($app['id'])) {
281
-				$formattedApps[count($formattedApps)-1]['update'] = $newVersion;
282
-			}
283
-		}
284
-
285
-		return $formattedApps;
286
-	}
287
-
288
-	private function getAppsWithUpdates() {
289
-		$appClass = new \OC_App();
290
-		$apps = $appClass->listAllApps();
291
-		foreach($apps as $key => $app) {
292
-			$newVersion = $this->installer->isUpdateAvailable($app['id']);
293
-			if($newVersion !== false) {
294
-				$apps[$key]['update'] = $newVersion;
295
-			} else {
296
-				unset($apps[$key]);
297
-			}
298
-		}
299
-		usort($apps, function ($a, $b) {
300
-			$a = (string)$a['name'];
301
-			$b = (string)$b['name'];
302
-			if ($a === $b) {
303
-				return 0;
304
-			}
305
-			return ($a < $b) ? -1 : 1;
306
-		});
307
-		return $apps;
308
-	}
309
-
310
-	/**
311
-	 * Get all available apps in a category
312
-	 *
313
-	 * @param string $category
314
-	 * @return JSONResponse
315
-	 */
316
-	public function listApps($category = '') {
317
-		$appClass = new \OC_App();
318
-
319
-		switch ($category) {
320
-			// installed apps
321
-			case 'installed':
322
-				$apps = $appClass->listAllApps();
323
-
324
-				foreach($apps as $key => $app) {
325
-					$newVersion = $this->installer->isUpdateAvailable($app['id']);
326
-					$apps[$key]['update'] = $newVersion;
327
-				}
328
-
329
-				usort($apps, function ($a, $b) {
330
-					$a = (string)$a['name'];
331
-					$b = (string)$b['name'];
332
-					if ($a === $b) {
333
-						return 0;
334
-					}
335
-					return ($a < $b) ? -1 : 1;
336
-				});
337
-				break;
338
-			// updates
339
-			case 'updates':
340
-				$apps = $this->getAppsWithUpdates();
341
-				break;
342
-			// enabled apps
343
-			case 'enabled':
344
-				$apps = $appClass->listAllApps();
345
-				$apps = array_filter($apps, function ($app) {
346
-					return $app['active'];
347
-				});
348
-
349
-				foreach($apps as $key => $app) {
350
-					$newVersion = $this->installer->isUpdateAvailable($app['id']);
351
-					$apps[$key]['update'] = $newVersion;
352
-				}
353
-
354
-				usort($apps, function ($a, $b) {
355
-					$a = (string)$a['name'];
356
-					$b = (string)$b['name'];
357
-					if ($a === $b) {
358
-						return 0;
359
-					}
360
-					return ($a < $b) ? -1 : 1;
361
-				});
362
-				break;
363
-			// disabled  apps
364
-			case 'disabled':
365
-				$apps = $appClass->listAllApps();
366
-				$apps = array_filter($apps, function ($app) {
367
-					return !$app['active'];
368
-				});
369
-
370
-				$apps = array_map(function ($app) {
371
-					$newVersion = $this->installer->isUpdateAvailable($app['id']);
372
-					if ($newVersion !== false) {
373
-						$app['update'] = $newVersion;
374
-					}
375
-					return $app;
376
-				}, $apps);
377
-
378
-				usort($apps, function ($a, $b) {
379
-					$a = (string)$a['name'];
380
-					$b = (string)$b['name'];
381
-					if ($a === $b) {
382
-						return 0;
383
-					}
384
-					return ($a < $b) ? -1 : 1;
385
-				});
386
-				break;
387
-			case 'app-bundles':
388
-				$bundles = $this->bundleFetcher->getBundles();
389
-				$apps = [];
390
-				foreach($bundles as $bundle) {
391
-					$newCategory = true;
392
-					$allApps = $appClass->listAllApps();
393
-					$categories = $this->getAllCategories();
394
-					foreach($categories as $singleCategory) {
395
-						$newApps = $this->getAppsForCategory($singleCategory['id']);
396
-						foreach($allApps as $app) {
397
-							foreach($newApps as $key => $newApp) {
398
-								if($app['id'] === $newApp['id']) {
399
-									unset($newApps[$key]);
400
-								}
401
-							}
402
-						}
403
-						$allApps = array_merge($allApps, $newApps);
404
-					}
405
-
406
-					foreach($bundle->getAppIdentifiers() as $identifier) {
407
-						foreach($allApps as $app) {
408
-							if($app['id'] === $identifier) {
409
-								if($newCategory) {
410
-									$app['newCategory'] = true;
411
-									$app['categoryName'] = $bundle->getName();
412
-								}
413
-								$app['bundleId'] = $bundle->getIdentifier();
414
-								$newCategory = false;
415
-								$apps[] = $app;
416
-								continue;
417
-							}
418
-						}
419
-					}
420
-				}
421
-				break;
422
-			default:
423
-				$apps = $this->getAppsForCategory($category);
424
-
425
-				// sort by score
426
-				usort($apps, function ($a, $b) {
427
-					$a = (int)$a['score'];
428
-					$b = (int)$b['score'];
429
-					if ($a === $b) {
430
-						return 0;
431
-					}
432
-					return ($a > $b) ? -1 : 1;
433
-				});
434
-				break;
435
-		}
436
-
437
-		// fix groups to be an array
438
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($this->config), $this->l10n);
439
-		$apps = array_map(function($app) use ($dependencyAnalyzer) {
440
-
441
-			// fix groups
442
-			$groups = array();
443
-			if (is_string($app['groups'])) {
444
-				$groups = json_decode($app['groups']);
445
-			}
446
-			$app['groups'] = $groups;
447
-			$app['canUnInstall'] = !$app['active'] && $app['removable'];
448
-
449
-			// fix licence vs license
450
-			if (isset($app['license']) && !isset($app['licence'])) {
451
-				$app['licence'] = $app['license'];
452
-			}
453
-
454
-			// analyse dependencies
455
-			$missing = $dependencyAnalyzer->analyze($app);
456
-			$app['canInstall'] = empty($missing);
457
-			$app['missingDependencies'] = $missing;
458
-
459
-			$app['missingMinOwnCloudVersion'] = !isset($app['dependencies']['nextcloud']['@attributes']['min-version']);
460
-			$app['missingMaxOwnCloudVersion'] = !isset($app['dependencies']['nextcloud']['@attributes']['max-version']);
461
-
462
-			return $app;
463
-		}, $apps);
464
-
465
-		return new JSONResponse(['apps' => $apps, 'status' => 'success']);
466
-	}
56
+    const CAT_ENABLED = 0;
57
+    const CAT_DISABLED = 1;
58
+    const CAT_ALL_INSTALLED = 2;
59
+    const CAT_APP_BUNDLES = 3;
60
+    const CAT_UPDATES = 4;
61
+
62
+    /** @var \OCP\IL10N */
63
+    private $l10n;
64
+    /** @var IConfig */
65
+    private $config;
66
+    /** @var INavigationManager */
67
+    private $navigationManager;
68
+    /** @var IAppManager */
69
+    private $appManager;
70
+    /** @var CategoryFetcher */
71
+    private $categoryFetcher;
72
+    /** @var AppFetcher */
73
+    private $appFetcher;
74
+    /** @var IFactory */
75
+    private $l10nFactory;
76
+    /** @var BundleFetcher */
77
+    private $bundleFetcher;
78
+    /** @var Installer */
79
+    private $installer;
80
+
81
+    /**
82
+     * @param string $appName
83
+     * @param IRequest $request
84
+     * @param IL10N $l10n
85
+     * @param IConfig $config
86
+     * @param INavigationManager $navigationManager
87
+     * @param IAppManager $appManager
88
+     * @param CategoryFetcher $categoryFetcher
89
+     * @param AppFetcher $appFetcher
90
+     * @param IFactory $l10nFactory
91
+     * @param BundleFetcher $bundleFetcher
92
+     * @param Installer $installer
93
+     */
94
+    public function __construct($appName,
95
+                                IRequest $request,
96
+                                IL10N $l10n,
97
+                                IConfig $config,
98
+                                INavigationManager $navigationManager,
99
+                                IAppManager $appManager,
100
+                                CategoryFetcher $categoryFetcher,
101
+                                AppFetcher $appFetcher,
102
+                                IFactory $l10nFactory,
103
+                                BundleFetcher $bundleFetcher,
104
+                                Installer $installer) {
105
+        parent::__construct($appName, $request);
106
+        $this->l10n = $l10n;
107
+        $this->config = $config;
108
+        $this->navigationManager = $navigationManager;
109
+        $this->appManager = $appManager;
110
+        $this->categoryFetcher = $categoryFetcher;
111
+        $this->appFetcher = $appFetcher;
112
+        $this->l10nFactory = $l10nFactory;
113
+        $this->bundleFetcher = $bundleFetcher;
114
+        $this->installer = $installer;
115
+    }
116
+
117
+    /**
118
+     * @NoCSRFRequired
119
+     *
120
+     * @param string $category
121
+     * @return TemplateResponse
122
+     */
123
+    public function viewApps($category = '') {
124
+        if ($category === '') {
125
+            $category = 'installed';
126
+        }
127
+
128
+        $params = [];
129
+        $params['category'] = $category;
130
+        $params['appstoreEnabled'] = $this->config->getSystemValue('appstoreenabled', true) === true;
131
+        $this->navigationManager->setActiveEntry('core_apps');
132
+
133
+        $templateResponse = new TemplateResponse($this->appName, 'apps', $params, 'user');
134
+        $policy = new ContentSecurityPolicy();
135
+        $policy->addAllowedImageDomain('https://usercontent.apps.nextcloud.com');
136
+        $templateResponse->setContentSecurityPolicy($policy);
137
+
138
+        return $templateResponse;
139
+    }
140
+
141
+    private function getAllCategories() {
142
+        $currentLanguage = substr($this->l10nFactory->findLanguage(), 0, 2);
143
+
144
+        $updateCount = count($this->getAppsWithUpdates());
145
+        $formattedCategories = [
146
+            ['id' => self::CAT_ALL_INSTALLED, 'ident' => 'installed', 'displayName' => (string)$this->l10n->t('Your apps')],
147
+            ['id' => self::CAT_UPDATES, 'ident' => 'updates', 'displayName' => (string)$this->l10n->t('Updates'), 'counter' => $updateCount],
148
+            ['id' => self::CAT_ENABLED, 'ident' => 'enabled', 'displayName' => (string)$this->l10n->t('Enabled apps')],
149
+            ['id' => self::CAT_DISABLED, 'ident' => 'disabled', 'displayName' => (string)$this->l10n->t('Disabled apps')],
150
+            ['id' => self::CAT_APP_BUNDLES, 'ident' => 'app-bundles', 'displayName' => (string)$this->l10n->t('App bundles')],
151
+        ];
152
+        $categories = $this->categoryFetcher->get();
153
+        foreach($categories as $category) {
154
+            $formattedCategories[] = [
155
+                'id' => $category['id'],
156
+                'ident' => $category['id'],
157
+                'displayName' => isset($category['translations'][$currentLanguage]['name']) ? $category['translations'][$currentLanguage]['name'] : $category['translations']['en']['name'],
158
+            ];
159
+        }
160
+
161
+        return $formattedCategories;
162
+    }
163
+
164
+    /**
165
+     * Get all available categories
166
+     *
167
+     * @return JSONResponse
168
+     */
169
+    public function listCategories() {
170
+        return new JSONResponse($this->getAllCategories());
171
+    }
172
+
173
+    /**
174
+     * Get all apps for a category
175
+     *
176
+     * @param string $requestedCategory
177
+     * @return array
178
+     */
179
+    private function getAppsForCategory($requestedCategory) {
180
+        $versionParser = new VersionParser();
181
+        $formattedApps = [];
182
+        $apps = $this->appFetcher->get();
183
+        foreach($apps as $app) {
184
+            if (isset($app['isFeatured'])) {
185
+                $app['featured'] = $app['isFeatured'];
186
+            }
187
+
188
+            // Skip all apps not in the requested category
189
+            $isInCategory = false;
190
+            foreach($app['categories'] as $category) {
191
+                if($category === $requestedCategory) {
192
+                    $isInCategory = true;
193
+                }
194
+            }
195
+            if(!$isInCategory) {
196
+                continue;
197
+            }
198
+
199
+            $nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']);
200
+            $nextCloudVersionDependencies = [];
201
+            if($nextCloudVersion->getMinimumVersion() !== '') {
202
+                $nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion();
203
+            }
204
+            if($nextCloudVersion->getMaximumVersion() !== '') {
205
+                $nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion();
206
+            }
207
+            $phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']);
208
+            $existsLocally = (\OC_App::getAppPath($app['id']) !== false) ? true : false;
209
+            $phpDependencies = [];
210
+            if($phpVersion->getMinimumVersion() !== '') {
211
+                $phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion();
212
+            }
213
+            if($phpVersion->getMaximumVersion() !== '') {
214
+                $phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion();
215
+            }
216
+            if(isset($app['releases'][0]['minIntSize'])) {
217
+                $phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize'];
218
+            }
219
+            $authors = '';
220
+            foreach($app['authors'] as $key => $author) {
221
+                $authors .= $author['name'];
222
+                if($key !== count($app['authors']) - 1) {
223
+                    $authors .= ', ';
224
+                }
225
+            }
226
+
227
+            $currentLanguage = substr(\OC::$server->getL10NFactory()->findLanguage(), 0, 2);
228
+            $enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no');
229
+            $groups = null;
230
+            if($enabledValue !== 'no' && $enabledValue !== 'yes') {
231
+                $groups = $enabledValue;
232
+            }
233
+
234
+            $currentVersion = '';
235
+            if($this->appManager->isInstalled($app['id'])) {
236
+                $currentVersion = \OC_App::getAppVersion($app['id']);
237
+            } else {
238
+                $currentLanguage = $app['releases'][0]['version'];
239
+            }
240
+
241
+            $formattedApps[] = [
242
+                'id' => $app['id'],
243
+                'name' => isset($app['translations'][$currentLanguage]['name']) ? $app['translations'][$currentLanguage]['name'] : $app['translations']['en']['name'],
244
+                'description' => isset($app['translations'][$currentLanguage]['description']) ? $app['translations'][$currentLanguage]['description'] : $app['translations']['en']['description'],
245
+                'license' => $app['releases'][0]['licenses'],
246
+                'author' => $authors,
247
+                'shipped' => false,
248
+                'version' => $currentVersion,
249
+                'default_enable' => '',
250
+                'types' => [],
251
+                'documentation' => [
252
+                    'admin' => $app['adminDocs'],
253
+                    'user' => $app['userDocs'],
254
+                    'developer' => $app['developerDocs']
255
+                ],
256
+                'website' => $app['website'],
257
+                'bugs' => $app['issueTracker'],
258
+                'detailpage' => $app['website'],
259
+                'dependencies' => array_merge(
260
+                    $nextCloudVersionDependencies,
261
+                    $phpDependencies
262
+                ),
263
+                'level' => ($app['featured'] === true) ? 200 : 100,
264
+                'missingMaxOwnCloudVersion' => false,
265
+                'missingMinOwnCloudVersion' => false,
266
+                'canInstall' => true,
267
+                'preview' => isset($app['screenshots'][0]['url']) ? 'https://usercontent.apps.nextcloud.com/'.base64_encode($app['screenshots'][0]['url']) : '',
268
+                'score' => $app['ratingOverall'],
269
+                'ratingNumOverall' => $app['ratingNumOverall'],
270
+                'ratingNumThresholdReached' => $app['ratingNumOverall'] > 5 ? true : false,
271
+                'removable' => $existsLocally,
272
+                'active' => $this->appManager->isEnabledForUser($app['id']),
273
+                'needsDownload' => !$existsLocally,
274
+                'groups' => $groups,
275
+                'fromAppStore' => true,
276
+            ];
277
+
278
+
279
+            $newVersion = $this->installer->isUpdateAvailable($app['id']);
280
+            if($newVersion && $this->appManager->isInstalled($app['id'])) {
281
+                $formattedApps[count($formattedApps)-1]['update'] = $newVersion;
282
+            }
283
+        }
284
+
285
+        return $formattedApps;
286
+    }
287
+
288
+    private function getAppsWithUpdates() {
289
+        $appClass = new \OC_App();
290
+        $apps = $appClass->listAllApps();
291
+        foreach($apps as $key => $app) {
292
+            $newVersion = $this->installer->isUpdateAvailable($app['id']);
293
+            if($newVersion !== false) {
294
+                $apps[$key]['update'] = $newVersion;
295
+            } else {
296
+                unset($apps[$key]);
297
+            }
298
+        }
299
+        usort($apps, function ($a, $b) {
300
+            $a = (string)$a['name'];
301
+            $b = (string)$b['name'];
302
+            if ($a === $b) {
303
+                return 0;
304
+            }
305
+            return ($a < $b) ? -1 : 1;
306
+        });
307
+        return $apps;
308
+    }
309
+
310
+    /**
311
+     * Get all available apps in a category
312
+     *
313
+     * @param string $category
314
+     * @return JSONResponse
315
+     */
316
+    public function listApps($category = '') {
317
+        $appClass = new \OC_App();
318
+
319
+        switch ($category) {
320
+            // installed apps
321
+            case 'installed':
322
+                $apps = $appClass->listAllApps();
323
+
324
+                foreach($apps as $key => $app) {
325
+                    $newVersion = $this->installer->isUpdateAvailable($app['id']);
326
+                    $apps[$key]['update'] = $newVersion;
327
+                }
328
+
329
+                usort($apps, function ($a, $b) {
330
+                    $a = (string)$a['name'];
331
+                    $b = (string)$b['name'];
332
+                    if ($a === $b) {
333
+                        return 0;
334
+                    }
335
+                    return ($a < $b) ? -1 : 1;
336
+                });
337
+                break;
338
+            // updates
339
+            case 'updates':
340
+                $apps = $this->getAppsWithUpdates();
341
+                break;
342
+            // enabled apps
343
+            case 'enabled':
344
+                $apps = $appClass->listAllApps();
345
+                $apps = array_filter($apps, function ($app) {
346
+                    return $app['active'];
347
+                });
348
+
349
+                foreach($apps as $key => $app) {
350
+                    $newVersion = $this->installer->isUpdateAvailable($app['id']);
351
+                    $apps[$key]['update'] = $newVersion;
352
+                }
353
+
354
+                usort($apps, function ($a, $b) {
355
+                    $a = (string)$a['name'];
356
+                    $b = (string)$b['name'];
357
+                    if ($a === $b) {
358
+                        return 0;
359
+                    }
360
+                    return ($a < $b) ? -1 : 1;
361
+                });
362
+                break;
363
+            // disabled  apps
364
+            case 'disabled':
365
+                $apps = $appClass->listAllApps();
366
+                $apps = array_filter($apps, function ($app) {
367
+                    return !$app['active'];
368
+                });
369
+
370
+                $apps = array_map(function ($app) {
371
+                    $newVersion = $this->installer->isUpdateAvailable($app['id']);
372
+                    if ($newVersion !== false) {
373
+                        $app['update'] = $newVersion;
374
+                    }
375
+                    return $app;
376
+                }, $apps);
377
+
378
+                usort($apps, function ($a, $b) {
379
+                    $a = (string)$a['name'];
380
+                    $b = (string)$b['name'];
381
+                    if ($a === $b) {
382
+                        return 0;
383
+                    }
384
+                    return ($a < $b) ? -1 : 1;
385
+                });
386
+                break;
387
+            case 'app-bundles':
388
+                $bundles = $this->bundleFetcher->getBundles();
389
+                $apps = [];
390
+                foreach($bundles as $bundle) {
391
+                    $newCategory = true;
392
+                    $allApps = $appClass->listAllApps();
393
+                    $categories = $this->getAllCategories();
394
+                    foreach($categories as $singleCategory) {
395
+                        $newApps = $this->getAppsForCategory($singleCategory['id']);
396
+                        foreach($allApps as $app) {
397
+                            foreach($newApps as $key => $newApp) {
398
+                                if($app['id'] === $newApp['id']) {
399
+                                    unset($newApps[$key]);
400
+                                }
401
+                            }
402
+                        }
403
+                        $allApps = array_merge($allApps, $newApps);
404
+                    }
405
+
406
+                    foreach($bundle->getAppIdentifiers() as $identifier) {
407
+                        foreach($allApps as $app) {
408
+                            if($app['id'] === $identifier) {
409
+                                if($newCategory) {
410
+                                    $app['newCategory'] = true;
411
+                                    $app['categoryName'] = $bundle->getName();
412
+                                }
413
+                                $app['bundleId'] = $bundle->getIdentifier();
414
+                                $newCategory = false;
415
+                                $apps[] = $app;
416
+                                continue;
417
+                            }
418
+                        }
419
+                    }
420
+                }
421
+                break;
422
+            default:
423
+                $apps = $this->getAppsForCategory($category);
424
+
425
+                // sort by score
426
+                usort($apps, function ($a, $b) {
427
+                    $a = (int)$a['score'];
428
+                    $b = (int)$b['score'];
429
+                    if ($a === $b) {
430
+                        return 0;
431
+                    }
432
+                    return ($a > $b) ? -1 : 1;
433
+                });
434
+                break;
435
+        }
436
+
437
+        // fix groups to be an array
438
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($this->config), $this->l10n);
439
+        $apps = array_map(function($app) use ($dependencyAnalyzer) {
440
+
441
+            // fix groups
442
+            $groups = array();
443
+            if (is_string($app['groups'])) {
444
+                $groups = json_decode($app['groups']);
445
+            }
446
+            $app['groups'] = $groups;
447
+            $app['canUnInstall'] = !$app['active'] && $app['removable'];
448
+
449
+            // fix licence vs license
450
+            if (isset($app['license']) && !isset($app['licence'])) {
451
+                $app['licence'] = $app['license'];
452
+            }
453
+
454
+            // analyse dependencies
455
+            $missing = $dependencyAnalyzer->analyze($app);
456
+            $app['canInstall'] = empty($missing);
457
+            $app['missingDependencies'] = $missing;
458
+
459
+            $app['missingMinOwnCloudVersion'] = !isset($app['dependencies']['nextcloud']['@attributes']['min-version']);
460
+            $app['missingMaxOwnCloudVersion'] = !isset($app['dependencies']['nextcloud']['@attributes']['max-version']);
461
+
462
+            return $app;
463
+        }, $apps);
464
+
465
+        return new JSONResponse(['apps' => $apps, 'status' => 'success']);
466
+    }
467 467
 }
Please login to merge, or discard this patch.
Spacing   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -143,14 +143,14 @@  discard block
 block discarded – undo
143 143
 
144 144
 		$updateCount = count($this->getAppsWithUpdates());
145 145
 		$formattedCategories = [
146
-			['id' => self::CAT_ALL_INSTALLED, 'ident' => 'installed', 'displayName' => (string)$this->l10n->t('Your apps')],
147
-			['id' => self::CAT_UPDATES, 'ident' => 'updates', 'displayName' => (string)$this->l10n->t('Updates'), 'counter' => $updateCount],
148
-			['id' => self::CAT_ENABLED, 'ident' => 'enabled', 'displayName' => (string)$this->l10n->t('Enabled apps')],
149
-			['id' => self::CAT_DISABLED, 'ident' => 'disabled', 'displayName' => (string)$this->l10n->t('Disabled apps')],
150
-			['id' => self::CAT_APP_BUNDLES, 'ident' => 'app-bundles', 'displayName' => (string)$this->l10n->t('App bundles')],
146
+			['id' => self::CAT_ALL_INSTALLED, 'ident' => 'installed', 'displayName' => (string) $this->l10n->t('Your apps')],
147
+			['id' => self::CAT_UPDATES, 'ident' => 'updates', 'displayName' => (string) $this->l10n->t('Updates'), 'counter' => $updateCount],
148
+			['id' => self::CAT_ENABLED, 'ident' => 'enabled', 'displayName' => (string) $this->l10n->t('Enabled apps')],
149
+			['id' => self::CAT_DISABLED, 'ident' => 'disabled', 'displayName' => (string) $this->l10n->t('Disabled apps')],
150
+			['id' => self::CAT_APP_BUNDLES, 'ident' => 'app-bundles', 'displayName' => (string) $this->l10n->t('App bundles')],
151 151
 		];
152 152
 		$categories = $this->categoryFetcher->get();
153
-		foreach($categories as $category) {
153
+		foreach ($categories as $category) {
154 154
 			$formattedCategories[] = [
155 155
 				'id' => $category['id'],
156 156
 				'ident' => $category['id'],
@@ -180,46 +180,46 @@  discard block
 block discarded – undo
180 180
 		$versionParser = new VersionParser();
181 181
 		$formattedApps = [];
182 182
 		$apps = $this->appFetcher->get();
183
-		foreach($apps as $app) {
183
+		foreach ($apps as $app) {
184 184
 			if (isset($app['isFeatured'])) {
185 185
 				$app['featured'] = $app['isFeatured'];
186 186
 			}
187 187
 
188 188
 			// Skip all apps not in the requested category
189 189
 			$isInCategory = false;
190
-			foreach($app['categories'] as $category) {
191
-				if($category === $requestedCategory) {
190
+			foreach ($app['categories'] as $category) {
191
+				if ($category === $requestedCategory) {
192 192
 					$isInCategory = true;
193 193
 				}
194 194
 			}
195
-			if(!$isInCategory) {
195
+			if (!$isInCategory) {
196 196
 				continue;
197 197
 			}
198 198
 
199 199
 			$nextCloudVersion = $versionParser->getVersion($app['releases'][0]['rawPlatformVersionSpec']);
200 200
 			$nextCloudVersionDependencies = [];
201
-			if($nextCloudVersion->getMinimumVersion() !== '') {
201
+			if ($nextCloudVersion->getMinimumVersion() !== '') {
202 202
 				$nextCloudVersionDependencies['nextcloud']['@attributes']['min-version'] = $nextCloudVersion->getMinimumVersion();
203 203
 			}
204
-			if($nextCloudVersion->getMaximumVersion() !== '') {
204
+			if ($nextCloudVersion->getMaximumVersion() !== '') {
205 205
 				$nextCloudVersionDependencies['nextcloud']['@attributes']['max-version'] = $nextCloudVersion->getMaximumVersion();
206 206
 			}
207 207
 			$phpVersion = $versionParser->getVersion($app['releases'][0]['rawPhpVersionSpec']);
208 208
 			$existsLocally = (\OC_App::getAppPath($app['id']) !== false) ? true : false;
209 209
 			$phpDependencies = [];
210
-			if($phpVersion->getMinimumVersion() !== '') {
210
+			if ($phpVersion->getMinimumVersion() !== '') {
211 211
 				$phpDependencies['php']['@attributes']['min-version'] = $phpVersion->getMinimumVersion();
212 212
 			}
213
-			if($phpVersion->getMaximumVersion() !== '') {
213
+			if ($phpVersion->getMaximumVersion() !== '') {
214 214
 				$phpDependencies['php']['@attributes']['max-version'] = $phpVersion->getMaximumVersion();
215 215
 			}
216
-			if(isset($app['releases'][0]['minIntSize'])) {
216
+			if (isset($app['releases'][0]['minIntSize'])) {
217 217
 				$phpDependencies['php']['@attributes']['min-int-size'] = $app['releases'][0]['minIntSize'];
218 218
 			}
219 219
 			$authors = '';
220
-			foreach($app['authors'] as $key => $author) {
220
+			foreach ($app['authors'] as $key => $author) {
221 221
 				$authors .= $author['name'];
222
-				if($key !== count($app['authors']) - 1) {
222
+				if ($key !== count($app['authors']) - 1) {
223 223
 					$authors .= ', ';
224 224
 				}
225 225
 			}
@@ -227,12 +227,12 @@  discard block
 block discarded – undo
227 227
 			$currentLanguage = substr(\OC::$server->getL10NFactory()->findLanguage(), 0, 2);
228 228
 			$enabledValue = $this->config->getAppValue($app['id'], 'enabled', 'no');
229 229
 			$groups = null;
230
-			if($enabledValue !== 'no' && $enabledValue !== 'yes') {
230
+			if ($enabledValue !== 'no' && $enabledValue !== 'yes') {
231 231
 				$groups = $enabledValue;
232 232
 			}
233 233
 
234 234
 			$currentVersion = '';
235
-			if($this->appManager->isInstalled($app['id'])) {
235
+			if ($this->appManager->isInstalled($app['id'])) {
236 236
 				$currentVersion = \OC_App::getAppVersion($app['id']);
237 237
 			} else {
238 238
 				$currentLanguage = $app['releases'][0]['version'];
@@ -277,8 +277,8 @@  discard block
 block discarded – undo
277 277
 
278 278
 
279 279
 			$newVersion = $this->installer->isUpdateAvailable($app['id']);
280
-			if($newVersion && $this->appManager->isInstalled($app['id'])) {
281
-				$formattedApps[count($formattedApps)-1]['update'] = $newVersion;
280
+			if ($newVersion && $this->appManager->isInstalled($app['id'])) {
281
+				$formattedApps[count($formattedApps) - 1]['update'] = $newVersion;
282 282
 			}
283 283
 		}
284 284
 
@@ -288,17 +288,17 @@  discard block
 block discarded – undo
288 288
 	private function getAppsWithUpdates() {
289 289
 		$appClass = new \OC_App();
290 290
 		$apps = $appClass->listAllApps();
291
-		foreach($apps as $key => $app) {
291
+		foreach ($apps as $key => $app) {
292 292
 			$newVersion = $this->installer->isUpdateAvailable($app['id']);
293
-			if($newVersion !== false) {
293
+			if ($newVersion !== false) {
294 294
 				$apps[$key]['update'] = $newVersion;
295 295
 			} else {
296 296
 				unset($apps[$key]);
297 297
 			}
298 298
 		}
299
-		usort($apps, function ($a, $b) {
300
-			$a = (string)$a['name'];
301
-			$b = (string)$b['name'];
299
+		usort($apps, function($a, $b) {
300
+			$a = (string) $a['name'];
301
+			$b = (string) $b['name'];
302 302
 			if ($a === $b) {
303 303
 				return 0;
304 304
 			}
@@ -321,14 +321,14 @@  discard block
 block discarded – undo
321 321
 			case 'installed':
322 322
 				$apps = $appClass->listAllApps();
323 323
 
324
-				foreach($apps as $key => $app) {
324
+				foreach ($apps as $key => $app) {
325 325
 					$newVersion = $this->installer->isUpdateAvailable($app['id']);
326 326
 					$apps[$key]['update'] = $newVersion;
327 327
 				}
328 328
 
329
-				usort($apps, function ($a, $b) {
330
-					$a = (string)$a['name'];
331
-					$b = (string)$b['name'];
329
+				usort($apps, function($a, $b) {
330
+					$a = (string) $a['name'];
331
+					$b = (string) $b['name'];
332 332
 					if ($a === $b) {
333 333
 						return 0;
334 334
 					}
@@ -342,18 +342,18 @@  discard block
 block discarded – undo
342 342
 			// enabled apps
343 343
 			case 'enabled':
344 344
 				$apps = $appClass->listAllApps();
345
-				$apps = array_filter($apps, function ($app) {
345
+				$apps = array_filter($apps, function($app) {
346 346
 					return $app['active'];
347 347
 				});
348 348
 
349
-				foreach($apps as $key => $app) {
349
+				foreach ($apps as $key => $app) {
350 350
 					$newVersion = $this->installer->isUpdateAvailable($app['id']);
351 351
 					$apps[$key]['update'] = $newVersion;
352 352
 				}
353 353
 
354
-				usort($apps, function ($a, $b) {
355
-					$a = (string)$a['name'];
356
-					$b = (string)$b['name'];
354
+				usort($apps, function($a, $b) {
355
+					$a = (string) $a['name'];
356
+					$b = (string) $b['name'];
357 357
 					if ($a === $b) {
358 358
 						return 0;
359 359
 					}
@@ -363,11 +363,11 @@  discard block
 block discarded – undo
363 363
 			// disabled  apps
364 364
 			case 'disabled':
365 365
 				$apps = $appClass->listAllApps();
366
-				$apps = array_filter($apps, function ($app) {
366
+				$apps = array_filter($apps, function($app) {
367 367
 					return !$app['active'];
368 368
 				});
369 369
 
370
-				$apps = array_map(function ($app) {
370
+				$apps = array_map(function($app) {
371 371
 					$newVersion = $this->installer->isUpdateAvailable($app['id']);
372 372
 					if ($newVersion !== false) {
373 373
 						$app['update'] = $newVersion;
@@ -375,9 +375,9 @@  discard block
 block discarded – undo
375 375
 					return $app;
376 376
 				}, $apps);
377 377
 
378
-				usort($apps, function ($a, $b) {
379
-					$a = (string)$a['name'];
380
-					$b = (string)$b['name'];
378
+				usort($apps, function($a, $b) {
379
+					$a = (string) $a['name'];
380
+					$b = (string) $b['name'];
381 381
 					if ($a === $b) {
382 382
 						return 0;
383 383
 					}
@@ -387,15 +387,15 @@  discard block
 block discarded – undo
387 387
 			case 'app-bundles':
388 388
 				$bundles = $this->bundleFetcher->getBundles();
389 389
 				$apps = [];
390
-				foreach($bundles as $bundle) {
390
+				foreach ($bundles as $bundle) {
391 391
 					$newCategory = true;
392 392
 					$allApps = $appClass->listAllApps();
393 393
 					$categories = $this->getAllCategories();
394
-					foreach($categories as $singleCategory) {
394
+					foreach ($categories as $singleCategory) {
395 395
 						$newApps = $this->getAppsForCategory($singleCategory['id']);
396
-						foreach($allApps as $app) {
397
-							foreach($newApps as $key => $newApp) {
398
-								if($app['id'] === $newApp['id']) {
396
+						foreach ($allApps as $app) {
397
+							foreach ($newApps as $key => $newApp) {
398
+								if ($app['id'] === $newApp['id']) {
399 399
 									unset($newApps[$key]);
400 400
 								}
401 401
 							}
@@ -403,10 +403,10 @@  discard block
 block discarded – undo
403 403
 						$allApps = array_merge($allApps, $newApps);
404 404
 					}
405 405
 
406
-					foreach($bundle->getAppIdentifiers() as $identifier) {
407
-						foreach($allApps as $app) {
408
-							if($app['id'] === $identifier) {
409
-								if($newCategory) {
406
+					foreach ($bundle->getAppIdentifiers() as $identifier) {
407
+						foreach ($allApps as $app) {
408
+							if ($app['id'] === $identifier) {
409
+								if ($newCategory) {
410 410
 									$app['newCategory'] = true;
411 411
 									$app['categoryName'] = $bundle->getName();
412 412
 								}
@@ -423,9 +423,9 @@  discard block
 block discarded – undo
423 423
 				$apps = $this->getAppsForCategory($category);
424 424
 
425 425
 				// sort by score
426
-				usort($apps, function ($a, $b) {
427
-					$a = (int)$a['score'];
428
-					$b = (int)$b['score'];
426
+				usort($apps, function($a, $b) {
427
+					$a = (int) $a['score'];
428
+					$b = (int) $b['score'];
429 429
 					if ($a === $b) {
430 430
 						return 0;
431 431
 					}
Please login to merge, or discard this patch.
settings/ajax/updateapp.php 2 patches
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -29,10 +29,10 @@  discard block
 block discarded – undo
29 29
 OCP\JSON::callCheck();
30 30
 
31 31
 if (!array_key_exists('appid', $_POST)) {
32
-	OCP\JSON::error(array(
33
-		'message' => 'No AppId given!'
34
-	));
35
-	return;
32
+    OCP\JSON::error(array(
33
+        'message' => 'No AppId given!'
34
+    ));
35
+    return;
36 36
 }
37 37
 
38 38
 $appId = (string)$_POST['appid'];
@@ -41,18 +41,18 @@  discard block
 block discarded – undo
41 41
 $config = \OC::$server->getConfig();
42 42
 $config->setSystemValue('maintenance', true);
43 43
 try {
44
-	$installer = \OC::$server->query(Installer::class);
45
-	$result = $installer->updateAppstoreApp($appId);
46
-	$config->setSystemValue('maintenance', false);
44
+    $installer = \OC::$server->query(Installer::class);
45
+    $result = $installer->updateAppstoreApp($appId);
46
+    $config->setSystemValue('maintenance', false);
47 47
 } catch(Exception $ex) {
48
-	$config->setSystemValue('maintenance', false);
49
-	OC_JSON::error(array('data' => array( 'message' => $ex->getMessage() )));
50
-	return;
48
+    $config->setSystemValue('maintenance', false);
49
+    OC_JSON::error(array('data' => array( 'message' => $ex->getMessage() )));
50
+    return;
51 51
 }
52 52
 
53 53
 if($result !== false) {
54
-	OC_JSON::success(array('data' => array('appid' => $appId)));
54
+    OC_JSON::success(array('data' => array('appid' => $appId)));
55 55
 } else {
56
-	$l = \OC::$server->getL10N('settings');
57
-	OC_JSON::error(array('data' => array( 'message' => $l->t("Couldn't update app.") )));
56
+    $l = \OC::$server->getL10N('settings');
57
+    OC_JSON::error(array('data' => array( 'message' => $l->t("Couldn't update app.") )));
58 58
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 	return;
36 36
 }
37 37
 
38
-$appId = (string)$_POST['appid'];
38
+$appId = (string) $_POST['appid'];
39 39
 $appId = OC_App::cleanAppId($appId);
40 40
 
41 41
 $config = \OC::$server->getConfig();
@@ -44,15 +44,15 @@  discard block
 block discarded – undo
44 44
 	$installer = \OC::$server->query(Installer::class);
45 45
 	$result = $installer->updateAppstoreApp($appId);
46 46
 	$config->setSystemValue('maintenance', false);
47
-} catch(Exception $ex) {
47
+} catch (Exception $ex) {
48 48
 	$config->setSystemValue('maintenance', false);
49
-	OC_JSON::error(array('data' => array( 'message' => $ex->getMessage() )));
49
+	OC_JSON::error(array('data' => array('message' => $ex->getMessage())));
50 50
 	return;
51 51
 }
52 52
 
53
-if($result !== false) {
53
+if ($result !== false) {
54 54
 	OC_JSON::success(array('data' => array('appid' => $appId)));
55 55
 } else {
56 56
 	$l = \OC::$server->getL10N('settings');
57
-	OC_JSON::error(array('data' => array( 'message' => $l->t("Couldn't update app.") )));
57
+	OC_JSON::error(array('data' => array('message' => $l->t("Couldn't update app."))));
58 58
 }
Please login to merge, or discard this patch.
core/register_command.php 1 patch
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -44,122 +44,122 @@
 block discarded – undo
44 44
 $application->add(new OC\Core\Command\App\CheckCode($infoParser));
45 45
 $application->add(new OC\Core\Command\L10n\CreateJs());
46 46
 $application->add(new \OC\Core\Command\Integrity\SignApp(
47
-		\OC::$server->getIntegrityCodeChecker(),
48
-		new \OC\IntegrityCheck\Helpers\FileAccessHelper(),
49
-		\OC::$server->getURLGenerator()
47
+        \OC::$server->getIntegrityCodeChecker(),
48
+        new \OC\IntegrityCheck\Helpers\FileAccessHelper(),
49
+        \OC::$server->getURLGenerator()
50 50
 ));
51 51
 $application->add(new \OC\Core\Command\Integrity\SignCore(
52
-		\OC::$server->getIntegrityCodeChecker(),
53
-		new \OC\IntegrityCheck\Helpers\FileAccessHelper()
52
+        \OC::$server->getIntegrityCodeChecker(),
53
+        new \OC\IntegrityCheck\Helpers\FileAccessHelper()
54 54
 ));
55 55
 $application->add(new \OC\Core\Command\Integrity\CheckApp(
56
-		\OC::$server->getIntegrityCodeChecker()
56
+        \OC::$server->getIntegrityCodeChecker()
57 57
 ));
58 58
 $application->add(new \OC\Core\Command\Integrity\CheckCore(
59
-		\OC::$server->getIntegrityCodeChecker()
59
+        \OC::$server->getIntegrityCodeChecker()
60 60
 ));
61 61
 
62 62
 
63 63
 if (\OC::$server->getConfig()->getSystemValue('installed', false)) {
64
-	$application->add(new OC\Core\Command\App\Disable(\OC::$server->getAppManager()));
65
-	$application->add(new OC\Core\Command\App\Enable(\OC::$server->getAppManager()));
66
-	$application->add(new OC\Core\Command\App\Install());
67
-	$application->add(new OC\Core\Command\App\GetPath());
68
-	$application->add(new OC\Core\Command\App\ListApps(\OC::$server->getAppManager()));
64
+    $application->add(new OC\Core\Command\App\Disable(\OC::$server->getAppManager()));
65
+    $application->add(new OC\Core\Command\App\Enable(\OC::$server->getAppManager()));
66
+    $application->add(new OC\Core\Command\App\Install());
67
+    $application->add(new OC\Core\Command\App\GetPath());
68
+    $application->add(new OC\Core\Command\App\ListApps(\OC::$server->getAppManager()));
69 69
 
70
-	$application->add(new OC\Core\Command\TwoFactorAuth\Enable(
71
-		\OC::$server->getTwoFactorAuthManager(), \OC::$server->getUserManager()
72
-	));
73
-	$application->add(new OC\Core\Command\TwoFactorAuth\Disable(
74
-		\OC::$server->getTwoFactorAuthManager(), \OC::$server->getUserManager()
75
-	));
70
+    $application->add(new OC\Core\Command\TwoFactorAuth\Enable(
71
+        \OC::$server->getTwoFactorAuthManager(), \OC::$server->getUserManager()
72
+    ));
73
+    $application->add(new OC\Core\Command\TwoFactorAuth\Disable(
74
+        \OC::$server->getTwoFactorAuthManager(), \OC::$server->getUserManager()
75
+    ));
76 76
 
77
-	$application->add(new OC\Core\Command\Background\Cron(\OC::$server->getConfig()));
78
-	$application->add(new OC\Core\Command\Background\WebCron(\OC::$server->getConfig()));
79
-	$application->add(new OC\Core\Command\Background\Ajax(\OC::$server->getConfig()));
77
+    $application->add(new OC\Core\Command\Background\Cron(\OC::$server->getConfig()));
78
+    $application->add(new OC\Core\Command\Background\WebCron(\OC::$server->getConfig()));
79
+    $application->add(new OC\Core\Command\Background\Ajax(\OC::$server->getConfig()));
80 80
 
81
-	$application->add(new OC\Core\Command\Config\App\DeleteConfig(\OC::$server->getConfig()));
82
-	$application->add(new OC\Core\Command\Config\App\GetConfig(\OC::$server->getConfig()));
83
-	$application->add(new OC\Core\Command\Config\App\SetConfig(\OC::$server->getConfig()));
84
-	$application->add(new OC\Core\Command\Config\Import(\OC::$server->getConfig()));
85
-	$application->add(new OC\Core\Command\Config\ListConfigs(\OC::$server->getSystemConfig(), \OC::$server->getAppConfig()));
86
-	$application->add(new OC\Core\Command\Config\System\DeleteConfig(\OC::$server->getSystemConfig()));
87
-	$application->add(new OC\Core\Command\Config\System\GetConfig(\OC::$server->getSystemConfig()));
88
-	$application->add(new OC\Core\Command\Config\System\SetConfig(\OC::$server->getSystemConfig()));
81
+    $application->add(new OC\Core\Command\Config\App\DeleteConfig(\OC::$server->getConfig()));
82
+    $application->add(new OC\Core\Command\Config\App\GetConfig(\OC::$server->getConfig()));
83
+    $application->add(new OC\Core\Command\Config\App\SetConfig(\OC::$server->getConfig()));
84
+    $application->add(new OC\Core\Command\Config\Import(\OC::$server->getConfig()));
85
+    $application->add(new OC\Core\Command\Config\ListConfigs(\OC::$server->getSystemConfig(), \OC::$server->getAppConfig()));
86
+    $application->add(new OC\Core\Command\Config\System\DeleteConfig(\OC::$server->getSystemConfig()));
87
+    $application->add(new OC\Core\Command\Config\System\GetConfig(\OC::$server->getSystemConfig()));
88
+    $application->add(new OC\Core\Command\Config\System\SetConfig(\OC::$server->getSystemConfig()));
89 89
 
90
-	$application->add(new OC\Core\Command\Db\ConvertType(\OC::$server->getConfig(), new \OC\DB\ConnectionFactory(\OC::$server->getSystemConfig())));
91
-	$application->add(new OC\Core\Command\Db\ConvertMysqlToMB4(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection(), \OC::$server->getURLGenerator(), \OC::$server->getLogger()));
92
-	$application->add(new OC\Core\Command\Db\ConvertFilecacheBigInt(\OC::$server->getDatabaseConnection()));
93
-	$application->add(new OC\Core\Command\Db\Migrations\StatusCommand(\OC::$server->getDatabaseConnection()));
94
-	$application->add(new OC\Core\Command\Db\Migrations\MigrateCommand(\OC::$server->getDatabaseConnection()));
95
-	$application->add(new OC\Core\Command\Db\Migrations\GenerateCommand(\OC::$server->getDatabaseConnection()));
96
-	$application->add(new OC\Core\Command\Db\Migrations\GenerateFromSchemaFileCommand(\OC::$server->getConfig(), \OC::$server->getAppManager(), \OC::$server->getDatabaseConnection()));
97
-	$application->add(new OC\Core\Command\Db\Migrations\ExecuteCommand(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()));
90
+    $application->add(new OC\Core\Command\Db\ConvertType(\OC::$server->getConfig(), new \OC\DB\ConnectionFactory(\OC::$server->getSystemConfig())));
91
+    $application->add(new OC\Core\Command\Db\ConvertMysqlToMB4(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection(), \OC::$server->getURLGenerator(), \OC::$server->getLogger()));
92
+    $application->add(new OC\Core\Command\Db\ConvertFilecacheBigInt(\OC::$server->getDatabaseConnection()));
93
+    $application->add(new OC\Core\Command\Db\Migrations\StatusCommand(\OC::$server->getDatabaseConnection()));
94
+    $application->add(new OC\Core\Command\Db\Migrations\MigrateCommand(\OC::$server->getDatabaseConnection()));
95
+    $application->add(new OC\Core\Command\Db\Migrations\GenerateCommand(\OC::$server->getDatabaseConnection()));
96
+    $application->add(new OC\Core\Command\Db\Migrations\GenerateFromSchemaFileCommand(\OC::$server->getConfig(), \OC::$server->getAppManager(), \OC::$server->getDatabaseConnection()));
97
+    $application->add(new OC\Core\Command\Db\Migrations\ExecuteCommand(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()));
98 98
 
99
-	$application->add(new OC\Core\Command\Encryption\Disable(\OC::$server->getConfig()));
100
-	$application->add(new OC\Core\Command\Encryption\Enable(\OC::$server->getConfig(), \OC::$server->getEncryptionManager()));
101
-	$application->add(new OC\Core\Command\Encryption\ListModules(\OC::$server->getEncryptionManager()));
102
-	$application->add(new OC\Core\Command\Encryption\SetDefaultModule(\OC::$server->getEncryptionManager()));
103
-	$application->add(new OC\Core\Command\Encryption\Status(\OC::$server->getEncryptionManager()));
104
-	$application->add(new OC\Core\Command\Encryption\EncryptAll(\OC::$server->getEncryptionManager(), \OC::$server->getAppManager(), \OC::$server->getConfig(), new \Symfony\Component\Console\Helper\QuestionHelper()));
105
-	$application->add(new OC\Core\Command\Encryption\DecryptAll(
106
-		\OC::$server->getEncryptionManager(),
107
-		\OC::$server->getAppManager(),
108
-		\OC::$server->getConfig(),
109
-		new \OC\Encryption\DecryptAll(\OC::$server->getEncryptionManager(), \OC::$server->getUserManager(), new \OC\Files\View()),
110
-		new \Symfony\Component\Console\Helper\QuestionHelper())
111
-	);
99
+    $application->add(new OC\Core\Command\Encryption\Disable(\OC::$server->getConfig()));
100
+    $application->add(new OC\Core\Command\Encryption\Enable(\OC::$server->getConfig(), \OC::$server->getEncryptionManager()));
101
+    $application->add(new OC\Core\Command\Encryption\ListModules(\OC::$server->getEncryptionManager()));
102
+    $application->add(new OC\Core\Command\Encryption\SetDefaultModule(\OC::$server->getEncryptionManager()));
103
+    $application->add(new OC\Core\Command\Encryption\Status(\OC::$server->getEncryptionManager()));
104
+    $application->add(new OC\Core\Command\Encryption\EncryptAll(\OC::$server->getEncryptionManager(), \OC::$server->getAppManager(), \OC::$server->getConfig(), new \Symfony\Component\Console\Helper\QuestionHelper()));
105
+    $application->add(new OC\Core\Command\Encryption\DecryptAll(
106
+        \OC::$server->getEncryptionManager(),
107
+        \OC::$server->getAppManager(),
108
+        \OC::$server->getConfig(),
109
+        new \OC\Encryption\DecryptAll(\OC::$server->getEncryptionManager(), \OC::$server->getUserManager(), new \OC\Files\View()),
110
+        new \Symfony\Component\Console\Helper\QuestionHelper())
111
+    );
112 112
 
113
-	$application->add(new OC\Core\Command\Log\Manage(\OC::$server->getConfig()));
114
-	$application->add(new OC\Core\Command\Log\File(\OC::$server->getConfig()));
113
+    $application->add(new OC\Core\Command\Log\Manage(\OC::$server->getConfig()));
114
+    $application->add(new OC\Core\Command\Log\File(\OC::$server->getConfig()));
115 115
 
116
-	$view = new \OC\Files\View();
117
-	$util = new \OC\Encryption\Util(
118
-		$view,
119
-		\OC::$server->getUserManager(),
120
-		\OC::$server->getGroupManager(),
121
-		\OC::$server->getConfig()
122
-	);
123
-	$application->add(new OC\Core\Command\Encryption\ChangeKeyStorageRoot(
124
-			$view,
125
-			\OC::$server->getUserManager(),
126
-			\OC::$server->getConfig(),
127
-			$util,
128
-			new \Symfony\Component\Console\Helper\QuestionHelper()
129
-		)
130
-	);
131
-	$application->add(new OC\Core\Command\Encryption\ShowKeyStorageRoot($util));
116
+    $view = new \OC\Files\View();
117
+    $util = new \OC\Encryption\Util(
118
+        $view,
119
+        \OC::$server->getUserManager(),
120
+        \OC::$server->getGroupManager(),
121
+        \OC::$server->getConfig()
122
+    );
123
+    $application->add(new OC\Core\Command\Encryption\ChangeKeyStorageRoot(
124
+            $view,
125
+            \OC::$server->getUserManager(),
126
+            \OC::$server->getConfig(),
127
+            $util,
128
+            new \Symfony\Component\Console\Helper\QuestionHelper()
129
+        )
130
+    );
131
+    $application->add(new OC\Core\Command\Encryption\ShowKeyStorageRoot($util));
132 132
 
133
-	$application->add(new OC\Core\Command\Maintenance\DataFingerprint(\OC::$server->getConfig(), new \OC\AppFramework\Utility\TimeFactory()));
134
-	$application->add(new OC\Core\Command\Maintenance\Mimetype\UpdateDB(\OC::$server->getMimeTypeDetector(), \OC::$server->getMimeTypeLoader()));
135
-	$application->add(new OC\Core\Command\Maintenance\Mimetype\UpdateJS(\OC::$server->getMimeTypeDetector()));
136
-	$application->add(new OC\Core\Command\Maintenance\Mode(\OC::$server->getConfig()));
137
-	$application->add(new OC\Core\Command\Maintenance\UpdateHtaccess());
138
-	$application->add(new OC\Core\Command\Maintenance\UpdateTheme(\OC::$server->getMimeTypeDetector(), \OC::$server->getMemCacheFactory()));
133
+    $application->add(new OC\Core\Command\Maintenance\DataFingerprint(\OC::$server->getConfig(), new \OC\AppFramework\Utility\TimeFactory()));
134
+    $application->add(new OC\Core\Command\Maintenance\Mimetype\UpdateDB(\OC::$server->getMimeTypeDetector(), \OC::$server->getMimeTypeLoader()));
135
+    $application->add(new OC\Core\Command\Maintenance\Mimetype\UpdateJS(\OC::$server->getMimeTypeDetector()));
136
+    $application->add(new OC\Core\Command\Maintenance\Mode(\OC::$server->getConfig()));
137
+    $application->add(new OC\Core\Command\Maintenance\UpdateHtaccess());
138
+    $application->add(new OC\Core\Command\Maintenance\UpdateTheme(\OC::$server->getMimeTypeDetector(), \OC::$server->getMemCacheFactory()));
139 139
 
140
-	$application->add(new OC\Core\Command\Upgrade(\OC::$server->getConfig(), \OC::$server->getLogger(), \OC::$server->query(Installer::class)));
141
-	$application->add(new OC\Core\Command\Maintenance\Repair(
142
-		new \OC\Repair(\OC\Repair::getRepairSteps(), \OC::$server->getEventDispatcher()), \OC::$server->getConfig(),
143
-		\OC::$server->getEventDispatcher(), \OC::$server->getAppManager()));
140
+    $application->add(new OC\Core\Command\Upgrade(\OC::$server->getConfig(), \OC::$server->getLogger(), \OC::$server->query(Installer::class)));
141
+    $application->add(new OC\Core\Command\Maintenance\Repair(
142
+        new \OC\Repair(\OC\Repair::getRepairSteps(), \OC::$server->getEventDispatcher()), \OC::$server->getConfig(),
143
+        \OC::$server->getEventDispatcher(), \OC::$server->getAppManager()));
144 144
 
145
-	$application->add(new OC\Core\Command\User\Add(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
146
-	$application->add(new OC\Core\Command\User\Delete(\OC::$server->getUserManager()));
147
-	$application->add(new OC\Core\Command\User\Disable(\OC::$server->getUserManager()));
148
-	$application->add(new OC\Core\Command\User\Enable(\OC::$server->getUserManager()));
149
-	$application->add(new OC\Core\Command\User\LastSeen(\OC::$server->getUserManager()));
150
-	$application->add(new OC\Core\Command\User\Report(\OC::$server->getUserManager()));
151
-	$application->add(new OC\Core\Command\User\ResetPassword(\OC::$server->getUserManager()));
152
-	$application->add(new OC\Core\Command\User\Setting(\OC::$server->getUserManager(), \OC::$server->getConfig(), \OC::$server->getDatabaseConnection()));
153
-	$application->add(new OC\Core\Command\User\ListCommand(\OC::$server->getUserManager()));
154
-	$application->add(new OC\Core\Command\User\Info(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
145
+    $application->add(new OC\Core\Command\User\Add(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
146
+    $application->add(new OC\Core\Command\User\Delete(\OC::$server->getUserManager()));
147
+    $application->add(new OC\Core\Command\User\Disable(\OC::$server->getUserManager()));
148
+    $application->add(new OC\Core\Command\User\Enable(\OC::$server->getUserManager()));
149
+    $application->add(new OC\Core\Command\User\LastSeen(\OC::$server->getUserManager()));
150
+    $application->add(new OC\Core\Command\User\Report(\OC::$server->getUserManager()));
151
+    $application->add(new OC\Core\Command\User\ResetPassword(\OC::$server->getUserManager()));
152
+    $application->add(new OC\Core\Command\User\Setting(\OC::$server->getUserManager(), \OC::$server->getConfig(), \OC::$server->getDatabaseConnection()));
153
+    $application->add(new OC\Core\Command\User\ListCommand(\OC::$server->getUserManager()));
154
+    $application->add(new OC\Core\Command\User\Info(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
155 155
 
156
-	$application->add(new OC\Core\Command\Group\ListCommand(\OC::$server->getGroupManager()));
157
-	$application->add(new OC\Core\Command\Group\AddUser(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
158
-	$application->add(new OC\Core\Command\Group\RemoveUser(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
156
+    $application->add(new OC\Core\Command\Group\ListCommand(\OC::$server->getGroupManager()));
157
+    $application->add(new OC\Core\Command\Group\AddUser(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
158
+    $application->add(new OC\Core\Command\Group\RemoveUser(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
159 159
 
160
-	$application->add(new OC\Core\Command\Security\ListCertificates(\OC::$server->getCertificateManager(null), \OC::$server->getL10N('core')));
161
-	$application->add(new OC\Core\Command\Security\ImportCertificate(\OC::$server->getCertificateManager(null)));
162
-	$application->add(new OC\Core\Command\Security\RemoveCertificate(\OC::$server->getCertificateManager(null)));
160
+    $application->add(new OC\Core\Command\Security\ListCertificates(\OC::$server->getCertificateManager(null), \OC::$server->getL10N('core')));
161
+    $application->add(new OC\Core\Command\Security\ImportCertificate(\OC::$server->getCertificateManager(null)));
162
+    $application->add(new OC\Core\Command\Security\RemoveCertificate(\OC::$server->getCertificateManager(null)));
163 163
 } else {
164
-	$application->add(new OC\Core\Command\Maintenance\Install(\OC::$server->getSystemConfig()));
164
+    $application->add(new OC\Core\Command\Maintenance\Install(\OC::$server->getSystemConfig()));
165 165
 }
Please login to merge, or discard this patch.
core/ajax/update.php 1 patch
Indentation   +181 added lines, -181 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
 use Symfony\Component\EventDispatcher\GenericEvent;
32 32
 
33 33
 if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
34
-	@set_time_limit(0);
34
+    @set_time_limit(0);
35 35
 }
36 36
 
37 37
 require_once '../../lib/base.php';
@@ -45,191 +45,191 @@  discard block
 block discarded – undo
45 45
 $eventSource->send('success', (string)$l->t('Preparing update'));
46 46
 
47 47
 class FeedBackHandler {
48
-	/** @var integer */
49
-	private $progressStateMax = 100;
50
-	/** @var integer */
51
-	private $progressStateStep = 0;
52
-	/** @var string */
53
-	private $currentStep;
54
-	/** @var \OCP\IEventSource */
55
-	private $eventSource;
56
-	/** @var \OCP\IL10N */
57
-	private $l10n;
58
-
59
-	public function __construct(\OCP\IEventSource $eventSource, \OCP\IL10N $l10n) {
60
-		$this->eventSource = $eventSource;
61
-		$this->l10n = $l10n;
62
-	}
63
-
64
-	public function handleRepairFeedback($event) {
65
-		if (!$event instanceof GenericEvent) {
66
-			return;
67
-		}
68
-
69
-		switch ($event->getSubject()) {
70
-			case '\OC\Repair::startProgress':
71
-				$this->progressStateMax = $event->getArgument(0);
72
-				$this->progressStateStep = 0;
73
-				$this->currentStep = $event->getArgument(1);
74
-				break;
75
-			case '\OC\Repair::advance':
76
-				$this->progressStateStep += $event->getArgument(0);
77
-				$desc = $event->getArgument(1);
78
-				if (empty($desc)) {
79
-					$desc = $this->currentStep;
80
-				}
81
-				$this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $desc]));
82
-				break;
83
-			case '\OC\Repair::finishProgress':
84
-				$this->progressStateMax = $this->progressStateStep;
85
-				$this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $this->currentStep]));
86
-				break;
87
-			case '\OC\Repair::step':
88
-				break;
89
-			case '\OC\Repair::info':
90
-				break;
91
-			case '\OC\Repair::warning':
92
-				$this->eventSource->send('notice', (string)$this->l10n->t('Repair warning: ') . $event->getArgument(0));
93
-				break;
94
-			case '\OC\Repair::error':
95
-				$this->eventSource->send('notice', (string)$this->l10n->t('Repair error: ') . $event->getArgument(0));
96
-				break;
97
-		}
98
-	}
48
+    /** @var integer */
49
+    private $progressStateMax = 100;
50
+    /** @var integer */
51
+    private $progressStateStep = 0;
52
+    /** @var string */
53
+    private $currentStep;
54
+    /** @var \OCP\IEventSource */
55
+    private $eventSource;
56
+    /** @var \OCP\IL10N */
57
+    private $l10n;
58
+
59
+    public function __construct(\OCP\IEventSource $eventSource, \OCP\IL10N $l10n) {
60
+        $this->eventSource = $eventSource;
61
+        $this->l10n = $l10n;
62
+    }
63
+
64
+    public function handleRepairFeedback($event) {
65
+        if (!$event instanceof GenericEvent) {
66
+            return;
67
+        }
68
+
69
+        switch ($event->getSubject()) {
70
+            case '\OC\Repair::startProgress':
71
+                $this->progressStateMax = $event->getArgument(0);
72
+                $this->progressStateStep = 0;
73
+                $this->currentStep = $event->getArgument(1);
74
+                break;
75
+            case '\OC\Repair::advance':
76
+                $this->progressStateStep += $event->getArgument(0);
77
+                $desc = $event->getArgument(1);
78
+                if (empty($desc)) {
79
+                    $desc = $this->currentStep;
80
+                }
81
+                $this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $desc]));
82
+                break;
83
+            case '\OC\Repair::finishProgress':
84
+                $this->progressStateMax = $this->progressStateStep;
85
+                $this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $this->currentStep]));
86
+                break;
87
+            case '\OC\Repair::step':
88
+                break;
89
+            case '\OC\Repair::info':
90
+                break;
91
+            case '\OC\Repair::warning':
92
+                $this->eventSource->send('notice', (string)$this->l10n->t('Repair warning: ') . $event->getArgument(0));
93
+                break;
94
+            case '\OC\Repair::error':
95
+                $this->eventSource->send('notice', (string)$this->l10n->t('Repair error: ') . $event->getArgument(0));
96
+                break;
97
+        }
98
+    }
99 99
 }
100 100
 
101 101
 if (OC::checkUpgrade(false)) {
102 102
 
103
-	$config = \OC::$server->getSystemConfig();
104
-	if ($config->getValue('upgrade.disable-web', false)) {
105
-		$eventSource->send('failure', (string)$l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
106
-		$eventSource->close();
107
-		exit();
108
-	}
109
-
110
-	// if a user is currently logged in, their session must be ignored to
111
-	// avoid side effects
112
-	\OC_User::setIncognitoMode(true);
113
-
114
-	$logger = \OC::$server->getLogger();
115
-	$config = \OC::$server->getConfig();
116
-	$updater = new \OC\Updater(
117
-			$config,
118
-			\OC::$server->getIntegrityCodeChecker(),
119
-			$logger,
120
-			\OC::$server->query(\OC\Installer::class)
121
-	);
122
-	$incompatibleApps = [];
123
-	$disabledThirdPartyApps = [];
124
-
125
-	$dispatcher = \OC::$server->getEventDispatcher();
126
-	$dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($eventSource, $l) {
127
-		if ($event instanceof GenericEvent) {
128
-			$eventSource->send('success', (string)$l->t('[%d / %d]: %s', [$event[0], $event[1], $event->getSubject()]));
129
-		}
130
-	});
131
-	$dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($eventSource, $l) {
132
-		if ($event instanceof GenericEvent) {
133
-			$eventSource->send('success', (string)$l->t('[%d / %d]: Checking table %s', [$event[0], $event[1], $event->getSubject()]));
134
-		}
135
-	});
136
-	$feedBack = new FeedBackHandler($eventSource, $l);
137
-	$dispatcher->addListener('\OC\Repair::startProgress', [$feedBack, 'handleRepairFeedback']);
138
-	$dispatcher->addListener('\OC\Repair::advance', [$feedBack, 'handleRepairFeedback']);
139
-	$dispatcher->addListener('\OC\Repair::finishProgress', [$feedBack, 'handleRepairFeedback']);
140
-	$dispatcher->addListener('\OC\Repair::step', [$feedBack, 'handleRepairFeedback']);
141
-	$dispatcher->addListener('\OC\Repair::info', [$feedBack, 'handleRepairFeedback']);
142
-	$dispatcher->addListener('\OC\Repair::warning', [$feedBack, 'handleRepairFeedback']);
143
-	$dispatcher->addListener('\OC\Repair::error', [$feedBack, 'handleRepairFeedback']);
144
-
145
-	$updater->listen('\OC\Updater', 'maintenanceEnabled', function () use ($eventSource, $l) {
146
-		$eventSource->send('success', (string)$l->t('Turned on maintenance mode'));
147
-	});
148
-	$updater->listen('\OC\Updater', 'maintenanceDisabled', function () use ($eventSource, $l) {
149
-		$eventSource->send('success', (string)$l->t('Turned off maintenance mode'));
150
-	});
151
-	$updater->listen('\OC\Updater', 'maintenanceActive', function () use ($eventSource, $l) {
152
-		$eventSource->send('success', (string)$l->t('Maintenance mode is kept active'));
153
-	});
154
-	$updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($eventSource, $l) {
155
-		$eventSource->send('success', (string)$l->t('Updating database schema'));
156
-	});
157
-	$updater->listen('\OC\Updater', 'dbUpgrade', function () use ($eventSource, $l) {
158
-		$eventSource->send('success', (string)$l->t('Updated database'));
159
-	});
160
-	$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($eventSource, $l) {
161
-		$eventSource->send('success', (string)$l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)'));
162
-	});
163
-	$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use ($eventSource, $l) {
164
-		$eventSource->send('success', (string)$l->t('Checked database schema update'));
165
-	});
166
-	$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($eventSource, $l) {
167
-		$eventSource->send('success', (string)$l->t('Checking updates of apps'));
168
-	});
169
-	$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($eventSource, $l) {
170
-		$eventSource->send('success', (string)$l->t('Checking for update of app "%s" in appstore', [$app]));
171
-	});
172
-	$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($eventSource, $l) {
173
-		$eventSource->send('success', (string)$l->t('Update app "%s" from appstore', [$app]));
174
-	});
175
-	$updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($eventSource, $l) {
176
-		$eventSource->send('success', (string)$l->t('Checked for update of app "%s" in appstore', [$app]));
177
-	});
178
-	$updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($eventSource, $l) {
179
-		$eventSource->send('success', (string)$l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app]));
180
-	});
181
-	$updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($eventSource, $l) {
182
-		$eventSource->send('success', (string)$l->t('Checked database schema update for apps'));
183
-	});
184
-	$updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($eventSource, $l) {
185
-		$eventSource->send('success', (string)$l->t('Updated "%s" to %s', array($app, $version)));
186
-	});
187
-	$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use (&$incompatibleApps) {
188
-		$incompatibleApps[]= $app;
189
-	});
190
-	$updater->listen('\OC\Updater', 'thirdPartyAppDisabled', function ($app) use (&$disabledThirdPartyApps) {
191
-		$disabledThirdPartyApps[]= $app;
192
-	});
193
-	$updater->listen('\OC\Updater', 'failure', function ($message) use ($eventSource, $config) {
194
-		$eventSource->send('failure', $message);
195
-		$eventSource->close();
196
-		$config->setSystemValue('maintenance', false);
197
-	});
198
-	$updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
199
-		$eventSource->send('success', (string)$l->t('Set log level to debug'));
200
-	});
201
-	$updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
202
-		$eventSource->send('success', (string)$l->t('Reset log level'));
203
-	});
204
-	$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($eventSource, $l) {
205
-		$eventSource->send('success', (string)$l->t('Starting code integrity check'));
206
-	});
207
-	$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($eventSource, $l) {
208
-		$eventSource->send('success', (string)$l->t('Finished code integrity check'));
209
-	});
210
-
211
-	try {
212
-		$updater->upgrade();
213
-	} catch (\Exception $e) {
214
-		$eventSource->send('failure', get_class($e) . ': ' . $e->getMessage());
215
-		$eventSource->close();
216
-		exit();
217
-	}
218
-
219
-	$disabledApps = [];
220
-	foreach ($disabledThirdPartyApps as $app) {
221
-		$disabledApps[$app] = (string) $l->t('%s (3rdparty)', [$app]);
222
-	}
223
-	foreach ($incompatibleApps as $app) {
224
-		$disabledApps[$app] = (string) $l->t('%s (incompatible)', [$app]);
225
-	}
226
-
227
-	if (!empty($disabledApps)) {
228
-		$eventSource->send('notice',
229
-			(string)$l->t('Following apps have been disabled: %s', [implode(', ', $disabledApps)]));
230
-	}
103
+    $config = \OC::$server->getSystemConfig();
104
+    if ($config->getValue('upgrade.disable-web', false)) {
105
+        $eventSource->send('failure', (string)$l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
106
+        $eventSource->close();
107
+        exit();
108
+    }
109
+
110
+    // if a user is currently logged in, their session must be ignored to
111
+    // avoid side effects
112
+    \OC_User::setIncognitoMode(true);
113
+
114
+    $logger = \OC::$server->getLogger();
115
+    $config = \OC::$server->getConfig();
116
+    $updater = new \OC\Updater(
117
+            $config,
118
+            \OC::$server->getIntegrityCodeChecker(),
119
+            $logger,
120
+            \OC::$server->query(\OC\Installer::class)
121
+    );
122
+    $incompatibleApps = [];
123
+    $disabledThirdPartyApps = [];
124
+
125
+    $dispatcher = \OC::$server->getEventDispatcher();
126
+    $dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($eventSource, $l) {
127
+        if ($event instanceof GenericEvent) {
128
+            $eventSource->send('success', (string)$l->t('[%d / %d]: %s', [$event[0], $event[1], $event->getSubject()]));
129
+        }
130
+    });
131
+    $dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($eventSource, $l) {
132
+        if ($event instanceof GenericEvent) {
133
+            $eventSource->send('success', (string)$l->t('[%d / %d]: Checking table %s', [$event[0], $event[1], $event->getSubject()]));
134
+        }
135
+    });
136
+    $feedBack = new FeedBackHandler($eventSource, $l);
137
+    $dispatcher->addListener('\OC\Repair::startProgress', [$feedBack, 'handleRepairFeedback']);
138
+    $dispatcher->addListener('\OC\Repair::advance', [$feedBack, 'handleRepairFeedback']);
139
+    $dispatcher->addListener('\OC\Repair::finishProgress', [$feedBack, 'handleRepairFeedback']);
140
+    $dispatcher->addListener('\OC\Repair::step', [$feedBack, 'handleRepairFeedback']);
141
+    $dispatcher->addListener('\OC\Repair::info', [$feedBack, 'handleRepairFeedback']);
142
+    $dispatcher->addListener('\OC\Repair::warning', [$feedBack, 'handleRepairFeedback']);
143
+    $dispatcher->addListener('\OC\Repair::error', [$feedBack, 'handleRepairFeedback']);
144
+
145
+    $updater->listen('\OC\Updater', 'maintenanceEnabled', function () use ($eventSource, $l) {
146
+        $eventSource->send('success', (string)$l->t('Turned on maintenance mode'));
147
+    });
148
+    $updater->listen('\OC\Updater', 'maintenanceDisabled', function () use ($eventSource, $l) {
149
+        $eventSource->send('success', (string)$l->t('Turned off maintenance mode'));
150
+    });
151
+    $updater->listen('\OC\Updater', 'maintenanceActive', function () use ($eventSource, $l) {
152
+        $eventSource->send('success', (string)$l->t('Maintenance mode is kept active'));
153
+    });
154
+    $updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($eventSource, $l) {
155
+        $eventSource->send('success', (string)$l->t('Updating database schema'));
156
+    });
157
+    $updater->listen('\OC\Updater', 'dbUpgrade', function () use ($eventSource, $l) {
158
+        $eventSource->send('success', (string)$l->t('Updated database'));
159
+    });
160
+    $updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($eventSource, $l) {
161
+        $eventSource->send('success', (string)$l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)'));
162
+    });
163
+    $updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use ($eventSource, $l) {
164
+        $eventSource->send('success', (string)$l->t('Checked database schema update'));
165
+    });
166
+    $updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($eventSource, $l) {
167
+        $eventSource->send('success', (string)$l->t('Checking updates of apps'));
168
+    });
169
+    $updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($eventSource, $l) {
170
+        $eventSource->send('success', (string)$l->t('Checking for update of app "%s" in appstore', [$app]));
171
+    });
172
+    $updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($eventSource, $l) {
173
+        $eventSource->send('success', (string)$l->t('Update app "%s" from appstore', [$app]));
174
+    });
175
+    $updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($eventSource, $l) {
176
+        $eventSource->send('success', (string)$l->t('Checked for update of app "%s" in appstore', [$app]));
177
+    });
178
+    $updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($eventSource, $l) {
179
+        $eventSource->send('success', (string)$l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app]));
180
+    });
181
+    $updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($eventSource, $l) {
182
+        $eventSource->send('success', (string)$l->t('Checked database schema update for apps'));
183
+    });
184
+    $updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($eventSource, $l) {
185
+        $eventSource->send('success', (string)$l->t('Updated "%s" to %s', array($app, $version)));
186
+    });
187
+    $updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use (&$incompatibleApps) {
188
+        $incompatibleApps[]= $app;
189
+    });
190
+    $updater->listen('\OC\Updater', 'thirdPartyAppDisabled', function ($app) use (&$disabledThirdPartyApps) {
191
+        $disabledThirdPartyApps[]= $app;
192
+    });
193
+    $updater->listen('\OC\Updater', 'failure', function ($message) use ($eventSource, $config) {
194
+        $eventSource->send('failure', $message);
195
+        $eventSource->close();
196
+        $config->setSystemValue('maintenance', false);
197
+    });
198
+    $updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
199
+        $eventSource->send('success', (string)$l->t('Set log level to debug'));
200
+    });
201
+    $updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
202
+        $eventSource->send('success', (string)$l->t('Reset log level'));
203
+    });
204
+    $updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($eventSource, $l) {
205
+        $eventSource->send('success', (string)$l->t('Starting code integrity check'));
206
+    });
207
+    $updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($eventSource, $l) {
208
+        $eventSource->send('success', (string)$l->t('Finished code integrity check'));
209
+    });
210
+
211
+    try {
212
+        $updater->upgrade();
213
+    } catch (\Exception $e) {
214
+        $eventSource->send('failure', get_class($e) . ': ' . $e->getMessage());
215
+        $eventSource->close();
216
+        exit();
217
+    }
218
+
219
+    $disabledApps = [];
220
+    foreach ($disabledThirdPartyApps as $app) {
221
+        $disabledApps[$app] = (string) $l->t('%s (3rdparty)', [$app]);
222
+    }
223
+    foreach ($incompatibleApps as $app) {
224
+        $disabledApps[$app] = (string) $l->t('%s (incompatible)', [$app]);
225
+    }
226
+
227
+    if (!empty($disabledApps)) {
228
+        $eventSource->send('notice',
229
+            (string)$l->t('Following apps have been disabled: %s', [implode(', ', $disabledApps)]));
230
+    }
231 231
 } else {
232
-	$eventSource->send('notice', (string)$l->t('Already up to date'));
232
+    $eventSource->send('notice', (string)$l->t('Already up to date'));
233 233
 }
234 234
 
235 235
 $eventSource->send('done', '');
Please login to merge, or discard this patch.
core/Command/Maintenance/Install.php 1 patch
Indentation   +158 added lines, -158 removed lines patch added patch discarded remove patch
@@ -43,162 +43,162 @@
 block discarded – undo
43 43
 
44 44
 class Install extends Command {
45 45
 
46
-	/**
47
-	 * @var SystemConfig
48
-	 */
49
-	private $config;
50
-
51
-	public function __construct(SystemConfig $config) {
52
-		parent::__construct();
53
-		$this->config = $config;
54
-	}
55
-
56
-	protected function configure() {
57
-		$this
58
-			->setName('maintenance:install')
59
-			->setDescription('install Nextcloud')
60
-			->addOption('database', null, InputOption::VALUE_REQUIRED, 'Supported database type', 'sqlite')
61
-			->addOption('database-name', null, InputOption::VALUE_REQUIRED, 'Name of the database')
62
-			->addOption('database-host', null, InputOption::VALUE_REQUIRED, 'Hostname of the database', 'localhost')
63
-			->addOption('database-port', null, InputOption::VALUE_REQUIRED, 'Port the database is listening on')
64
-			->addOption('database-user', null, InputOption::VALUE_REQUIRED, 'User name to connect to the database')
65
-			->addOption('database-pass', null, InputOption::VALUE_OPTIONAL, 'Password of the database user', null)
66
-			->addOption('database-table-prefix', null, InputOption::VALUE_OPTIONAL, 'Prefix for all tables (default: oc_)', null)
67
-			->addOption('database-table-space', null, InputOption::VALUE_OPTIONAL, 'Table space of the database (oci only)', null)
68
-			->addOption('admin-user', null, InputOption::VALUE_REQUIRED, 'User name of the admin account', 'admin')
69
-			->addOption('admin-pass', null, InputOption::VALUE_REQUIRED, 'Password of the admin account')
70
-			->addOption('data-dir', null, InputOption::VALUE_REQUIRED, 'Path to data directory', \OC::$SERVERROOT."/data");
71
-	}
72
-
73
-	protected function execute(InputInterface $input, OutputInterface $output) {
74
-
75
-		// validate the environment
76
-		$server = \OC::$server;
77
-		$setupHelper = new Setup(
78
-			$this->config,
79
-			$server->getIniWrapper(),
80
-			$server->getL10N('lib'),
81
-			$server->query(Defaults::class),
82
-			$server->getLogger(),
83
-			$server->getSecureRandom(),
84
-			\OC::$server->query(Installer::class)
85
-		);
86
-		$sysInfo = $setupHelper->getSystemInfo(true);
87
-		$errors = $sysInfo['errors'];
88
-		if (count($errors) > 0) {
89
-			$this->printErrors($output, $errors);
90
-
91
-			// ignore the OS X setup warning
92
-			if(count($errors) !== 1 ||
93
-				(string)($errors[0]['error']) !== 'Mac OS X is not supported and Nextcloud will not work properly on this platform. Use it at your own risk! ') {
94
-				return 1;
95
-			}
96
-		}
97
-
98
-		// validate user input
99
-		$options = $this->validateInput($input, $output, array_keys($sysInfo['databases']));
100
-
101
-		// perform installation
102
-		$errors = $setupHelper->install($options);
103
-		if (count($errors) > 0) {
104
-			$this->printErrors($output, $errors);
105
-			return 1;
106
-		}
107
-		$output->writeln("Nextcloud was successfully installed");
108
-		return 0;
109
-	}
110
-
111
-	/**
112
-	 * @param InputInterface $input
113
-	 * @param OutputInterface $output
114
-	 * @param string[] $supportedDatabases
115
-	 * @return array
116
-	 */
117
-	protected function validateInput(InputInterface $input, OutputInterface $output, $supportedDatabases) {
118
-		$db = strtolower($input->getOption('database'));
119
-
120
-		if (!in_array($db, $supportedDatabases)) {
121
-			throw new InvalidArgumentException("Database <$db> is not supported.");
122
-		}
123
-
124
-		$dbUser = $input->getOption('database-user');
125
-		$dbPass = $input->getOption('database-pass');
126
-		$dbName = $input->getOption('database-name');
127
-		$dbPort = $input->getOption('database-port');
128
-		if ($db === 'oci') {
129
-			// an empty hostname needs to be read from the raw parameters
130
-			$dbHost = $input->getParameterOption('--database-host', '');
131
-		} else {
132
-			$dbHost = $input->getOption('database-host');
133
-		}
134
-		$dbTablePrefix = 'oc_';
135
-		if ($input->hasParameterOption('--database-table-prefix')) {
136
-			$dbTablePrefix = (string) $input->getOption('database-table-prefix');
137
-			$dbTablePrefix = trim($dbTablePrefix);
138
-		}
139
-		if ($input->hasParameterOption('--database-pass')) {
140
-			$dbPass = (string) $input->getOption('database-pass');
141
-		}
142
-		$adminLogin = $input->getOption('admin-user');
143
-		$adminPassword = $input->getOption('admin-pass');
144
-		$dataDir = $input->getOption('data-dir');
145
-
146
-		if ($db !== 'sqlite') {
147
-			if (is_null($dbUser)) {
148
-				throw new InvalidArgumentException("Database user not provided.");
149
-			}
150
-			if (is_null($dbName)) {
151
-				throw new InvalidArgumentException("Database name not provided.");
152
-			}
153
-			if (is_null($dbPass)) {
154
-				/** @var QuestionHelper $helper */
155
-				$helper = $this->getHelper('question');
156
-				$question = new Question('What is the password to access the database with user <'.$dbUser.'>?');
157
-				$question->setHidden(true);
158
-				$question->setHiddenFallback(false);
159
-				$dbPass = $helper->ask($input, $output, $question);
160
-			}
161
-		}
162
-
163
-		if (is_null($adminPassword)) {
164
-			/** @var QuestionHelper $helper */
165
-			$helper = $this->getHelper('question');
166
-			$question = new Question('What is the password you like to use for the admin account <'.$adminLogin.'>?');
167
-			$question->setHidden(true);
168
-			$question->setHiddenFallback(false);
169
-			$adminPassword = $helper->ask($input, $output, $question);
170
-		}
171
-
172
-		$options = [
173
-			'dbtype' => $db,
174
-			'dbuser' => $dbUser,
175
-			'dbpass' => $dbPass,
176
-			'dbname' => $dbName,
177
-			'dbhost' => $dbHost,
178
-			'dbport' => $dbPort,
179
-			'dbtableprefix' => $dbTablePrefix,
180
-			'adminlogin' => $adminLogin,
181
-			'adminpass' => $adminPassword,
182
-			'directory' => $dataDir
183
-		];
184
-		if ($db === 'oci') {
185
-			$options['dbtablespace'] = $input->getParameterOption('--database-table-space', '');
186
-		}
187
-		return $options;
188
-	}
189
-
190
-	/**
191
-	 * @param OutputInterface $output
192
-	 * @param $errors
193
-	 */
194
-	protected function printErrors(OutputInterface $output, $errors) {
195
-		foreach ($errors as $error) {
196
-			if (is_array($error)) {
197
-				$output->writeln('<error>' . (string)$error['error'] . '</error>');
198
-				$output->writeln('<info> -> ' . (string)$error['hint'] . '</info>');
199
-			} else {
200
-				$output->writeln('<error>' . (string)$error . '</error>');
201
-			}
202
-		}
203
-	}
46
+    /**
47
+     * @var SystemConfig
48
+     */
49
+    private $config;
50
+
51
+    public function __construct(SystemConfig $config) {
52
+        parent::__construct();
53
+        $this->config = $config;
54
+    }
55
+
56
+    protected function configure() {
57
+        $this
58
+            ->setName('maintenance:install')
59
+            ->setDescription('install Nextcloud')
60
+            ->addOption('database', null, InputOption::VALUE_REQUIRED, 'Supported database type', 'sqlite')
61
+            ->addOption('database-name', null, InputOption::VALUE_REQUIRED, 'Name of the database')
62
+            ->addOption('database-host', null, InputOption::VALUE_REQUIRED, 'Hostname of the database', 'localhost')
63
+            ->addOption('database-port', null, InputOption::VALUE_REQUIRED, 'Port the database is listening on')
64
+            ->addOption('database-user', null, InputOption::VALUE_REQUIRED, 'User name to connect to the database')
65
+            ->addOption('database-pass', null, InputOption::VALUE_OPTIONAL, 'Password of the database user', null)
66
+            ->addOption('database-table-prefix', null, InputOption::VALUE_OPTIONAL, 'Prefix for all tables (default: oc_)', null)
67
+            ->addOption('database-table-space', null, InputOption::VALUE_OPTIONAL, 'Table space of the database (oci only)', null)
68
+            ->addOption('admin-user', null, InputOption::VALUE_REQUIRED, 'User name of the admin account', 'admin')
69
+            ->addOption('admin-pass', null, InputOption::VALUE_REQUIRED, 'Password of the admin account')
70
+            ->addOption('data-dir', null, InputOption::VALUE_REQUIRED, 'Path to data directory', \OC::$SERVERROOT."/data");
71
+    }
72
+
73
+    protected function execute(InputInterface $input, OutputInterface $output) {
74
+
75
+        // validate the environment
76
+        $server = \OC::$server;
77
+        $setupHelper = new Setup(
78
+            $this->config,
79
+            $server->getIniWrapper(),
80
+            $server->getL10N('lib'),
81
+            $server->query(Defaults::class),
82
+            $server->getLogger(),
83
+            $server->getSecureRandom(),
84
+            \OC::$server->query(Installer::class)
85
+        );
86
+        $sysInfo = $setupHelper->getSystemInfo(true);
87
+        $errors = $sysInfo['errors'];
88
+        if (count($errors) > 0) {
89
+            $this->printErrors($output, $errors);
90
+
91
+            // ignore the OS X setup warning
92
+            if(count($errors) !== 1 ||
93
+                (string)($errors[0]['error']) !== 'Mac OS X is not supported and Nextcloud will not work properly on this platform. Use it at your own risk! ') {
94
+                return 1;
95
+            }
96
+        }
97
+
98
+        // validate user input
99
+        $options = $this->validateInput($input, $output, array_keys($sysInfo['databases']));
100
+
101
+        // perform installation
102
+        $errors = $setupHelper->install($options);
103
+        if (count($errors) > 0) {
104
+            $this->printErrors($output, $errors);
105
+            return 1;
106
+        }
107
+        $output->writeln("Nextcloud was successfully installed");
108
+        return 0;
109
+    }
110
+
111
+    /**
112
+     * @param InputInterface $input
113
+     * @param OutputInterface $output
114
+     * @param string[] $supportedDatabases
115
+     * @return array
116
+     */
117
+    protected function validateInput(InputInterface $input, OutputInterface $output, $supportedDatabases) {
118
+        $db = strtolower($input->getOption('database'));
119
+
120
+        if (!in_array($db, $supportedDatabases)) {
121
+            throw new InvalidArgumentException("Database <$db> is not supported.");
122
+        }
123
+
124
+        $dbUser = $input->getOption('database-user');
125
+        $dbPass = $input->getOption('database-pass');
126
+        $dbName = $input->getOption('database-name');
127
+        $dbPort = $input->getOption('database-port');
128
+        if ($db === 'oci') {
129
+            // an empty hostname needs to be read from the raw parameters
130
+            $dbHost = $input->getParameterOption('--database-host', '');
131
+        } else {
132
+            $dbHost = $input->getOption('database-host');
133
+        }
134
+        $dbTablePrefix = 'oc_';
135
+        if ($input->hasParameterOption('--database-table-prefix')) {
136
+            $dbTablePrefix = (string) $input->getOption('database-table-prefix');
137
+            $dbTablePrefix = trim($dbTablePrefix);
138
+        }
139
+        if ($input->hasParameterOption('--database-pass')) {
140
+            $dbPass = (string) $input->getOption('database-pass');
141
+        }
142
+        $adminLogin = $input->getOption('admin-user');
143
+        $adminPassword = $input->getOption('admin-pass');
144
+        $dataDir = $input->getOption('data-dir');
145
+
146
+        if ($db !== 'sqlite') {
147
+            if (is_null($dbUser)) {
148
+                throw new InvalidArgumentException("Database user not provided.");
149
+            }
150
+            if (is_null($dbName)) {
151
+                throw new InvalidArgumentException("Database name not provided.");
152
+            }
153
+            if (is_null($dbPass)) {
154
+                /** @var QuestionHelper $helper */
155
+                $helper = $this->getHelper('question');
156
+                $question = new Question('What is the password to access the database with user <'.$dbUser.'>?');
157
+                $question->setHidden(true);
158
+                $question->setHiddenFallback(false);
159
+                $dbPass = $helper->ask($input, $output, $question);
160
+            }
161
+        }
162
+
163
+        if (is_null($adminPassword)) {
164
+            /** @var QuestionHelper $helper */
165
+            $helper = $this->getHelper('question');
166
+            $question = new Question('What is the password you like to use for the admin account <'.$adminLogin.'>?');
167
+            $question->setHidden(true);
168
+            $question->setHiddenFallback(false);
169
+            $adminPassword = $helper->ask($input, $output, $question);
170
+        }
171
+
172
+        $options = [
173
+            'dbtype' => $db,
174
+            'dbuser' => $dbUser,
175
+            'dbpass' => $dbPass,
176
+            'dbname' => $dbName,
177
+            'dbhost' => $dbHost,
178
+            'dbport' => $dbPort,
179
+            'dbtableprefix' => $dbTablePrefix,
180
+            'adminlogin' => $adminLogin,
181
+            'adminpass' => $adminPassword,
182
+            'directory' => $dataDir
183
+        ];
184
+        if ($db === 'oci') {
185
+            $options['dbtablespace'] = $input->getParameterOption('--database-table-space', '');
186
+        }
187
+        return $options;
188
+    }
189
+
190
+    /**
191
+     * @param OutputInterface $output
192
+     * @param $errors
193
+     */
194
+    protected function printErrors(OutputInterface $output, $errors) {
195
+        foreach ($errors as $error) {
196
+            if (is_array($error)) {
197
+                $output->writeln('<error>' . (string)$error['error'] . '</error>');
198
+                $output->writeln('<info> -> ' . (string)$error['hint'] . '</info>');
199
+            } else {
200
+                $output->writeln('<error>' . (string)$error . '</error>');
201
+            }
202
+        }
203
+    }
204 204
 }
Please login to merge, or discard this patch.
core/Command/App/Install.php 2 patches
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -30,42 +30,42 @@
 block discarded – undo
30 30
 
31 31
 class Install extends Command {
32 32
 
33
-	protected function configure() {
34
-		$this
35
-			->setName('app:install')
36
-			->setDescription('install an app')
37
-			->addArgument(
38
-				'app-id',
39
-				InputArgument::REQUIRED,
40
-				'install the specified app'
41
-			)
42
-		;
43
-	}
33
+    protected function configure() {
34
+        $this
35
+            ->setName('app:install')
36
+            ->setDescription('install an app')
37
+            ->addArgument(
38
+                'app-id',
39
+                InputArgument::REQUIRED,
40
+                'install the specified app'
41
+            )
42
+        ;
43
+    }
44 44
 
45
-	protected function execute(InputInterface $input, OutputInterface $output) {
46
-		$appId = $input->getArgument('app-id');
45
+    protected function execute(InputInterface $input, OutputInterface $output) {
46
+        $appId = $input->getArgument('app-id');
47 47
 
48
-		if (\OC_App::getAppPath($appId)) {
49
-			$output->writeln($appId . ' already installed');
50
-			return 1;
51
-		}
48
+        if (\OC_App::getAppPath($appId)) {
49
+            $output->writeln($appId . ' already installed');
50
+            return 1;
51
+        }
52 52
 
53
-		try {
54
-			$installer = \OC::$server->query(Installer::class);
55
-			$installer->downloadApp($appId);
56
-			$result = $installer->installApp($appId);
57
-		} catch(\Exception $e) {
58
-			$output->writeln('Error: ' . $e->getMessage());
59
-			return 1;
60
-		}
53
+        try {
54
+            $installer = \OC::$server->query(Installer::class);
55
+            $installer->downloadApp($appId);
56
+            $result = $installer->installApp($appId);
57
+        } catch(\Exception $e) {
58
+            $output->writeln('Error: ' . $e->getMessage());
59
+            return 1;
60
+        }
61 61
 
62
-		if($result === false) {
63
-			$output->writeln($appId . ' couldn\'t be installed');
64
-			return 1;
65
-		}
62
+        if($result === false) {
63
+            $output->writeln($appId . ' couldn\'t be installed');
64
+            return 1;
65
+        }
66 66
 
67
-		$output->writeln($appId . ' installed');
67
+        $output->writeln($appId . ' installed');
68 68
 
69
-		return 0;
70
-	}
69
+        return 0;
70
+    }
71 71
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
 		$appId = $input->getArgument('app-id');
47 47
 
48 48
 		if (\OC_App::getAppPath($appId)) {
49
-			$output->writeln($appId . ' already installed');
49
+			$output->writeln($appId.' already installed');
50 50
 			return 1;
51 51
 		}
52 52
 
@@ -54,17 +54,17 @@  discard block
 block discarded – undo
54 54
 			$installer = \OC::$server->query(Installer::class);
55 55
 			$installer->downloadApp($appId);
56 56
 			$result = $installer->installApp($appId);
57
-		} catch(\Exception $e) {
58
-			$output->writeln('Error: ' . $e->getMessage());
57
+		} catch (\Exception $e) {
58
+			$output->writeln('Error: '.$e->getMessage());
59 59
 			return 1;
60 60
 		}
61 61
 
62
-		if($result === false) {
63
-			$output->writeln($appId . ' couldn\'t be installed');
62
+		if ($result === false) {
63
+			$output->writeln($appId.' couldn\'t be installed');
64 64
 			return 1;
65 65
 		}
66 66
 
67
-		$output->writeln($appId . ' installed');
67
+		$output->writeln($appId.' installed');
68 68
 
69 69
 		return 0;
70 70
 	}
Please login to merge, or discard this patch.
core/Command/Upgrade.php 1 patch
Indentation   +242 added lines, -242 removed lines patch added patch discarded remove patch
@@ -48,263 +48,263 @@
 block discarded – undo
48 48
 
49 49
 class Upgrade extends Command {
50 50
 
51
-	const ERROR_SUCCESS = 0;
52
-	const ERROR_NOT_INSTALLED = 1;
53
-	const ERROR_MAINTENANCE_MODE = 2;
54
-	const ERROR_UP_TO_DATE = 0;
55
-	const ERROR_INVALID_ARGUMENTS = 4;
56
-	const ERROR_FAILURE = 5;
51
+    const ERROR_SUCCESS = 0;
52
+    const ERROR_NOT_INSTALLED = 1;
53
+    const ERROR_MAINTENANCE_MODE = 2;
54
+    const ERROR_UP_TO_DATE = 0;
55
+    const ERROR_INVALID_ARGUMENTS = 4;
56
+    const ERROR_FAILURE = 5;
57 57
 
58
-	/** @var IConfig */
59
-	private $config;
58
+    /** @var IConfig */
59
+    private $config;
60 60
 
61
-	/** @var ILogger */
62
-	private $logger;
61
+    /** @var ILogger */
62
+    private $logger;
63 63
 
64
-	/**
65
-	 * @param IConfig $config
66
-	 * @param ILogger $logger
67
-	 * @param Installer $installer
68
-	 */
69
-	public function __construct(IConfig $config, ILogger $logger, Installer $installer) {
70
-		parent::__construct();
71
-		$this->config = $config;
72
-		$this->logger = $logger;
73
-		$this->installer = $installer;
74
-	}
64
+    /**
65
+     * @param IConfig $config
66
+     * @param ILogger $logger
67
+     * @param Installer $installer
68
+     */
69
+    public function __construct(IConfig $config, ILogger $logger, Installer $installer) {
70
+        parent::__construct();
71
+        $this->config = $config;
72
+        $this->logger = $logger;
73
+        $this->installer = $installer;
74
+    }
75 75
 
76
-	protected function configure() {
77
-		$this
78
-			->setName('upgrade')
79
-			->setDescription('run upgrade routines after installation of a new release. The release has to be installed before.')
80
-			->addOption(
81
-				'--no-app-disable',
82
-				null,
83
-				InputOption::VALUE_NONE,
84
-				'skips the disable of third party apps'
85
-			);
86
-	}
76
+    protected function configure() {
77
+        $this
78
+            ->setName('upgrade')
79
+            ->setDescription('run upgrade routines after installation of a new release. The release has to be installed before.')
80
+            ->addOption(
81
+                '--no-app-disable',
82
+                null,
83
+                InputOption::VALUE_NONE,
84
+                'skips the disable of third party apps'
85
+            );
86
+    }
87 87
 
88
-	/**
89
-	 * Execute the upgrade command
90
-	 *
91
-	 * @param InputInterface $input input interface
92
-	 * @param OutputInterface $output output interface
93
-	 */
94
-	protected function execute(InputInterface $input, OutputInterface $output) {
88
+    /**
89
+     * Execute the upgrade command
90
+     *
91
+     * @param InputInterface $input input interface
92
+     * @param OutputInterface $output output interface
93
+     */
94
+    protected function execute(InputInterface $input, OutputInterface $output) {
95 95
 
96
-		if(\OC::checkUpgrade(false)) {
97
-			if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
98
-				// Prepend each line with a little timestamp
99
-				$timestampFormatter = new TimestampFormatter($this->config, $output->getFormatter());
100
-				$output->setFormatter($timestampFormatter);
101
-			}
96
+        if(\OC::checkUpgrade(false)) {
97
+            if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
98
+                // Prepend each line with a little timestamp
99
+                $timestampFormatter = new TimestampFormatter($this->config, $output->getFormatter());
100
+                $output->setFormatter($timestampFormatter);
101
+            }
102 102
 
103
-			$self = $this;
104
-			$updater = new Updater(
105
-					$this->config,
106
-					\OC::$server->getIntegrityCodeChecker(),
107
-					$this->logger,
108
-					$this->installer
109
-			);
103
+            $self = $this;
104
+            $updater = new Updater(
105
+                    $this->config,
106
+                    \OC::$server->getIntegrityCodeChecker(),
107
+                    $this->logger,
108
+                    $this->installer
109
+            );
110 110
 
111
-			if ($input->getOption('no-app-disable')) {
112
-				$updater->setSkip3rdPartyAppsDisable(true);
113
-			}
114
-			$dispatcher = \OC::$server->getEventDispatcher();
115
-			$progress = new ProgressBar($output);
116
-			$progress->setFormat(" %message%\n %current%/%max% [%bar%] %percent:3s%%");
117
-			$listener = function($event) use ($progress, $output) {
118
-				if ($event instanceof GenericEvent) {
119
-					$message = $event->getSubject();
120
-					if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
121
-						$output->writeln(' Checking table ' . $message);
122
-					} else {
123
-						if (strlen($message) > 60) {
124
-							$message = substr($message, 0, 57) . '...';
125
-						}
126
-						$progress->setMessage($message);
127
-						if ($event[0] === 1) {
128
-							$output->writeln('');
129
-							$progress->start($event[1]);
130
-						}
131
-						$progress->setProgress($event[0]);
132
-						if ($event[0] === $event[1]) {
133
-							$progress->setMessage('Done');
134
-							$progress->finish();
135
-							$output->writeln('');
136
-						}
137
-					}
138
-				}
139
-			};
140
-			$repairListener = function($event) use ($progress, $output) {
141
-				if (!$event instanceof GenericEvent) {
142
-					return;
143
-				}
144
-				switch ($event->getSubject()) {
145
-					case '\OC\Repair::startProgress':
146
-						$progress->setMessage('Starting ...');
147
-						$output->writeln($event->getArgument(1));
148
-						$output->writeln('');
149
-						$progress->start($event->getArgument(0));
150
-						break;
151
-					case '\OC\Repair::advance':
152
-						$desc = $event->getArgument(1);
153
-						if (!empty($desc)) {
154
-							$progress->setMessage($desc);
155
-						}
156
-						$progress->advance($event->getArgument(0));
111
+            if ($input->getOption('no-app-disable')) {
112
+                $updater->setSkip3rdPartyAppsDisable(true);
113
+            }
114
+            $dispatcher = \OC::$server->getEventDispatcher();
115
+            $progress = new ProgressBar($output);
116
+            $progress->setFormat(" %message%\n %current%/%max% [%bar%] %percent:3s%%");
117
+            $listener = function($event) use ($progress, $output) {
118
+                if ($event instanceof GenericEvent) {
119
+                    $message = $event->getSubject();
120
+                    if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
121
+                        $output->writeln(' Checking table ' . $message);
122
+                    } else {
123
+                        if (strlen($message) > 60) {
124
+                            $message = substr($message, 0, 57) . '...';
125
+                        }
126
+                        $progress->setMessage($message);
127
+                        if ($event[0] === 1) {
128
+                            $output->writeln('');
129
+                            $progress->start($event[1]);
130
+                        }
131
+                        $progress->setProgress($event[0]);
132
+                        if ($event[0] === $event[1]) {
133
+                            $progress->setMessage('Done');
134
+                            $progress->finish();
135
+                            $output->writeln('');
136
+                        }
137
+                    }
138
+                }
139
+            };
140
+            $repairListener = function($event) use ($progress, $output) {
141
+                if (!$event instanceof GenericEvent) {
142
+                    return;
143
+                }
144
+                switch ($event->getSubject()) {
145
+                    case '\OC\Repair::startProgress':
146
+                        $progress->setMessage('Starting ...');
147
+                        $output->writeln($event->getArgument(1));
148
+                        $output->writeln('');
149
+                        $progress->start($event->getArgument(0));
150
+                        break;
151
+                    case '\OC\Repair::advance':
152
+                        $desc = $event->getArgument(1);
153
+                        if (!empty($desc)) {
154
+                            $progress->setMessage($desc);
155
+                        }
156
+                        $progress->advance($event->getArgument(0));
157 157
 
158
-						break;
159
-					case '\OC\Repair::finishProgress':
160
-						$progress->setMessage('Done');
161
-						$progress->finish();
162
-						$output->writeln('');
163
-						break;
164
-					case '\OC\Repair::step':
165
-						if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
166
-							$output->writeln('<info>Repair step: ' . $event->getArgument(0) . '</info>');
167
-						}
168
-						break;
169
-					case '\OC\Repair::info':
170
-						if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
171
-							$output->writeln('<info>Repair info: ' . $event->getArgument(0) . '</info>');
172
-						}
173
-						break;
174
-					case '\OC\Repair::warning':
175
-						$output->writeln('<error>Repair warning: ' . $event->getArgument(0) . '</error>');
176
-						break;
177
-					case '\OC\Repair::error':
178
-						$output->writeln('<error>Repair error: ' . $event->getArgument(0) . '</error>');
179
-						break;
180
-				}
181
-			};
158
+                        break;
159
+                    case '\OC\Repair::finishProgress':
160
+                        $progress->setMessage('Done');
161
+                        $progress->finish();
162
+                        $output->writeln('');
163
+                        break;
164
+                    case '\OC\Repair::step':
165
+                        if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
166
+                            $output->writeln('<info>Repair step: ' . $event->getArgument(0) . '</info>');
167
+                        }
168
+                        break;
169
+                    case '\OC\Repair::info':
170
+                        if(OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
171
+                            $output->writeln('<info>Repair info: ' . $event->getArgument(0) . '</info>');
172
+                        }
173
+                        break;
174
+                    case '\OC\Repair::warning':
175
+                        $output->writeln('<error>Repair warning: ' . $event->getArgument(0) . '</error>');
176
+                        break;
177
+                    case '\OC\Repair::error':
178
+                        $output->writeln('<error>Repair error: ' . $event->getArgument(0) . '</error>');
179
+                        break;
180
+                }
181
+            };
182 182
 
183
-			$dispatcher->addListener('\OC\DB\Migrator::executeSql', $listener);
184
-			$dispatcher->addListener('\OC\DB\Migrator::checkTable', $listener);
185
-			$dispatcher->addListener('\OC\Repair::startProgress', $repairListener);
186
-			$dispatcher->addListener('\OC\Repair::advance', $repairListener);
187
-			$dispatcher->addListener('\OC\Repair::finishProgress', $repairListener);
188
-			$dispatcher->addListener('\OC\Repair::step', $repairListener);
189
-			$dispatcher->addListener('\OC\Repair::info', $repairListener);
190
-			$dispatcher->addListener('\OC\Repair::warning', $repairListener);
191
-			$dispatcher->addListener('\OC\Repair::error', $repairListener);
183
+            $dispatcher->addListener('\OC\DB\Migrator::executeSql', $listener);
184
+            $dispatcher->addListener('\OC\DB\Migrator::checkTable', $listener);
185
+            $dispatcher->addListener('\OC\Repair::startProgress', $repairListener);
186
+            $dispatcher->addListener('\OC\Repair::advance', $repairListener);
187
+            $dispatcher->addListener('\OC\Repair::finishProgress', $repairListener);
188
+            $dispatcher->addListener('\OC\Repair::step', $repairListener);
189
+            $dispatcher->addListener('\OC\Repair::info', $repairListener);
190
+            $dispatcher->addListener('\OC\Repair::warning', $repairListener);
191
+            $dispatcher->addListener('\OC\Repair::error', $repairListener);
192 192
 			
193 193
 
194
-			$updater->listen('\OC\Updater', 'maintenanceEnabled', function () use($output) {
195
-				$output->writeln('<info>Turned on maintenance mode</info>');
196
-			});
197
-			$updater->listen('\OC\Updater', 'maintenanceDisabled', function () use($output) {
198
-				$output->writeln('<info>Turned off maintenance mode</info>');
199
-			});
200
-			$updater->listen('\OC\Updater', 'maintenanceActive', function () use($output) {
201
-				$output->writeln('<info>Maintenance mode is kept active</info>');
202
-			});
203
-			$updater->listen('\OC\Updater', 'updateEnd',
204
-				function ($success) use($output, $self) {
205
-					if ($success) {
206
-						$message = "<info>Update successful</info>";
207
-					} else {
208
-						$message = "<error>Update failed</error>";
209
-					}
210
-					$output->writeln($message);
211
-				});
212
-			$updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($output) {
213
-				$output->writeln('<info>Updating database schema</info>');
214
-			});
215
-			$updater->listen('\OC\Updater', 'dbUpgrade', function () use($output) {
216
-				$output->writeln('<info>Updated database</info>');
217
-			});
218
-			$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($output) {
219
-				$output->writeln('<info>Checking whether the database schema can be updated (this can take a long time depending on the database size)</info>');
220
-			});
221
-			$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($output) {
222
-				$output->writeln('<info>Checked database schema update</info>');
223
-			});
224
-			$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($output) {
225
-				$output->writeln('<comment>Disabled incompatible app: ' . $app . '</comment>');
226
-			});
227
-			$updater->listen('\OC\Updater', 'thirdPartyAppDisabled', function ($app) use ($output) {
228
-				$output->writeln('<comment>Disabled 3rd-party app: ' . $app . '</comment>');
229
-			});
230
-			$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use($output) {
231
-				$output->writeln('<info>Checking for update of app ' . $app . ' in appstore</info>');
232
-			});
233
-			$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($output) {
234
-				$output->writeln('<info>Update app ' . $app . ' from appstore</info>');
235
-			});
236
-			$updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use($output) {
237
-				$output->writeln('<info>Checked for update of app "' . $app . '" in appstore </info>');
238
-			});
239
-			$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($output) {
240
-				$output->writeln('<info>Checking updates of apps</info>');
241
-			});
242
-			$updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($output) {
243
-				$output->writeln("<info>Checking whether the database schema for <$app> can be updated (this can take a long time depending on the database size)</info>");
244
-			});
245
-			$updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($output) {
246
-				$output->writeln('<info>Checked database schema update for apps</info>');
247
-			});
248
-			$updater->listen('\OC\Updater', 'appUpgradeStarted', function ($app, $version) use ($output) {
249
-				$output->writeln("<info>Updating <$app> ...</info>");
250
-			});
251
-			$updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($output) {
252
-				$output->writeln("<info>Updated <$app> to $version</info>");
253
-			});
254
-			$updater->listen('\OC\Updater', 'failure', function ($message) use($output, $self) {
255
-				$output->writeln("<error>$message</error>");
256
-			});
257
-			$updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($output) {
258
-				$output->writeln("<info>Set log level to debug</info>");
259
-			});
260
-			$updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($output) {
261
-				$output->writeln("<info>Reset log level</info>");
262
-			});
263
-			$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($output) {
264
-				$output->writeln("<info>Starting code integrity check...</info>");
265
-			});
266
-			$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($output) {
267
-				$output->writeln("<info>Finished code integrity check</info>");
268
-			});
194
+            $updater->listen('\OC\Updater', 'maintenanceEnabled', function () use($output) {
195
+                $output->writeln('<info>Turned on maintenance mode</info>');
196
+            });
197
+            $updater->listen('\OC\Updater', 'maintenanceDisabled', function () use($output) {
198
+                $output->writeln('<info>Turned off maintenance mode</info>');
199
+            });
200
+            $updater->listen('\OC\Updater', 'maintenanceActive', function () use($output) {
201
+                $output->writeln('<info>Maintenance mode is kept active</info>');
202
+            });
203
+            $updater->listen('\OC\Updater', 'updateEnd',
204
+                function ($success) use($output, $self) {
205
+                    if ($success) {
206
+                        $message = "<info>Update successful</info>";
207
+                    } else {
208
+                        $message = "<error>Update failed</error>";
209
+                    }
210
+                    $output->writeln($message);
211
+                });
212
+            $updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($output) {
213
+                $output->writeln('<info>Updating database schema</info>');
214
+            });
215
+            $updater->listen('\OC\Updater', 'dbUpgrade', function () use($output) {
216
+                $output->writeln('<info>Updated database</info>');
217
+            });
218
+            $updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($output) {
219
+                $output->writeln('<info>Checking whether the database schema can be updated (this can take a long time depending on the database size)</info>');
220
+            });
221
+            $updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($output) {
222
+                $output->writeln('<info>Checked database schema update</info>');
223
+            });
224
+            $updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($output) {
225
+                $output->writeln('<comment>Disabled incompatible app: ' . $app . '</comment>');
226
+            });
227
+            $updater->listen('\OC\Updater', 'thirdPartyAppDisabled', function ($app) use ($output) {
228
+                $output->writeln('<comment>Disabled 3rd-party app: ' . $app . '</comment>');
229
+            });
230
+            $updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use($output) {
231
+                $output->writeln('<info>Checking for update of app ' . $app . ' in appstore</info>');
232
+            });
233
+            $updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($output) {
234
+                $output->writeln('<info>Update app ' . $app . ' from appstore</info>');
235
+            });
236
+            $updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use($output) {
237
+                $output->writeln('<info>Checked for update of app "' . $app . '" in appstore </info>');
238
+            });
239
+            $updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($output) {
240
+                $output->writeln('<info>Checking updates of apps</info>');
241
+            });
242
+            $updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($output) {
243
+                $output->writeln("<info>Checking whether the database schema for <$app> can be updated (this can take a long time depending on the database size)</info>");
244
+            });
245
+            $updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($output) {
246
+                $output->writeln('<info>Checked database schema update for apps</info>');
247
+            });
248
+            $updater->listen('\OC\Updater', 'appUpgradeStarted', function ($app, $version) use ($output) {
249
+                $output->writeln("<info>Updating <$app> ...</info>");
250
+            });
251
+            $updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($output) {
252
+                $output->writeln("<info>Updated <$app> to $version</info>");
253
+            });
254
+            $updater->listen('\OC\Updater', 'failure', function ($message) use($output, $self) {
255
+                $output->writeln("<error>$message</error>");
256
+            });
257
+            $updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($output) {
258
+                $output->writeln("<info>Set log level to debug</info>");
259
+            });
260
+            $updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($output) {
261
+                $output->writeln("<info>Reset log level</info>");
262
+            });
263
+            $updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($output) {
264
+                $output->writeln("<info>Starting code integrity check...</info>");
265
+            });
266
+            $updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($output) {
267
+                $output->writeln("<info>Finished code integrity check</info>");
268
+            });
269 269
 
270
-			$success = $updater->upgrade();
270
+            $success = $updater->upgrade();
271 271
 
272
-			$this->postUpgradeCheck($input, $output);
272
+            $this->postUpgradeCheck($input, $output);
273 273
 
274
-			if(!$success) {
275
-				return self::ERROR_FAILURE;
276
-			}
274
+            if(!$success) {
275
+                return self::ERROR_FAILURE;
276
+            }
277 277
 
278
-			return self::ERROR_SUCCESS;
279
-		} else if($this->config->getSystemValue('maintenance', false)) {
280
-			//Possible scenario: Nextcloud core is updated but an app failed
281
-			$output->writeln('<warning>Nextcloud is in maintenance mode</warning>');
282
-			$output->write('<comment>Maybe an upgrade is already in process. Please check the '
283
-				. 'logfile (data/nextcloud.log). If you want to re-run the '
284
-				. 'upgrade procedure, remove the "maintenance mode" from '
285
-				. 'config.php and call this script again.</comment>'
286
-				, true);
287
-			return self::ERROR_MAINTENANCE_MODE;
288
-		} else {
289
-			$output->writeln('<info>Nextcloud is already latest version</info>');
290
-			return self::ERROR_UP_TO_DATE;
291
-		}
292
-	}
278
+            return self::ERROR_SUCCESS;
279
+        } else if($this->config->getSystemValue('maintenance', false)) {
280
+            //Possible scenario: Nextcloud core is updated but an app failed
281
+            $output->writeln('<warning>Nextcloud is in maintenance mode</warning>');
282
+            $output->write('<comment>Maybe an upgrade is already in process. Please check the '
283
+                . 'logfile (data/nextcloud.log). If you want to re-run the '
284
+                . 'upgrade procedure, remove the "maintenance mode" from '
285
+                . 'config.php and call this script again.</comment>'
286
+                , true);
287
+            return self::ERROR_MAINTENANCE_MODE;
288
+        } else {
289
+            $output->writeln('<info>Nextcloud is already latest version</info>');
290
+            return self::ERROR_UP_TO_DATE;
291
+        }
292
+    }
293 293
 
294
-	/**
295
-	 * Perform a post upgrade check (specific to the command line tool)
296
-	 *
297
-	 * @param InputInterface $input input interface
298
-	 * @param OutputInterface $output output interface
299
-	 */
300
-	protected function postUpgradeCheck(InputInterface $input, OutputInterface $output) {
301
-		$trustedDomains = $this->config->getSystemValue('trusted_domains', array());
302
-		if (empty($trustedDomains)) {
303
-			$output->write(
304
-				'<warning>The setting "trusted_domains" could not be ' .
305
-				'set automatically by the upgrade script, ' .
306
-				'please set it manually</warning>'
307
-			);
308
-		}
309
-	}
294
+    /**
295
+     * Perform a post upgrade check (specific to the command line tool)
296
+     *
297
+     * @param InputInterface $input input interface
298
+     * @param OutputInterface $output output interface
299
+     */
300
+    protected function postUpgradeCheck(InputInterface $input, OutputInterface $output) {
301
+        $trustedDomains = $this->config->getSystemValue('trusted_domains', array());
302
+        if (empty($trustedDomains)) {
303
+            $output->write(
304
+                '<warning>The setting "trusted_domains" could not be ' .
305
+                'set automatically by the upgrade script, ' .
306
+                'please set it manually</warning>'
307
+            );
308
+        }
309
+    }
310 310
 }
Please login to merge, or discard this patch.
lib/base.php 1 patch
Indentation   +996 added lines, -996 removed lines patch added patch discarded remove patch
@@ -62,1002 +62,1002 @@
 block discarded – undo
62 62
  * OC_autoload!
63 63
  */
64 64
 class OC {
65
-	/**
66
-	 * Associative array for autoloading. classname => filename
67
-	 */
68
-	public static $CLASSPATH = array();
69
-	/**
70
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
71
-	 */
72
-	public static $SERVERROOT = '';
73
-	/**
74
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
75
-	 */
76
-	private static $SUBURI = '';
77
-	/**
78
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
79
-	 */
80
-	public static $WEBROOT = '';
81
-	/**
82
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
83
-	 * web path in 'url'
84
-	 */
85
-	public static $APPSROOTS = array();
86
-
87
-	/**
88
-	 * @var string
89
-	 */
90
-	public static $configDir;
91
-
92
-	/**
93
-	 * requested app
94
-	 */
95
-	public static $REQUESTEDAPP = '';
96
-
97
-	/**
98
-	 * check if Nextcloud runs in cli mode
99
-	 */
100
-	public static $CLI = false;
101
-
102
-	/**
103
-	 * @var \OC\Autoloader $loader
104
-	 */
105
-	public static $loader = null;
106
-
107
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
108
-	public static $composerAutoloader = null;
109
-
110
-	/**
111
-	 * @var \OC\Server
112
-	 */
113
-	public static $server = null;
114
-
115
-	/**
116
-	 * @var \OC\Config
117
-	 */
118
-	private static $config = null;
119
-
120
-	/**
121
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
122
-	 * the app path list is empty or contains an invalid path
123
-	 */
124
-	public static function initPaths() {
125
-		if(defined('PHPUNIT_CONFIG_DIR')) {
126
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
127
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
128
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
129
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
130
-			self::$configDir = rtrim($dir, '/') . '/';
131
-		} else {
132
-			self::$configDir = OC::$SERVERROOT . '/config/';
133
-		}
134
-		self::$config = new \OC\Config(self::$configDir);
135
-
136
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
137
-		/**
138
-		 * FIXME: The following lines are required because we can't yet instantiate
139
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
140
-		 */
141
-		$params = [
142
-			'server' => [
143
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
144
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
145
-			],
146
-		];
147
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
148
-		$scriptName = $fakeRequest->getScriptName();
149
-		if (substr($scriptName, -1) == '/') {
150
-			$scriptName .= 'index.php';
151
-			//make sure suburi follows the same rules as scriptName
152
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
153
-				if (substr(OC::$SUBURI, -1) != '/') {
154
-					OC::$SUBURI = OC::$SUBURI . '/';
155
-				}
156
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
157
-			}
158
-		}
159
-
160
-
161
-		if (OC::$CLI) {
162
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
163
-		} else {
164
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
165
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
166
-
167
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
168
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
169
-				}
170
-			} else {
171
-				// The scriptName is not ending with OC::$SUBURI
172
-				// This most likely means that we are calling from CLI.
173
-				// However some cron jobs still need to generate
174
-				// a web URL, so we use overwritewebroot as a fallback.
175
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
176
-			}
177
-
178
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
179
-			// slash which is required by URL generation.
180
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
181
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
182
-				header('Location: '.\OC::$WEBROOT.'/');
183
-				exit();
184
-			}
185
-		}
186
-
187
-		// search the apps folder
188
-		$config_paths = self::$config->getValue('apps_paths', array());
189
-		if (!empty($config_paths)) {
190
-			foreach ($config_paths as $paths) {
191
-				if (isset($paths['url']) && isset($paths['path'])) {
192
-					$paths['url'] = rtrim($paths['url'], '/');
193
-					$paths['path'] = rtrim($paths['path'], '/');
194
-					OC::$APPSROOTS[] = $paths;
195
-				}
196
-			}
197
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
198
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
199
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
200
-			OC::$APPSROOTS[] = array(
201
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
202
-				'url' => '/apps',
203
-				'writable' => true
204
-			);
205
-		}
206
-
207
-		if (empty(OC::$APPSROOTS)) {
208
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
209
-				. ' or the folder above. You can also configure the location in the config.php file.');
210
-		}
211
-		$paths = array();
212
-		foreach (OC::$APPSROOTS as $path) {
213
-			$paths[] = $path['path'];
214
-			if (!is_dir($path['path'])) {
215
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
216
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
217
-					. ' config.php file.', $path['path']));
218
-			}
219
-		}
220
-
221
-		// set the right include path
222
-		set_include_path(
223
-			implode(PATH_SEPARATOR, $paths)
224
-		);
225
-	}
226
-
227
-	public static function checkConfig() {
228
-		$l = \OC::$server->getL10N('lib');
229
-
230
-		// Create config if it does not already exist
231
-		$configFilePath = self::$configDir .'/config.php';
232
-		if(!file_exists($configFilePath)) {
233
-			@touch($configFilePath);
234
-		}
235
-
236
-		// Check if config is writable
237
-		$configFileWritable = is_writable($configFilePath);
238
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
239
-			|| !$configFileWritable && self::checkUpgrade(false)) {
240
-
241
-			$urlGenerator = \OC::$server->getURLGenerator();
242
-
243
-			if (self::$CLI) {
244
-				echo $l->t('Cannot write into "config" directory!')."\n";
245
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
246
-				echo "\n";
247
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
248
-				exit;
249
-			} else {
250
-				OC_Template::printErrorPage(
251
-					$l->t('Cannot write into "config" directory!'),
252
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
253
-					 [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
254
-				);
255
-			}
256
-		}
257
-	}
258
-
259
-	public static function checkInstalled() {
260
-		if (defined('OC_CONSOLE')) {
261
-			return;
262
-		}
263
-		// Redirect to installer if not installed
264
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
265
-			if (OC::$CLI) {
266
-				throw new Exception('Not installed');
267
-			} else {
268
-				$url = OC::$WEBROOT . '/index.php';
269
-				header('Location: ' . $url);
270
-			}
271
-			exit();
272
-		}
273
-	}
274
-
275
-	public static function checkMaintenanceMode() {
276
-		// Allow ajax update script to execute without being stopped
277
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
278
-			// send http status 503
279
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
280
-			header('Status: 503 Service Temporarily Unavailable');
281
-			header('Retry-After: 120');
282
-
283
-			// render error page
284
-			$template = new OC_Template('', 'update.user', 'guest');
285
-			OC_Util::addScript('maintenance-check');
286
-			OC_Util::addStyle('core', 'guest');
287
-			$template->printPage();
288
-			die();
289
-		}
290
-	}
291
-
292
-	/**
293
-	 * Checks if the version requires an update and shows
294
-	 * @param bool $showTemplate Whether an update screen should get shown
295
-	 * @return bool|void
296
-	 */
297
-	public static function checkUpgrade($showTemplate = true) {
298
-		if (\OCP\Util::needUpgrade()) {
299
-			if (function_exists('opcache_reset')) {
300
-				opcache_reset();
301
-			}
302
-			$systemConfig = \OC::$server->getSystemConfig();
303
-			if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
304
-				self::printUpgradePage();
305
-				exit();
306
-			} else {
307
-				return true;
308
-			}
309
-		}
310
-		return false;
311
-	}
312
-
313
-	/**
314
-	 * Prints the upgrade page
315
-	 */
316
-	private static function printUpgradePage() {
317
-		$systemConfig = \OC::$server->getSystemConfig();
318
-
319
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
320
-		$tooBig = false;
321
-		if (!$disableWebUpdater) {
322
-			$apps = \OC::$server->getAppManager();
323
-			$tooBig = false;
324
-			if ($apps->isInstalled('user_ldap')) {
325
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
326
-
327
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
328
-					->from('ldap_user_mapping')
329
-					->execute();
330
-				$row = $result->fetch();
331
-				$result->closeCursor();
332
-
333
-				$tooBig = ($row['user_count'] > 50);
334
-			}
335
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
336
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
337
-
338
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
339
-					->from('user_saml_users')
340
-					->execute();
341
-				$row = $result->fetch();
342
-				$result->closeCursor();
343
-
344
-				$tooBig = ($row['user_count'] > 50);
345
-			}
346
-			if (!$tooBig) {
347
-				// count users
348
-				$stats = \OC::$server->getUserManager()->countUsers();
349
-				$totalUsers = array_sum($stats);
350
-				$tooBig = ($totalUsers > 50);
351
-			}
352
-		}
353
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
354
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
355
-
356
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
357
-			// send http status 503
358
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
359
-			header('Status: 503 Service Temporarily Unavailable');
360
-			header('Retry-After: 120');
361
-
362
-			// render error page
363
-			$template = new OC_Template('', 'update.use-cli', 'guest');
364
-			$template->assign('productName', 'nextcloud'); // for now
365
-			$template->assign('version', OC_Util::getVersionString());
366
-			$template->assign('tooBig', $tooBig);
367
-
368
-			$template->printPage();
369
-			die();
370
-		}
371
-
372
-		// check whether this is a core update or apps update
373
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
374
-		$currentVersion = implode('.', \OCP\Util::getVersion());
375
-
376
-		// if not a core upgrade, then it's apps upgrade
377
-		$isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
378
-
379
-		$oldTheme = $systemConfig->getValue('theme');
380
-		$systemConfig->setValue('theme', '');
381
-		OC_Util::addScript('config'); // needed for web root
382
-		OC_Util::addScript('update');
383
-
384
-		/** @var \OC\App\AppManager $appManager */
385
-		$appManager = \OC::$server->getAppManager();
386
-
387
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
388
-		$tmpl->assign('version', OC_Util::getVersionString());
389
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
390
-
391
-		// get third party apps
392
-		$ocVersion = \OCP\Util::getVersion();
393
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
394
-		$incompatibleShippedApps = [];
395
-		foreach ($incompatibleApps as $appInfo) {
396
-			if ($appManager->isShipped($appInfo['id'])) {
397
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
398
-			}
399
-		}
400
-
401
-		if (!empty($incompatibleShippedApps)) {
402
-			$l = \OC::$server->getL10N('core');
403
-			$hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
404
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
405
-		}
406
-
407
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
408
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
409
-		$tmpl->assign('productName', 'Nextcloud'); // for now
410
-		$tmpl->assign('oldTheme', $oldTheme);
411
-		$tmpl->printPage();
412
-	}
413
-
414
-	public static function initSession() {
415
-		// prevents javascript from accessing php session cookies
416
-		ini_set('session.cookie_httponly', true);
417
-
418
-		// set the cookie path to the Nextcloud directory
419
-		$cookie_path = OC::$WEBROOT ? : '/';
420
-		ini_set('session.cookie_path', $cookie_path);
421
-
422
-		// Let the session name be changed in the initSession Hook
423
-		$sessionName = OC_Util::getInstanceId();
424
-
425
-		try {
426
-			// Allow session apps to create a custom session object
427
-			$useCustomSession = false;
428
-			$session = self::$server->getSession();
429
-			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
430
-			if (!$useCustomSession) {
431
-				// set the session name to the instance id - which is unique
432
-				$session = new \OC\Session\Internal($sessionName);
433
-			}
434
-
435
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
436
-			$session = $cryptoWrapper->wrapSession($session);
437
-			self::$server->setSession($session);
438
-
439
-			// if session can't be started break with http 500 error
440
-		} catch (Exception $e) {
441
-			\OCP\Util::logException('base', $e);
442
-			//show the user a detailed error page
443
-			OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
444
-			OC_Template::printExceptionErrorPage($e);
445
-			die();
446
-		}
447
-
448
-		$sessionLifeTime = self::getSessionLifeTime();
449
-
450
-		// session timeout
451
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
452
-			if (isset($_COOKIE[session_name()])) {
453
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
454
-			}
455
-			\OC::$server->getUserSession()->logout();
456
-		}
457
-
458
-		$session->set('LAST_ACTIVITY', time());
459
-	}
460
-
461
-	/**
462
-	 * @return string
463
-	 */
464
-	private static function getSessionLifeTime() {
465
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
466
-	}
467
-
468
-	public static function loadAppClassPaths() {
469
-		foreach (OC_App::getEnabledApps() as $app) {
470
-			$appPath = OC_App::getAppPath($app);
471
-			if ($appPath === false) {
472
-				continue;
473
-			}
474
-
475
-			$file = $appPath . '/appinfo/classpath.php';
476
-			if (file_exists($file)) {
477
-				require_once $file;
478
-			}
479
-		}
480
-	}
481
-
482
-	/**
483
-	 * Try to set some values to the required Nextcloud default
484
-	 */
485
-	public static function setRequiredIniValues() {
486
-		@ini_set('default_charset', 'UTF-8');
487
-		@ini_set('gd.jpeg_ignore_warning', 1);
488
-	}
489
-
490
-	/**
491
-	 * Send the same site cookies
492
-	 */
493
-	private static function sendSameSiteCookies() {
494
-		$cookieParams = session_get_cookie_params();
495
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
496
-		$policies = [
497
-			'lax',
498
-			'strict',
499
-		];
500
-
501
-		// Append __Host to the cookie if it meets the requirements
502
-		$cookiePrefix = '';
503
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
504
-			$cookiePrefix = '__Host-';
505
-		}
506
-
507
-		foreach($policies as $policy) {
508
-			header(
509
-				sprintf(
510
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
511
-					$cookiePrefix,
512
-					$policy,
513
-					$cookieParams['path'],
514
-					$policy
515
-				),
516
-				false
517
-			);
518
-		}
519
-	}
520
-
521
-	/**
522
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
523
-	 * be set in every request if cookies are sent to add a second level of
524
-	 * defense against CSRF.
525
-	 *
526
-	 * If the cookie is not sent this will set the cookie and reload the page.
527
-	 * We use an additional cookie since we want to protect logout CSRF and
528
-	 * also we can't directly interfere with PHP's session mechanism.
529
-	 */
530
-	private static function performSameSiteCookieProtection() {
531
-		$request = \OC::$server->getRequest();
532
-
533
-		// Some user agents are notorious and don't really properly follow HTTP
534
-		// specifications. For those, have an automated opt-out. Since the protection
535
-		// for remote.php is applied in base.php as starting point we need to opt out
536
-		// here.
537
-		$incompatibleUserAgents = [
538
-			// OS X Finder
539
-			'/^WebDAVFS/',
540
-		];
541
-		if($request->isUserAgent($incompatibleUserAgents)) {
542
-			return;
543
-		}
544
-
545
-		if(count($_COOKIE) > 0) {
546
-			$requestUri = $request->getScriptName();
547
-			$processingScript = explode('/', $requestUri);
548
-			$processingScript = $processingScript[count($processingScript)-1];
549
-
550
-			// index.php routes are handled in the middleware
551
-			if($processingScript === 'index.php') {
552
-				return;
553
-			}
554
-
555
-			// All other endpoints require the lax and the strict cookie
556
-			if(!$request->passesStrictCookieCheck()) {
557
-				self::sendSameSiteCookies();
558
-				// Debug mode gets access to the resources without strict cookie
559
-				// due to the fact that the SabreDAV browser also lives there.
560
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
561
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
562
-					exit();
563
-				}
564
-			}
565
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
566
-			self::sendSameSiteCookies();
567
-		}
568
-	}
569
-
570
-	public static function init() {
571
-		// calculate the root directories
572
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
573
-
574
-		// register autoloader
575
-		$loaderStart = microtime(true);
576
-		require_once __DIR__ . '/autoloader.php';
577
-		self::$loader = new \OC\Autoloader([
578
-			OC::$SERVERROOT . '/lib/private/legacy',
579
-		]);
580
-		if (defined('PHPUNIT_RUN')) {
581
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
582
-		}
583
-		spl_autoload_register(array(self::$loader, 'load'));
584
-		$loaderEnd = microtime(true);
585
-
586
-		self::$CLI = (php_sapi_name() == 'cli');
587
-
588
-		// Add default composer PSR-4 autoloader
589
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
590
-
591
-		try {
592
-			self::initPaths();
593
-			// setup 3rdparty autoloader
594
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
595
-			if (!file_exists($vendorAutoLoad)) {
596
-				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
597
-			}
598
-			require_once $vendorAutoLoad;
599
-
600
-		} catch (\RuntimeException $e) {
601
-			if (!self::$CLI) {
602
-				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
603
-				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
604
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
605
-			}
606
-			// we can't use the template error page here, because this needs the
607
-			// DI container which isn't available yet
608
-			print($e->getMessage());
609
-			exit();
610
-		}
611
-
612
-		// setup the basic server
613
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
614
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
615
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
616
-
617
-		// Don't display errors and log them
618
-		error_reporting(E_ALL | E_STRICT);
619
-		@ini_set('display_errors', 0);
620
-		@ini_set('log_errors', 1);
621
-
622
-		if(!date_default_timezone_set('UTC')) {
623
-			throw new \RuntimeException('Could not set timezone to UTC');
624
-		};
625
-
626
-		//try to configure php to enable big file uploads.
627
-		//this doesn´t work always depending on the webserver and php configuration.
628
-		//Let´s try to overwrite some defaults anyway
629
-
630
-		//try to set the maximum execution time to 60min
631
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
632
-			@set_time_limit(3600);
633
-		}
634
-		@ini_set('max_execution_time', 3600);
635
-		@ini_set('max_input_time', 3600);
636
-
637
-		//try to set the maximum filesize to 10G
638
-		@ini_set('upload_max_filesize', '10G');
639
-		@ini_set('post_max_size', '10G');
640
-		@ini_set('file_uploads', '50');
641
-
642
-		self::setRequiredIniValues();
643
-		self::handleAuthHeaders();
644
-		self::registerAutoloaderCache();
645
-
646
-		// initialize intl fallback is necessary
647
-		\Patchwork\Utf8\Bootup::initIntl();
648
-		OC_Util::isSetLocaleWorking();
649
-
650
-		if (!defined('PHPUNIT_RUN')) {
651
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
652
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
653
-			OC\Log\ErrorHandler::register($debug);
654
-		}
655
-
656
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
657
-		OC_App::loadApps(array('session'));
658
-		if (!self::$CLI) {
659
-			self::initSession();
660
-		}
661
-		\OC::$server->getEventLogger()->end('init_session');
662
-		self::checkConfig();
663
-		self::checkInstalled();
664
-
665
-		OC_Response::addSecurityHeaders();
666
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
667
-			ini_set('session.cookie_secure', true);
668
-		}
669
-
670
-		self::performSameSiteCookieProtection();
671
-
672
-		if (!defined('OC_CONSOLE')) {
673
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
674
-			if (count($errors) > 0) {
675
-				if (self::$CLI) {
676
-					// Convert l10n string into regular string for usage in database
677
-					$staticErrors = [];
678
-					foreach ($errors as $error) {
679
-						echo $error['error'] . "\n";
680
-						echo $error['hint'] . "\n\n";
681
-						$staticErrors[] = [
682
-							'error' => (string)$error['error'],
683
-							'hint' => (string)$error['hint'],
684
-						];
685
-					}
686
-
687
-					try {
688
-						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
689
-					} catch (\Exception $e) {
690
-						echo('Writing to database failed');
691
-					}
692
-					exit(1);
693
-				} else {
694
-					OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
695
-					OC_Util::addStyle('guest');
696
-					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
697
-					exit;
698
-				}
699
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
700
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
701
-			}
702
-		}
703
-		//try to set the session lifetime
704
-		$sessionLifeTime = self::getSessionLifeTime();
705
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
706
-
707
-		$systemConfig = \OC::$server->getSystemConfig();
708
-
709
-		// User and Groups
710
-		if (!$systemConfig->getValue("installed", false)) {
711
-			self::$server->getSession()->set('user_id', '');
712
-		}
713
-
714
-		OC_User::useBackend(new \OC\User\Database());
715
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
716
-
717
-		// Subscribe to the hook
718
-		\OCP\Util::connectHook(
719
-			'\OCA\Files_Sharing\API\Server2Server',
720
-			'preLoginNameUsedAsUserName',
721
-			'\OC\User\Database',
722
-			'preLoginNameUsedAsUserName'
723
-		);
724
-
725
-		//setup extra user backends
726
-		if (!self::checkUpgrade(false)) {
727
-			OC_User::setupBackends();
728
-		} else {
729
-			// Run upgrades in incognito mode
730
-			OC_User::setIncognitoMode(true);
731
-		}
732
-
733
-		self::registerCacheHooks();
734
-		self::registerFilesystemHooks();
735
-		self::registerShareHooks();
736
-		self::registerEncryptionWrapper();
737
-		self::registerEncryptionHooks();
738
-		self::registerAccountHooks();
739
-		self::registerSettingsHooks();
740
-
741
-		$settings = new \OC\Settings\Application();
742
-		$settings->register();
743
-
744
-		//make sure temporary files are cleaned up
745
-		$tmpManager = \OC::$server->getTempManager();
746
-		register_shutdown_function(array($tmpManager, 'clean'));
747
-		$lockProvider = \OC::$server->getLockingProvider();
748
-		register_shutdown_function(array($lockProvider, 'releaseAll'));
749
-
750
-		// Check whether the sample configuration has been copied
751
-		if($systemConfig->getValue('copied_sample_config', false)) {
752
-			$l = \OC::$server->getL10N('lib');
753
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
754
-			header('Status: 503 Service Temporarily Unavailable');
755
-			OC_Template::printErrorPage(
756
-				$l->t('Sample configuration detected'),
757
-				$l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php')
758
-			);
759
-			return;
760
-		}
761
-
762
-		$request = \OC::$server->getRequest();
763
-		$host = $request->getInsecureServerHost();
764
-		/**
765
-		 * if the host passed in headers isn't trusted
766
-		 * FIXME: Should not be in here at all :see_no_evil:
767
-		 */
768
-		if (!OC::$CLI
769
-			// overwritehost is always trusted, workaround to not have to make
770
-			// \OC\AppFramework\Http\Request::getOverwriteHost public
771
-			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
772
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
773
-			&& self::$server->getConfig()->getSystemValue('installed', false)
774
-		) {
775
-			// Allow access to CSS resources
776
-			$isScssRequest = false;
777
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
778
-				$isScssRequest = true;
779
-			}
780
-
781
-			if (!$isScssRequest) {
782
-				header('HTTP/1.1 400 Bad Request');
783
-				header('Status: 400 Bad Request');
784
-
785
-				\OC::$server->getLogger()->warning(
786
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
787
-					[
788
-						'app' => 'core',
789
-						'remoteAddress' => $request->getRemoteAddress(),
790
-						'host' => $host,
791
-					]
792
-				);
793
-
794
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
795
-				$tmpl->assign('domain', $host);
796
-				$tmpl->printPage();
797
-
798
-				exit();
799
-			}
800
-		}
801
-		\OC::$server->getEventLogger()->end('boot');
802
-	}
803
-
804
-	/**
805
-	 * register hooks for the cache
806
-	 */
807
-	public static function registerCacheHooks() {
808
-		//don't try to do this before we are properly setup
809
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
810
-
811
-			// NOTE: This will be replaced to use OCP
812
-			$userSession = self::$server->getUserSession();
813
-			$userSession->listen('\OC\User', 'postLogin', function () {
814
-				try {
815
-					$cache = new \OC\Cache\File();
816
-					$cache->gc();
817
-				} catch (\OC\ServerNotAvailableException $e) {
818
-					// not a GC exception, pass it on
819
-					throw $e;
820
-				} catch (\OC\ForbiddenException $e) {
821
-					// filesystem blocked for this request, ignore
822
-				} catch (\Exception $e) {
823
-					// a GC exception should not prevent users from using OC,
824
-					// so log the exception
825
-					\OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
826
-				}
827
-			});
828
-		}
829
-	}
830
-
831
-	public static function registerSettingsHooks() {
832
-		$dispatcher = \OC::$server->getEventDispatcher();
833
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
834
-			/** @var \OCP\App\ManagerEvent $event */
835
-			\OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
836
-		});
837
-		$dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
838
-			/** @var \OCP\App\ManagerEvent $event */
839
-			$jobList = \OC::$server->getJobList();
840
-			$job = 'OC\\Settings\\RemoveOrphaned';
841
-			if(!($jobList->has($job, null))) {
842
-				$jobList->add($job);
843
-			}
844
-		});
845
-	}
846
-
847
-	private static function registerEncryptionWrapper() {
848
-		$manager = self::$server->getEncryptionManager();
849
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
850
-	}
851
-
852
-	private static function registerEncryptionHooks() {
853
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
854
-		if ($enabled) {
855
-			\OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
856
-			\OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
857
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
858
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
859
-		}
860
-	}
861
-
862
-	private static function registerAccountHooks() {
863
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
864
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
865
-	}
866
-
867
-	/**
868
-	 * register hooks for the filesystem
869
-	 */
870
-	public static function registerFilesystemHooks() {
871
-		// Check for blacklisted files
872
-		OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
873
-		OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
874
-	}
875
-
876
-	/**
877
-	 * register hooks for sharing
878
-	 */
879
-	public static function registerShareHooks() {
880
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
881
-			OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
882
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
883
-			OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
884
-		}
885
-	}
886
-
887
-	protected static function registerAutoloaderCache() {
888
-		// The class loader takes an optional low-latency cache, which MUST be
889
-		// namespaced. The instanceid is used for namespacing, but might be
890
-		// unavailable at this point. Furthermore, it might not be possible to
891
-		// generate an instanceid via \OC_Util::getInstanceId() because the
892
-		// config file may not be writable. As such, we only register a class
893
-		// loader cache if instanceid is available without trying to create one.
894
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
895
-		if ($instanceId) {
896
-			try {
897
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
898
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
899
-			} catch (\Exception $ex) {
900
-			}
901
-		}
902
-	}
903
-
904
-	/**
905
-	 * Handle the request
906
-	 */
907
-	public static function handleRequest() {
908
-
909
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
910
-		$systemConfig = \OC::$server->getSystemConfig();
911
-		// load all the classpaths from the enabled apps so they are available
912
-		// in the routing files of each app
913
-		OC::loadAppClassPaths();
914
-
915
-		// Check if Nextcloud is installed or in maintenance (update) mode
916
-		if (!$systemConfig->getValue('installed', false)) {
917
-			\OC::$server->getSession()->clear();
918
-			$setupHelper = new OC\Setup(
919
-				\OC::$server->getSystemConfig(),
920
-				\OC::$server->getIniWrapper(),
921
-				\OC::$server->getL10N('lib'),
922
-				\OC::$server->query(\OCP\Defaults::class),
923
-				\OC::$server->getLogger(),
924
-				\OC::$server->getSecureRandom(),
925
-				\OC::$server->query(Installer::class)
926
-			);
927
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
928
-			$controller->run($_POST);
929
-			exit();
930
-		}
931
-
932
-		$request = \OC::$server->getRequest();
933
-		$requestPath = $request->getRawPathInfo();
934
-		if ($requestPath === '/heartbeat') {
935
-			return;
936
-		}
937
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
938
-			self::checkMaintenanceMode();
939
-			self::checkUpgrade();
940
-		}
941
-
942
-		// emergency app disabling
943
-		if ($requestPath === '/disableapp'
944
-			&& $request->getMethod() === 'POST'
945
-			&& ((array)$request->getParam('appid')) !== ''
946
-		) {
947
-			\OCP\JSON::callCheck();
948
-			\OCP\JSON::checkAdminUser();
949
-			$appIds = (array)$request->getParam('appid');
950
-			foreach($appIds as $appId) {
951
-				$appId = \OC_App::cleanAppId($appId);
952
-				\OC_App::disable($appId);
953
-			}
954
-			\OC_JSON::success();
955
-			exit();
956
-		}
957
-
958
-		// Always load authentication apps
959
-		OC_App::loadApps(['authentication']);
960
-
961
-		// Load minimum set of apps
962
-		if (!self::checkUpgrade(false)
963
-			&& !$systemConfig->getValue('maintenance', false)) {
964
-			// For logged-in users: Load everything
965
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
966
-				OC_App::loadApps();
967
-			} else {
968
-				// For guests: Load only filesystem and logging
969
-				OC_App::loadApps(array('filesystem', 'logging'));
970
-				self::handleLogin($request);
971
-			}
972
-		}
973
-
974
-		if (!self::$CLI) {
975
-			try {
976
-				if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
977
-					OC_App::loadApps(array('filesystem', 'logging'));
978
-					OC_App::loadApps();
979
-				}
980
-				OC_Util::setupFS();
981
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
982
-				return;
983
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
984
-				//header('HTTP/1.0 404 Not Found');
985
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
986
-				OC_Response::setStatus(405);
987
-				return;
988
-			}
989
-		}
990
-
991
-		// Handle WebDAV
992
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
993
-			// not allowed any more to prevent people
994
-			// mounting this root directly.
995
-			// Users need to mount remote.php/webdav instead.
996
-			header('HTTP/1.1 405 Method Not Allowed');
997
-			header('Status: 405 Method Not Allowed');
998
-			return;
999
-		}
1000
-
1001
-		// Someone is logged in
1002
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1003
-			OC_App::loadApps();
1004
-			OC_User::setupBackends();
1005
-			OC_Util::setupFS();
1006
-			// FIXME
1007
-			// Redirect to default application
1008
-			OC_Util::redirectToDefaultPage();
1009
-		} else {
1010
-			// Not handled and not logged in
1011
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1012
-		}
1013
-	}
1014
-
1015
-	/**
1016
-	 * Check login: apache auth, auth token, basic auth
1017
-	 *
1018
-	 * @param OCP\IRequest $request
1019
-	 * @return boolean
1020
-	 */
1021
-	static function handleLogin(OCP\IRequest $request) {
1022
-		$userSession = self::$server->getUserSession();
1023
-		if (OC_User::handleApacheAuth()) {
1024
-			return true;
1025
-		}
1026
-		if ($userSession->tryTokenLogin($request)) {
1027
-			return true;
1028
-		}
1029
-		if (isset($_COOKIE['nc_username'])
1030
-			&& isset($_COOKIE['nc_token'])
1031
-			&& isset($_COOKIE['nc_session_id'])
1032
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1033
-			return true;
1034
-		}
1035
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1036
-			return true;
1037
-		}
1038
-		return false;
1039
-	}
1040
-
1041
-	protected static function handleAuthHeaders() {
1042
-		//copy http auth headers for apache+php-fcgid work around
1043
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1044
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1045
-		}
1046
-
1047
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1048
-		$vars = array(
1049
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1050
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1051
-		);
1052
-		foreach ($vars as $var) {
1053
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1054
-				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1055
-				$_SERVER['PHP_AUTH_USER'] = $name;
1056
-				$_SERVER['PHP_AUTH_PW'] = $password;
1057
-				break;
1058
-			}
1059
-		}
1060
-	}
65
+    /**
66
+     * Associative array for autoloading. classname => filename
67
+     */
68
+    public static $CLASSPATH = array();
69
+    /**
70
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
71
+     */
72
+    public static $SERVERROOT = '';
73
+    /**
74
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
75
+     */
76
+    private static $SUBURI = '';
77
+    /**
78
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
79
+     */
80
+    public static $WEBROOT = '';
81
+    /**
82
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
83
+     * web path in 'url'
84
+     */
85
+    public static $APPSROOTS = array();
86
+
87
+    /**
88
+     * @var string
89
+     */
90
+    public static $configDir;
91
+
92
+    /**
93
+     * requested app
94
+     */
95
+    public static $REQUESTEDAPP = '';
96
+
97
+    /**
98
+     * check if Nextcloud runs in cli mode
99
+     */
100
+    public static $CLI = false;
101
+
102
+    /**
103
+     * @var \OC\Autoloader $loader
104
+     */
105
+    public static $loader = null;
106
+
107
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
108
+    public static $composerAutoloader = null;
109
+
110
+    /**
111
+     * @var \OC\Server
112
+     */
113
+    public static $server = null;
114
+
115
+    /**
116
+     * @var \OC\Config
117
+     */
118
+    private static $config = null;
119
+
120
+    /**
121
+     * @throws \RuntimeException when the 3rdparty directory is missing or
122
+     * the app path list is empty or contains an invalid path
123
+     */
124
+    public static function initPaths() {
125
+        if(defined('PHPUNIT_CONFIG_DIR')) {
126
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
127
+        } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
128
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
129
+        } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
130
+            self::$configDir = rtrim($dir, '/') . '/';
131
+        } else {
132
+            self::$configDir = OC::$SERVERROOT . '/config/';
133
+        }
134
+        self::$config = new \OC\Config(self::$configDir);
135
+
136
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
137
+        /**
138
+         * FIXME: The following lines are required because we can't yet instantiate
139
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
140
+         */
141
+        $params = [
142
+            'server' => [
143
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
144
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
145
+            ],
146
+        ];
147
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
148
+        $scriptName = $fakeRequest->getScriptName();
149
+        if (substr($scriptName, -1) == '/') {
150
+            $scriptName .= 'index.php';
151
+            //make sure suburi follows the same rules as scriptName
152
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
153
+                if (substr(OC::$SUBURI, -1) != '/') {
154
+                    OC::$SUBURI = OC::$SUBURI . '/';
155
+                }
156
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
157
+            }
158
+        }
159
+
160
+
161
+        if (OC::$CLI) {
162
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
163
+        } else {
164
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
165
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
166
+
167
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
168
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
169
+                }
170
+            } else {
171
+                // The scriptName is not ending with OC::$SUBURI
172
+                // This most likely means that we are calling from CLI.
173
+                // However some cron jobs still need to generate
174
+                // a web URL, so we use overwritewebroot as a fallback.
175
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
176
+            }
177
+
178
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
179
+            // slash which is required by URL generation.
180
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
181
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
182
+                header('Location: '.\OC::$WEBROOT.'/');
183
+                exit();
184
+            }
185
+        }
186
+
187
+        // search the apps folder
188
+        $config_paths = self::$config->getValue('apps_paths', array());
189
+        if (!empty($config_paths)) {
190
+            foreach ($config_paths as $paths) {
191
+                if (isset($paths['url']) && isset($paths['path'])) {
192
+                    $paths['url'] = rtrim($paths['url'], '/');
193
+                    $paths['path'] = rtrim($paths['path'], '/');
194
+                    OC::$APPSROOTS[] = $paths;
195
+                }
196
+            }
197
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
198
+            OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
199
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
200
+            OC::$APPSROOTS[] = array(
201
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
202
+                'url' => '/apps',
203
+                'writable' => true
204
+            );
205
+        }
206
+
207
+        if (empty(OC::$APPSROOTS)) {
208
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
209
+                . ' or the folder above. You can also configure the location in the config.php file.');
210
+        }
211
+        $paths = array();
212
+        foreach (OC::$APPSROOTS as $path) {
213
+            $paths[] = $path['path'];
214
+            if (!is_dir($path['path'])) {
215
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
216
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
217
+                    . ' config.php file.', $path['path']));
218
+            }
219
+        }
220
+
221
+        // set the right include path
222
+        set_include_path(
223
+            implode(PATH_SEPARATOR, $paths)
224
+        );
225
+    }
226
+
227
+    public static function checkConfig() {
228
+        $l = \OC::$server->getL10N('lib');
229
+
230
+        // Create config if it does not already exist
231
+        $configFilePath = self::$configDir .'/config.php';
232
+        if(!file_exists($configFilePath)) {
233
+            @touch($configFilePath);
234
+        }
235
+
236
+        // Check if config is writable
237
+        $configFileWritable = is_writable($configFilePath);
238
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
239
+            || !$configFileWritable && self::checkUpgrade(false)) {
240
+
241
+            $urlGenerator = \OC::$server->getURLGenerator();
242
+
243
+            if (self::$CLI) {
244
+                echo $l->t('Cannot write into "config" directory!')."\n";
245
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
246
+                echo "\n";
247
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
248
+                exit;
249
+            } else {
250
+                OC_Template::printErrorPage(
251
+                    $l->t('Cannot write into "config" directory!'),
252
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
253
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
254
+                );
255
+            }
256
+        }
257
+    }
258
+
259
+    public static function checkInstalled() {
260
+        if (defined('OC_CONSOLE')) {
261
+            return;
262
+        }
263
+        // Redirect to installer if not installed
264
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
265
+            if (OC::$CLI) {
266
+                throw new Exception('Not installed');
267
+            } else {
268
+                $url = OC::$WEBROOT . '/index.php';
269
+                header('Location: ' . $url);
270
+            }
271
+            exit();
272
+        }
273
+    }
274
+
275
+    public static function checkMaintenanceMode() {
276
+        // Allow ajax update script to execute without being stopped
277
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
278
+            // send http status 503
279
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
280
+            header('Status: 503 Service Temporarily Unavailable');
281
+            header('Retry-After: 120');
282
+
283
+            // render error page
284
+            $template = new OC_Template('', 'update.user', 'guest');
285
+            OC_Util::addScript('maintenance-check');
286
+            OC_Util::addStyle('core', 'guest');
287
+            $template->printPage();
288
+            die();
289
+        }
290
+    }
291
+
292
+    /**
293
+     * Checks if the version requires an update and shows
294
+     * @param bool $showTemplate Whether an update screen should get shown
295
+     * @return bool|void
296
+     */
297
+    public static function checkUpgrade($showTemplate = true) {
298
+        if (\OCP\Util::needUpgrade()) {
299
+            if (function_exists('opcache_reset')) {
300
+                opcache_reset();
301
+            }
302
+            $systemConfig = \OC::$server->getSystemConfig();
303
+            if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
304
+                self::printUpgradePage();
305
+                exit();
306
+            } else {
307
+                return true;
308
+            }
309
+        }
310
+        return false;
311
+    }
312
+
313
+    /**
314
+     * Prints the upgrade page
315
+     */
316
+    private static function printUpgradePage() {
317
+        $systemConfig = \OC::$server->getSystemConfig();
318
+
319
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
320
+        $tooBig = false;
321
+        if (!$disableWebUpdater) {
322
+            $apps = \OC::$server->getAppManager();
323
+            $tooBig = false;
324
+            if ($apps->isInstalled('user_ldap')) {
325
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
326
+
327
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
328
+                    ->from('ldap_user_mapping')
329
+                    ->execute();
330
+                $row = $result->fetch();
331
+                $result->closeCursor();
332
+
333
+                $tooBig = ($row['user_count'] > 50);
334
+            }
335
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
336
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
337
+
338
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
339
+                    ->from('user_saml_users')
340
+                    ->execute();
341
+                $row = $result->fetch();
342
+                $result->closeCursor();
343
+
344
+                $tooBig = ($row['user_count'] > 50);
345
+            }
346
+            if (!$tooBig) {
347
+                // count users
348
+                $stats = \OC::$server->getUserManager()->countUsers();
349
+                $totalUsers = array_sum($stats);
350
+                $tooBig = ($totalUsers > 50);
351
+            }
352
+        }
353
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
354
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
355
+
356
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
357
+            // send http status 503
358
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
359
+            header('Status: 503 Service Temporarily Unavailable');
360
+            header('Retry-After: 120');
361
+
362
+            // render error page
363
+            $template = new OC_Template('', 'update.use-cli', 'guest');
364
+            $template->assign('productName', 'nextcloud'); // for now
365
+            $template->assign('version', OC_Util::getVersionString());
366
+            $template->assign('tooBig', $tooBig);
367
+
368
+            $template->printPage();
369
+            die();
370
+        }
371
+
372
+        // check whether this is a core update or apps update
373
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
374
+        $currentVersion = implode('.', \OCP\Util::getVersion());
375
+
376
+        // if not a core upgrade, then it's apps upgrade
377
+        $isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
378
+
379
+        $oldTheme = $systemConfig->getValue('theme');
380
+        $systemConfig->setValue('theme', '');
381
+        OC_Util::addScript('config'); // needed for web root
382
+        OC_Util::addScript('update');
383
+
384
+        /** @var \OC\App\AppManager $appManager */
385
+        $appManager = \OC::$server->getAppManager();
386
+
387
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
388
+        $tmpl->assign('version', OC_Util::getVersionString());
389
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
390
+
391
+        // get third party apps
392
+        $ocVersion = \OCP\Util::getVersion();
393
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
394
+        $incompatibleShippedApps = [];
395
+        foreach ($incompatibleApps as $appInfo) {
396
+            if ($appManager->isShipped($appInfo['id'])) {
397
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
398
+            }
399
+        }
400
+
401
+        if (!empty($incompatibleShippedApps)) {
402
+            $l = \OC::$server->getL10N('core');
403
+            $hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
404
+            throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
405
+        }
406
+
407
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
408
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
409
+        $tmpl->assign('productName', 'Nextcloud'); // for now
410
+        $tmpl->assign('oldTheme', $oldTheme);
411
+        $tmpl->printPage();
412
+    }
413
+
414
+    public static function initSession() {
415
+        // prevents javascript from accessing php session cookies
416
+        ini_set('session.cookie_httponly', true);
417
+
418
+        // set the cookie path to the Nextcloud directory
419
+        $cookie_path = OC::$WEBROOT ? : '/';
420
+        ini_set('session.cookie_path', $cookie_path);
421
+
422
+        // Let the session name be changed in the initSession Hook
423
+        $sessionName = OC_Util::getInstanceId();
424
+
425
+        try {
426
+            // Allow session apps to create a custom session object
427
+            $useCustomSession = false;
428
+            $session = self::$server->getSession();
429
+            OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
430
+            if (!$useCustomSession) {
431
+                // set the session name to the instance id - which is unique
432
+                $session = new \OC\Session\Internal($sessionName);
433
+            }
434
+
435
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
436
+            $session = $cryptoWrapper->wrapSession($session);
437
+            self::$server->setSession($session);
438
+
439
+            // if session can't be started break with http 500 error
440
+        } catch (Exception $e) {
441
+            \OCP\Util::logException('base', $e);
442
+            //show the user a detailed error page
443
+            OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
444
+            OC_Template::printExceptionErrorPage($e);
445
+            die();
446
+        }
447
+
448
+        $sessionLifeTime = self::getSessionLifeTime();
449
+
450
+        // session timeout
451
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
452
+            if (isset($_COOKIE[session_name()])) {
453
+                setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
454
+            }
455
+            \OC::$server->getUserSession()->logout();
456
+        }
457
+
458
+        $session->set('LAST_ACTIVITY', time());
459
+    }
460
+
461
+    /**
462
+     * @return string
463
+     */
464
+    private static function getSessionLifeTime() {
465
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
466
+    }
467
+
468
+    public static function loadAppClassPaths() {
469
+        foreach (OC_App::getEnabledApps() as $app) {
470
+            $appPath = OC_App::getAppPath($app);
471
+            if ($appPath === false) {
472
+                continue;
473
+            }
474
+
475
+            $file = $appPath . '/appinfo/classpath.php';
476
+            if (file_exists($file)) {
477
+                require_once $file;
478
+            }
479
+        }
480
+    }
481
+
482
+    /**
483
+     * Try to set some values to the required Nextcloud default
484
+     */
485
+    public static function setRequiredIniValues() {
486
+        @ini_set('default_charset', 'UTF-8');
487
+        @ini_set('gd.jpeg_ignore_warning', 1);
488
+    }
489
+
490
+    /**
491
+     * Send the same site cookies
492
+     */
493
+    private static function sendSameSiteCookies() {
494
+        $cookieParams = session_get_cookie_params();
495
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
496
+        $policies = [
497
+            'lax',
498
+            'strict',
499
+        ];
500
+
501
+        // Append __Host to the cookie if it meets the requirements
502
+        $cookiePrefix = '';
503
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
504
+            $cookiePrefix = '__Host-';
505
+        }
506
+
507
+        foreach($policies as $policy) {
508
+            header(
509
+                sprintf(
510
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
511
+                    $cookiePrefix,
512
+                    $policy,
513
+                    $cookieParams['path'],
514
+                    $policy
515
+                ),
516
+                false
517
+            );
518
+        }
519
+    }
520
+
521
+    /**
522
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
523
+     * be set in every request if cookies are sent to add a second level of
524
+     * defense against CSRF.
525
+     *
526
+     * If the cookie is not sent this will set the cookie and reload the page.
527
+     * We use an additional cookie since we want to protect logout CSRF and
528
+     * also we can't directly interfere with PHP's session mechanism.
529
+     */
530
+    private static function performSameSiteCookieProtection() {
531
+        $request = \OC::$server->getRequest();
532
+
533
+        // Some user agents are notorious and don't really properly follow HTTP
534
+        // specifications. For those, have an automated opt-out. Since the protection
535
+        // for remote.php is applied in base.php as starting point we need to opt out
536
+        // here.
537
+        $incompatibleUserAgents = [
538
+            // OS X Finder
539
+            '/^WebDAVFS/',
540
+        ];
541
+        if($request->isUserAgent($incompatibleUserAgents)) {
542
+            return;
543
+        }
544
+
545
+        if(count($_COOKIE) > 0) {
546
+            $requestUri = $request->getScriptName();
547
+            $processingScript = explode('/', $requestUri);
548
+            $processingScript = $processingScript[count($processingScript)-1];
549
+
550
+            // index.php routes are handled in the middleware
551
+            if($processingScript === 'index.php') {
552
+                return;
553
+            }
554
+
555
+            // All other endpoints require the lax and the strict cookie
556
+            if(!$request->passesStrictCookieCheck()) {
557
+                self::sendSameSiteCookies();
558
+                // Debug mode gets access to the resources without strict cookie
559
+                // due to the fact that the SabreDAV browser also lives there.
560
+                if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
561
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
562
+                    exit();
563
+                }
564
+            }
565
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
566
+            self::sendSameSiteCookies();
567
+        }
568
+    }
569
+
570
+    public static function init() {
571
+        // calculate the root directories
572
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
573
+
574
+        // register autoloader
575
+        $loaderStart = microtime(true);
576
+        require_once __DIR__ . '/autoloader.php';
577
+        self::$loader = new \OC\Autoloader([
578
+            OC::$SERVERROOT . '/lib/private/legacy',
579
+        ]);
580
+        if (defined('PHPUNIT_RUN')) {
581
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
582
+        }
583
+        spl_autoload_register(array(self::$loader, 'load'));
584
+        $loaderEnd = microtime(true);
585
+
586
+        self::$CLI = (php_sapi_name() == 'cli');
587
+
588
+        // Add default composer PSR-4 autoloader
589
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
590
+
591
+        try {
592
+            self::initPaths();
593
+            // setup 3rdparty autoloader
594
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
595
+            if (!file_exists($vendorAutoLoad)) {
596
+                throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
597
+            }
598
+            require_once $vendorAutoLoad;
599
+
600
+        } catch (\RuntimeException $e) {
601
+            if (!self::$CLI) {
602
+                $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
603
+                $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
604
+                header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
605
+            }
606
+            // we can't use the template error page here, because this needs the
607
+            // DI container which isn't available yet
608
+            print($e->getMessage());
609
+            exit();
610
+        }
611
+
612
+        // setup the basic server
613
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
614
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
615
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
616
+
617
+        // Don't display errors and log them
618
+        error_reporting(E_ALL | E_STRICT);
619
+        @ini_set('display_errors', 0);
620
+        @ini_set('log_errors', 1);
621
+
622
+        if(!date_default_timezone_set('UTC')) {
623
+            throw new \RuntimeException('Could not set timezone to UTC');
624
+        };
625
+
626
+        //try to configure php to enable big file uploads.
627
+        //this doesn´t work always depending on the webserver and php configuration.
628
+        //Let´s try to overwrite some defaults anyway
629
+
630
+        //try to set the maximum execution time to 60min
631
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
632
+            @set_time_limit(3600);
633
+        }
634
+        @ini_set('max_execution_time', 3600);
635
+        @ini_set('max_input_time', 3600);
636
+
637
+        //try to set the maximum filesize to 10G
638
+        @ini_set('upload_max_filesize', '10G');
639
+        @ini_set('post_max_size', '10G');
640
+        @ini_set('file_uploads', '50');
641
+
642
+        self::setRequiredIniValues();
643
+        self::handleAuthHeaders();
644
+        self::registerAutoloaderCache();
645
+
646
+        // initialize intl fallback is necessary
647
+        \Patchwork\Utf8\Bootup::initIntl();
648
+        OC_Util::isSetLocaleWorking();
649
+
650
+        if (!defined('PHPUNIT_RUN')) {
651
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
652
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
653
+            OC\Log\ErrorHandler::register($debug);
654
+        }
655
+
656
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
657
+        OC_App::loadApps(array('session'));
658
+        if (!self::$CLI) {
659
+            self::initSession();
660
+        }
661
+        \OC::$server->getEventLogger()->end('init_session');
662
+        self::checkConfig();
663
+        self::checkInstalled();
664
+
665
+        OC_Response::addSecurityHeaders();
666
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
667
+            ini_set('session.cookie_secure', true);
668
+        }
669
+
670
+        self::performSameSiteCookieProtection();
671
+
672
+        if (!defined('OC_CONSOLE')) {
673
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
674
+            if (count($errors) > 0) {
675
+                if (self::$CLI) {
676
+                    // Convert l10n string into regular string for usage in database
677
+                    $staticErrors = [];
678
+                    foreach ($errors as $error) {
679
+                        echo $error['error'] . "\n";
680
+                        echo $error['hint'] . "\n\n";
681
+                        $staticErrors[] = [
682
+                            'error' => (string)$error['error'],
683
+                            'hint' => (string)$error['hint'],
684
+                        ];
685
+                    }
686
+
687
+                    try {
688
+                        \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
689
+                    } catch (\Exception $e) {
690
+                        echo('Writing to database failed');
691
+                    }
692
+                    exit(1);
693
+                } else {
694
+                    OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
695
+                    OC_Util::addStyle('guest');
696
+                    OC_Template::printGuestPage('', 'error', array('errors' => $errors));
697
+                    exit;
698
+                }
699
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
700
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
701
+            }
702
+        }
703
+        //try to set the session lifetime
704
+        $sessionLifeTime = self::getSessionLifeTime();
705
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
706
+
707
+        $systemConfig = \OC::$server->getSystemConfig();
708
+
709
+        // User and Groups
710
+        if (!$systemConfig->getValue("installed", false)) {
711
+            self::$server->getSession()->set('user_id', '');
712
+        }
713
+
714
+        OC_User::useBackend(new \OC\User\Database());
715
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
716
+
717
+        // Subscribe to the hook
718
+        \OCP\Util::connectHook(
719
+            '\OCA\Files_Sharing\API\Server2Server',
720
+            'preLoginNameUsedAsUserName',
721
+            '\OC\User\Database',
722
+            'preLoginNameUsedAsUserName'
723
+        );
724
+
725
+        //setup extra user backends
726
+        if (!self::checkUpgrade(false)) {
727
+            OC_User::setupBackends();
728
+        } else {
729
+            // Run upgrades in incognito mode
730
+            OC_User::setIncognitoMode(true);
731
+        }
732
+
733
+        self::registerCacheHooks();
734
+        self::registerFilesystemHooks();
735
+        self::registerShareHooks();
736
+        self::registerEncryptionWrapper();
737
+        self::registerEncryptionHooks();
738
+        self::registerAccountHooks();
739
+        self::registerSettingsHooks();
740
+
741
+        $settings = new \OC\Settings\Application();
742
+        $settings->register();
743
+
744
+        //make sure temporary files are cleaned up
745
+        $tmpManager = \OC::$server->getTempManager();
746
+        register_shutdown_function(array($tmpManager, 'clean'));
747
+        $lockProvider = \OC::$server->getLockingProvider();
748
+        register_shutdown_function(array($lockProvider, 'releaseAll'));
749
+
750
+        // Check whether the sample configuration has been copied
751
+        if($systemConfig->getValue('copied_sample_config', false)) {
752
+            $l = \OC::$server->getL10N('lib');
753
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
754
+            header('Status: 503 Service Temporarily Unavailable');
755
+            OC_Template::printErrorPage(
756
+                $l->t('Sample configuration detected'),
757
+                $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php')
758
+            );
759
+            return;
760
+        }
761
+
762
+        $request = \OC::$server->getRequest();
763
+        $host = $request->getInsecureServerHost();
764
+        /**
765
+         * if the host passed in headers isn't trusted
766
+         * FIXME: Should not be in here at all :see_no_evil:
767
+         */
768
+        if (!OC::$CLI
769
+            // overwritehost is always trusted, workaround to not have to make
770
+            // \OC\AppFramework\Http\Request::getOverwriteHost public
771
+            && self::$server->getConfig()->getSystemValue('overwritehost') === ''
772
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
773
+            && self::$server->getConfig()->getSystemValue('installed', false)
774
+        ) {
775
+            // Allow access to CSS resources
776
+            $isScssRequest = false;
777
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
778
+                $isScssRequest = true;
779
+            }
780
+
781
+            if (!$isScssRequest) {
782
+                header('HTTP/1.1 400 Bad Request');
783
+                header('Status: 400 Bad Request');
784
+
785
+                \OC::$server->getLogger()->warning(
786
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
787
+                    [
788
+                        'app' => 'core',
789
+                        'remoteAddress' => $request->getRemoteAddress(),
790
+                        'host' => $host,
791
+                    ]
792
+                );
793
+
794
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
795
+                $tmpl->assign('domain', $host);
796
+                $tmpl->printPage();
797
+
798
+                exit();
799
+            }
800
+        }
801
+        \OC::$server->getEventLogger()->end('boot');
802
+    }
803
+
804
+    /**
805
+     * register hooks for the cache
806
+     */
807
+    public static function registerCacheHooks() {
808
+        //don't try to do this before we are properly setup
809
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
810
+
811
+            // NOTE: This will be replaced to use OCP
812
+            $userSession = self::$server->getUserSession();
813
+            $userSession->listen('\OC\User', 'postLogin', function () {
814
+                try {
815
+                    $cache = new \OC\Cache\File();
816
+                    $cache->gc();
817
+                } catch (\OC\ServerNotAvailableException $e) {
818
+                    // not a GC exception, pass it on
819
+                    throw $e;
820
+                } catch (\OC\ForbiddenException $e) {
821
+                    // filesystem blocked for this request, ignore
822
+                } catch (\Exception $e) {
823
+                    // a GC exception should not prevent users from using OC,
824
+                    // so log the exception
825
+                    \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
826
+                }
827
+            });
828
+        }
829
+    }
830
+
831
+    public static function registerSettingsHooks() {
832
+        $dispatcher = \OC::$server->getEventDispatcher();
833
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
834
+            /** @var \OCP\App\ManagerEvent $event */
835
+            \OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
836
+        });
837
+        $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
838
+            /** @var \OCP\App\ManagerEvent $event */
839
+            $jobList = \OC::$server->getJobList();
840
+            $job = 'OC\\Settings\\RemoveOrphaned';
841
+            if(!($jobList->has($job, null))) {
842
+                $jobList->add($job);
843
+            }
844
+        });
845
+    }
846
+
847
+    private static function registerEncryptionWrapper() {
848
+        $manager = self::$server->getEncryptionManager();
849
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
850
+    }
851
+
852
+    private static function registerEncryptionHooks() {
853
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
854
+        if ($enabled) {
855
+            \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
856
+            \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
857
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
858
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
859
+        }
860
+    }
861
+
862
+    private static function registerAccountHooks() {
863
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
864
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
865
+    }
866
+
867
+    /**
868
+     * register hooks for the filesystem
869
+     */
870
+    public static function registerFilesystemHooks() {
871
+        // Check for blacklisted files
872
+        OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
873
+        OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
874
+    }
875
+
876
+    /**
877
+     * register hooks for sharing
878
+     */
879
+    public static function registerShareHooks() {
880
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
881
+            OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
882
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
883
+            OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
884
+        }
885
+    }
886
+
887
+    protected static function registerAutoloaderCache() {
888
+        // The class loader takes an optional low-latency cache, which MUST be
889
+        // namespaced. The instanceid is used for namespacing, but might be
890
+        // unavailable at this point. Furthermore, it might not be possible to
891
+        // generate an instanceid via \OC_Util::getInstanceId() because the
892
+        // config file may not be writable. As such, we only register a class
893
+        // loader cache if instanceid is available without trying to create one.
894
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
895
+        if ($instanceId) {
896
+            try {
897
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
898
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
899
+            } catch (\Exception $ex) {
900
+            }
901
+        }
902
+    }
903
+
904
+    /**
905
+     * Handle the request
906
+     */
907
+    public static function handleRequest() {
908
+
909
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
910
+        $systemConfig = \OC::$server->getSystemConfig();
911
+        // load all the classpaths from the enabled apps so they are available
912
+        // in the routing files of each app
913
+        OC::loadAppClassPaths();
914
+
915
+        // Check if Nextcloud is installed or in maintenance (update) mode
916
+        if (!$systemConfig->getValue('installed', false)) {
917
+            \OC::$server->getSession()->clear();
918
+            $setupHelper = new OC\Setup(
919
+                \OC::$server->getSystemConfig(),
920
+                \OC::$server->getIniWrapper(),
921
+                \OC::$server->getL10N('lib'),
922
+                \OC::$server->query(\OCP\Defaults::class),
923
+                \OC::$server->getLogger(),
924
+                \OC::$server->getSecureRandom(),
925
+                \OC::$server->query(Installer::class)
926
+            );
927
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
928
+            $controller->run($_POST);
929
+            exit();
930
+        }
931
+
932
+        $request = \OC::$server->getRequest();
933
+        $requestPath = $request->getRawPathInfo();
934
+        if ($requestPath === '/heartbeat') {
935
+            return;
936
+        }
937
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
938
+            self::checkMaintenanceMode();
939
+            self::checkUpgrade();
940
+        }
941
+
942
+        // emergency app disabling
943
+        if ($requestPath === '/disableapp'
944
+            && $request->getMethod() === 'POST'
945
+            && ((array)$request->getParam('appid')) !== ''
946
+        ) {
947
+            \OCP\JSON::callCheck();
948
+            \OCP\JSON::checkAdminUser();
949
+            $appIds = (array)$request->getParam('appid');
950
+            foreach($appIds as $appId) {
951
+                $appId = \OC_App::cleanAppId($appId);
952
+                \OC_App::disable($appId);
953
+            }
954
+            \OC_JSON::success();
955
+            exit();
956
+        }
957
+
958
+        // Always load authentication apps
959
+        OC_App::loadApps(['authentication']);
960
+
961
+        // Load minimum set of apps
962
+        if (!self::checkUpgrade(false)
963
+            && !$systemConfig->getValue('maintenance', false)) {
964
+            // For logged-in users: Load everything
965
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
966
+                OC_App::loadApps();
967
+            } else {
968
+                // For guests: Load only filesystem and logging
969
+                OC_App::loadApps(array('filesystem', 'logging'));
970
+                self::handleLogin($request);
971
+            }
972
+        }
973
+
974
+        if (!self::$CLI) {
975
+            try {
976
+                if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
977
+                    OC_App::loadApps(array('filesystem', 'logging'));
978
+                    OC_App::loadApps();
979
+                }
980
+                OC_Util::setupFS();
981
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
982
+                return;
983
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
984
+                //header('HTTP/1.0 404 Not Found');
985
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
986
+                OC_Response::setStatus(405);
987
+                return;
988
+            }
989
+        }
990
+
991
+        // Handle WebDAV
992
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
993
+            // not allowed any more to prevent people
994
+            // mounting this root directly.
995
+            // Users need to mount remote.php/webdav instead.
996
+            header('HTTP/1.1 405 Method Not Allowed');
997
+            header('Status: 405 Method Not Allowed');
998
+            return;
999
+        }
1000
+
1001
+        // Someone is logged in
1002
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1003
+            OC_App::loadApps();
1004
+            OC_User::setupBackends();
1005
+            OC_Util::setupFS();
1006
+            // FIXME
1007
+            // Redirect to default application
1008
+            OC_Util::redirectToDefaultPage();
1009
+        } else {
1010
+            // Not handled and not logged in
1011
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1012
+        }
1013
+    }
1014
+
1015
+    /**
1016
+     * Check login: apache auth, auth token, basic auth
1017
+     *
1018
+     * @param OCP\IRequest $request
1019
+     * @return boolean
1020
+     */
1021
+    static function handleLogin(OCP\IRequest $request) {
1022
+        $userSession = self::$server->getUserSession();
1023
+        if (OC_User::handleApacheAuth()) {
1024
+            return true;
1025
+        }
1026
+        if ($userSession->tryTokenLogin($request)) {
1027
+            return true;
1028
+        }
1029
+        if (isset($_COOKIE['nc_username'])
1030
+            && isset($_COOKIE['nc_token'])
1031
+            && isset($_COOKIE['nc_session_id'])
1032
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1033
+            return true;
1034
+        }
1035
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1036
+            return true;
1037
+        }
1038
+        return false;
1039
+    }
1040
+
1041
+    protected static function handleAuthHeaders() {
1042
+        //copy http auth headers for apache+php-fcgid work around
1043
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1044
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1045
+        }
1046
+
1047
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1048
+        $vars = array(
1049
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1050
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1051
+        );
1052
+        foreach ($vars as $var) {
1053
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1054
+                list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1055
+                $_SERVER['PHP_AUTH_USER'] = $name;
1056
+                $_SERVER['PHP_AUTH_PW'] = $password;
1057
+                break;
1058
+            }
1059
+        }
1060
+    }
1061 1061
 }
1062 1062
 
1063 1063
 OC::init();
Please login to merge, or discard this patch.