Completed
Pull Request — master (#7264)
by Morris
12:15
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/private/legacy/util.php 1 patch
Indentation   +1437 added lines, -1437 removed lines patch added patch discarded remove patch
@@ -65,1445 +65,1445 @@
 block discarded – undo
65 65
 use OCP\IUser;
66 66
 
67 67
 class OC_Util {
68
-	public static $scripts = array();
69
-	public static $styles = array();
70
-	public static $headers = array();
71
-	private static $rootMounted = false;
72
-	private static $fsSetup = false;
73
-
74
-	/** @var array Local cache of version.php */
75
-	private static $versionCache = null;
76
-
77
-	protected static function getAppManager() {
78
-		return \OC::$server->getAppManager();
79
-	}
80
-
81
-	private static function initLocalStorageRootFS() {
82
-		// mount local file backend as root
83
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
84
-		//first set up the local "root" storage
85
-		\OC\Files\Filesystem::initMountManager();
86
-		if (!self::$rootMounted) {
87
-			\OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
88
-			self::$rootMounted = true;
89
-		}
90
-	}
91
-
92
-	/**
93
-	 * mounting an object storage as the root fs will in essence remove the
94
-	 * necessity of a data folder being present.
95
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
96
-	 *
97
-	 * @param array $config containing 'class' and optional 'arguments'
98
-	 * @suppress PhanDeprecatedFunction
99
-	 */
100
-	private static function initObjectStoreRootFS($config) {
101
-		// check misconfiguration
102
-		if (empty($config['class'])) {
103
-			\OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
104
-		}
105
-		if (!isset($config['arguments'])) {
106
-			$config['arguments'] = array();
107
-		}
108
-
109
-		// instantiate object store implementation
110
-		$name = $config['class'];
111
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
112
-			$segments = explode('\\', $name);
113
-			OC_App::loadApp(strtolower($segments[1]));
114
-		}
115
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
116
-		// mount with plain / root object store implementation
117
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
118
-
119
-		// mount object storage as root
120
-		\OC\Files\Filesystem::initMountManager();
121
-		if (!self::$rootMounted) {
122
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
123
-			self::$rootMounted = true;
124
-		}
125
-	}
126
-
127
-	/**
128
-	 * mounting an object storage as the root fs will in essence remove the
129
-	 * necessity of a data folder being present.
130
-	 *
131
-	 * @param array $config containing 'class' and optional 'arguments'
132
-	 * @suppress PhanDeprecatedFunction
133
-	 */
134
-	private static function initObjectStoreMultibucketRootFS($config) {
135
-		// check misconfiguration
136
-		if (empty($config['class'])) {
137
-			\OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
138
-		}
139
-		if (!isset($config['arguments'])) {
140
-			$config['arguments'] = array();
141
-		}
142
-
143
-		// instantiate object store implementation
144
-		$name = $config['class'];
145
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
146
-			$segments = explode('\\', $name);
147
-			OC_App::loadApp(strtolower($segments[1]));
148
-		}
149
-
150
-		if (!isset($config['arguments']['bucket'])) {
151
-			$config['arguments']['bucket'] = '';
152
-		}
153
-		// put the root FS always in first bucket for multibucket configuration
154
-		$config['arguments']['bucket'] .= '0';
155
-
156
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
157
-		// mount with plain / root object store implementation
158
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
159
-
160
-		// mount object storage as root
161
-		\OC\Files\Filesystem::initMountManager();
162
-		if (!self::$rootMounted) {
163
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
164
-			self::$rootMounted = true;
165
-		}
166
-	}
167
-
168
-	/**
169
-	 * Can be set up
170
-	 *
171
-	 * @param string $user
172
-	 * @return boolean
173
-	 * @description configure the initial filesystem based on the configuration
174
-	 * @suppress PhanDeprecatedFunction
175
-	 * @suppress PhanAccessMethodInternal
176
-	 */
177
-	public static function setupFS($user = '') {
178
-		//setting up the filesystem twice can only lead to trouble
179
-		if (self::$fsSetup) {
180
-			return false;
181
-		}
182
-
183
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
184
-
185
-		// If we are not forced to load a specific user we load the one that is logged in
186
-		if ($user === null) {
187
-			$user = '';
188
-		} else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
189
-			$user = OC_User::getUser();
190
-		}
191
-
192
-		// load all filesystem apps before, so no setup-hook gets lost
193
-		OC_App::loadApps(array('filesystem'));
194
-
195
-		// the filesystem will finish when $user is not empty,
196
-		// mark fs setup here to avoid doing the setup from loading
197
-		// OC_Filesystem
198
-		if ($user != '') {
199
-			self::$fsSetup = true;
200
-		}
201
-
202
-		\OC\Files\Filesystem::initMountManager();
203
-
204
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
205
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
206
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
207
-				/** @var \OC\Files\Storage\Common $storage */
208
-				$storage->setMountOptions($mount->getOptions());
209
-			}
210
-			return $storage;
211
-		});
212
-
213
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
214
-			if (!$mount->getOption('enable_sharing', true)) {
215
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
216
-					'storage' => $storage,
217
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
218
-				]);
219
-			}
220
-			return $storage;
221
-		});
222
-
223
-		// install storage availability wrapper, before most other wrappers
224
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
225
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
226
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
227
-			}
228
-			return $storage;
229
-		});
230
-
231
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
232
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
233
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
234
-			}
235
-			return $storage;
236
-		});
237
-
238
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
239
-			// set up quota for home storages, even for other users
240
-			// which can happen when using sharing
241
-
242
-			/**
243
-			 * @var \OC\Files\Storage\Storage $storage
244
-			 */
245
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
246
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
247
-			) {
248
-				/** @var \OC\Files\Storage\Home $storage */
249
-				if (is_object($storage->getUser())) {
250
-					$user = $storage->getUser()->getUID();
251
-					$quota = OC_Util::getUserQuota($user);
252
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
253
-						return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
254
-					}
255
-				}
256
-			}
257
-
258
-			return $storage;
259
-		});
260
-
261
-		OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
262
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
263
-
264
-		//check if we are using an object storage
265
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
266
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
267
-
268
-		// use the same order as in ObjectHomeMountProvider
269
-		if (isset($objectStoreMultibucket)) {
270
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
271
-		} elseif (isset($objectStore)) {
272
-			self::initObjectStoreRootFS($objectStore);
273
-		} else {
274
-			self::initLocalStorageRootFS();
275
-		}
276
-
277
-		if ($user != '' && !OCP\User::userExists($user)) {
278
-			\OC::$server->getEventLogger()->end('setup_fs');
279
-			return false;
280
-		}
281
-
282
-		//if we aren't logged in, there is no use to set up the filesystem
283
-		if ($user != "") {
284
-
285
-			$userDir = '/' . $user . '/files';
286
-
287
-			//jail the user into his "home" directory
288
-			\OC\Files\Filesystem::init($user, $userDir);
289
-
290
-			OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
291
-		}
292
-		\OC::$server->getEventLogger()->end('setup_fs');
293
-		return true;
294
-	}
295
-
296
-	/**
297
-	 * check if a password is required for each public link
298
-	 *
299
-	 * @return boolean
300
-	 * @suppress PhanDeprecatedFunction
301
-	 */
302
-	public static function isPublicLinkPasswordRequired() {
303
-		$appConfig = \OC::$server->getAppConfig();
304
-		$enforcePassword = $appConfig->getValue('core', 'shareapi_enforce_links_password', 'no');
305
-		return ($enforcePassword === 'yes') ? true : false;
306
-	}
307
-
308
-	/**
309
-	 * check if sharing is disabled for the current user
310
-	 * @param IConfig $config
311
-	 * @param IGroupManager $groupManager
312
-	 * @param IUser|null $user
313
-	 * @return bool
314
-	 */
315
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
316
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
317
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
318
-			$excludedGroups = json_decode($groupsList);
319
-			if (is_null($excludedGroups)) {
320
-				$excludedGroups = explode(',', $groupsList);
321
-				$newValue = json_encode($excludedGroups);
322
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
323
-			}
324
-			$usersGroups = $groupManager->getUserGroupIds($user);
325
-			if (!empty($usersGroups)) {
326
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
327
-				// if the user is only in groups which are disabled for sharing then
328
-				// sharing is also disabled for the user
329
-				if (empty($remainingGroups)) {
330
-					return true;
331
-				}
332
-			}
333
-		}
334
-		return false;
335
-	}
336
-
337
-	/**
338
-	 * check if share API enforces a default expire date
339
-	 *
340
-	 * @return boolean
341
-	 * @suppress PhanDeprecatedFunction
342
-	 */
343
-	public static function isDefaultExpireDateEnforced() {
344
-		$isDefaultExpireDateEnabled = \OCP\Config::getAppValue('core', 'shareapi_default_expire_date', 'no');
345
-		$enforceDefaultExpireDate = false;
346
-		if ($isDefaultExpireDateEnabled === 'yes') {
347
-			$value = \OCP\Config::getAppValue('core', 'shareapi_enforce_expire_date', 'no');
348
-			$enforceDefaultExpireDate = ($value === 'yes') ? true : false;
349
-		}
350
-
351
-		return $enforceDefaultExpireDate;
352
-	}
353
-
354
-	/**
355
-	 * Get the quota of a user
356
-	 *
357
-	 * @param string $userId
358
-	 * @return float Quota bytes
359
-	 */
360
-	public static function getUserQuota($userId) {
361
-		$user = \OC::$server->getUserManager()->get($userId);
362
-		if (is_null($user)) {
363
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
364
-		}
365
-		$userQuota = $user->getQuota();
366
-		if($userQuota === 'none') {
367
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
368
-		}
369
-		return OC_Helper::computerFileSize($userQuota);
370
-	}
371
-
372
-	/**
373
-	 * copies the skeleton to the users /files
374
-	 *
375
-	 * @param String $userId
376
-	 * @param \OCP\Files\Folder $userDirectory
377
-	 * @throws \RuntimeException
378
-	 * @suppress PhanDeprecatedFunction
379
-	 */
380
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
381
-
382
-		$skeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
383
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
384
-
385
-		if ($instanceId === null) {
386
-			throw new \RuntimeException('no instance id!');
387
-		}
388
-		$appdata = 'appdata_' . $instanceId;
389
-		if ($userId === $appdata) {
390
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
391
-		}
392
-
393
-		if (!empty($skeletonDirectory)) {
394
-			\OCP\Util::writeLog(
395
-				'files_skeleton',
396
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
397
-				\OCP\Util::DEBUG
398
-			);
399
-			self::copyr($skeletonDirectory, $userDirectory);
400
-			// update the file cache
401
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
402
-		}
403
-	}
404
-
405
-	/**
406
-	 * copies a directory recursively by using streams
407
-	 *
408
-	 * @param string $source
409
-	 * @param \OCP\Files\Folder $target
410
-	 * @return void
411
-	 */
412
-	public static function copyr($source, \OCP\Files\Folder $target) {
413
-		$logger = \OC::$server->getLogger();
414
-
415
-		// Verify if folder exists
416
-		$dir = opendir($source);
417
-		if($dir === false) {
418
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
419
-			return;
420
-		}
421
-
422
-		// Copy the files
423
-		while (false !== ($file = readdir($dir))) {
424
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
425
-				if (is_dir($source . '/' . $file)) {
426
-					$child = $target->newFolder($file);
427
-					self::copyr($source . '/' . $file, $child);
428
-				} else {
429
-					$child = $target->newFile($file);
430
-					$sourceStream = fopen($source . '/' . $file, 'r');
431
-					if($sourceStream === false) {
432
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
433
-						closedir($dir);
434
-						return;
435
-					}
436
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
437
-				}
438
-			}
439
-		}
440
-		closedir($dir);
441
-	}
442
-
443
-	/**
444
-	 * @return void
445
-	 * @suppress PhanUndeclaredMethod
446
-	 */
447
-	public static function tearDownFS() {
448
-		\OC\Files\Filesystem::tearDown();
449
-		\OC::$server->getRootFolder()->clearCache();
450
-		self::$fsSetup = false;
451
-		self::$rootMounted = false;
452
-	}
453
-
454
-	/**
455
-	 * get the current installed version of ownCloud
456
-	 *
457
-	 * @return array
458
-	 */
459
-	public static function getVersion() {
460
-		OC_Util::loadVersion();
461
-		return self::$versionCache['OC_Version'];
462
-	}
463
-
464
-	/**
465
-	 * get the current installed version string of ownCloud
466
-	 *
467
-	 * @return string
468
-	 */
469
-	public static function getVersionString() {
470
-		OC_Util::loadVersion();
471
-		return self::$versionCache['OC_VersionString'];
472
-	}
473
-
474
-	/**
475
-	 * @deprecated the value is of no use anymore
476
-	 * @return string
477
-	 */
478
-	public static function getEditionString() {
479
-		return '';
480
-	}
481
-
482
-	/**
483
-	 * @description get the update channel of the current installed of ownCloud.
484
-	 * @return string
485
-	 */
486
-	public static function getChannel() {
487
-		OC_Util::loadVersion();
488
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
489
-	}
490
-
491
-	/**
492
-	 * @description get the build number of the current installed of ownCloud.
493
-	 * @return string
494
-	 */
495
-	public static function getBuild() {
496
-		OC_Util::loadVersion();
497
-		return self::$versionCache['OC_Build'];
498
-	}
499
-
500
-	/**
501
-	 * @description load the version.php into the session as cache
502
-	 * @suppress PhanUndeclaredVariable
503
-	 */
504
-	private static function loadVersion() {
505
-		if (self::$versionCache !== null) {
506
-			return;
507
-		}
508
-
509
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
510
-		require OC::$SERVERROOT . '/version.php';
511
-		/** @var $timestamp int */
512
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
513
-		/** @var $OC_Version string */
514
-		self::$versionCache['OC_Version'] = $OC_Version;
515
-		/** @var $OC_VersionString string */
516
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
517
-		/** @var $OC_Build string */
518
-		self::$versionCache['OC_Build'] = $OC_Build;
519
-
520
-		/** @var $OC_Channel string */
521
-		self::$versionCache['OC_Channel'] = $OC_Channel;
522
-	}
523
-
524
-	/**
525
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
526
-	 *
527
-	 * @param string $application application to get the files from
528
-	 * @param string $directory directory within this application (css, js, vendor, etc)
529
-	 * @param string $file the file inside of the above folder
530
-	 * @return string the path
531
-	 */
532
-	private static function generatePath($application, $directory, $file) {
533
-		if (is_null($file)) {
534
-			$file = $application;
535
-			$application = "";
536
-		}
537
-		if (!empty($application)) {
538
-			return "$application/$directory/$file";
539
-		} else {
540
-			return "$directory/$file";
541
-		}
542
-	}
543
-
544
-	/**
545
-	 * add a javascript file
546
-	 *
547
-	 * @param string $application application id
548
-	 * @param string|null $file filename
549
-	 * @param bool $prepend prepend the Script to the beginning of the list
550
-	 * @return void
551
-	 */
552
-	public static function addScript($application, $file = null, $prepend = false) {
553
-		$path = OC_Util::generatePath($application, 'js', $file);
554
-
555
-		// core js files need separate handling
556
-		if ($application !== 'core' && $file !== null) {
557
-			self::addTranslations ( $application );
558
-		}
559
-		self::addExternalResource($application, $prepend, $path, "script");
560
-	}
561
-
562
-	/**
563
-	 * add a javascript file from the vendor sub folder
564
-	 *
565
-	 * @param string $application application id
566
-	 * @param string|null $file filename
567
-	 * @param bool $prepend prepend the Script to the beginning of the list
568
-	 * @return void
569
-	 */
570
-	public static function addVendorScript($application, $file = null, $prepend = false) {
571
-		$path = OC_Util::generatePath($application, 'vendor', $file);
572
-		self::addExternalResource($application, $prepend, $path, "script");
573
-	}
574
-
575
-	/**
576
-	 * add a translation JS file
577
-	 *
578
-	 * @param string $application application id
579
-	 * @param string|null $languageCode language code, defaults to the current language
580
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
581
-	 */
582
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
583
-		if (is_null($languageCode)) {
584
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
585
-		}
586
-		if (!empty($application)) {
587
-			$path = "$application/l10n/$languageCode";
588
-		} else {
589
-			$path = "l10n/$languageCode";
590
-		}
591
-		self::addExternalResource($application, $prepend, $path, "script");
592
-	}
593
-
594
-	/**
595
-	 * add a css file
596
-	 *
597
-	 * @param string $application application id
598
-	 * @param string|null $file filename
599
-	 * @param bool $prepend prepend the Style to the beginning of the list
600
-	 * @return void
601
-	 */
602
-	public static function addStyle($application, $file = null, $prepend = false) {
603
-		$path = OC_Util::generatePath($application, 'css', $file);
604
-		self::addExternalResource($application, $prepend, $path, "style");
605
-	}
606
-
607
-	/**
608
-	 * add a css file from the vendor sub folder
609
-	 *
610
-	 * @param string $application application id
611
-	 * @param string|null $file filename
612
-	 * @param bool $prepend prepend the Style to the beginning of the list
613
-	 * @return void
614
-	 */
615
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
616
-		$path = OC_Util::generatePath($application, 'vendor', $file);
617
-		self::addExternalResource($application, $prepend, $path, "style");
618
-	}
619
-
620
-	/**
621
-	 * add an external resource css/js file
622
-	 *
623
-	 * @param string $application application id
624
-	 * @param bool $prepend prepend the file to the beginning of the list
625
-	 * @param string $path
626
-	 * @param string $type (script or style)
627
-	 * @return void
628
-	 */
629
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
630
-
631
-		if ($type === "style") {
632
-			if (!in_array($path, self::$styles)) {
633
-				if ($prepend === true) {
634
-					array_unshift ( self::$styles, $path );
635
-				} else {
636
-					self::$styles[] = $path;
637
-				}
638
-			}
639
-		} elseif ($type === "script") {
640
-			if (!in_array($path, self::$scripts)) {
641
-				if ($prepend === true) {
642
-					array_unshift ( self::$scripts, $path );
643
-				} else {
644
-					self::$scripts [] = $path;
645
-				}
646
-			}
647
-		}
648
-	}
649
-
650
-	/**
651
-	 * Add a custom element to the header
652
-	 * If $text is null then the element will be written as empty element.
653
-	 * So use "" to get a closing tag.
654
-	 * @param string $tag tag name of the element
655
-	 * @param array $attributes array of attributes for the element
656
-	 * @param string $text the text content for the element
657
-	 */
658
-	public static function addHeader($tag, $attributes, $text=null) {
659
-		self::$headers[] = array(
660
-			'tag' => $tag,
661
-			'attributes' => $attributes,
662
-			'text' => $text
663
-		);
664
-	}
665
-
666
-	/**
667
-	 * formats a timestamp in the "right" way
668
-	 *
669
-	 * @param int $timestamp
670
-	 * @param bool $dateOnly option to omit time from the result
671
-	 * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
672
-	 * @return string timestamp
673
-	 *
674
-	 * @deprecated Use \OC::$server->query('DateTimeFormatter') instead
675
-	 */
676
-	public static function formatDate($timestamp, $dateOnly = false, $timeZone = null) {
677
-		if ($timeZone !== null && !$timeZone instanceof \DateTimeZone) {
678
-			$timeZone = new \DateTimeZone($timeZone);
679
-		}
680
-
681
-		/** @var \OC\DateTimeFormatter $formatter */
682
-		$formatter = \OC::$server->query('DateTimeFormatter');
683
-		if ($dateOnly) {
684
-			return $formatter->formatDate($timestamp, 'long', $timeZone);
685
-		}
686
-		return $formatter->formatDateTime($timestamp, 'long', 'long', $timeZone);
687
-	}
688
-
689
-	/**
690
-	 * check if the current server configuration is suitable for ownCloud
691
-	 *
692
-	 * @param \OC\SystemConfig $config
693
-	 * @return array arrays with error messages and hints
694
-	 */
695
-	public static function checkServer(\OC\SystemConfig $config) {
696
-		$l = \OC::$server->getL10N('lib');
697
-		$errors = array();
698
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
699
-
700
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
701
-			// this check needs to be done every time
702
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
703
-		}
704
-
705
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
706
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
707
-			return $errors;
708
-		}
709
-
710
-		$webServerRestart = false;
711
-		$setup = new \OC\Setup(
712
-			$config,
713
-			\OC::$server->getIniWrapper(),
714
-			\OC::$server->getL10N('lib'),
715
-			\OC::$server->query(\OCP\Defaults::class),
716
-			\OC::$server->getLogger(),
717
-			\OC::$server->getSecureRandom(),
718
-			\OC::$server->query(\OC\Installer::class)
719
-		);
720
-
721
-		$urlGenerator = \OC::$server->getURLGenerator();
722
-
723
-		$availableDatabases = $setup->getSupportedDatabases();
724
-		if (empty($availableDatabases)) {
725
-			$errors[] = array(
726
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
727
-				'hint' => '' //TODO: sane hint
728
-			);
729
-			$webServerRestart = true;
730
-		}
731
-
732
-		// Check if config folder is writable.
733
-		if(!OC_Helper::isReadOnlyConfigEnabled()) {
734
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
735
-				$errors[] = array(
736
-					'error' => $l->t('Cannot write into "config" directory'),
737
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
738
-						[$urlGenerator->linkToDocs('admin-dir_permissions')])
739
-				);
740
-			}
741
-		}
742
-
743
-		// Check if there is a writable install folder.
744
-		if ($config->getValue('appstoreenabled', true)) {
745
-			if (OC_App::getInstallPath() === null
746
-				|| !is_writable(OC_App::getInstallPath())
747
-				|| !is_readable(OC_App::getInstallPath())
748
-			) {
749
-				$errors[] = array(
750
-					'error' => $l->t('Cannot write into "apps" directory'),
751
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
752
-						. ' or disabling the appstore in the config file. See %s',
753
-						[$urlGenerator->linkToDocs('admin-dir_permissions')])
754
-				);
755
-			}
756
-		}
757
-		// Create root dir.
758
-		if ($config->getValue('installed', false)) {
759
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
760
-				$success = @mkdir($CONFIG_DATADIRECTORY);
761
-				if ($success) {
762
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
763
-				} else {
764
-					$errors[] = [
765
-						'error' => $l->t('Cannot create "data" directory'),
766
-						'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
767
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
768
-					];
769
-				}
770
-			} else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
771
-				//common hint for all file permissions error messages
772
-				$permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
773
-					[$urlGenerator->linkToDocs('admin-dir_permissions')]);
774
-				$errors[] = [
775
-					'error' => 'Your data directory is not writable',
776
-					'hint' => $permissionsHint
777
-				];
778
-			} else {
779
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
780
-			}
781
-		}
782
-
783
-		if (!OC_Util::isSetLocaleWorking()) {
784
-			$errors[] = array(
785
-				'error' => $l->t('Setting locale to %s failed',
786
-					array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
787
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
788
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
789
-			);
790
-		}
791
-
792
-		// Contains the dependencies that should be checked against
793
-		// classes = class_exists
794
-		// functions = function_exists
795
-		// defined = defined
796
-		// ini = ini_get
797
-		// If the dependency is not found the missing module name is shown to the EndUser
798
-		// When adding new checks always verify that they pass on Travis as well
799
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
800
-		$dependencies = array(
801
-			'classes' => array(
802
-				'ZipArchive' => 'zip',
803
-				'DOMDocument' => 'dom',
804
-				'XMLWriter' => 'XMLWriter',
805
-				'XMLReader' => 'XMLReader',
806
-			),
807
-			'functions' => [
808
-				'xml_parser_create' => 'libxml',
809
-				'mb_strcut' => 'mb multibyte',
810
-				'ctype_digit' => 'ctype',
811
-				'json_encode' => 'JSON',
812
-				'gd_info' => 'GD',
813
-				'gzencode' => 'zlib',
814
-				'iconv' => 'iconv',
815
-				'simplexml_load_string' => 'SimpleXML',
816
-				'hash' => 'HASH Message Digest Framework',
817
-				'curl_init' => 'cURL',
818
-				'openssl_verify' => 'OpenSSL',
819
-			],
820
-			'defined' => array(
821
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
822
-			),
823
-			'ini' => [
824
-				'default_charset' => 'UTF-8',
825
-			],
826
-		);
827
-		$missingDependencies = array();
828
-		$invalidIniSettings = [];
829
-		$moduleHint = $l->t('Please ask your server administrator to install the module.');
830
-
831
-		/**
832
-		 * FIXME: The dependency check does not work properly on HHVM on the moment
833
-		 *        and prevents installation. Once HHVM is more compatible with our
834
-		 *        approach to check for these values we should re-enable those
835
-		 *        checks.
836
-		 */
837
-		$iniWrapper = \OC::$server->getIniWrapper();
838
-		if (!self::runningOnHhvm()) {
839
-			foreach ($dependencies['classes'] as $class => $module) {
840
-				if (!class_exists($class)) {
841
-					$missingDependencies[] = $module;
842
-				}
843
-			}
844
-			foreach ($dependencies['functions'] as $function => $module) {
845
-				if (!function_exists($function)) {
846
-					$missingDependencies[] = $module;
847
-				}
848
-			}
849
-			foreach ($dependencies['defined'] as $defined => $module) {
850
-				if (!defined($defined)) {
851
-					$missingDependencies[] = $module;
852
-				}
853
-			}
854
-			foreach ($dependencies['ini'] as $setting => $expected) {
855
-				if (is_bool($expected)) {
856
-					if ($iniWrapper->getBool($setting) !== $expected) {
857
-						$invalidIniSettings[] = [$setting, $expected];
858
-					}
859
-				}
860
-				if (is_int($expected)) {
861
-					if ($iniWrapper->getNumeric($setting) !== $expected) {
862
-						$invalidIniSettings[] = [$setting, $expected];
863
-					}
864
-				}
865
-				if (is_string($expected)) {
866
-					if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
867
-						$invalidIniSettings[] = [$setting, $expected];
868
-					}
869
-				}
870
-			}
871
-		}
872
-
873
-		foreach($missingDependencies as $missingDependency) {
874
-			$errors[] = array(
875
-				'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
876
-				'hint' => $moduleHint
877
-			);
878
-			$webServerRestart = true;
879
-		}
880
-		foreach($invalidIniSettings as $setting) {
881
-			if(is_bool($setting[1])) {
882
-				$setting[1] = ($setting[1]) ? 'on' : 'off';
883
-			}
884
-			$errors[] = [
885
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
886
-				'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
887
-			];
888
-			$webServerRestart = true;
889
-		}
890
-
891
-		/**
892
-		 * The mbstring.func_overload check can only be performed if the mbstring
893
-		 * module is installed as it will return null if the checking setting is
894
-		 * not available and thus a check on the boolean value fails.
895
-		 *
896
-		 * TODO: Should probably be implemented in the above generic dependency
897
-		 *       check somehow in the long-term.
898
-		 */
899
-		if($iniWrapper->getBool('mbstring.func_overload') !== null &&
900
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
901
-			$errors[] = array(
902
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
903
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
904
-			);
905
-		}
906
-
907
-		if(function_exists('xml_parser_create') &&
908
-			LIBXML_LOADED_VERSION < 20700 ) {
909
-			$version = LIBXML_LOADED_VERSION;
910
-			$major = floor($version/10000);
911
-			$version -= ($major * 10000);
912
-			$minor = floor($version/100);
913
-			$version -= ($minor * 100);
914
-			$patch = $version;
915
-			$errors[] = array(
916
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
917
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
918
-			);
919
-		}
920
-
921
-		if (!self::isAnnotationsWorking()) {
922
-			$errors[] = array(
923
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
924
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
925
-			);
926
-		}
927
-
928
-		if (!\OC::$CLI && $webServerRestart) {
929
-			$errors[] = array(
930
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
931
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
932
-			);
933
-		}
934
-
935
-		$errors = array_merge($errors, self::checkDatabaseVersion());
936
-
937
-		// Cache the result of this function
938
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
939
-
940
-		return $errors;
941
-	}
942
-
943
-	/**
944
-	 * Check the database version
945
-	 *
946
-	 * @return array errors array
947
-	 */
948
-	public static function checkDatabaseVersion() {
949
-		$l = \OC::$server->getL10N('lib');
950
-		$errors = array();
951
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
952
-		if ($dbType === 'pgsql') {
953
-			// check PostgreSQL version
954
-			try {
955
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
956
-				$data = $result->fetchRow();
957
-				if (isset($data['server_version'])) {
958
-					$version = $data['server_version'];
959
-					if (version_compare($version, '9.0.0', '<')) {
960
-						$errors[] = array(
961
-							'error' => $l->t('PostgreSQL >= 9 required'),
962
-							'hint' => $l->t('Please upgrade your database version')
963
-						);
964
-					}
965
-				}
966
-			} catch (\Doctrine\DBAL\DBALException $e) {
967
-				$logger = \OC::$server->getLogger();
968
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
969
-				$logger->logException($e);
970
-			}
971
-		}
972
-		return $errors;
973
-	}
974
-
975
-	/**
976
-	 * Check for correct file permissions of data directory
977
-	 *
978
-	 * @param string $dataDirectory
979
-	 * @return array arrays with error messages and hints
980
-	 */
981
-	public static function checkDataDirectoryPermissions($dataDirectory) {
982
-		$l = \OC::$server->getL10N('lib');
983
-		$errors = array();
984
-		$permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
985
-			. ' cannot be listed by other users.');
986
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
987
-		if (substr($perms, -1) !== '0') {
988
-			chmod($dataDirectory, 0770);
989
-			clearstatcache();
990
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
991
-			if ($perms[2] !== '0') {
992
-				$errors[] = [
993
-					'error' => $l->t('Your data directory is readable by other users'),
994
-					'hint' => $permissionsModHint
995
-				];
996
-			}
997
-		}
998
-		return $errors;
999
-	}
1000
-
1001
-	/**
1002
-	 * Check that the data directory exists and is valid by
1003
-	 * checking the existence of the ".ocdata" file.
1004
-	 *
1005
-	 * @param string $dataDirectory data directory path
1006
-	 * @return array errors found
1007
-	 */
1008
-	public static function checkDataDirectoryValidity($dataDirectory) {
1009
-		$l = \OC::$server->getL10N('lib');
1010
-		$errors = [];
1011
-		if ($dataDirectory[0] !== '/') {
1012
-			$errors[] = [
1013
-				'error' => $l->t('Your data directory must be an absolute path'),
1014
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1015
-			];
1016
-		}
1017
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1018
-			$errors[] = [
1019
-				'error' => $l->t('Your data directory is invalid'),
1020
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1021
-					' in the root of the data directory.')
1022
-			];
1023
-		}
1024
-		return $errors;
1025
-	}
1026
-
1027
-	/**
1028
-	 * Check if the user is logged in, redirects to home if not. With
1029
-	 * redirect URL parameter to the request URI.
1030
-	 *
1031
-	 * @return void
1032
-	 */
1033
-	public static function checkLoggedIn() {
1034
-		// Check if we are a user
1035
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1036
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1037
-						'core.login.showLoginForm',
1038
-						[
1039
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1040
-						]
1041
-					)
1042
-			);
1043
-			exit();
1044
-		}
1045
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1046
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1047
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1048
-			exit();
1049
-		}
1050
-	}
1051
-
1052
-	/**
1053
-	 * Check if the user is a admin, redirects to home if not
1054
-	 *
1055
-	 * @return void
1056
-	 */
1057
-	public static function checkAdminUser() {
1058
-		OC_Util::checkLoggedIn();
1059
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1060
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1061
-			exit();
1062
-		}
1063
-	}
1064
-
1065
-	/**
1066
-	 * Check if the user is a subadmin, redirects to home if not
1067
-	 *
1068
-	 * @return null|boolean $groups where the current user is subadmin
1069
-	 */
1070
-	public static function checkSubAdminUser() {
1071
-		OC_Util::checkLoggedIn();
1072
-		$userObject = \OC::$server->getUserSession()->getUser();
1073
-		$isSubAdmin = false;
1074
-		if($userObject !== null) {
1075
-			$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1076
-		}
1077
-
1078
-		if (!$isSubAdmin) {
1079
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1080
-			exit();
1081
-		}
1082
-		return true;
1083
-	}
1084
-
1085
-	/**
1086
-	 * Returns the URL of the default page
1087
-	 * based on the system configuration and
1088
-	 * the apps visible for the current user
1089
-	 *
1090
-	 * @return string URL
1091
-	 * @suppress PhanDeprecatedFunction
1092
-	 */
1093
-	public static function getDefaultPageUrl() {
1094
-		$urlGenerator = \OC::$server->getURLGenerator();
1095
-		// Deny the redirect if the URL contains a @
1096
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1097
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1098
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1099
-		} else {
1100
-			$defaultPage = \OC::$server->getAppConfig()->getValue('core', 'defaultpage');
1101
-			if ($defaultPage) {
1102
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1103
-			} else {
1104
-				$appId = 'files';
1105
-				$config = \OC::$server->getConfig();
1106
-				$defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1107
-				// find the first app that is enabled for the current user
1108
-				foreach ($defaultApps as $defaultApp) {
1109
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1110
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1111
-						$appId = $defaultApp;
1112
-						break;
1113
-					}
1114
-				}
1115
-
1116
-				if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1117
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1118
-				} else {
1119
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1120
-				}
1121
-			}
1122
-		}
1123
-		return $location;
1124
-	}
1125
-
1126
-	/**
1127
-	 * Redirect to the user default page
1128
-	 *
1129
-	 * @return void
1130
-	 */
1131
-	public static function redirectToDefaultPage() {
1132
-		$location = self::getDefaultPageUrl();
1133
-		header('Location: ' . $location);
1134
-		exit();
1135
-	}
1136
-
1137
-	/**
1138
-	 * get an id unique for this instance
1139
-	 *
1140
-	 * @return string
1141
-	 */
1142
-	public static function getInstanceId() {
1143
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1144
-		if (is_null($id)) {
1145
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1146
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1147
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1148
-		}
1149
-		return $id;
1150
-	}
1151
-
1152
-	/**
1153
-	 * Public function to sanitize HTML
1154
-	 *
1155
-	 * This function is used to sanitize HTML and should be applied on any
1156
-	 * string or array of strings before displaying it on a web page.
1157
-	 *
1158
-	 * @param string|array $value
1159
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1160
-	 */
1161
-	public static function sanitizeHTML($value) {
1162
-		if (is_array($value)) {
1163
-			$value = array_map(function($value) {
1164
-				return self::sanitizeHTML($value);
1165
-			}, $value);
1166
-		} else {
1167
-			// Specify encoding for PHP<5.4
1168
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1169
-		}
1170
-		return $value;
1171
-	}
1172
-
1173
-	/**
1174
-	 * Public function to encode url parameters
1175
-	 *
1176
-	 * This function is used to encode path to file before output.
1177
-	 * Encoding is done according to RFC 3986 with one exception:
1178
-	 * Character '/' is preserved as is.
1179
-	 *
1180
-	 * @param string $component part of URI to encode
1181
-	 * @return string
1182
-	 */
1183
-	public static function encodePath($component) {
1184
-		$encoded = rawurlencode($component);
1185
-		$encoded = str_replace('%2F', '/', $encoded);
1186
-		return $encoded;
1187
-	}
1188
-
1189
-
1190
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1191
-		// php dev server does not support htaccess
1192
-		if (php_sapi_name() === 'cli-server') {
1193
-			return false;
1194
-		}
1195
-
1196
-		// testdata
1197
-		$fileName = '/htaccesstest.txt';
1198
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1199
-
1200
-		// creating a test file
1201
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1202
-
1203
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1204
-			return false;
1205
-		}
1206
-
1207
-		$fp = @fopen($testFile, 'w');
1208
-		if (!$fp) {
1209
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1210
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1211
-		}
1212
-		fwrite($fp, $testContent);
1213
-		fclose($fp);
1214
-
1215
-		return $testContent;
1216
-	}
1217
-
1218
-	/**
1219
-	 * Check if the .htaccess file is working
1220
-	 * @param \OCP\IConfig $config
1221
-	 * @return bool
1222
-	 * @throws Exception
1223
-	 * @throws \OC\HintException If the test file can't get written.
1224
-	 */
1225
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1226
-
1227
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1228
-			return true;
1229
-		}
1230
-
1231
-		$testContent = $this->createHtaccessTestFile($config);
1232
-		if ($testContent === false) {
1233
-			return false;
1234
-		}
1235
-
1236
-		$fileName = '/htaccesstest.txt';
1237
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1238
-
1239
-		// accessing the file via http
1240
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1241
-		try {
1242
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1243
-		} catch (\Exception $e) {
1244
-			$content = false;
1245
-		}
1246
-
1247
-		// cleanup
1248
-		@unlink($testFile);
1249
-
1250
-		/*
68
+    public static $scripts = array();
69
+    public static $styles = array();
70
+    public static $headers = array();
71
+    private static $rootMounted = false;
72
+    private static $fsSetup = false;
73
+
74
+    /** @var array Local cache of version.php */
75
+    private static $versionCache = null;
76
+
77
+    protected static function getAppManager() {
78
+        return \OC::$server->getAppManager();
79
+    }
80
+
81
+    private static function initLocalStorageRootFS() {
82
+        // mount local file backend as root
83
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
84
+        //first set up the local "root" storage
85
+        \OC\Files\Filesystem::initMountManager();
86
+        if (!self::$rootMounted) {
87
+            \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
88
+            self::$rootMounted = true;
89
+        }
90
+    }
91
+
92
+    /**
93
+     * mounting an object storage as the root fs will in essence remove the
94
+     * necessity of a data folder being present.
95
+     * TODO make home storage aware of this and use the object storage instead of local disk access
96
+     *
97
+     * @param array $config containing 'class' and optional 'arguments'
98
+     * @suppress PhanDeprecatedFunction
99
+     */
100
+    private static function initObjectStoreRootFS($config) {
101
+        // check misconfiguration
102
+        if (empty($config['class'])) {
103
+            \OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
104
+        }
105
+        if (!isset($config['arguments'])) {
106
+            $config['arguments'] = array();
107
+        }
108
+
109
+        // instantiate object store implementation
110
+        $name = $config['class'];
111
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
112
+            $segments = explode('\\', $name);
113
+            OC_App::loadApp(strtolower($segments[1]));
114
+        }
115
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
116
+        // mount with plain / root object store implementation
117
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
118
+
119
+        // mount object storage as root
120
+        \OC\Files\Filesystem::initMountManager();
121
+        if (!self::$rootMounted) {
122
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
123
+            self::$rootMounted = true;
124
+        }
125
+    }
126
+
127
+    /**
128
+     * mounting an object storage as the root fs will in essence remove the
129
+     * necessity of a data folder being present.
130
+     *
131
+     * @param array $config containing 'class' and optional 'arguments'
132
+     * @suppress PhanDeprecatedFunction
133
+     */
134
+    private static function initObjectStoreMultibucketRootFS($config) {
135
+        // check misconfiguration
136
+        if (empty($config['class'])) {
137
+            \OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
138
+        }
139
+        if (!isset($config['arguments'])) {
140
+            $config['arguments'] = array();
141
+        }
142
+
143
+        // instantiate object store implementation
144
+        $name = $config['class'];
145
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
146
+            $segments = explode('\\', $name);
147
+            OC_App::loadApp(strtolower($segments[1]));
148
+        }
149
+
150
+        if (!isset($config['arguments']['bucket'])) {
151
+            $config['arguments']['bucket'] = '';
152
+        }
153
+        // put the root FS always in first bucket for multibucket configuration
154
+        $config['arguments']['bucket'] .= '0';
155
+
156
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
157
+        // mount with plain / root object store implementation
158
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
159
+
160
+        // mount object storage as root
161
+        \OC\Files\Filesystem::initMountManager();
162
+        if (!self::$rootMounted) {
163
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
164
+            self::$rootMounted = true;
165
+        }
166
+    }
167
+
168
+    /**
169
+     * Can be set up
170
+     *
171
+     * @param string $user
172
+     * @return boolean
173
+     * @description configure the initial filesystem based on the configuration
174
+     * @suppress PhanDeprecatedFunction
175
+     * @suppress PhanAccessMethodInternal
176
+     */
177
+    public static function setupFS($user = '') {
178
+        //setting up the filesystem twice can only lead to trouble
179
+        if (self::$fsSetup) {
180
+            return false;
181
+        }
182
+
183
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
184
+
185
+        // If we are not forced to load a specific user we load the one that is logged in
186
+        if ($user === null) {
187
+            $user = '';
188
+        } else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
189
+            $user = OC_User::getUser();
190
+        }
191
+
192
+        // load all filesystem apps before, so no setup-hook gets lost
193
+        OC_App::loadApps(array('filesystem'));
194
+
195
+        // the filesystem will finish when $user is not empty,
196
+        // mark fs setup here to avoid doing the setup from loading
197
+        // OC_Filesystem
198
+        if ($user != '') {
199
+            self::$fsSetup = true;
200
+        }
201
+
202
+        \OC\Files\Filesystem::initMountManager();
203
+
204
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
205
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
206
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
207
+                /** @var \OC\Files\Storage\Common $storage */
208
+                $storage->setMountOptions($mount->getOptions());
209
+            }
210
+            return $storage;
211
+        });
212
+
213
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
214
+            if (!$mount->getOption('enable_sharing', true)) {
215
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
216
+                    'storage' => $storage,
217
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
218
+                ]);
219
+            }
220
+            return $storage;
221
+        });
222
+
223
+        // install storage availability wrapper, before most other wrappers
224
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
225
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
226
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
227
+            }
228
+            return $storage;
229
+        });
230
+
231
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
232
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
233
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
234
+            }
235
+            return $storage;
236
+        });
237
+
238
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
239
+            // set up quota for home storages, even for other users
240
+            // which can happen when using sharing
241
+
242
+            /**
243
+             * @var \OC\Files\Storage\Storage $storage
244
+             */
245
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
246
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
247
+            ) {
248
+                /** @var \OC\Files\Storage\Home $storage */
249
+                if (is_object($storage->getUser())) {
250
+                    $user = $storage->getUser()->getUID();
251
+                    $quota = OC_Util::getUserQuota($user);
252
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
253
+                        return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
254
+                    }
255
+                }
256
+            }
257
+
258
+            return $storage;
259
+        });
260
+
261
+        OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
262
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
263
+
264
+        //check if we are using an object storage
265
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
266
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
267
+
268
+        // use the same order as in ObjectHomeMountProvider
269
+        if (isset($objectStoreMultibucket)) {
270
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
271
+        } elseif (isset($objectStore)) {
272
+            self::initObjectStoreRootFS($objectStore);
273
+        } else {
274
+            self::initLocalStorageRootFS();
275
+        }
276
+
277
+        if ($user != '' && !OCP\User::userExists($user)) {
278
+            \OC::$server->getEventLogger()->end('setup_fs');
279
+            return false;
280
+        }
281
+
282
+        //if we aren't logged in, there is no use to set up the filesystem
283
+        if ($user != "") {
284
+
285
+            $userDir = '/' . $user . '/files';
286
+
287
+            //jail the user into his "home" directory
288
+            \OC\Files\Filesystem::init($user, $userDir);
289
+
290
+            OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
291
+        }
292
+        \OC::$server->getEventLogger()->end('setup_fs');
293
+        return true;
294
+    }
295
+
296
+    /**
297
+     * check if a password is required for each public link
298
+     *
299
+     * @return boolean
300
+     * @suppress PhanDeprecatedFunction
301
+     */
302
+    public static function isPublicLinkPasswordRequired() {
303
+        $appConfig = \OC::$server->getAppConfig();
304
+        $enforcePassword = $appConfig->getValue('core', 'shareapi_enforce_links_password', 'no');
305
+        return ($enforcePassword === 'yes') ? true : false;
306
+    }
307
+
308
+    /**
309
+     * check if sharing is disabled for the current user
310
+     * @param IConfig $config
311
+     * @param IGroupManager $groupManager
312
+     * @param IUser|null $user
313
+     * @return bool
314
+     */
315
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
316
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
317
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
318
+            $excludedGroups = json_decode($groupsList);
319
+            if (is_null($excludedGroups)) {
320
+                $excludedGroups = explode(',', $groupsList);
321
+                $newValue = json_encode($excludedGroups);
322
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
323
+            }
324
+            $usersGroups = $groupManager->getUserGroupIds($user);
325
+            if (!empty($usersGroups)) {
326
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
327
+                // if the user is only in groups which are disabled for sharing then
328
+                // sharing is also disabled for the user
329
+                if (empty($remainingGroups)) {
330
+                    return true;
331
+                }
332
+            }
333
+        }
334
+        return false;
335
+    }
336
+
337
+    /**
338
+     * check if share API enforces a default expire date
339
+     *
340
+     * @return boolean
341
+     * @suppress PhanDeprecatedFunction
342
+     */
343
+    public static function isDefaultExpireDateEnforced() {
344
+        $isDefaultExpireDateEnabled = \OCP\Config::getAppValue('core', 'shareapi_default_expire_date', 'no');
345
+        $enforceDefaultExpireDate = false;
346
+        if ($isDefaultExpireDateEnabled === 'yes') {
347
+            $value = \OCP\Config::getAppValue('core', 'shareapi_enforce_expire_date', 'no');
348
+            $enforceDefaultExpireDate = ($value === 'yes') ? true : false;
349
+        }
350
+
351
+        return $enforceDefaultExpireDate;
352
+    }
353
+
354
+    /**
355
+     * Get the quota of a user
356
+     *
357
+     * @param string $userId
358
+     * @return float Quota bytes
359
+     */
360
+    public static function getUserQuota($userId) {
361
+        $user = \OC::$server->getUserManager()->get($userId);
362
+        if (is_null($user)) {
363
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
364
+        }
365
+        $userQuota = $user->getQuota();
366
+        if($userQuota === 'none') {
367
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
368
+        }
369
+        return OC_Helper::computerFileSize($userQuota);
370
+    }
371
+
372
+    /**
373
+     * copies the skeleton to the users /files
374
+     *
375
+     * @param String $userId
376
+     * @param \OCP\Files\Folder $userDirectory
377
+     * @throws \RuntimeException
378
+     * @suppress PhanDeprecatedFunction
379
+     */
380
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
381
+
382
+        $skeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
383
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
384
+
385
+        if ($instanceId === null) {
386
+            throw new \RuntimeException('no instance id!');
387
+        }
388
+        $appdata = 'appdata_' . $instanceId;
389
+        if ($userId === $appdata) {
390
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
391
+        }
392
+
393
+        if (!empty($skeletonDirectory)) {
394
+            \OCP\Util::writeLog(
395
+                'files_skeleton',
396
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
397
+                \OCP\Util::DEBUG
398
+            );
399
+            self::copyr($skeletonDirectory, $userDirectory);
400
+            // update the file cache
401
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
402
+        }
403
+    }
404
+
405
+    /**
406
+     * copies a directory recursively by using streams
407
+     *
408
+     * @param string $source
409
+     * @param \OCP\Files\Folder $target
410
+     * @return void
411
+     */
412
+    public static function copyr($source, \OCP\Files\Folder $target) {
413
+        $logger = \OC::$server->getLogger();
414
+
415
+        // Verify if folder exists
416
+        $dir = opendir($source);
417
+        if($dir === false) {
418
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
419
+            return;
420
+        }
421
+
422
+        // Copy the files
423
+        while (false !== ($file = readdir($dir))) {
424
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
425
+                if (is_dir($source . '/' . $file)) {
426
+                    $child = $target->newFolder($file);
427
+                    self::copyr($source . '/' . $file, $child);
428
+                } else {
429
+                    $child = $target->newFile($file);
430
+                    $sourceStream = fopen($source . '/' . $file, 'r');
431
+                    if($sourceStream === false) {
432
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
433
+                        closedir($dir);
434
+                        return;
435
+                    }
436
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
437
+                }
438
+            }
439
+        }
440
+        closedir($dir);
441
+    }
442
+
443
+    /**
444
+     * @return void
445
+     * @suppress PhanUndeclaredMethod
446
+     */
447
+    public static function tearDownFS() {
448
+        \OC\Files\Filesystem::tearDown();
449
+        \OC::$server->getRootFolder()->clearCache();
450
+        self::$fsSetup = false;
451
+        self::$rootMounted = false;
452
+    }
453
+
454
+    /**
455
+     * get the current installed version of ownCloud
456
+     *
457
+     * @return array
458
+     */
459
+    public static function getVersion() {
460
+        OC_Util::loadVersion();
461
+        return self::$versionCache['OC_Version'];
462
+    }
463
+
464
+    /**
465
+     * get the current installed version string of ownCloud
466
+     *
467
+     * @return string
468
+     */
469
+    public static function getVersionString() {
470
+        OC_Util::loadVersion();
471
+        return self::$versionCache['OC_VersionString'];
472
+    }
473
+
474
+    /**
475
+     * @deprecated the value is of no use anymore
476
+     * @return string
477
+     */
478
+    public static function getEditionString() {
479
+        return '';
480
+    }
481
+
482
+    /**
483
+     * @description get the update channel of the current installed of ownCloud.
484
+     * @return string
485
+     */
486
+    public static function getChannel() {
487
+        OC_Util::loadVersion();
488
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
489
+    }
490
+
491
+    /**
492
+     * @description get the build number of the current installed of ownCloud.
493
+     * @return string
494
+     */
495
+    public static function getBuild() {
496
+        OC_Util::loadVersion();
497
+        return self::$versionCache['OC_Build'];
498
+    }
499
+
500
+    /**
501
+     * @description load the version.php into the session as cache
502
+     * @suppress PhanUndeclaredVariable
503
+     */
504
+    private static function loadVersion() {
505
+        if (self::$versionCache !== null) {
506
+            return;
507
+        }
508
+
509
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
510
+        require OC::$SERVERROOT . '/version.php';
511
+        /** @var $timestamp int */
512
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
513
+        /** @var $OC_Version string */
514
+        self::$versionCache['OC_Version'] = $OC_Version;
515
+        /** @var $OC_VersionString string */
516
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
517
+        /** @var $OC_Build string */
518
+        self::$versionCache['OC_Build'] = $OC_Build;
519
+
520
+        /** @var $OC_Channel string */
521
+        self::$versionCache['OC_Channel'] = $OC_Channel;
522
+    }
523
+
524
+    /**
525
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
526
+     *
527
+     * @param string $application application to get the files from
528
+     * @param string $directory directory within this application (css, js, vendor, etc)
529
+     * @param string $file the file inside of the above folder
530
+     * @return string the path
531
+     */
532
+    private static function generatePath($application, $directory, $file) {
533
+        if (is_null($file)) {
534
+            $file = $application;
535
+            $application = "";
536
+        }
537
+        if (!empty($application)) {
538
+            return "$application/$directory/$file";
539
+        } else {
540
+            return "$directory/$file";
541
+        }
542
+    }
543
+
544
+    /**
545
+     * add a javascript file
546
+     *
547
+     * @param string $application application id
548
+     * @param string|null $file filename
549
+     * @param bool $prepend prepend the Script to the beginning of the list
550
+     * @return void
551
+     */
552
+    public static function addScript($application, $file = null, $prepend = false) {
553
+        $path = OC_Util::generatePath($application, 'js', $file);
554
+
555
+        // core js files need separate handling
556
+        if ($application !== 'core' && $file !== null) {
557
+            self::addTranslations ( $application );
558
+        }
559
+        self::addExternalResource($application, $prepend, $path, "script");
560
+    }
561
+
562
+    /**
563
+     * add a javascript file from the vendor sub folder
564
+     *
565
+     * @param string $application application id
566
+     * @param string|null $file filename
567
+     * @param bool $prepend prepend the Script to the beginning of the list
568
+     * @return void
569
+     */
570
+    public static function addVendorScript($application, $file = null, $prepend = false) {
571
+        $path = OC_Util::generatePath($application, 'vendor', $file);
572
+        self::addExternalResource($application, $prepend, $path, "script");
573
+    }
574
+
575
+    /**
576
+     * add a translation JS file
577
+     *
578
+     * @param string $application application id
579
+     * @param string|null $languageCode language code, defaults to the current language
580
+     * @param bool|null $prepend prepend the Script to the beginning of the list
581
+     */
582
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
583
+        if (is_null($languageCode)) {
584
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
585
+        }
586
+        if (!empty($application)) {
587
+            $path = "$application/l10n/$languageCode";
588
+        } else {
589
+            $path = "l10n/$languageCode";
590
+        }
591
+        self::addExternalResource($application, $prepend, $path, "script");
592
+    }
593
+
594
+    /**
595
+     * add a css file
596
+     *
597
+     * @param string $application application id
598
+     * @param string|null $file filename
599
+     * @param bool $prepend prepend the Style to the beginning of the list
600
+     * @return void
601
+     */
602
+    public static function addStyle($application, $file = null, $prepend = false) {
603
+        $path = OC_Util::generatePath($application, 'css', $file);
604
+        self::addExternalResource($application, $prepend, $path, "style");
605
+    }
606
+
607
+    /**
608
+     * add a css file from the vendor sub folder
609
+     *
610
+     * @param string $application application id
611
+     * @param string|null $file filename
612
+     * @param bool $prepend prepend the Style to the beginning of the list
613
+     * @return void
614
+     */
615
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
616
+        $path = OC_Util::generatePath($application, 'vendor', $file);
617
+        self::addExternalResource($application, $prepend, $path, "style");
618
+    }
619
+
620
+    /**
621
+     * add an external resource css/js file
622
+     *
623
+     * @param string $application application id
624
+     * @param bool $prepend prepend the file to the beginning of the list
625
+     * @param string $path
626
+     * @param string $type (script or style)
627
+     * @return void
628
+     */
629
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
630
+
631
+        if ($type === "style") {
632
+            if (!in_array($path, self::$styles)) {
633
+                if ($prepend === true) {
634
+                    array_unshift ( self::$styles, $path );
635
+                } else {
636
+                    self::$styles[] = $path;
637
+                }
638
+            }
639
+        } elseif ($type === "script") {
640
+            if (!in_array($path, self::$scripts)) {
641
+                if ($prepend === true) {
642
+                    array_unshift ( self::$scripts, $path );
643
+                } else {
644
+                    self::$scripts [] = $path;
645
+                }
646
+            }
647
+        }
648
+    }
649
+
650
+    /**
651
+     * Add a custom element to the header
652
+     * If $text is null then the element will be written as empty element.
653
+     * So use "" to get a closing tag.
654
+     * @param string $tag tag name of the element
655
+     * @param array $attributes array of attributes for the element
656
+     * @param string $text the text content for the element
657
+     */
658
+    public static function addHeader($tag, $attributes, $text=null) {
659
+        self::$headers[] = array(
660
+            'tag' => $tag,
661
+            'attributes' => $attributes,
662
+            'text' => $text
663
+        );
664
+    }
665
+
666
+    /**
667
+     * formats a timestamp in the "right" way
668
+     *
669
+     * @param int $timestamp
670
+     * @param bool $dateOnly option to omit time from the result
671
+     * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
672
+     * @return string timestamp
673
+     *
674
+     * @deprecated Use \OC::$server->query('DateTimeFormatter') instead
675
+     */
676
+    public static function formatDate($timestamp, $dateOnly = false, $timeZone = null) {
677
+        if ($timeZone !== null && !$timeZone instanceof \DateTimeZone) {
678
+            $timeZone = new \DateTimeZone($timeZone);
679
+        }
680
+
681
+        /** @var \OC\DateTimeFormatter $formatter */
682
+        $formatter = \OC::$server->query('DateTimeFormatter');
683
+        if ($dateOnly) {
684
+            return $formatter->formatDate($timestamp, 'long', $timeZone);
685
+        }
686
+        return $formatter->formatDateTime($timestamp, 'long', 'long', $timeZone);
687
+    }
688
+
689
+    /**
690
+     * check if the current server configuration is suitable for ownCloud
691
+     *
692
+     * @param \OC\SystemConfig $config
693
+     * @return array arrays with error messages and hints
694
+     */
695
+    public static function checkServer(\OC\SystemConfig $config) {
696
+        $l = \OC::$server->getL10N('lib');
697
+        $errors = array();
698
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
699
+
700
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
701
+            // this check needs to be done every time
702
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
703
+        }
704
+
705
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
706
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
707
+            return $errors;
708
+        }
709
+
710
+        $webServerRestart = false;
711
+        $setup = new \OC\Setup(
712
+            $config,
713
+            \OC::$server->getIniWrapper(),
714
+            \OC::$server->getL10N('lib'),
715
+            \OC::$server->query(\OCP\Defaults::class),
716
+            \OC::$server->getLogger(),
717
+            \OC::$server->getSecureRandom(),
718
+            \OC::$server->query(\OC\Installer::class)
719
+        );
720
+
721
+        $urlGenerator = \OC::$server->getURLGenerator();
722
+
723
+        $availableDatabases = $setup->getSupportedDatabases();
724
+        if (empty($availableDatabases)) {
725
+            $errors[] = array(
726
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
727
+                'hint' => '' //TODO: sane hint
728
+            );
729
+            $webServerRestart = true;
730
+        }
731
+
732
+        // Check if config folder is writable.
733
+        if(!OC_Helper::isReadOnlyConfigEnabled()) {
734
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
735
+                $errors[] = array(
736
+                    'error' => $l->t('Cannot write into "config" directory'),
737
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
738
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')])
739
+                );
740
+            }
741
+        }
742
+
743
+        // Check if there is a writable install folder.
744
+        if ($config->getValue('appstoreenabled', true)) {
745
+            if (OC_App::getInstallPath() === null
746
+                || !is_writable(OC_App::getInstallPath())
747
+                || !is_readable(OC_App::getInstallPath())
748
+            ) {
749
+                $errors[] = array(
750
+                    'error' => $l->t('Cannot write into "apps" directory'),
751
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
752
+                        . ' or disabling the appstore in the config file. See %s',
753
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')])
754
+                );
755
+            }
756
+        }
757
+        // Create root dir.
758
+        if ($config->getValue('installed', false)) {
759
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
760
+                $success = @mkdir($CONFIG_DATADIRECTORY);
761
+                if ($success) {
762
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
763
+                } else {
764
+                    $errors[] = [
765
+                        'error' => $l->t('Cannot create "data" directory'),
766
+                        'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
767
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
768
+                    ];
769
+                }
770
+            } else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
771
+                //common hint for all file permissions error messages
772
+                $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
773
+                    [$urlGenerator->linkToDocs('admin-dir_permissions')]);
774
+                $errors[] = [
775
+                    'error' => 'Your data directory is not writable',
776
+                    'hint' => $permissionsHint
777
+                ];
778
+            } else {
779
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
780
+            }
781
+        }
782
+
783
+        if (!OC_Util::isSetLocaleWorking()) {
784
+            $errors[] = array(
785
+                'error' => $l->t('Setting locale to %s failed',
786
+                    array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
787
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
788
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
789
+            );
790
+        }
791
+
792
+        // Contains the dependencies that should be checked against
793
+        // classes = class_exists
794
+        // functions = function_exists
795
+        // defined = defined
796
+        // ini = ini_get
797
+        // If the dependency is not found the missing module name is shown to the EndUser
798
+        // When adding new checks always verify that they pass on Travis as well
799
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
800
+        $dependencies = array(
801
+            'classes' => array(
802
+                'ZipArchive' => 'zip',
803
+                'DOMDocument' => 'dom',
804
+                'XMLWriter' => 'XMLWriter',
805
+                'XMLReader' => 'XMLReader',
806
+            ),
807
+            'functions' => [
808
+                'xml_parser_create' => 'libxml',
809
+                'mb_strcut' => 'mb multibyte',
810
+                'ctype_digit' => 'ctype',
811
+                'json_encode' => 'JSON',
812
+                'gd_info' => 'GD',
813
+                'gzencode' => 'zlib',
814
+                'iconv' => 'iconv',
815
+                'simplexml_load_string' => 'SimpleXML',
816
+                'hash' => 'HASH Message Digest Framework',
817
+                'curl_init' => 'cURL',
818
+                'openssl_verify' => 'OpenSSL',
819
+            ],
820
+            'defined' => array(
821
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
822
+            ),
823
+            'ini' => [
824
+                'default_charset' => 'UTF-8',
825
+            ],
826
+        );
827
+        $missingDependencies = array();
828
+        $invalidIniSettings = [];
829
+        $moduleHint = $l->t('Please ask your server administrator to install the module.');
830
+
831
+        /**
832
+         * FIXME: The dependency check does not work properly on HHVM on the moment
833
+         *        and prevents installation. Once HHVM is more compatible with our
834
+         *        approach to check for these values we should re-enable those
835
+         *        checks.
836
+         */
837
+        $iniWrapper = \OC::$server->getIniWrapper();
838
+        if (!self::runningOnHhvm()) {
839
+            foreach ($dependencies['classes'] as $class => $module) {
840
+                if (!class_exists($class)) {
841
+                    $missingDependencies[] = $module;
842
+                }
843
+            }
844
+            foreach ($dependencies['functions'] as $function => $module) {
845
+                if (!function_exists($function)) {
846
+                    $missingDependencies[] = $module;
847
+                }
848
+            }
849
+            foreach ($dependencies['defined'] as $defined => $module) {
850
+                if (!defined($defined)) {
851
+                    $missingDependencies[] = $module;
852
+                }
853
+            }
854
+            foreach ($dependencies['ini'] as $setting => $expected) {
855
+                if (is_bool($expected)) {
856
+                    if ($iniWrapper->getBool($setting) !== $expected) {
857
+                        $invalidIniSettings[] = [$setting, $expected];
858
+                    }
859
+                }
860
+                if (is_int($expected)) {
861
+                    if ($iniWrapper->getNumeric($setting) !== $expected) {
862
+                        $invalidIniSettings[] = [$setting, $expected];
863
+                    }
864
+                }
865
+                if (is_string($expected)) {
866
+                    if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
867
+                        $invalidIniSettings[] = [$setting, $expected];
868
+                    }
869
+                }
870
+            }
871
+        }
872
+
873
+        foreach($missingDependencies as $missingDependency) {
874
+            $errors[] = array(
875
+                'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
876
+                'hint' => $moduleHint
877
+            );
878
+            $webServerRestart = true;
879
+        }
880
+        foreach($invalidIniSettings as $setting) {
881
+            if(is_bool($setting[1])) {
882
+                $setting[1] = ($setting[1]) ? 'on' : 'off';
883
+            }
884
+            $errors[] = [
885
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
886
+                'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
887
+            ];
888
+            $webServerRestart = true;
889
+        }
890
+
891
+        /**
892
+         * The mbstring.func_overload check can only be performed if the mbstring
893
+         * module is installed as it will return null if the checking setting is
894
+         * not available and thus a check on the boolean value fails.
895
+         *
896
+         * TODO: Should probably be implemented in the above generic dependency
897
+         *       check somehow in the long-term.
898
+         */
899
+        if($iniWrapper->getBool('mbstring.func_overload') !== null &&
900
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
901
+            $errors[] = array(
902
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
903
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
904
+            );
905
+        }
906
+
907
+        if(function_exists('xml_parser_create') &&
908
+            LIBXML_LOADED_VERSION < 20700 ) {
909
+            $version = LIBXML_LOADED_VERSION;
910
+            $major = floor($version/10000);
911
+            $version -= ($major * 10000);
912
+            $minor = floor($version/100);
913
+            $version -= ($minor * 100);
914
+            $patch = $version;
915
+            $errors[] = array(
916
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
917
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
918
+            );
919
+        }
920
+
921
+        if (!self::isAnnotationsWorking()) {
922
+            $errors[] = array(
923
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
924
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
925
+            );
926
+        }
927
+
928
+        if (!\OC::$CLI && $webServerRestart) {
929
+            $errors[] = array(
930
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
931
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
932
+            );
933
+        }
934
+
935
+        $errors = array_merge($errors, self::checkDatabaseVersion());
936
+
937
+        // Cache the result of this function
938
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
939
+
940
+        return $errors;
941
+    }
942
+
943
+    /**
944
+     * Check the database version
945
+     *
946
+     * @return array errors array
947
+     */
948
+    public static function checkDatabaseVersion() {
949
+        $l = \OC::$server->getL10N('lib');
950
+        $errors = array();
951
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
952
+        if ($dbType === 'pgsql') {
953
+            // check PostgreSQL version
954
+            try {
955
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
956
+                $data = $result->fetchRow();
957
+                if (isset($data['server_version'])) {
958
+                    $version = $data['server_version'];
959
+                    if (version_compare($version, '9.0.0', '<')) {
960
+                        $errors[] = array(
961
+                            'error' => $l->t('PostgreSQL >= 9 required'),
962
+                            'hint' => $l->t('Please upgrade your database version')
963
+                        );
964
+                    }
965
+                }
966
+            } catch (\Doctrine\DBAL\DBALException $e) {
967
+                $logger = \OC::$server->getLogger();
968
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
969
+                $logger->logException($e);
970
+            }
971
+        }
972
+        return $errors;
973
+    }
974
+
975
+    /**
976
+     * Check for correct file permissions of data directory
977
+     *
978
+     * @param string $dataDirectory
979
+     * @return array arrays with error messages and hints
980
+     */
981
+    public static function checkDataDirectoryPermissions($dataDirectory) {
982
+        $l = \OC::$server->getL10N('lib');
983
+        $errors = array();
984
+        $permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
985
+            . ' cannot be listed by other users.');
986
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
987
+        if (substr($perms, -1) !== '0') {
988
+            chmod($dataDirectory, 0770);
989
+            clearstatcache();
990
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
991
+            if ($perms[2] !== '0') {
992
+                $errors[] = [
993
+                    'error' => $l->t('Your data directory is readable by other users'),
994
+                    'hint' => $permissionsModHint
995
+                ];
996
+            }
997
+        }
998
+        return $errors;
999
+    }
1000
+
1001
+    /**
1002
+     * Check that the data directory exists and is valid by
1003
+     * checking the existence of the ".ocdata" file.
1004
+     *
1005
+     * @param string $dataDirectory data directory path
1006
+     * @return array errors found
1007
+     */
1008
+    public static function checkDataDirectoryValidity($dataDirectory) {
1009
+        $l = \OC::$server->getL10N('lib');
1010
+        $errors = [];
1011
+        if ($dataDirectory[0] !== '/') {
1012
+            $errors[] = [
1013
+                'error' => $l->t('Your data directory must be an absolute path'),
1014
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1015
+            ];
1016
+        }
1017
+        if (!file_exists($dataDirectory . '/.ocdata')) {
1018
+            $errors[] = [
1019
+                'error' => $l->t('Your data directory is invalid'),
1020
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1021
+                    ' in the root of the data directory.')
1022
+            ];
1023
+        }
1024
+        return $errors;
1025
+    }
1026
+
1027
+    /**
1028
+     * Check if the user is logged in, redirects to home if not. With
1029
+     * redirect URL parameter to the request URI.
1030
+     *
1031
+     * @return void
1032
+     */
1033
+    public static function checkLoggedIn() {
1034
+        // Check if we are a user
1035
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1036
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1037
+                        'core.login.showLoginForm',
1038
+                        [
1039
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1040
+                        ]
1041
+                    )
1042
+            );
1043
+            exit();
1044
+        }
1045
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1046
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1047
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1048
+            exit();
1049
+        }
1050
+    }
1051
+
1052
+    /**
1053
+     * Check if the user is a admin, redirects to home if not
1054
+     *
1055
+     * @return void
1056
+     */
1057
+    public static function checkAdminUser() {
1058
+        OC_Util::checkLoggedIn();
1059
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1060
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1061
+            exit();
1062
+        }
1063
+    }
1064
+
1065
+    /**
1066
+     * Check if the user is a subadmin, redirects to home if not
1067
+     *
1068
+     * @return null|boolean $groups where the current user is subadmin
1069
+     */
1070
+    public static function checkSubAdminUser() {
1071
+        OC_Util::checkLoggedIn();
1072
+        $userObject = \OC::$server->getUserSession()->getUser();
1073
+        $isSubAdmin = false;
1074
+        if($userObject !== null) {
1075
+            $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1076
+        }
1077
+
1078
+        if (!$isSubAdmin) {
1079
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1080
+            exit();
1081
+        }
1082
+        return true;
1083
+    }
1084
+
1085
+    /**
1086
+     * Returns the URL of the default page
1087
+     * based on the system configuration and
1088
+     * the apps visible for the current user
1089
+     *
1090
+     * @return string URL
1091
+     * @suppress PhanDeprecatedFunction
1092
+     */
1093
+    public static function getDefaultPageUrl() {
1094
+        $urlGenerator = \OC::$server->getURLGenerator();
1095
+        // Deny the redirect if the URL contains a @
1096
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1097
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1098
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1099
+        } else {
1100
+            $defaultPage = \OC::$server->getAppConfig()->getValue('core', 'defaultpage');
1101
+            if ($defaultPage) {
1102
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1103
+            } else {
1104
+                $appId = 'files';
1105
+                $config = \OC::$server->getConfig();
1106
+                $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1107
+                // find the first app that is enabled for the current user
1108
+                foreach ($defaultApps as $defaultApp) {
1109
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1110
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1111
+                        $appId = $defaultApp;
1112
+                        break;
1113
+                    }
1114
+                }
1115
+
1116
+                if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1117
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1118
+                } else {
1119
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1120
+                }
1121
+            }
1122
+        }
1123
+        return $location;
1124
+    }
1125
+
1126
+    /**
1127
+     * Redirect to the user default page
1128
+     *
1129
+     * @return void
1130
+     */
1131
+    public static function redirectToDefaultPage() {
1132
+        $location = self::getDefaultPageUrl();
1133
+        header('Location: ' . $location);
1134
+        exit();
1135
+    }
1136
+
1137
+    /**
1138
+     * get an id unique for this instance
1139
+     *
1140
+     * @return string
1141
+     */
1142
+    public static function getInstanceId() {
1143
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1144
+        if (is_null($id)) {
1145
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1146
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1147
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1148
+        }
1149
+        return $id;
1150
+    }
1151
+
1152
+    /**
1153
+     * Public function to sanitize HTML
1154
+     *
1155
+     * This function is used to sanitize HTML and should be applied on any
1156
+     * string or array of strings before displaying it on a web page.
1157
+     *
1158
+     * @param string|array $value
1159
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1160
+     */
1161
+    public static function sanitizeHTML($value) {
1162
+        if (is_array($value)) {
1163
+            $value = array_map(function($value) {
1164
+                return self::sanitizeHTML($value);
1165
+            }, $value);
1166
+        } else {
1167
+            // Specify encoding for PHP<5.4
1168
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1169
+        }
1170
+        return $value;
1171
+    }
1172
+
1173
+    /**
1174
+     * Public function to encode url parameters
1175
+     *
1176
+     * This function is used to encode path to file before output.
1177
+     * Encoding is done according to RFC 3986 with one exception:
1178
+     * Character '/' is preserved as is.
1179
+     *
1180
+     * @param string $component part of URI to encode
1181
+     * @return string
1182
+     */
1183
+    public static function encodePath($component) {
1184
+        $encoded = rawurlencode($component);
1185
+        $encoded = str_replace('%2F', '/', $encoded);
1186
+        return $encoded;
1187
+    }
1188
+
1189
+
1190
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1191
+        // php dev server does not support htaccess
1192
+        if (php_sapi_name() === 'cli-server') {
1193
+            return false;
1194
+        }
1195
+
1196
+        // testdata
1197
+        $fileName = '/htaccesstest.txt';
1198
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1199
+
1200
+        // creating a test file
1201
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1202
+
1203
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1204
+            return false;
1205
+        }
1206
+
1207
+        $fp = @fopen($testFile, 'w');
1208
+        if (!$fp) {
1209
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1210
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1211
+        }
1212
+        fwrite($fp, $testContent);
1213
+        fclose($fp);
1214
+
1215
+        return $testContent;
1216
+    }
1217
+
1218
+    /**
1219
+     * Check if the .htaccess file is working
1220
+     * @param \OCP\IConfig $config
1221
+     * @return bool
1222
+     * @throws Exception
1223
+     * @throws \OC\HintException If the test file can't get written.
1224
+     */
1225
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1226
+
1227
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1228
+            return true;
1229
+        }
1230
+
1231
+        $testContent = $this->createHtaccessTestFile($config);
1232
+        if ($testContent === false) {
1233
+            return false;
1234
+        }
1235
+
1236
+        $fileName = '/htaccesstest.txt';
1237
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1238
+
1239
+        // accessing the file via http
1240
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1241
+        try {
1242
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1243
+        } catch (\Exception $e) {
1244
+            $content = false;
1245
+        }
1246
+
1247
+        // cleanup
1248
+        @unlink($testFile);
1249
+
1250
+        /*
1251 1251
 		 * If the content is not equal to test content our .htaccess
1252 1252
 		 * is working as required
1253 1253
 		 */
1254
-		return $content !== $testContent;
1255
-	}
1256
-
1257
-	/**
1258
-	 * Check if the setlocal call does not work. This can happen if the right
1259
-	 * local packages are not available on the server.
1260
-	 *
1261
-	 * @return bool
1262
-	 */
1263
-	public static function isSetLocaleWorking() {
1264
-		\Patchwork\Utf8\Bootup::initLocale();
1265
-		if ('' === basename('§')) {
1266
-			return false;
1267
-		}
1268
-		return true;
1269
-	}
1270
-
1271
-	/**
1272
-	 * Check if it's possible to get the inline annotations
1273
-	 *
1274
-	 * @return bool
1275
-	 */
1276
-	public static function isAnnotationsWorking() {
1277
-		$reflection = new \ReflectionMethod(__METHOD__);
1278
-		$docs = $reflection->getDocComment();
1279
-
1280
-		return (is_string($docs) && strlen($docs) > 50);
1281
-	}
1282
-
1283
-	/**
1284
-	 * Check if the PHP module fileinfo is loaded.
1285
-	 *
1286
-	 * @return bool
1287
-	 */
1288
-	public static function fileInfoLoaded() {
1289
-		return function_exists('finfo_open');
1290
-	}
1291
-
1292
-	/**
1293
-	 * clear all levels of output buffering
1294
-	 *
1295
-	 * @return void
1296
-	 */
1297
-	public static function obEnd() {
1298
-		while (ob_get_level()) {
1299
-			ob_end_clean();
1300
-		}
1301
-	}
1302
-
1303
-	/**
1304
-	 * Checks whether the server is running on Mac OS X
1305
-	 *
1306
-	 * @return bool true if running on Mac OS X, false otherwise
1307
-	 */
1308
-	public static function runningOnMac() {
1309
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1310
-	}
1311
-
1312
-	/**
1313
-	 * Checks whether server is running on HHVM
1314
-	 *
1315
-	 * @return bool True if running on HHVM, false otherwise
1316
-	 */
1317
-	public static function runningOnHhvm() {
1318
-		return defined('HHVM_VERSION');
1319
-	}
1320
-
1321
-	/**
1322
-	 * Handles the case that there may not be a theme, then check if a "default"
1323
-	 * theme exists and take that one
1324
-	 *
1325
-	 * @return string the theme
1326
-	 */
1327
-	public static function getTheme() {
1328
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1329
-
1330
-		if ($theme === '') {
1331
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1332
-				$theme = 'default';
1333
-			}
1334
-		}
1335
-
1336
-		return $theme;
1337
-	}
1338
-
1339
-	/**
1340
-	 * Clear a single file from the opcode cache
1341
-	 * This is useful for writing to the config file
1342
-	 * in case the opcode cache does not re-validate files
1343
-	 * Returns true if successful, false if unsuccessful:
1344
-	 * caller should fall back on clearing the entire cache
1345
-	 * with clearOpcodeCache() if unsuccessful
1346
-	 *
1347
-	 * @param string $path the path of the file to clear from the cache
1348
-	 * @return bool true if underlying function returns true, otherwise false
1349
-	 */
1350
-	public static function deleteFromOpcodeCache($path) {
1351
-		$ret = false;
1352
-		if ($path) {
1353
-			// APC >= 3.1.1
1354
-			if (function_exists('apc_delete_file')) {
1355
-				$ret = @apc_delete_file($path);
1356
-			}
1357
-			// Zend OpCache >= 7.0.0, PHP >= 5.5.0
1358
-			if (function_exists('opcache_invalidate')) {
1359
-				$ret = opcache_invalidate($path);
1360
-			}
1361
-		}
1362
-		return $ret;
1363
-	}
1364
-
1365
-	/**
1366
-	 * Clear the opcode cache if one exists
1367
-	 * This is necessary for writing to the config file
1368
-	 * in case the opcode cache does not re-validate files
1369
-	 *
1370
-	 * @return void
1371
-	 * @suppress PhanDeprecatedFunction
1372
-	 * @suppress PhanUndeclaredConstant
1373
-	 */
1374
-	public static function clearOpcodeCache() {
1375
-		// APC
1376
-		if (function_exists('apc_clear_cache')) {
1377
-			apc_clear_cache();
1378
-		}
1379
-		// Zend Opcache
1380
-		if (function_exists('accelerator_reset')) {
1381
-			accelerator_reset();
1382
-		}
1383
-		// XCache
1384
-		if (function_exists('xcache_clear_cache')) {
1385
-			if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1386
-				\OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', \OCP\Util::WARN);
1387
-			} else {
1388
-				@xcache_clear_cache(XC_TYPE_PHP, 0);
1389
-			}
1390
-		}
1391
-		// Opcache (PHP >= 5.5)
1392
-		if (function_exists('opcache_reset')) {
1393
-			opcache_reset();
1394
-		}
1395
-	}
1396
-
1397
-	/**
1398
-	 * Normalize a unicode string
1399
-	 *
1400
-	 * @param string $value a not normalized string
1401
-	 * @return bool|string
1402
-	 */
1403
-	public static function normalizeUnicode($value) {
1404
-		if(Normalizer::isNormalized($value)) {
1405
-			return $value;
1406
-		}
1407
-
1408
-		$normalizedValue = Normalizer::normalize($value);
1409
-		if ($normalizedValue === null || $normalizedValue === false) {
1410
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1411
-			return $value;
1412
-		}
1413
-
1414
-		return $normalizedValue;
1415
-	}
1416
-
1417
-	/**
1418
-	 * A human readable string is generated based on version and build number
1419
-	 *
1420
-	 * @return string
1421
-	 */
1422
-	public static function getHumanVersion() {
1423
-		$version = OC_Util::getVersionString();
1424
-		$build = OC_Util::getBuild();
1425
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1426
-			$version .= ' Build:' . $build;
1427
-		}
1428
-		return $version;
1429
-	}
1430
-
1431
-	/**
1432
-	 * Returns whether the given file name is valid
1433
-	 *
1434
-	 * @param string $file file name to check
1435
-	 * @return bool true if the file name is valid, false otherwise
1436
-	 * @deprecated use \OC\Files\View::verifyPath()
1437
-	 */
1438
-	public static function isValidFileName($file) {
1439
-		$trimmed = trim($file);
1440
-		if ($trimmed === '') {
1441
-			return false;
1442
-		}
1443
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1444
-			return false;
1445
-		}
1446
-
1447
-		// detect part files
1448
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1449
-			return false;
1450
-		}
1451
-
1452
-		foreach (str_split($trimmed) as $char) {
1453
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1454
-				return false;
1455
-			}
1456
-		}
1457
-		return true;
1458
-	}
1459
-
1460
-	/**
1461
-	 * Check whether the instance needs to perform an upgrade,
1462
-	 * either when the core version is higher or any app requires
1463
-	 * an upgrade.
1464
-	 *
1465
-	 * @param \OC\SystemConfig $config
1466
-	 * @return bool whether the core or any app needs an upgrade
1467
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1468
-	 */
1469
-	public static function needUpgrade(\OC\SystemConfig $config) {
1470
-		if ($config->getValue('installed', false)) {
1471
-			$installedVersion = $config->getValue('version', '0.0.0');
1472
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1473
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1474
-			if ($versionDiff > 0) {
1475
-				return true;
1476
-			} else if ($config->getValue('debug', false) && $versionDiff < 0) {
1477
-				// downgrade with debug
1478
-				$installedMajor = explode('.', $installedVersion);
1479
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1480
-				$currentMajor = explode('.', $currentVersion);
1481
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1482
-				if ($installedMajor === $currentMajor) {
1483
-					// Same major, allow downgrade for developers
1484
-					return true;
1485
-				} else {
1486
-					// downgrade attempt, throw exception
1487
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1488
-				}
1489
-			} else if ($versionDiff < 0) {
1490
-				// downgrade attempt, throw exception
1491
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1492
-			}
1493
-
1494
-			// also check for upgrades for apps (independently from the user)
1495
-			$apps = \OC_App::getEnabledApps(false, true);
1496
-			$shouldUpgrade = false;
1497
-			foreach ($apps as $app) {
1498
-				if (\OC_App::shouldUpgrade($app)) {
1499
-					$shouldUpgrade = true;
1500
-					break;
1501
-				}
1502
-			}
1503
-			return $shouldUpgrade;
1504
-		} else {
1505
-			return false;
1506
-		}
1507
-	}
1254
+        return $content !== $testContent;
1255
+    }
1256
+
1257
+    /**
1258
+     * Check if the setlocal call does not work. This can happen if the right
1259
+     * local packages are not available on the server.
1260
+     *
1261
+     * @return bool
1262
+     */
1263
+    public static function isSetLocaleWorking() {
1264
+        \Patchwork\Utf8\Bootup::initLocale();
1265
+        if ('' === basename('§')) {
1266
+            return false;
1267
+        }
1268
+        return true;
1269
+    }
1270
+
1271
+    /**
1272
+     * Check if it's possible to get the inline annotations
1273
+     *
1274
+     * @return bool
1275
+     */
1276
+    public static function isAnnotationsWorking() {
1277
+        $reflection = new \ReflectionMethod(__METHOD__);
1278
+        $docs = $reflection->getDocComment();
1279
+
1280
+        return (is_string($docs) && strlen($docs) > 50);
1281
+    }
1282
+
1283
+    /**
1284
+     * Check if the PHP module fileinfo is loaded.
1285
+     *
1286
+     * @return bool
1287
+     */
1288
+    public static function fileInfoLoaded() {
1289
+        return function_exists('finfo_open');
1290
+    }
1291
+
1292
+    /**
1293
+     * clear all levels of output buffering
1294
+     *
1295
+     * @return void
1296
+     */
1297
+    public static function obEnd() {
1298
+        while (ob_get_level()) {
1299
+            ob_end_clean();
1300
+        }
1301
+    }
1302
+
1303
+    /**
1304
+     * Checks whether the server is running on Mac OS X
1305
+     *
1306
+     * @return bool true if running on Mac OS X, false otherwise
1307
+     */
1308
+    public static function runningOnMac() {
1309
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1310
+    }
1311
+
1312
+    /**
1313
+     * Checks whether server is running on HHVM
1314
+     *
1315
+     * @return bool True if running on HHVM, false otherwise
1316
+     */
1317
+    public static function runningOnHhvm() {
1318
+        return defined('HHVM_VERSION');
1319
+    }
1320
+
1321
+    /**
1322
+     * Handles the case that there may not be a theme, then check if a "default"
1323
+     * theme exists and take that one
1324
+     *
1325
+     * @return string the theme
1326
+     */
1327
+    public static function getTheme() {
1328
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1329
+
1330
+        if ($theme === '') {
1331
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1332
+                $theme = 'default';
1333
+            }
1334
+        }
1335
+
1336
+        return $theme;
1337
+    }
1338
+
1339
+    /**
1340
+     * Clear a single file from the opcode cache
1341
+     * This is useful for writing to the config file
1342
+     * in case the opcode cache does not re-validate files
1343
+     * Returns true if successful, false if unsuccessful:
1344
+     * caller should fall back on clearing the entire cache
1345
+     * with clearOpcodeCache() if unsuccessful
1346
+     *
1347
+     * @param string $path the path of the file to clear from the cache
1348
+     * @return bool true if underlying function returns true, otherwise false
1349
+     */
1350
+    public static function deleteFromOpcodeCache($path) {
1351
+        $ret = false;
1352
+        if ($path) {
1353
+            // APC >= 3.1.1
1354
+            if (function_exists('apc_delete_file')) {
1355
+                $ret = @apc_delete_file($path);
1356
+            }
1357
+            // Zend OpCache >= 7.0.0, PHP >= 5.5.0
1358
+            if (function_exists('opcache_invalidate')) {
1359
+                $ret = opcache_invalidate($path);
1360
+            }
1361
+        }
1362
+        return $ret;
1363
+    }
1364
+
1365
+    /**
1366
+     * Clear the opcode cache if one exists
1367
+     * This is necessary for writing to the config file
1368
+     * in case the opcode cache does not re-validate files
1369
+     *
1370
+     * @return void
1371
+     * @suppress PhanDeprecatedFunction
1372
+     * @suppress PhanUndeclaredConstant
1373
+     */
1374
+    public static function clearOpcodeCache() {
1375
+        // APC
1376
+        if (function_exists('apc_clear_cache')) {
1377
+            apc_clear_cache();
1378
+        }
1379
+        // Zend Opcache
1380
+        if (function_exists('accelerator_reset')) {
1381
+            accelerator_reset();
1382
+        }
1383
+        // XCache
1384
+        if (function_exists('xcache_clear_cache')) {
1385
+            if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1386
+                \OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', \OCP\Util::WARN);
1387
+            } else {
1388
+                @xcache_clear_cache(XC_TYPE_PHP, 0);
1389
+            }
1390
+        }
1391
+        // Opcache (PHP >= 5.5)
1392
+        if (function_exists('opcache_reset')) {
1393
+            opcache_reset();
1394
+        }
1395
+    }
1396
+
1397
+    /**
1398
+     * Normalize a unicode string
1399
+     *
1400
+     * @param string $value a not normalized string
1401
+     * @return bool|string
1402
+     */
1403
+    public static function normalizeUnicode($value) {
1404
+        if(Normalizer::isNormalized($value)) {
1405
+            return $value;
1406
+        }
1407
+
1408
+        $normalizedValue = Normalizer::normalize($value);
1409
+        if ($normalizedValue === null || $normalizedValue === false) {
1410
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1411
+            return $value;
1412
+        }
1413
+
1414
+        return $normalizedValue;
1415
+    }
1416
+
1417
+    /**
1418
+     * A human readable string is generated based on version and build number
1419
+     *
1420
+     * @return string
1421
+     */
1422
+    public static function getHumanVersion() {
1423
+        $version = OC_Util::getVersionString();
1424
+        $build = OC_Util::getBuild();
1425
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1426
+            $version .= ' Build:' . $build;
1427
+        }
1428
+        return $version;
1429
+    }
1430
+
1431
+    /**
1432
+     * Returns whether the given file name is valid
1433
+     *
1434
+     * @param string $file file name to check
1435
+     * @return bool true if the file name is valid, false otherwise
1436
+     * @deprecated use \OC\Files\View::verifyPath()
1437
+     */
1438
+    public static function isValidFileName($file) {
1439
+        $trimmed = trim($file);
1440
+        if ($trimmed === '') {
1441
+            return false;
1442
+        }
1443
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1444
+            return false;
1445
+        }
1446
+
1447
+        // detect part files
1448
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1449
+            return false;
1450
+        }
1451
+
1452
+        foreach (str_split($trimmed) as $char) {
1453
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1454
+                return false;
1455
+            }
1456
+        }
1457
+        return true;
1458
+    }
1459
+
1460
+    /**
1461
+     * Check whether the instance needs to perform an upgrade,
1462
+     * either when the core version is higher or any app requires
1463
+     * an upgrade.
1464
+     *
1465
+     * @param \OC\SystemConfig $config
1466
+     * @return bool whether the core or any app needs an upgrade
1467
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1468
+     */
1469
+    public static function needUpgrade(\OC\SystemConfig $config) {
1470
+        if ($config->getValue('installed', false)) {
1471
+            $installedVersion = $config->getValue('version', '0.0.0');
1472
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1473
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1474
+            if ($versionDiff > 0) {
1475
+                return true;
1476
+            } else if ($config->getValue('debug', false) && $versionDiff < 0) {
1477
+                // downgrade with debug
1478
+                $installedMajor = explode('.', $installedVersion);
1479
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1480
+                $currentMajor = explode('.', $currentVersion);
1481
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1482
+                if ($installedMajor === $currentMajor) {
1483
+                    // Same major, allow downgrade for developers
1484
+                    return true;
1485
+                } else {
1486
+                    // downgrade attempt, throw exception
1487
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1488
+                }
1489
+            } else if ($versionDiff < 0) {
1490
+                // downgrade attempt, throw exception
1491
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1492
+            }
1493
+
1494
+            // also check for upgrades for apps (independently from the user)
1495
+            $apps = \OC_App::getEnabledApps(false, true);
1496
+            $shouldUpgrade = false;
1497
+            foreach ($apps as $app) {
1498
+                if (\OC_App::shouldUpgrade($app)) {
1499
+                    $shouldUpgrade = true;
1500
+                    break;
1501
+                }
1502
+            }
1503
+            return $shouldUpgrade;
1504
+        } else {
1505
+            return false;
1506
+        }
1507
+    }
1508 1508
 
1509 1509
 }
Please login to merge, or discard this patch.