Completed
Pull Request — master (#4304)
by Lukas
12:54 queued 01:14
created
apps/dav/lib/Connector/Sabre/ShareTypeList.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -61,7 +61,7 @@
 block discarded – undo
61 61
 	 * The deserialize method is called during xml parsing.
62 62
 	 *
63 63
 	 * @param Reader $reader
64
-	 * @return mixed
64
+	 * @return null|ShareTypeList
65 65
 	 */
66 66
 	static function xmlDeserialize(Reader $reader) {
67 67
 		$shareTypes = [];
Please login to merge, or discard this patch.
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -32,61 +32,61 @@
 block discarded – undo
32 32
  * This property contains multiple "share-type" elements, each containing a share type.
33 33
  */
34 34
 class ShareTypeList implements Element {
35
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
35
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
36 36
 
37
-	/**
38
-	 * Share types
39
-	 *
40
-	 * @var int[]
41
-	 */
42
-	private $shareTypes;
37
+    /**
38
+     * Share types
39
+     *
40
+     * @var int[]
41
+     */
42
+    private $shareTypes;
43 43
 
44
-	/**
45
-	 * @param int[] $shareTypes
46
-	 */
47
-	public function __construct($shareTypes) {
48
-		$this->shareTypes = $shareTypes;
49
-	}
44
+    /**
45
+     * @param int[] $shareTypes
46
+     */
47
+    public function __construct($shareTypes) {
48
+        $this->shareTypes = $shareTypes;
49
+    }
50 50
 
51
-	/**
52
-	 * Returns the share types
53
-	 *
54
-	 * @return int[]
55
-	 */
56
-	public function getShareTypes() {
57
-		return $this->shareTypes;
58
-	}
51
+    /**
52
+     * Returns the share types
53
+     *
54
+     * @return int[]
55
+     */
56
+    public function getShareTypes() {
57
+        return $this->shareTypes;
58
+    }
59 59
 
60
-	/**
61
-	 * The deserialize method is called during xml parsing.
62
-	 *
63
-	 * @param Reader $reader
64
-	 * @return mixed
65
-	 */
66
-	static function xmlDeserialize(Reader $reader) {
67
-		$shareTypes = [];
60
+    /**
61
+     * The deserialize method is called during xml parsing.
62
+     *
63
+     * @param Reader $reader
64
+     * @return mixed
65
+     */
66
+    static function xmlDeserialize(Reader $reader) {
67
+        $shareTypes = [];
68 68
 
69
-		$tree = $reader->parseInnerTree();
70
-		if ($tree === null) {
71
-			return null;
72
-		}
73
-		foreach ($tree as $elem) {
74
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
-				$shareTypes[] = (int)$elem['value'];
76
-			}
77
-		}
78
-		return new self($shareTypes);
79
-	}
69
+        $tree = $reader->parseInnerTree();
70
+        if ($tree === null) {
71
+            return null;
72
+        }
73
+        foreach ($tree as $elem) {
74
+            if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
+                $shareTypes[] = (int)$elem['value'];
76
+            }
77
+        }
78
+        return new self($shareTypes);
79
+    }
80 80
 
81
-	/**
82
-	 * The xmlSerialize metod is called during xml writing.
83
-	 *
84
-	 * @param Writer $writer
85
-	 * @return void
86
-	 */
87
-	function xmlSerialize(Writer $writer) {
88
-		foreach ($this->shareTypes as $shareType) {
89
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
90
-		}
91
-	}
81
+    /**
82
+     * The xmlSerialize metod is called during xml writing.
83
+     *
84
+     * @param Writer $writer
85
+     * @return void
86
+     */
87
+    function xmlSerialize(Writer $writer) {
88
+        foreach ($this->shareTypes as $shareType) {
89
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
90
+        }
91
+    }
92 92
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -71,8 +71,8 @@  discard block
 block discarded – undo
71 71
 			return null;
72 72
 		}
73 73
 		foreach ($tree as $elem) {
74
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
-				$shareTypes[] = (int)$elem['value'];
74
+			if ($elem['name'] === '{'.self::NS_OWNCLOUD.'}share-type') {
75
+				$shareTypes[] = (int) $elem['value'];
76 76
 			}
77 77
 		}
78 78
 		return new self($shareTypes);
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 	 */
87 87
 	function xmlSerialize(Writer $writer) {
88 88
 		foreach ($this->shareTypes as $shareType) {
89
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
89
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}share-type', $shareType);
90 90
 		}
91 91
 	}
92 92
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/TagList.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@
 block discarded – undo
80 80
 	 * the next element.
81 81
 	 *
82 82
 	 * @param Reader $reader
83
-	 * @return mixed
83
+	 * @return null|TagList
84 84
 	 */
85 85
 	static function xmlDeserialize(Reader $reader) {
86 86
 		$tags = [];
Please login to merge, or discard this patch.
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -34,92 +34,92 @@
 block discarded – undo
34 34
  * This property contains multiple "tag" elements, each containing a tag name.
35 35
  */
36 36
 class TagList implements Element {
37
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
37
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
38 38
 
39
-	/**
40
-	 * tags
41
-	 *
42
-	 * @var array
43
-	 */
44
-	private $tags;
39
+    /**
40
+     * tags
41
+     *
42
+     * @var array
43
+     */
44
+    private $tags;
45 45
 
46
-	/**
47
-	 * @param array $tags
48
-	 */
49
-	public function __construct(array $tags) {
50
-		$this->tags = $tags;
51
-	}
46
+    /**
47
+     * @param array $tags
48
+     */
49
+    public function __construct(array $tags) {
50
+        $this->tags = $tags;
51
+    }
52 52
 
53
-	/**
54
-	 * Returns the tags
55
-	 *
56
-	 * @return array
57
-	 */
58
-	public function getTags() {
53
+    /**
54
+     * Returns the tags
55
+     *
56
+     * @return array
57
+     */
58
+    public function getTags() {
59 59
 
60
-		return $this->tags;
60
+        return $this->tags;
61 61
 
62
-	}
62
+    }
63 63
 
64
-	/**
65
-	 * The deserialize method is called during xml parsing.
66
-	 *
67
-	 * This method is called statictly, this is because in theory this method
68
-	 * may be used as a type of constructor, or factory method.
69
-	 *
70
-	 * Often you want to return an instance of the current class, but you are
71
-	 * free to return other data as well.
72
-	 *
73
-	 * You are responsible for advancing the reader to the next element. Not
74
-	 * doing anything will result in a never-ending loop.
75
-	 *
76
-	 * If you just want to skip parsing for this element altogether, you can
77
-	 * just call $reader->next();
78
-	 *
79
-	 * $reader->parseInnerTree() will parse the entire sub-tree, and advance to
80
-	 * the next element.
81
-	 *
82
-	 * @param Reader $reader
83
-	 * @return mixed
84
-	 */
85
-	static function xmlDeserialize(Reader $reader) {
86
-		$tags = [];
64
+    /**
65
+     * The deserialize method is called during xml parsing.
66
+     *
67
+     * This method is called statictly, this is because in theory this method
68
+     * may be used as a type of constructor, or factory method.
69
+     *
70
+     * Often you want to return an instance of the current class, but you are
71
+     * free to return other data as well.
72
+     *
73
+     * You are responsible for advancing the reader to the next element. Not
74
+     * doing anything will result in a never-ending loop.
75
+     *
76
+     * If you just want to skip parsing for this element altogether, you can
77
+     * just call $reader->next();
78
+     *
79
+     * $reader->parseInnerTree() will parse the entire sub-tree, and advance to
80
+     * the next element.
81
+     *
82
+     * @param Reader $reader
83
+     * @return mixed
84
+     */
85
+    static function xmlDeserialize(Reader $reader) {
86
+        $tags = [];
87 87
 
88
-		$tree = $reader->parseInnerTree();
89
-		if ($tree === null) {
90
-			return null;
91
-		}
92
-		foreach ($tree as $elem) {
93
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
94
-				$tags[] = $elem['value'];
95
-			}
96
-		}
97
-		return new self($tags);
98
-	}
88
+        $tree = $reader->parseInnerTree();
89
+        if ($tree === null) {
90
+            return null;
91
+        }
92
+        foreach ($tree as $elem) {
93
+            if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
94
+                $tags[] = $elem['value'];
95
+            }
96
+        }
97
+        return new self($tags);
98
+    }
99 99
 
100
-	/**
101
-	 * The xmlSerialize metod is called during xml writing.
102
-	 *
103
-	 * Use the $writer argument to write its own xml serialization.
104
-	 *
105
-	 * An important note: do _not_ create a parent element. Any element
106
-	 * implementing XmlSerializble should only ever write what's considered
107
-	 * its 'inner xml'.
108
-	 *
109
-	 * The parent of the current element is responsible for writing a
110
-	 * containing element.
111
-	 *
112
-	 * This allows serializers to be re-used for different element names.
113
-	 *
114
-	 * If you are opening new elements, you must also close them again.
115
-	 *
116
-	 * @param Writer $writer
117
-	 * @return void
118
-	 */
119
-	function xmlSerialize(Writer $writer) {
100
+    /**
101
+     * The xmlSerialize metod is called during xml writing.
102
+     *
103
+     * Use the $writer argument to write its own xml serialization.
104
+     *
105
+     * An important note: do _not_ create a parent element. Any element
106
+     * implementing XmlSerializble should only ever write what's considered
107
+     * its 'inner xml'.
108
+     *
109
+     * The parent of the current element is responsible for writing a
110
+     * containing element.
111
+     *
112
+     * This allows serializers to be re-used for different element names.
113
+     *
114
+     * If you are opening new elements, you must also close them again.
115
+     *
116
+     * @param Writer $writer
117
+     * @return void
118
+     */
119
+    function xmlSerialize(Writer $writer) {
120 120
 
121
-		foreach ($this->tags as $tag) {
122
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
123
-		}
124
-	}
121
+        foreach ($this->tags as $tag) {
122
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
123
+        }
124
+    }
125 125
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 			return null;
91 91
 		}
92 92
 		foreach ($tree as $elem) {
93
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
93
+			if ($elem['name'] === '{'.self::NS_OWNCLOUD.'}tag') {
94 94
 				$tags[] = $elem['value'];
95 95
 			}
96 96
 		}
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
 	function xmlSerialize(Writer $writer) {
120 120
 
121 121
 		foreach ($this->tags as $tag) {
122
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
122
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}tag', $tag);
123 123
 		}
124 124
 	}
125 125
 }
Please login to merge, or discard this patch.
lib/private/legacy/app.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -51,7 +51,6 @@
 block discarded – undo
51 51
 use OC\App\InfoParser;
52 52
 use OC\App\Platform;
53 53
 use OC\Installer;
54
-use OC\OCSClient;
55 54
 use OC\Repair;
56 55
 use OCP\App\ManagerEvent;
57 56
 
Please login to merge, or discard this patch.
Doc Comments   +6 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1063,7 +1063,7 @@  discard block
 block discarded – undo
1063 1063
 	 * @param string $app
1064 1064
 	 * @param \OCP\IConfig $config
1065 1065
 	 * @param \OCP\IL10N $l
1066
-	 * @return bool
1066
+	 * @return string
1067 1067
 	 *
1068 1068
 	 * @throws Exception if app is not compatible with this version of ownCloud
1069 1069
 	 * @throws Exception if no app-name was specified
@@ -1243,6 +1243,11 @@  discard block
 block discarded – undo
1243 1243
 		}
1244 1244
 	}
1245 1245
 
1246
+	/**
1247
+	 * @param string $lang
1248
+	 *
1249
+	 * @return string
1250
+	 */
1246 1251
 	protected static function findBestL10NOption($options, $lang) {
1247 1252
 		$fallback = $similarLangFallback = $englishFallback = false;
1248 1253
 
Please login to merge, or discard this patch.
Indentation   +1276 added lines, -1276 removed lines patch added patch discarded remove patch
@@ -61,1280 +61,1280 @@
 block discarded – undo
61 61
  * upgrading and removing apps.
62 62
  */
63 63
 class OC_App {
64
-	static private $appVersion = [];
65
-	static private $adminForms = array();
66
-	static private $personalForms = array();
67
-	static private $appInfo = array();
68
-	static private $appTypes = array();
69
-	static private $loadedApps = array();
70
-	static private $altLogin = array();
71
-	static private $alreadyRegistered = [];
72
-	const officialApp = 200;
73
-
74
-	/**
75
-	 * clean the appId
76
-	 *
77
-	 * @param string|boolean $app AppId that needs to be cleaned
78
-	 * @return string
79
-	 */
80
-	public static function cleanAppId($app) {
81
-		return str_replace(array('\0', '/', '\\', '..'), '', $app);
82
-	}
83
-
84
-	/**
85
-	 * Check if an app is loaded
86
-	 *
87
-	 * @param string $app
88
-	 * @return bool
89
-	 */
90
-	public static function isAppLoaded($app) {
91
-		return in_array($app, self::$loadedApps, true);
92
-	}
93
-
94
-	/**
95
-	 * loads all apps
96
-	 *
97
-	 * @param string[] | string | null $types
98
-	 * @return bool
99
-	 *
100
-	 * This function walks through the ownCloud directory and loads all apps
101
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
102
-	 * exists.
103
-	 *
104
-	 * if $types is set, only apps of those types will be loaded
105
-	 */
106
-	public static function loadApps($types = null) {
107
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
108
-			return false;
109
-		}
110
-		// Load the enabled apps here
111
-		$apps = self::getEnabledApps();
112
-
113
-		// Add each apps' folder as allowed class path
114
-		foreach($apps as $app) {
115
-			$path = self::getAppPath($app);
116
-			if($path !== false) {
117
-				self::registerAutoloading($app, $path);
118
-			}
119
-		}
120
-
121
-		// prevent app.php from printing output
122
-		ob_start();
123
-		foreach ($apps as $app) {
124
-			if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
125
-				self::loadApp($app);
126
-			}
127
-		}
128
-		ob_end_clean();
129
-
130
-		return true;
131
-	}
132
-
133
-	/**
134
-	 * load a single app
135
-	 *
136
-	 * @param string $app
137
-	 */
138
-	public static function loadApp($app) {
139
-		self::$loadedApps[] = $app;
140
-		$appPath = self::getAppPath($app);
141
-		if($appPath === false) {
142
-			return;
143
-		}
144
-
145
-		// in case someone calls loadApp() directly
146
-		self::registerAutoloading($app, $appPath);
147
-
148
-		if (is_file($appPath . '/appinfo/app.php')) {
149
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
-			self::requireAppFile($app);
151
-			if (self::isType($app, array('authentication'))) {
152
-				// since authentication apps affect the "is app enabled for group" check,
153
-				// the enabled apps cache needs to be cleared to make sure that the
154
-				// next time getEnableApps() is called it will also include apps that were
155
-				// enabled for groups
156
-				self::$enabledAppsCache = array();
157
-			}
158
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
159
-		}
160
-
161
-		$info = self::getAppInfo($app);
162
-		if (!empty($info['activity']['filters'])) {
163
-			foreach ($info['activity']['filters'] as $filter) {
164
-				\OC::$server->getActivityManager()->registerFilter($filter);
165
-			}
166
-		}
167
-		if (!empty($info['activity']['settings'])) {
168
-			foreach ($info['activity']['settings'] as $setting) {
169
-				\OC::$server->getActivityManager()->registerSetting($setting);
170
-			}
171
-		}
172
-		if (!empty($info['activity']['providers'])) {
173
-			foreach ($info['activity']['providers'] as $provider) {
174
-				\OC::$server->getActivityManager()->registerProvider($provider);
175
-			}
176
-		}
177
-	}
178
-
179
-	/**
180
-	 * @internal
181
-	 * @param string $app
182
-	 * @param string $path
183
-	 */
184
-	public static function registerAutoloading($app, $path) {
185
-		$key = $app . '-' . $path;
186
-		if(isset(self::$alreadyRegistered[$key])) {
187
-			return;
188
-		}
189
-		self::$alreadyRegistered[$key] = true;
190
-		// Register on PSR-4 composer autoloader
191
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
192
-		\OC::$server->registerNamespace($app, $appNamespace);
193
-		\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
194
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
195
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
196
-		}
197
-
198
-		// Register on legacy autoloader
199
-		\OC::$loader->addValidRoot($path);
200
-	}
201
-
202
-	/**
203
-	 * Load app.php from the given app
204
-	 *
205
-	 * @param string $app app name
206
-	 */
207
-	private static function requireAppFile($app) {
208
-		try {
209
-			// encapsulated here to avoid variable scope conflicts
210
-			require_once $app . '/appinfo/app.php';
211
-		} catch (Error $ex) {
212
-			\OC::$server->getLogger()->logException($ex);
213
-			$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
214
-			if (!in_array($app, $blacklist)) {
215
-				self::disable($app);
216
-			}
217
-		}
218
-	}
219
-
220
-	/**
221
-	 * check if an app is of a specific type
222
-	 *
223
-	 * @param string $app
224
-	 * @param string|array $types
225
-	 * @return bool
226
-	 */
227
-	public static function isType($app, $types) {
228
-		if (is_string($types)) {
229
-			$types = array($types);
230
-		}
231
-		$appTypes = self::getAppTypes($app);
232
-		foreach ($types as $type) {
233
-			if (array_search($type, $appTypes) !== false) {
234
-				return true;
235
-			}
236
-		}
237
-		return false;
238
-	}
239
-
240
-	/**
241
-	 * get the types of an app
242
-	 *
243
-	 * @param string $app
244
-	 * @return array
245
-	 */
246
-	private static function getAppTypes($app) {
247
-		//load the cache
248
-		if (count(self::$appTypes) == 0) {
249
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
250
-		}
251
-
252
-		if (isset(self::$appTypes[$app])) {
253
-			return explode(',', self::$appTypes[$app]);
254
-		} else {
255
-			return array();
256
-		}
257
-	}
258
-
259
-	/**
260
-	 * read app types from info.xml and cache them in the database
261
-	 */
262
-	public static function setAppTypes($app) {
263
-		$appData = self::getAppInfo($app);
264
-		if(!is_array($appData)) {
265
-			return;
266
-		}
267
-
268
-		if (isset($appData['types'])) {
269
-			$appTypes = implode(',', $appData['types']);
270
-		} else {
271
-			$appTypes = '';
272
-			$appData['types'] = [];
273
-		}
274
-
275
-		\OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
276
-
277
-		if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
278
-			$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
279
-			if ($enabled !== 'yes' && $enabled !== 'no') {
280
-				\OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
281
-			}
282
-		}
283
-	}
284
-
285
-	/**
286
-	 * check if app is shipped
287
-	 *
288
-	 * @param string $appId the id of the app to check
289
-	 * @return bool
290
-	 *
291
-	 * Check if an app that is installed is a shipped app or installed from the appstore.
292
-	 */
293
-	public static function isShipped($appId) {
294
-		return \OC::$server->getAppManager()->isShipped($appId);
295
-	}
296
-
297
-	/**
298
-	 * get all enabled apps
299
-	 */
300
-	protected static $enabledAppsCache = array();
301
-
302
-	/**
303
-	 * Returns apps enabled for the current user.
304
-	 *
305
-	 * @param bool $forceRefresh whether to refresh the cache
306
-	 * @param bool $all whether to return apps for all users, not only the
307
-	 * currently logged in one
308
-	 * @return string[]
309
-	 */
310
-	public static function getEnabledApps($forceRefresh = false, $all = false) {
311
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
312
-			return array();
313
-		}
314
-		// in incognito mode or when logged out, $user will be false,
315
-		// which is also the case during an upgrade
316
-		$appManager = \OC::$server->getAppManager();
317
-		if ($all) {
318
-			$user = null;
319
-		} else {
320
-			$user = \OC::$server->getUserSession()->getUser();
321
-		}
322
-
323
-		if (is_null($user)) {
324
-			$apps = $appManager->getInstalledApps();
325
-		} else {
326
-			$apps = $appManager->getEnabledAppsForUser($user);
327
-		}
328
-		$apps = array_filter($apps, function ($app) {
329
-			return $app !== 'files';//we add this manually
330
-		});
331
-		sort($apps);
332
-		array_unshift($apps, 'files');
333
-		return $apps;
334
-	}
335
-
336
-	/**
337
-	 * checks whether or not an app is enabled
338
-	 *
339
-	 * @param string $app app
340
-	 * @return bool
341
-	 *
342
-	 * This function checks whether or not an app is enabled.
343
-	 */
344
-	public static function isEnabled($app) {
345
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
346
-	}
347
-
348
-	/**
349
-	 * enables an app
350
-	 *
351
-	 * @param string $appId
352
-	 * @param array $groups (optional) when set, only these groups will have access to the app
353
-	 * @throws \Exception
354
-	 * @return void
355
-	 *
356
-	 * This function set an app as enabled in appconfig.
357
-	 */
358
-	public function enable($appId,
359
-						   $groups = null) {
360
-		self::$enabledAppsCache = []; // flush
361
-		$l = \OC::$server->getL10N('core');
362
-		$config = \OC::$server->getConfig();
363
-
364
-		// Check if app is already downloaded
365
-		$installer = new Installer(
366
-			\OC::$server->getAppFetcher(),
367
-			\OC::$server->getHTTPClientService(),
368
-			\OC::$server->getTempManager(),
369
-			\OC::$server->getLogger()
370
-		);
371
-		$isDownloaded = $installer->isDownloaded($appId);
372
-
373
-		if(!$isDownloaded) {
374
-			$installer->downloadApp($appId);
375
-		}
376
-
377
-		if (!Installer::isInstalled($appId)) {
378
-			$appId = self::installApp(
379
-				$appId,
380
-				$config,
381
-				$l
382
-			);
383
-			$appPath = self::getAppPath($appId);
384
-			self::registerAutoloading($appId, $appPath);
385
-			$installer->installApp($appId);
386
-		} else {
387
-			// check for required dependencies
388
-			$info = self::getAppInfo($appId);
389
-			self::checkAppDependencies($config, $l, $info);
390
-			$appPath = self::getAppPath($appId);
391
-			self::registerAutoloading($appId, $appPath);
392
-			$installer->installApp($appId);
393
-		}
394
-
395
-		$appManager = \OC::$server->getAppManager();
396
-		if (!is_null($groups)) {
397
-			$groupManager = \OC::$server->getGroupManager();
398
-			$groupsList = [];
399
-			foreach ($groups as $group) {
400
-				$groupItem = $groupManager->get($group);
401
-				if ($groupItem instanceof \OCP\IGroup) {
402
-					$groupsList[] = $groupManager->get($group);
403
-				}
404
-			}
405
-			$appManager->enableAppForGroups($appId, $groupsList);
406
-		} else {
407
-			$appManager->enableApp($appId);
408
-		}
409
-
410
-		$info = self::getAppInfo($appId);
411
-		if(isset($info['settings']) && is_array($info['settings'])) {
412
-			$appPath = self::getAppPath($appId);
413
-			self::registerAutoloading($appId, $appPath);
414
-			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
415
-		}
416
-	}
417
-
418
-	/**
419
-	 * @param string $app
420
-	 * @return bool
421
-	 */
422
-	public static function removeApp($app) {
423
-		if (self::isShipped($app)) {
424
-			return false;
425
-		}
426
-
427
-		$installer = new Installer(
428
-			\OC::$server->getAppFetcher(),
429
-			\OC::$server->getHTTPClientService(),
430
-			\OC::$server->getTempManager(),
431
-			\OC::$server->getLogger()
432
-		);
433
-		return $installer->removeApp($app);
434
-	}
435
-
436
-	/**
437
-	 * This function set an app as disabled in appconfig.
438
-	 *
439
-	 * @param string $app app
440
-	 * @throws Exception
441
-	 */
442
-	public static function disable($app) {
443
-		// flush
444
-		self::$enabledAppsCache = array();
445
-
446
-		// run uninstall steps
447
-		$appData = OC_App::getAppInfo($app);
448
-		if (!is_null($appData)) {
449
-			OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
450
-		}
451
-
452
-		// emit disable hook - needed anymore ?
453
-		\OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
454
-
455
-		// finally disable it
456
-		$appManager = \OC::$server->getAppManager();
457
-		$appManager->disableApp($app);
458
-	}
459
-
460
-	// This is private as well. It simply works, so don't ask for more details
461
-	private static function proceedNavigation($list) {
462
-		usort($list, function($a, $b) {
463
-			if (isset($a['order']) && isset($b['order'])) {
464
-				return ($a['order'] < $b['order']) ? -1 : 1;
465
-			} else if (isset($a['order']) || isset($b['order'])) {
466
-				return isset($a['order']) ? -1 : 1;
467
-			} else {
468
-				return ($a['name'] < $b['name']) ? -1 : 1;
469
-			}
470
-		});
471
-
472
-		$activeAppIndex = -1;
473
-		$activeApp = OC::$server->getNavigationManager()->getActiveEntry();
474
-		foreach ($list as $index => &$navEntry) {
475
-			$navEntry['showInHeader'] = true;
476
-			if ($navEntry['id'] == $activeApp) {
477
-				$navEntry['active'] = true;
478
-				$activeAppIndex = $index;
479
-			} else {
480
-				$navEntry['active'] = false;
481
-			}
482
-		}
483
-		unset($navEntry);
484
-
485
-		if (count($list) <= 8) {
486
-			return $list;
487
-		}
488
-
489
-		$headerIconCount = 7;
490
-		if($activeAppIndex > ($headerIconCount-1)) {
491
-			$active = $list[$activeAppIndex];
492
-			$lastInHeader = $list[$headerIconCount-1];
493
-			$list[$headerIconCount-1] = $active;
494
-			$list[$activeAppIndex] = $lastInHeader;
495
-		}
496
-
497
-		foreach ($list as $index => &$navEntry) {
498
-			if($index >= $headerIconCount) {
499
-				$navEntry['showInHeader'] = false;
500
-			}
501
-		}
502
-
503
-		return $list;
504
-	}
505
-
506
-	public static function proceedAppNavigation($entries) {
507
-		$activeAppIndex = -1;
508
-		$list = self::proceedNavigation($entries);
509
-
510
-		$activeApp = OC::$server->getNavigationManager()->getActiveEntry();
511
-		foreach ($list as $index => &$navEntry) {
512
-			if ($navEntry['id'] == $activeApp) {
513
-				$navEntry['active'] = true;
514
-				$activeAppIndex = $index;
515
-			} else {
516
-				$navEntry['active'] = false;
517
-			}
518
-		}
519
-
520
-
521
-		if (count($list) <= 8) {
522
-			return $list;
523
-		}
524
-
525
-		$headerIconCount = 7;
526
-		// move active item to last position
527
-		if($activeAppIndex > ($headerIconCount-1)) {
528
-			$active = $list[$activeAppIndex];
529
-			$lastInHeader = $list[$headerIconCount-1];
530
-			$list[$headerIconCount-1] = $active;
531
-			$list[$activeAppIndex] = $lastInHeader;
532
-		}
533
-		$list = array_slice($list, 0, $headerIconCount);
534
-
535
-		return $list;
536
-	}
537
-
538
-	/**
539
-	 * Get the path where to install apps
540
-	 *
541
-	 * @return string|false
542
-	 */
543
-	public static function getInstallPath() {
544
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
545
-			return false;
546
-		}
547
-
548
-		foreach (OC::$APPSROOTS as $dir) {
549
-			if (isset($dir['writable']) && $dir['writable'] === true) {
550
-				return $dir['path'];
551
-			}
552
-		}
553
-
554
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
555
-		return null;
556
-	}
557
-
558
-
559
-	/**
560
-	 * search for an app in all app-directories
561
-	 *
562
-	 * @param string $appId
563
-	 * @return false|string
564
-	 */
565
-	public static function findAppInDirectories($appId) {
566
-		$sanitizedAppId = self::cleanAppId($appId);
567
-		if($sanitizedAppId !== $appId) {
568
-			return false;
569
-		}
570
-		static $app_dir = array();
571
-
572
-		if (isset($app_dir[$appId])) {
573
-			return $app_dir[$appId];
574
-		}
575
-
576
-		$possibleApps = array();
577
-		foreach (OC::$APPSROOTS as $dir) {
578
-			if (file_exists($dir['path'] . '/' . $appId)) {
579
-				$possibleApps[] = $dir;
580
-			}
581
-		}
582
-
583
-		if (empty($possibleApps)) {
584
-			return false;
585
-		} elseif (count($possibleApps) === 1) {
586
-			$dir = array_shift($possibleApps);
587
-			$app_dir[$appId] = $dir;
588
-			return $dir;
589
-		} else {
590
-			$versionToLoad = array();
591
-			foreach ($possibleApps as $possibleApp) {
592
-				$version = self::getAppVersionByPath($possibleApp['path']);
593
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
594
-					$versionToLoad = array(
595
-						'dir' => $possibleApp,
596
-						'version' => $version,
597
-					);
598
-				}
599
-			}
600
-			$app_dir[$appId] = $versionToLoad['dir'];
601
-			return $versionToLoad['dir'];
602
-			//TODO - write test
603
-		}
604
-	}
605
-
606
-	/**
607
-	 * Get the directory for the given app.
608
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
609
-	 *
610
-	 * @param string $appId
611
-	 * @return string|false
612
-	 */
613
-	public static function getAppPath($appId) {
614
-		if ($appId === null || trim($appId) === '') {
615
-			return false;
616
-		}
617
-
618
-		if (($dir = self::findAppInDirectories($appId)) != false) {
619
-			return $dir['path'] . '/' . $appId;
620
-		}
621
-		return false;
622
-	}
623
-
624
-	/**
625
-	 * Get the path for the given app on the access
626
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
627
-	 *
628
-	 * @param string $appId
629
-	 * @return string|false
630
-	 */
631
-	public static function getAppWebPath($appId) {
632
-		if (($dir = self::findAppInDirectories($appId)) != false) {
633
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
634
-		}
635
-		return false;
636
-	}
637
-
638
-	/**
639
-	 * get the last version of the app from appinfo/info.xml
640
-	 *
641
-	 * @param string $appId
642
-	 * @param bool $useCache
643
-	 * @return string
644
-	 */
645
-	public static function getAppVersion($appId, $useCache = true) {
646
-		if($useCache && isset(self::$appVersion[$appId])) {
647
-			return self::$appVersion[$appId];
648
-		}
649
-
650
-		$file = self::getAppPath($appId);
651
-		self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
652
-		return self::$appVersion[$appId];
653
-	}
654
-
655
-	/**
656
-	 * get app's version based on it's path
657
-	 *
658
-	 * @param string $path
659
-	 * @return string
660
-	 */
661
-	public static function getAppVersionByPath($path) {
662
-		$infoFile = $path . '/appinfo/info.xml';
663
-		$appData = self::getAppInfo($infoFile, true);
664
-		return isset($appData['version']) ? $appData['version'] : '';
665
-	}
666
-
667
-
668
-	/**
669
-	 * Read all app metadata from the info.xml file
670
-	 *
671
-	 * @param string $appId id of the app or the path of the info.xml file
672
-	 * @param bool $path
673
-	 * @param string $lang
674
-	 * @return array|null
675
-	 * @note all data is read from info.xml, not just pre-defined fields
676
-	 */
677
-	public static function getAppInfo($appId, $path = false, $lang = null) {
678
-		if ($path) {
679
-			$file = $appId;
680
-		} else {
681
-			if ($lang === null && isset(self::$appInfo[$appId])) {
682
-				return self::$appInfo[$appId];
683
-			}
684
-			$appPath = self::getAppPath($appId);
685
-			if($appPath === false) {
686
-				return null;
687
-			}
688
-			$file = $appPath . '/appinfo/info.xml';
689
-		}
690
-
691
-		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->create('core.appinfo'));
692
-		$data = $parser->parse($file);
693
-
694
-		if (is_array($data)) {
695
-			$data = OC_App::parseAppInfo($data, $lang);
696
-		}
697
-		if(isset($data['ocsid'])) {
698
-			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
699
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
700
-				$data['ocsid'] = $storedId;
701
-			}
702
-		}
703
-
704
-		if ($lang === null) {
705
-			self::$appInfo[$appId] = $data;
706
-		}
707
-
708
-		return $data;
709
-	}
710
-
711
-	/**
712
-	 * Returns the navigation
713
-	 *
714
-	 * @return array
715
-	 *
716
-	 * This function returns an array containing all entries added. The
717
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
718
-	 * given for each app the following keys exist:
719
-	 *   - active: boolean, signals if the user is on this navigation entry
720
-	 */
721
-	public static function getNavigation() {
722
-		$entries = OC::$server->getNavigationManager()->getAll();
723
-		return self::proceedNavigation($entries);
724
-	}
725
-
726
-	/**
727
-	 * Returns the navigation inside the header bar
728
-	 *
729
-	 * @return array
730
-	 *
731
-	 * This function returns an array containing all entries added. The
732
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
733
-	 * given for each app the following keys exist:
734
-	 *   - active: boolean, signals if the user is on this navigation entry
735
-	 */
736
-	public static function getHeaderNavigation() {
737
-		$entries = OC::$server->getNavigationManager()->getAll();
738
-		return self::proceedAppNavigation($entries);
739
-	}
740
-
741
-	/**
742
-	 * Returns the Settings Navigation
743
-	 *
744
-	 * @return string[]
745
-	 *
746
-	 * This function returns an array containing all settings pages added. The
747
-	 * entries are sorted by the key 'order' ascending.
748
-	 */
749
-	public static function getSettingsNavigation() {
750
-		$entries = OC::$server->getNavigationManager()->getAll('settings');
751
-		return self::proceedNavigation($entries);
752
-	}
753
-
754
-	/**
755
-	 * get the id of loaded app
756
-	 *
757
-	 * @return string
758
-	 */
759
-	public static function getCurrentApp() {
760
-		$request = \OC::$server->getRequest();
761
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
762
-		$topFolder = substr($script, 0, strpos($script, '/'));
763
-		if (empty($topFolder)) {
764
-			$path_info = $request->getPathInfo();
765
-			if ($path_info) {
766
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
767
-			}
768
-		}
769
-		if ($topFolder == 'apps') {
770
-			$length = strlen($topFolder);
771
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
772
-		} else {
773
-			return $topFolder;
774
-		}
775
-	}
776
-
777
-	/**
778
-	 * @param string $type
779
-	 * @return array
780
-	 */
781
-	public static function getForms($type) {
782
-		$forms = array();
783
-		switch ($type) {
784
-			case 'admin':
785
-				$source = self::$adminForms;
786
-				break;
787
-			case 'personal':
788
-				$source = self::$personalForms;
789
-				break;
790
-			default:
791
-				return array();
792
-		}
793
-		foreach ($source as $form) {
794
-			$forms[] = include $form;
795
-		}
796
-		return $forms;
797
-	}
798
-
799
-	/**
800
-	 * register an admin form to be shown
801
-	 *
802
-	 * @param string $app
803
-	 * @param string $page
804
-	 */
805
-	public static function registerAdmin($app, $page) {
806
-		self::$adminForms[] = $app . '/' . $page . '.php';
807
-	}
808
-
809
-	/**
810
-	 * register a personal form to be shown
811
-	 * @param string $app
812
-	 * @param string $page
813
-	 */
814
-	public static function registerPersonal($app, $page) {
815
-		self::$personalForms[] = $app . '/' . $page . '.php';
816
-	}
817
-
818
-	/**
819
-	 * @param array $entry
820
-	 */
821
-	public static function registerLogIn(array $entry) {
822
-		self::$altLogin[] = $entry;
823
-	}
824
-
825
-	/**
826
-	 * @return array
827
-	 */
828
-	public static function getAlternativeLogIns() {
829
-		return self::$altLogin;
830
-	}
831
-
832
-	/**
833
-	 * get a list of all apps in the apps folder
834
-	 *
835
-	 * @return array an array of app names (string IDs)
836
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
837
-	 */
838
-	public static function getAllApps() {
839
-
840
-		$apps = array();
841
-
842
-		foreach (OC::$APPSROOTS as $apps_dir) {
843
-			if (!is_readable($apps_dir['path'])) {
844
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
845
-				continue;
846
-			}
847
-			$dh = opendir($apps_dir['path']);
848
-
849
-			if (is_resource($dh)) {
850
-				while (($file = readdir($dh)) !== false) {
851
-
852
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
853
-
854
-						$apps[] = $file;
855
-					}
856
-				}
857
-			}
858
-		}
859
-
860
-		return $apps;
861
-	}
862
-
863
-	/**
864
-	 * List all apps, this is used in apps.php
865
-	 *
866
-	 * @return array
867
-	 */
868
-	public function listAllApps() {
869
-		$installedApps = OC_App::getAllApps();
870
-
871
-		//we don't want to show configuration for these
872
-		$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
873
-		$appList = array();
874
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
875
-		$urlGenerator = \OC::$server->getURLGenerator();
876
-
877
-		foreach ($installedApps as $app) {
878
-			if (array_search($app, $blacklist) === false) {
879
-
880
-				$info = OC_App::getAppInfo($app, false, $langCode);
881
-				if (!is_array($info)) {
882
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
883
-					continue;
884
-				}
885
-
886
-				if (!isset($info['name'])) {
887
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
888
-					continue;
889
-				}
890
-
891
-				$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
892
-				$info['groups'] = null;
893
-				if ($enabled === 'yes') {
894
-					$active = true;
895
-				} else if ($enabled === 'no') {
896
-					$active = false;
897
-				} else {
898
-					$active = true;
899
-					$info['groups'] = $enabled;
900
-				}
901
-
902
-				$info['active'] = $active;
903
-
904
-				if (self::isShipped($app)) {
905
-					$info['internal'] = true;
906
-					$info['level'] = self::officialApp;
907
-					$info['removable'] = false;
908
-				} else {
909
-					$info['internal'] = false;
910
-					$info['removable'] = true;
911
-				}
912
-
913
-				$appPath = self::getAppPath($app);
914
-				if($appPath !== false) {
915
-					$appIcon = $appPath . '/img/' . $app . '.svg';
916
-					if (file_exists($appIcon)) {
917
-						$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app . '.svg');
918
-						$info['previewAsIcon'] = true;
919
-					} else {
920
-						$appIcon = $appPath . '/img/app.svg';
921
-						if (file_exists($appIcon)) {
922
-							$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, 'app.svg');
923
-							$info['previewAsIcon'] = true;
924
-						}
925
-					}
926
-				}
927
-				// fix documentation
928
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
929
-					foreach ($info['documentation'] as $key => $url) {
930
-						// If it is not an absolute URL we assume it is a key
931
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
932
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
933
-							$url = $urlGenerator->linkToDocs($url);
934
-						}
935
-
936
-						$info['documentation'][$key] = $url;
937
-					}
938
-				}
939
-
940
-				$info['version'] = OC_App::getAppVersion($app);
941
-				$appList[] = $info;
942
-			}
943
-		}
944
-
945
-		return $appList;
946
-	}
947
-
948
-	/**
949
-	 * Returns the internal app ID or false
950
-	 * @param string $ocsID
951
-	 * @return string|false
952
-	 */
953
-	public static function getInternalAppIdByOcs($ocsID) {
954
-		if(is_numeric($ocsID)) {
955
-			$idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
956
-			if(array_search($ocsID, $idArray)) {
957
-				return array_search($ocsID, $idArray);
958
-			}
959
-		}
960
-		return false;
961
-	}
962
-
963
-	public static function shouldUpgrade($app) {
964
-		$versions = self::getAppVersions();
965
-		$currentVersion = OC_App::getAppVersion($app);
966
-		if ($currentVersion && isset($versions[$app])) {
967
-			$installedVersion = $versions[$app];
968
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
969
-				return true;
970
-			}
971
-		}
972
-		return false;
973
-	}
974
-
975
-	/**
976
-	 * Adjust the number of version parts of $version1 to match
977
-	 * the number of version parts of $version2.
978
-	 *
979
-	 * @param string $version1 version to adjust
980
-	 * @param string $version2 version to take the number of parts from
981
-	 * @return string shortened $version1
982
-	 */
983
-	private static function adjustVersionParts($version1, $version2) {
984
-		$version1 = explode('.', $version1);
985
-		$version2 = explode('.', $version2);
986
-		// reduce $version1 to match the number of parts in $version2
987
-		while (count($version1) > count($version2)) {
988
-			array_pop($version1);
989
-		}
990
-		// if $version1 does not have enough parts, add some
991
-		while (count($version1) < count($version2)) {
992
-			$version1[] = '0';
993
-		}
994
-		return implode('.', $version1);
995
-	}
996
-
997
-	/**
998
-	 * Check whether the current ownCloud version matches the given
999
-	 * application's version requirements.
1000
-	 *
1001
-	 * The comparison is made based on the number of parts that the
1002
-	 * app info version has. For example for ownCloud 6.0.3 if the
1003
-	 * app info version is expecting version 6.0, the comparison is
1004
-	 * made on the first two parts of the ownCloud version.
1005
-	 * This means that it's possible to specify "requiremin" => 6
1006
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
1007
-	 *
1008
-	 * @param string $ocVersion ownCloud version to check against
1009
-	 * @param array $appInfo app info (from xml)
1010
-	 *
1011
-	 * @return boolean true if compatible, otherwise false
1012
-	 */
1013
-	public static function isAppCompatible($ocVersion, $appInfo) {
1014
-		$requireMin = '';
1015
-		$requireMax = '';
1016
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
1017
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
1018
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
1019
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
1020
-		} else if (isset($appInfo['requiremin'])) {
1021
-			$requireMin = $appInfo['requiremin'];
1022
-		} else if (isset($appInfo['require'])) {
1023
-			$requireMin = $appInfo['require'];
1024
-		}
1025
-
1026
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
1027
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
1028
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
1029
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
1030
-		} else if (isset($appInfo['requiremax'])) {
1031
-			$requireMax = $appInfo['requiremax'];
1032
-		}
1033
-
1034
-		if (is_array($ocVersion)) {
1035
-			$ocVersion = implode('.', $ocVersion);
1036
-		}
1037
-
1038
-		if (!empty($requireMin)
1039
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
1040
-		) {
1041
-
1042
-			return false;
1043
-		}
1044
-
1045
-		if (!empty($requireMax)
1046
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
1047
-		) {
1048
-			return false;
1049
-		}
1050
-
1051
-		return true;
1052
-	}
1053
-
1054
-	/**
1055
-	 * get the installed version of all apps
1056
-	 */
1057
-	public static function getAppVersions() {
1058
-		static $versions;
1059
-
1060
-		if(!$versions) {
1061
-			$appConfig = \OC::$server->getAppConfig();
1062
-			$versions = $appConfig->getValues(false, 'installed_version');
1063
-		}
1064
-		return $versions;
1065
-	}
1066
-
1067
-	/**
1068
-	 * @param string $app
1069
-	 * @param \OCP\IConfig $config
1070
-	 * @param \OCP\IL10N $l
1071
-	 * @return bool
1072
-	 *
1073
-	 * @throws Exception if app is not compatible with this version of ownCloud
1074
-	 * @throws Exception if no app-name was specified
1075
-	 */
1076
-	public function installApp($app,
1077
-							   \OCP\IConfig $config,
1078
-							   \OCP\IL10N $l) {
1079
-		if ($app !== false) {
1080
-			// check if the app is compatible with this version of ownCloud
1081
-			$info = self::getAppInfo($app);
1082
-			if(!is_array($info)) {
1083
-				throw new \Exception(
1084
-					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1085
-						[$info['name']]
1086
-					)
1087
-				);
1088
-			}
1089
-
1090
-			$version = \OCP\Util::getVersion();
1091
-			if (!self::isAppCompatible($version, $info)) {
1092
-				throw new \Exception(
1093
-					$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1094
-						array($info['name'])
1095
-					)
1096
-				);
1097
-			}
1098
-
1099
-			// check for required dependencies
1100
-			self::checkAppDependencies($config, $l, $info);
1101
-
1102
-			$config->setAppValue($app, 'enabled', 'yes');
1103
-			if (isset($appData['id'])) {
1104
-				$config->setAppValue($app, 'ocsid', $appData['id']);
1105
-			}
1106
-
1107
-			if(isset($info['settings']) && is_array($info['settings'])) {
1108
-				$appPath = self::getAppPath($app);
1109
-				self::registerAutoloading($app, $appPath);
1110
-				\OC::$server->getSettingsManager()->setupSettings($info['settings']);
1111
-			}
1112
-
1113
-			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1114
-		} else {
1115
-			if(empty($appName) ) {
1116
-				throw new \Exception($l->t("No app name specified"));
1117
-			} else {
1118
-				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1119
-			}
1120
-		}
1121
-
1122
-		return $app;
1123
-	}
1124
-
1125
-	/**
1126
-	 * update the database for the app and call the update script
1127
-	 *
1128
-	 * @param string $appId
1129
-	 * @return bool
1130
-	 */
1131
-	public static function updateApp($appId) {
1132
-		$appPath = self::getAppPath($appId);
1133
-		if($appPath === false) {
1134
-			return false;
1135
-		}
1136
-		$appData = self::getAppInfo($appId);
1137
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1138
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1139
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1140
-		}
1141
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1142
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1143
-		unset(self::$appVersion[$appId]);
1144
-		// run upgrade code
1145
-		if (file_exists($appPath . '/appinfo/update.php')) {
1146
-			self::loadApp($appId);
1147
-			include $appPath . '/appinfo/update.php';
1148
-		}
1149
-		self::setupBackgroundJobs($appData['background-jobs']);
1150
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
1151
-			$appPath = self::getAppPath($appId);
1152
-			self::registerAutoloading($appId, $appPath);
1153
-			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1154
-		}
1155
-
1156
-		//set remote/public handlers
1157
-		if (array_key_exists('ocsid', $appData)) {
1158
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1159
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1160
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1161
-		}
1162
-		foreach ($appData['remote'] as $name => $path) {
1163
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1164
-		}
1165
-		foreach ($appData['public'] as $name => $path) {
1166
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1167
-		}
1168
-
1169
-		self::setAppTypes($appId);
1170
-
1171
-		$version = \OC_App::getAppVersion($appId);
1172
-		\OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1173
-
1174
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1175
-			ManagerEvent::EVENT_APP_UPDATE, $appId
1176
-		));
1177
-
1178
-		return true;
1179
-	}
1180
-
1181
-	/**
1182
-	 * @param string $appId
1183
-	 * @param string[] $steps
1184
-	 * @throws \OC\NeedsUpdateException
1185
-	 */
1186
-	public static function executeRepairSteps($appId, array $steps) {
1187
-		if (empty($steps)) {
1188
-			return;
1189
-		}
1190
-		// load the app
1191
-		self::loadApp($appId);
1192
-
1193
-		$dispatcher = OC::$server->getEventDispatcher();
1194
-
1195
-		// load the steps
1196
-		$r = new Repair([], $dispatcher);
1197
-		foreach ($steps as $step) {
1198
-			try {
1199
-				$r->addStep($step);
1200
-			} catch (Exception $ex) {
1201
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1202
-				\OC::$server->getLogger()->logException($ex);
1203
-			}
1204
-		}
1205
-		// run the steps
1206
-		$r->run();
1207
-	}
1208
-
1209
-	public static function setupBackgroundJobs(array $jobs) {
1210
-		$queue = \OC::$server->getJobList();
1211
-		foreach ($jobs as $job) {
1212
-			$queue->add($job);
1213
-		}
1214
-	}
1215
-
1216
-	/**
1217
-	 * @param string $appId
1218
-	 * @param string[] $steps
1219
-	 */
1220
-	private static function setupLiveMigrations($appId, array $steps) {
1221
-		$queue = \OC::$server->getJobList();
1222
-		foreach ($steps as $step) {
1223
-			$queue->add('OC\Migration\BackgroundRepair', [
1224
-				'app' => $appId,
1225
-				'step' => $step]);
1226
-		}
1227
-	}
1228
-
1229
-	/**
1230
-	 * @param string $appId
1231
-	 * @return \OC\Files\View|false
1232
-	 */
1233
-	public static function getStorage($appId) {
1234
-		if (OC_App::isEnabled($appId)) { //sanity check
1235
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1236
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1237
-				if (!$view->file_exists($appId)) {
1238
-					$view->mkdir($appId);
1239
-				}
1240
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1241
-			} else {
1242
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1243
-				return false;
1244
-			}
1245
-		} else {
1246
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1247
-			return false;
1248
-		}
1249
-	}
1250
-
1251
-	protected static function findBestL10NOption($options, $lang) {
1252
-		$fallback = $similarLangFallback = $englishFallback = false;
1253
-
1254
-		$lang = strtolower($lang);
1255
-		$similarLang = $lang;
1256
-		if (strpos($similarLang, '_')) {
1257
-			// For "de_DE" we want to find "de" and the other way around
1258
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1259
-		}
1260
-
1261
-		foreach ($options as $option) {
1262
-			if (is_array($option)) {
1263
-				if ($fallback === false) {
1264
-					$fallback = $option['@value'];
1265
-				}
1266
-
1267
-				if (!isset($option['@attributes']['lang'])) {
1268
-					continue;
1269
-				}
1270
-
1271
-				$attributeLang = strtolower($option['@attributes']['lang']);
1272
-				if ($attributeLang === $lang) {
1273
-					return $option['@value'];
1274
-				}
1275
-
1276
-				if ($attributeLang === $similarLang) {
1277
-					$similarLangFallback = $option['@value'];
1278
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1279
-					if ($similarLangFallback === false) {
1280
-						$similarLangFallback =  $option['@value'];
1281
-					}
1282
-				}
1283
-			} else {
1284
-				$englishFallback = $option;
1285
-			}
1286
-		}
1287
-
1288
-		if ($similarLangFallback !== false) {
1289
-			return $similarLangFallback;
1290
-		} else if ($englishFallback !== false) {
1291
-			return $englishFallback;
1292
-		}
1293
-		return (string) $fallback;
1294
-	}
1295
-
1296
-	/**
1297
-	 * parses the app data array and enhanced the 'description' value
1298
-	 *
1299
-	 * @param array $data the app data
1300
-	 * @param string $lang
1301
-	 * @return array improved app data
1302
-	 */
1303
-	public static function parseAppInfo(array $data, $lang = null) {
1304
-
1305
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1306
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1307
-		}
1308
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1309
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1310
-		}
1311
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1312
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1313
-		} else if (isset($data['description']) && is_string($data['description'])) {
1314
-			$data['description'] = trim($data['description']);
1315
-		} else  {
1316
-			$data['description'] = '';
1317
-		}
1318
-
1319
-		return $data;
1320
-	}
1321
-
1322
-	/**
1323
-	 * @param \OCP\IConfig $config
1324
-	 * @param \OCP\IL10N $l
1325
-	 * @param array $info
1326
-	 * @throws \Exception
1327
-	 */
1328
-	protected static function checkAppDependencies($config, $l, $info) {
1329
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1330
-		$missing = $dependencyAnalyzer->analyze($info);
1331
-		if (!empty($missing)) {
1332
-			$missingMsg = join(PHP_EOL, $missing);
1333
-			throw new \Exception(
1334
-				$l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1335
-					[$info['name'], $missingMsg]
1336
-				)
1337
-			);
1338
-		}
1339
-	}
64
+    static private $appVersion = [];
65
+    static private $adminForms = array();
66
+    static private $personalForms = array();
67
+    static private $appInfo = array();
68
+    static private $appTypes = array();
69
+    static private $loadedApps = array();
70
+    static private $altLogin = array();
71
+    static private $alreadyRegistered = [];
72
+    const officialApp = 200;
73
+
74
+    /**
75
+     * clean the appId
76
+     *
77
+     * @param string|boolean $app AppId that needs to be cleaned
78
+     * @return string
79
+     */
80
+    public static function cleanAppId($app) {
81
+        return str_replace(array('\0', '/', '\\', '..'), '', $app);
82
+    }
83
+
84
+    /**
85
+     * Check if an app is loaded
86
+     *
87
+     * @param string $app
88
+     * @return bool
89
+     */
90
+    public static function isAppLoaded($app) {
91
+        return in_array($app, self::$loadedApps, true);
92
+    }
93
+
94
+    /**
95
+     * loads all apps
96
+     *
97
+     * @param string[] | string | null $types
98
+     * @return bool
99
+     *
100
+     * This function walks through the ownCloud directory and loads all apps
101
+     * it can find. A directory contains an app if the file /appinfo/info.xml
102
+     * exists.
103
+     *
104
+     * if $types is set, only apps of those types will be loaded
105
+     */
106
+    public static function loadApps($types = null) {
107
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
108
+            return false;
109
+        }
110
+        // Load the enabled apps here
111
+        $apps = self::getEnabledApps();
112
+
113
+        // Add each apps' folder as allowed class path
114
+        foreach($apps as $app) {
115
+            $path = self::getAppPath($app);
116
+            if($path !== false) {
117
+                self::registerAutoloading($app, $path);
118
+            }
119
+        }
120
+
121
+        // prevent app.php from printing output
122
+        ob_start();
123
+        foreach ($apps as $app) {
124
+            if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
125
+                self::loadApp($app);
126
+            }
127
+        }
128
+        ob_end_clean();
129
+
130
+        return true;
131
+    }
132
+
133
+    /**
134
+     * load a single app
135
+     *
136
+     * @param string $app
137
+     */
138
+    public static function loadApp($app) {
139
+        self::$loadedApps[] = $app;
140
+        $appPath = self::getAppPath($app);
141
+        if($appPath === false) {
142
+            return;
143
+        }
144
+
145
+        // in case someone calls loadApp() directly
146
+        self::registerAutoloading($app, $appPath);
147
+
148
+        if (is_file($appPath . '/appinfo/app.php')) {
149
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
+            self::requireAppFile($app);
151
+            if (self::isType($app, array('authentication'))) {
152
+                // since authentication apps affect the "is app enabled for group" check,
153
+                // the enabled apps cache needs to be cleared to make sure that the
154
+                // next time getEnableApps() is called it will also include apps that were
155
+                // enabled for groups
156
+                self::$enabledAppsCache = array();
157
+            }
158
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
159
+        }
160
+
161
+        $info = self::getAppInfo($app);
162
+        if (!empty($info['activity']['filters'])) {
163
+            foreach ($info['activity']['filters'] as $filter) {
164
+                \OC::$server->getActivityManager()->registerFilter($filter);
165
+            }
166
+        }
167
+        if (!empty($info['activity']['settings'])) {
168
+            foreach ($info['activity']['settings'] as $setting) {
169
+                \OC::$server->getActivityManager()->registerSetting($setting);
170
+            }
171
+        }
172
+        if (!empty($info['activity']['providers'])) {
173
+            foreach ($info['activity']['providers'] as $provider) {
174
+                \OC::$server->getActivityManager()->registerProvider($provider);
175
+            }
176
+        }
177
+    }
178
+
179
+    /**
180
+     * @internal
181
+     * @param string $app
182
+     * @param string $path
183
+     */
184
+    public static function registerAutoloading($app, $path) {
185
+        $key = $app . '-' . $path;
186
+        if(isset(self::$alreadyRegistered[$key])) {
187
+            return;
188
+        }
189
+        self::$alreadyRegistered[$key] = true;
190
+        // Register on PSR-4 composer autoloader
191
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
192
+        \OC::$server->registerNamespace($app, $appNamespace);
193
+        \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
194
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
195
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
196
+        }
197
+
198
+        // Register on legacy autoloader
199
+        \OC::$loader->addValidRoot($path);
200
+    }
201
+
202
+    /**
203
+     * Load app.php from the given app
204
+     *
205
+     * @param string $app app name
206
+     */
207
+    private static function requireAppFile($app) {
208
+        try {
209
+            // encapsulated here to avoid variable scope conflicts
210
+            require_once $app . '/appinfo/app.php';
211
+        } catch (Error $ex) {
212
+            \OC::$server->getLogger()->logException($ex);
213
+            $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
214
+            if (!in_array($app, $blacklist)) {
215
+                self::disable($app);
216
+            }
217
+        }
218
+    }
219
+
220
+    /**
221
+     * check if an app is of a specific type
222
+     *
223
+     * @param string $app
224
+     * @param string|array $types
225
+     * @return bool
226
+     */
227
+    public static function isType($app, $types) {
228
+        if (is_string($types)) {
229
+            $types = array($types);
230
+        }
231
+        $appTypes = self::getAppTypes($app);
232
+        foreach ($types as $type) {
233
+            if (array_search($type, $appTypes) !== false) {
234
+                return true;
235
+            }
236
+        }
237
+        return false;
238
+    }
239
+
240
+    /**
241
+     * get the types of an app
242
+     *
243
+     * @param string $app
244
+     * @return array
245
+     */
246
+    private static function getAppTypes($app) {
247
+        //load the cache
248
+        if (count(self::$appTypes) == 0) {
249
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
250
+        }
251
+
252
+        if (isset(self::$appTypes[$app])) {
253
+            return explode(',', self::$appTypes[$app]);
254
+        } else {
255
+            return array();
256
+        }
257
+    }
258
+
259
+    /**
260
+     * read app types from info.xml and cache them in the database
261
+     */
262
+    public static function setAppTypes($app) {
263
+        $appData = self::getAppInfo($app);
264
+        if(!is_array($appData)) {
265
+            return;
266
+        }
267
+
268
+        if (isset($appData['types'])) {
269
+            $appTypes = implode(',', $appData['types']);
270
+        } else {
271
+            $appTypes = '';
272
+            $appData['types'] = [];
273
+        }
274
+
275
+        \OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
276
+
277
+        if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
278
+            $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
279
+            if ($enabled !== 'yes' && $enabled !== 'no') {
280
+                \OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
281
+            }
282
+        }
283
+    }
284
+
285
+    /**
286
+     * check if app is shipped
287
+     *
288
+     * @param string $appId the id of the app to check
289
+     * @return bool
290
+     *
291
+     * Check if an app that is installed is a shipped app or installed from the appstore.
292
+     */
293
+    public static function isShipped($appId) {
294
+        return \OC::$server->getAppManager()->isShipped($appId);
295
+    }
296
+
297
+    /**
298
+     * get all enabled apps
299
+     */
300
+    protected static $enabledAppsCache = array();
301
+
302
+    /**
303
+     * Returns apps enabled for the current user.
304
+     *
305
+     * @param bool $forceRefresh whether to refresh the cache
306
+     * @param bool $all whether to return apps for all users, not only the
307
+     * currently logged in one
308
+     * @return string[]
309
+     */
310
+    public static function getEnabledApps($forceRefresh = false, $all = false) {
311
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
312
+            return array();
313
+        }
314
+        // in incognito mode or when logged out, $user will be false,
315
+        // which is also the case during an upgrade
316
+        $appManager = \OC::$server->getAppManager();
317
+        if ($all) {
318
+            $user = null;
319
+        } else {
320
+            $user = \OC::$server->getUserSession()->getUser();
321
+        }
322
+
323
+        if (is_null($user)) {
324
+            $apps = $appManager->getInstalledApps();
325
+        } else {
326
+            $apps = $appManager->getEnabledAppsForUser($user);
327
+        }
328
+        $apps = array_filter($apps, function ($app) {
329
+            return $app !== 'files';//we add this manually
330
+        });
331
+        sort($apps);
332
+        array_unshift($apps, 'files');
333
+        return $apps;
334
+    }
335
+
336
+    /**
337
+     * checks whether or not an app is enabled
338
+     *
339
+     * @param string $app app
340
+     * @return bool
341
+     *
342
+     * This function checks whether or not an app is enabled.
343
+     */
344
+    public static function isEnabled($app) {
345
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
346
+    }
347
+
348
+    /**
349
+     * enables an app
350
+     *
351
+     * @param string $appId
352
+     * @param array $groups (optional) when set, only these groups will have access to the app
353
+     * @throws \Exception
354
+     * @return void
355
+     *
356
+     * This function set an app as enabled in appconfig.
357
+     */
358
+    public function enable($appId,
359
+                            $groups = null) {
360
+        self::$enabledAppsCache = []; // flush
361
+        $l = \OC::$server->getL10N('core');
362
+        $config = \OC::$server->getConfig();
363
+
364
+        // Check if app is already downloaded
365
+        $installer = new Installer(
366
+            \OC::$server->getAppFetcher(),
367
+            \OC::$server->getHTTPClientService(),
368
+            \OC::$server->getTempManager(),
369
+            \OC::$server->getLogger()
370
+        );
371
+        $isDownloaded = $installer->isDownloaded($appId);
372
+
373
+        if(!$isDownloaded) {
374
+            $installer->downloadApp($appId);
375
+        }
376
+
377
+        if (!Installer::isInstalled($appId)) {
378
+            $appId = self::installApp(
379
+                $appId,
380
+                $config,
381
+                $l
382
+            );
383
+            $appPath = self::getAppPath($appId);
384
+            self::registerAutoloading($appId, $appPath);
385
+            $installer->installApp($appId);
386
+        } else {
387
+            // check for required dependencies
388
+            $info = self::getAppInfo($appId);
389
+            self::checkAppDependencies($config, $l, $info);
390
+            $appPath = self::getAppPath($appId);
391
+            self::registerAutoloading($appId, $appPath);
392
+            $installer->installApp($appId);
393
+        }
394
+
395
+        $appManager = \OC::$server->getAppManager();
396
+        if (!is_null($groups)) {
397
+            $groupManager = \OC::$server->getGroupManager();
398
+            $groupsList = [];
399
+            foreach ($groups as $group) {
400
+                $groupItem = $groupManager->get($group);
401
+                if ($groupItem instanceof \OCP\IGroup) {
402
+                    $groupsList[] = $groupManager->get($group);
403
+                }
404
+            }
405
+            $appManager->enableAppForGroups($appId, $groupsList);
406
+        } else {
407
+            $appManager->enableApp($appId);
408
+        }
409
+
410
+        $info = self::getAppInfo($appId);
411
+        if(isset($info['settings']) && is_array($info['settings'])) {
412
+            $appPath = self::getAppPath($appId);
413
+            self::registerAutoloading($appId, $appPath);
414
+            \OC::$server->getSettingsManager()->setupSettings($info['settings']);
415
+        }
416
+    }
417
+
418
+    /**
419
+     * @param string $app
420
+     * @return bool
421
+     */
422
+    public static function removeApp($app) {
423
+        if (self::isShipped($app)) {
424
+            return false;
425
+        }
426
+
427
+        $installer = new Installer(
428
+            \OC::$server->getAppFetcher(),
429
+            \OC::$server->getHTTPClientService(),
430
+            \OC::$server->getTempManager(),
431
+            \OC::$server->getLogger()
432
+        );
433
+        return $installer->removeApp($app);
434
+    }
435
+
436
+    /**
437
+     * This function set an app as disabled in appconfig.
438
+     *
439
+     * @param string $app app
440
+     * @throws Exception
441
+     */
442
+    public static function disable($app) {
443
+        // flush
444
+        self::$enabledAppsCache = array();
445
+
446
+        // run uninstall steps
447
+        $appData = OC_App::getAppInfo($app);
448
+        if (!is_null($appData)) {
449
+            OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
450
+        }
451
+
452
+        // emit disable hook - needed anymore ?
453
+        \OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
454
+
455
+        // finally disable it
456
+        $appManager = \OC::$server->getAppManager();
457
+        $appManager->disableApp($app);
458
+    }
459
+
460
+    // This is private as well. It simply works, so don't ask for more details
461
+    private static function proceedNavigation($list) {
462
+        usort($list, function($a, $b) {
463
+            if (isset($a['order']) && isset($b['order'])) {
464
+                return ($a['order'] < $b['order']) ? -1 : 1;
465
+            } else if (isset($a['order']) || isset($b['order'])) {
466
+                return isset($a['order']) ? -1 : 1;
467
+            } else {
468
+                return ($a['name'] < $b['name']) ? -1 : 1;
469
+            }
470
+        });
471
+
472
+        $activeAppIndex = -1;
473
+        $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
474
+        foreach ($list as $index => &$navEntry) {
475
+            $navEntry['showInHeader'] = true;
476
+            if ($navEntry['id'] == $activeApp) {
477
+                $navEntry['active'] = true;
478
+                $activeAppIndex = $index;
479
+            } else {
480
+                $navEntry['active'] = false;
481
+            }
482
+        }
483
+        unset($navEntry);
484
+
485
+        if (count($list) <= 8) {
486
+            return $list;
487
+        }
488
+
489
+        $headerIconCount = 7;
490
+        if($activeAppIndex > ($headerIconCount-1)) {
491
+            $active = $list[$activeAppIndex];
492
+            $lastInHeader = $list[$headerIconCount-1];
493
+            $list[$headerIconCount-1] = $active;
494
+            $list[$activeAppIndex] = $lastInHeader;
495
+        }
496
+
497
+        foreach ($list as $index => &$navEntry) {
498
+            if($index >= $headerIconCount) {
499
+                $navEntry['showInHeader'] = false;
500
+            }
501
+        }
502
+
503
+        return $list;
504
+    }
505
+
506
+    public static function proceedAppNavigation($entries) {
507
+        $activeAppIndex = -1;
508
+        $list = self::proceedNavigation($entries);
509
+
510
+        $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
511
+        foreach ($list as $index => &$navEntry) {
512
+            if ($navEntry['id'] == $activeApp) {
513
+                $navEntry['active'] = true;
514
+                $activeAppIndex = $index;
515
+            } else {
516
+                $navEntry['active'] = false;
517
+            }
518
+        }
519
+
520
+
521
+        if (count($list) <= 8) {
522
+            return $list;
523
+        }
524
+
525
+        $headerIconCount = 7;
526
+        // move active item to last position
527
+        if($activeAppIndex > ($headerIconCount-1)) {
528
+            $active = $list[$activeAppIndex];
529
+            $lastInHeader = $list[$headerIconCount-1];
530
+            $list[$headerIconCount-1] = $active;
531
+            $list[$activeAppIndex] = $lastInHeader;
532
+        }
533
+        $list = array_slice($list, 0, $headerIconCount);
534
+
535
+        return $list;
536
+    }
537
+
538
+    /**
539
+     * Get the path where to install apps
540
+     *
541
+     * @return string|false
542
+     */
543
+    public static function getInstallPath() {
544
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
545
+            return false;
546
+        }
547
+
548
+        foreach (OC::$APPSROOTS as $dir) {
549
+            if (isset($dir['writable']) && $dir['writable'] === true) {
550
+                return $dir['path'];
551
+            }
552
+        }
553
+
554
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
555
+        return null;
556
+    }
557
+
558
+
559
+    /**
560
+     * search for an app in all app-directories
561
+     *
562
+     * @param string $appId
563
+     * @return false|string
564
+     */
565
+    public static function findAppInDirectories($appId) {
566
+        $sanitizedAppId = self::cleanAppId($appId);
567
+        if($sanitizedAppId !== $appId) {
568
+            return false;
569
+        }
570
+        static $app_dir = array();
571
+
572
+        if (isset($app_dir[$appId])) {
573
+            return $app_dir[$appId];
574
+        }
575
+
576
+        $possibleApps = array();
577
+        foreach (OC::$APPSROOTS as $dir) {
578
+            if (file_exists($dir['path'] . '/' . $appId)) {
579
+                $possibleApps[] = $dir;
580
+            }
581
+        }
582
+
583
+        if (empty($possibleApps)) {
584
+            return false;
585
+        } elseif (count($possibleApps) === 1) {
586
+            $dir = array_shift($possibleApps);
587
+            $app_dir[$appId] = $dir;
588
+            return $dir;
589
+        } else {
590
+            $versionToLoad = array();
591
+            foreach ($possibleApps as $possibleApp) {
592
+                $version = self::getAppVersionByPath($possibleApp['path']);
593
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
594
+                    $versionToLoad = array(
595
+                        'dir' => $possibleApp,
596
+                        'version' => $version,
597
+                    );
598
+                }
599
+            }
600
+            $app_dir[$appId] = $versionToLoad['dir'];
601
+            return $versionToLoad['dir'];
602
+            //TODO - write test
603
+        }
604
+    }
605
+
606
+    /**
607
+     * Get the directory for the given app.
608
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
609
+     *
610
+     * @param string $appId
611
+     * @return string|false
612
+     */
613
+    public static function getAppPath($appId) {
614
+        if ($appId === null || trim($appId) === '') {
615
+            return false;
616
+        }
617
+
618
+        if (($dir = self::findAppInDirectories($appId)) != false) {
619
+            return $dir['path'] . '/' . $appId;
620
+        }
621
+        return false;
622
+    }
623
+
624
+    /**
625
+     * Get the path for the given app on the access
626
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
627
+     *
628
+     * @param string $appId
629
+     * @return string|false
630
+     */
631
+    public static function getAppWebPath($appId) {
632
+        if (($dir = self::findAppInDirectories($appId)) != false) {
633
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
634
+        }
635
+        return false;
636
+    }
637
+
638
+    /**
639
+     * get the last version of the app from appinfo/info.xml
640
+     *
641
+     * @param string $appId
642
+     * @param bool $useCache
643
+     * @return string
644
+     */
645
+    public static function getAppVersion($appId, $useCache = true) {
646
+        if($useCache && isset(self::$appVersion[$appId])) {
647
+            return self::$appVersion[$appId];
648
+        }
649
+
650
+        $file = self::getAppPath($appId);
651
+        self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
652
+        return self::$appVersion[$appId];
653
+    }
654
+
655
+    /**
656
+     * get app's version based on it's path
657
+     *
658
+     * @param string $path
659
+     * @return string
660
+     */
661
+    public static function getAppVersionByPath($path) {
662
+        $infoFile = $path . '/appinfo/info.xml';
663
+        $appData = self::getAppInfo($infoFile, true);
664
+        return isset($appData['version']) ? $appData['version'] : '';
665
+    }
666
+
667
+
668
+    /**
669
+     * Read all app metadata from the info.xml file
670
+     *
671
+     * @param string $appId id of the app or the path of the info.xml file
672
+     * @param bool $path
673
+     * @param string $lang
674
+     * @return array|null
675
+     * @note all data is read from info.xml, not just pre-defined fields
676
+     */
677
+    public static function getAppInfo($appId, $path = false, $lang = null) {
678
+        if ($path) {
679
+            $file = $appId;
680
+        } else {
681
+            if ($lang === null && isset(self::$appInfo[$appId])) {
682
+                return self::$appInfo[$appId];
683
+            }
684
+            $appPath = self::getAppPath($appId);
685
+            if($appPath === false) {
686
+                return null;
687
+            }
688
+            $file = $appPath . '/appinfo/info.xml';
689
+        }
690
+
691
+        $parser = new InfoParser(\OC::$server->getMemCacheFactory()->create('core.appinfo'));
692
+        $data = $parser->parse($file);
693
+
694
+        if (is_array($data)) {
695
+            $data = OC_App::parseAppInfo($data, $lang);
696
+        }
697
+        if(isset($data['ocsid'])) {
698
+            $storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
699
+            if($storedId !== '' && $storedId !== $data['ocsid']) {
700
+                $data['ocsid'] = $storedId;
701
+            }
702
+        }
703
+
704
+        if ($lang === null) {
705
+            self::$appInfo[$appId] = $data;
706
+        }
707
+
708
+        return $data;
709
+    }
710
+
711
+    /**
712
+     * Returns the navigation
713
+     *
714
+     * @return array
715
+     *
716
+     * This function returns an array containing all entries added. The
717
+     * entries are sorted by the key 'order' ascending. Additional to the keys
718
+     * given for each app the following keys exist:
719
+     *   - active: boolean, signals if the user is on this navigation entry
720
+     */
721
+    public static function getNavigation() {
722
+        $entries = OC::$server->getNavigationManager()->getAll();
723
+        return self::proceedNavigation($entries);
724
+    }
725
+
726
+    /**
727
+     * Returns the navigation inside the header bar
728
+     *
729
+     * @return array
730
+     *
731
+     * This function returns an array containing all entries added. The
732
+     * entries are sorted by the key 'order' ascending. Additional to the keys
733
+     * given for each app the following keys exist:
734
+     *   - active: boolean, signals if the user is on this navigation entry
735
+     */
736
+    public static function getHeaderNavigation() {
737
+        $entries = OC::$server->getNavigationManager()->getAll();
738
+        return self::proceedAppNavigation($entries);
739
+    }
740
+
741
+    /**
742
+     * Returns the Settings Navigation
743
+     *
744
+     * @return string[]
745
+     *
746
+     * This function returns an array containing all settings pages added. The
747
+     * entries are sorted by the key 'order' ascending.
748
+     */
749
+    public static function getSettingsNavigation() {
750
+        $entries = OC::$server->getNavigationManager()->getAll('settings');
751
+        return self::proceedNavigation($entries);
752
+    }
753
+
754
+    /**
755
+     * get the id of loaded app
756
+     *
757
+     * @return string
758
+     */
759
+    public static function getCurrentApp() {
760
+        $request = \OC::$server->getRequest();
761
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
762
+        $topFolder = substr($script, 0, strpos($script, '/'));
763
+        if (empty($topFolder)) {
764
+            $path_info = $request->getPathInfo();
765
+            if ($path_info) {
766
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
767
+            }
768
+        }
769
+        if ($topFolder == 'apps') {
770
+            $length = strlen($topFolder);
771
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
772
+        } else {
773
+            return $topFolder;
774
+        }
775
+    }
776
+
777
+    /**
778
+     * @param string $type
779
+     * @return array
780
+     */
781
+    public static function getForms($type) {
782
+        $forms = array();
783
+        switch ($type) {
784
+            case 'admin':
785
+                $source = self::$adminForms;
786
+                break;
787
+            case 'personal':
788
+                $source = self::$personalForms;
789
+                break;
790
+            default:
791
+                return array();
792
+        }
793
+        foreach ($source as $form) {
794
+            $forms[] = include $form;
795
+        }
796
+        return $forms;
797
+    }
798
+
799
+    /**
800
+     * register an admin form to be shown
801
+     *
802
+     * @param string $app
803
+     * @param string $page
804
+     */
805
+    public static function registerAdmin($app, $page) {
806
+        self::$adminForms[] = $app . '/' . $page . '.php';
807
+    }
808
+
809
+    /**
810
+     * register a personal form to be shown
811
+     * @param string $app
812
+     * @param string $page
813
+     */
814
+    public static function registerPersonal($app, $page) {
815
+        self::$personalForms[] = $app . '/' . $page . '.php';
816
+    }
817
+
818
+    /**
819
+     * @param array $entry
820
+     */
821
+    public static function registerLogIn(array $entry) {
822
+        self::$altLogin[] = $entry;
823
+    }
824
+
825
+    /**
826
+     * @return array
827
+     */
828
+    public static function getAlternativeLogIns() {
829
+        return self::$altLogin;
830
+    }
831
+
832
+    /**
833
+     * get a list of all apps in the apps folder
834
+     *
835
+     * @return array an array of app names (string IDs)
836
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
837
+     */
838
+    public static function getAllApps() {
839
+
840
+        $apps = array();
841
+
842
+        foreach (OC::$APPSROOTS as $apps_dir) {
843
+            if (!is_readable($apps_dir['path'])) {
844
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
845
+                continue;
846
+            }
847
+            $dh = opendir($apps_dir['path']);
848
+
849
+            if (is_resource($dh)) {
850
+                while (($file = readdir($dh)) !== false) {
851
+
852
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
853
+
854
+                        $apps[] = $file;
855
+                    }
856
+                }
857
+            }
858
+        }
859
+
860
+        return $apps;
861
+    }
862
+
863
+    /**
864
+     * List all apps, this is used in apps.php
865
+     *
866
+     * @return array
867
+     */
868
+    public function listAllApps() {
869
+        $installedApps = OC_App::getAllApps();
870
+
871
+        //we don't want to show configuration for these
872
+        $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
873
+        $appList = array();
874
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
875
+        $urlGenerator = \OC::$server->getURLGenerator();
876
+
877
+        foreach ($installedApps as $app) {
878
+            if (array_search($app, $blacklist) === false) {
879
+
880
+                $info = OC_App::getAppInfo($app, false, $langCode);
881
+                if (!is_array($info)) {
882
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
883
+                    continue;
884
+                }
885
+
886
+                if (!isset($info['name'])) {
887
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
888
+                    continue;
889
+                }
890
+
891
+                $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
892
+                $info['groups'] = null;
893
+                if ($enabled === 'yes') {
894
+                    $active = true;
895
+                } else if ($enabled === 'no') {
896
+                    $active = false;
897
+                } else {
898
+                    $active = true;
899
+                    $info['groups'] = $enabled;
900
+                }
901
+
902
+                $info['active'] = $active;
903
+
904
+                if (self::isShipped($app)) {
905
+                    $info['internal'] = true;
906
+                    $info['level'] = self::officialApp;
907
+                    $info['removable'] = false;
908
+                } else {
909
+                    $info['internal'] = false;
910
+                    $info['removable'] = true;
911
+                }
912
+
913
+                $appPath = self::getAppPath($app);
914
+                if($appPath !== false) {
915
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
916
+                    if (file_exists($appIcon)) {
917
+                        $info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app . '.svg');
918
+                        $info['previewAsIcon'] = true;
919
+                    } else {
920
+                        $appIcon = $appPath . '/img/app.svg';
921
+                        if (file_exists($appIcon)) {
922
+                            $info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, 'app.svg');
923
+                            $info['previewAsIcon'] = true;
924
+                        }
925
+                    }
926
+                }
927
+                // fix documentation
928
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
929
+                    foreach ($info['documentation'] as $key => $url) {
930
+                        // If it is not an absolute URL we assume it is a key
931
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
932
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
933
+                            $url = $urlGenerator->linkToDocs($url);
934
+                        }
935
+
936
+                        $info['documentation'][$key] = $url;
937
+                    }
938
+                }
939
+
940
+                $info['version'] = OC_App::getAppVersion($app);
941
+                $appList[] = $info;
942
+            }
943
+        }
944
+
945
+        return $appList;
946
+    }
947
+
948
+    /**
949
+     * Returns the internal app ID or false
950
+     * @param string $ocsID
951
+     * @return string|false
952
+     */
953
+    public static function getInternalAppIdByOcs($ocsID) {
954
+        if(is_numeric($ocsID)) {
955
+            $idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
956
+            if(array_search($ocsID, $idArray)) {
957
+                return array_search($ocsID, $idArray);
958
+            }
959
+        }
960
+        return false;
961
+    }
962
+
963
+    public static function shouldUpgrade($app) {
964
+        $versions = self::getAppVersions();
965
+        $currentVersion = OC_App::getAppVersion($app);
966
+        if ($currentVersion && isset($versions[$app])) {
967
+            $installedVersion = $versions[$app];
968
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
969
+                return true;
970
+            }
971
+        }
972
+        return false;
973
+    }
974
+
975
+    /**
976
+     * Adjust the number of version parts of $version1 to match
977
+     * the number of version parts of $version2.
978
+     *
979
+     * @param string $version1 version to adjust
980
+     * @param string $version2 version to take the number of parts from
981
+     * @return string shortened $version1
982
+     */
983
+    private static function adjustVersionParts($version1, $version2) {
984
+        $version1 = explode('.', $version1);
985
+        $version2 = explode('.', $version2);
986
+        // reduce $version1 to match the number of parts in $version2
987
+        while (count($version1) > count($version2)) {
988
+            array_pop($version1);
989
+        }
990
+        // if $version1 does not have enough parts, add some
991
+        while (count($version1) < count($version2)) {
992
+            $version1[] = '0';
993
+        }
994
+        return implode('.', $version1);
995
+    }
996
+
997
+    /**
998
+     * Check whether the current ownCloud version matches the given
999
+     * application's version requirements.
1000
+     *
1001
+     * The comparison is made based on the number of parts that the
1002
+     * app info version has. For example for ownCloud 6.0.3 if the
1003
+     * app info version is expecting version 6.0, the comparison is
1004
+     * made on the first two parts of the ownCloud version.
1005
+     * This means that it's possible to specify "requiremin" => 6
1006
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
1007
+     *
1008
+     * @param string $ocVersion ownCloud version to check against
1009
+     * @param array $appInfo app info (from xml)
1010
+     *
1011
+     * @return boolean true if compatible, otherwise false
1012
+     */
1013
+    public static function isAppCompatible($ocVersion, $appInfo) {
1014
+        $requireMin = '';
1015
+        $requireMax = '';
1016
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
1017
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
1018
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
1019
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
1020
+        } else if (isset($appInfo['requiremin'])) {
1021
+            $requireMin = $appInfo['requiremin'];
1022
+        } else if (isset($appInfo['require'])) {
1023
+            $requireMin = $appInfo['require'];
1024
+        }
1025
+
1026
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
1027
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
1028
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
1029
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
1030
+        } else if (isset($appInfo['requiremax'])) {
1031
+            $requireMax = $appInfo['requiremax'];
1032
+        }
1033
+
1034
+        if (is_array($ocVersion)) {
1035
+            $ocVersion = implode('.', $ocVersion);
1036
+        }
1037
+
1038
+        if (!empty($requireMin)
1039
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
1040
+        ) {
1041
+
1042
+            return false;
1043
+        }
1044
+
1045
+        if (!empty($requireMax)
1046
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
1047
+        ) {
1048
+            return false;
1049
+        }
1050
+
1051
+        return true;
1052
+    }
1053
+
1054
+    /**
1055
+     * get the installed version of all apps
1056
+     */
1057
+    public static function getAppVersions() {
1058
+        static $versions;
1059
+
1060
+        if(!$versions) {
1061
+            $appConfig = \OC::$server->getAppConfig();
1062
+            $versions = $appConfig->getValues(false, 'installed_version');
1063
+        }
1064
+        return $versions;
1065
+    }
1066
+
1067
+    /**
1068
+     * @param string $app
1069
+     * @param \OCP\IConfig $config
1070
+     * @param \OCP\IL10N $l
1071
+     * @return bool
1072
+     *
1073
+     * @throws Exception if app is not compatible with this version of ownCloud
1074
+     * @throws Exception if no app-name was specified
1075
+     */
1076
+    public function installApp($app,
1077
+                                \OCP\IConfig $config,
1078
+                                \OCP\IL10N $l) {
1079
+        if ($app !== false) {
1080
+            // check if the app is compatible with this version of ownCloud
1081
+            $info = self::getAppInfo($app);
1082
+            if(!is_array($info)) {
1083
+                throw new \Exception(
1084
+                    $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1085
+                        [$info['name']]
1086
+                    )
1087
+                );
1088
+            }
1089
+
1090
+            $version = \OCP\Util::getVersion();
1091
+            if (!self::isAppCompatible($version, $info)) {
1092
+                throw new \Exception(
1093
+                    $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1094
+                        array($info['name'])
1095
+                    )
1096
+                );
1097
+            }
1098
+
1099
+            // check for required dependencies
1100
+            self::checkAppDependencies($config, $l, $info);
1101
+
1102
+            $config->setAppValue($app, 'enabled', 'yes');
1103
+            if (isset($appData['id'])) {
1104
+                $config->setAppValue($app, 'ocsid', $appData['id']);
1105
+            }
1106
+
1107
+            if(isset($info['settings']) && is_array($info['settings'])) {
1108
+                $appPath = self::getAppPath($app);
1109
+                self::registerAutoloading($app, $appPath);
1110
+                \OC::$server->getSettingsManager()->setupSettings($info['settings']);
1111
+            }
1112
+
1113
+            \OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1114
+        } else {
1115
+            if(empty($appName) ) {
1116
+                throw new \Exception($l->t("No app name specified"));
1117
+            } else {
1118
+                throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1119
+            }
1120
+        }
1121
+
1122
+        return $app;
1123
+    }
1124
+
1125
+    /**
1126
+     * update the database for the app and call the update script
1127
+     *
1128
+     * @param string $appId
1129
+     * @return bool
1130
+     */
1131
+    public static function updateApp($appId) {
1132
+        $appPath = self::getAppPath($appId);
1133
+        if($appPath === false) {
1134
+            return false;
1135
+        }
1136
+        $appData = self::getAppInfo($appId);
1137
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1138
+        if (file_exists($appPath . '/appinfo/database.xml')) {
1139
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1140
+        }
1141
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1142
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1143
+        unset(self::$appVersion[$appId]);
1144
+        // run upgrade code
1145
+        if (file_exists($appPath . '/appinfo/update.php')) {
1146
+            self::loadApp($appId);
1147
+            include $appPath . '/appinfo/update.php';
1148
+        }
1149
+        self::setupBackgroundJobs($appData['background-jobs']);
1150
+        if(isset($appData['settings']) && is_array($appData['settings'])) {
1151
+            $appPath = self::getAppPath($appId);
1152
+            self::registerAutoloading($appId, $appPath);
1153
+            \OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1154
+        }
1155
+
1156
+        //set remote/public handlers
1157
+        if (array_key_exists('ocsid', $appData)) {
1158
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1159
+        } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1160
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1161
+        }
1162
+        foreach ($appData['remote'] as $name => $path) {
1163
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1164
+        }
1165
+        foreach ($appData['public'] as $name => $path) {
1166
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1167
+        }
1168
+
1169
+        self::setAppTypes($appId);
1170
+
1171
+        $version = \OC_App::getAppVersion($appId);
1172
+        \OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1173
+
1174
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1175
+            ManagerEvent::EVENT_APP_UPDATE, $appId
1176
+        ));
1177
+
1178
+        return true;
1179
+    }
1180
+
1181
+    /**
1182
+     * @param string $appId
1183
+     * @param string[] $steps
1184
+     * @throws \OC\NeedsUpdateException
1185
+     */
1186
+    public static function executeRepairSteps($appId, array $steps) {
1187
+        if (empty($steps)) {
1188
+            return;
1189
+        }
1190
+        // load the app
1191
+        self::loadApp($appId);
1192
+
1193
+        $dispatcher = OC::$server->getEventDispatcher();
1194
+
1195
+        // load the steps
1196
+        $r = new Repair([], $dispatcher);
1197
+        foreach ($steps as $step) {
1198
+            try {
1199
+                $r->addStep($step);
1200
+            } catch (Exception $ex) {
1201
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1202
+                \OC::$server->getLogger()->logException($ex);
1203
+            }
1204
+        }
1205
+        // run the steps
1206
+        $r->run();
1207
+    }
1208
+
1209
+    public static function setupBackgroundJobs(array $jobs) {
1210
+        $queue = \OC::$server->getJobList();
1211
+        foreach ($jobs as $job) {
1212
+            $queue->add($job);
1213
+        }
1214
+    }
1215
+
1216
+    /**
1217
+     * @param string $appId
1218
+     * @param string[] $steps
1219
+     */
1220
+    private static function setupLiveMigrations($appId, array $steps) {
1221
+        $queue = \OC::$server->getJobList();
1222
+        foreach ($steps as $step) {
1223
+            $queue->add('OC\Migration\BackgroundRepair', [
1224
+                'app' => $appId,
1225
+                'step' => $step]);
1226
+        }
1227
+    }
1228
+
1229
+    /**
1230
+     * @param string $appId
1231
+     * @return \OC\Files\View|false
1232
+     */
1233
+    public static function getStorage($appId) {
1234
+        if (OC_App::isEnabled($appId)) { //sanity check
1235
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1236
+                $view = new \OC\Files\View('/' . OC_User::getUser());
1237
+                if (!$view->file_exists($appId)) {
1238
+                    $view->mkdir($appId);
1239
+                }
1240
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1241
+            } else {
1242
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1243
+                return false;
1244
+            }
1245
+        } else {
1246
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1247
+            return false;
1248
+        }
1249
+    }
1250
+
1251
+    protected static function findBestL10NOption($options, $lang) {
1252
+        $fallback = $similarLangFallback = $englishFallback = false;
1253
+
1254
+        $lang = strtolower($lang);
1255
+        $similarLang = $lang;
1256
+        if (strpos($similarLang, '_')) {
1257
+            // For "de_DE" we want to find "de" and the other way around
1258
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1259
+        }
1260
+
1261
+        foreach ($options as $option) {
1262
+            if (is_array($option)) {
1263
+                if ($fallback === false) {
1264
+                    $fallback = $option['@value'];
1265
+                }
1266
+
1267
+                if (!isset($option['@attributes']['lang'])) {
1268
+                    continue;
1269
+                }
1270
+
1271
+                $attributeLang = strtolower($option['@attributes']['lang']);
1272
+                if ($attributeLang === $lang) {
1273
+                    return $option['@value'];
1274
+                }
1275
+
1276
+                if ($attributeLang === $similarLang) {
1277
+                    $similarLangFallback = $option['@value'];
1278
+                } else if (strpos($attributeLang, $similarLang . '_') === 0) {
1279
+                    if ($similarLangFallback === false) {
1280
+                        $similarLangFallback =  $option['@value'];
1281
+                    }
1282
+                }
1283
+            } else {
1284
+                $englishFallback = $option;
1285
+            }
1286
+        }
1287
+
1288
+        if ($similarLangFallback !== false) {
1289
+            return $similarLangFallback;
1290
+        } else if ($englishFallback !== false) {
1291
+            return $englishFallback;
1292
+        }
1293
+        return (string) $fallback;
1294
+    }
1295
+
1296
+    /**
1297
+     * parses the app data array and enhanced the 'description' value
1298
+     *
1299
+     * @param array $data the app data
1300
+     * @param string $lang
1301
+     * @return array improved app data
1302
+     */
1303
+    public static function parseAppInfo(array $data, $lang = null) {
1304
+
1305
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1306
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1307
+        }
1308
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1309
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1310
+        }
1311
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1312
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1313
+        } else if (isset($data['description']) && is_string($data['description'])) {
1314
+            $data['description'] = trim($data['description']);
1315
+        } else  {
1316
+            $data['description'] = '';
1317
+        }
1318
+
1319
+        return $data;
1320
+    }
1321
+
1322
+    /**
1323
+     * @param \OCP\IConfig $config
1324
+     * @param \OCP\IL10N $l
1325
+     * @param array $info
1326
+     * @throws \Exception
1327
+     */
1328
+    protected static function checkAppDependencies($config, $l, $info) {
1329
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1330
+        $missing = $dependencyAnalyzer->analyze($info);
1331
+        if (!empty($missing)) {
1332
+            $missingMsg = join(PHP_EOL, $missing);
1333
+            throw new \Exception(
1334
+                $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1335
+                    [$info['name'], $missingMsg]
1336
+                )
1337
+            );
1338
+        }
1339
+    }
1340 1340
 }
Please login to merge, or discard this patch.
Spacing   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -111,9 +111,9 @@  discard block
 block discarded – undo
111 111
 		$apps = self::getEnabledApps();
112 112
 
113 113
 		// Add each apps' folder as allowed class path
114
-		foreach($apps as $app) {
114
+		foreach ($apps as $app) {
115 115
 			$path = self::getAppPath($app);
116
-			if($path !== false) {
116
+			if ($path !== false) {
117 117
 				self::registerAutoloading($app, $path);
118 118
 			}
119 119
 		}
@@ -138,15 +138,15 @@  discard block
 block discarded – undo
138 138
 	public static function loadApp($app) {
139 139
 		self::$loadedApps[] = $app;
140 140
 		$appPath = self::getAppPath($app);
141
-		if($appPath === false) {
141
+		if ($appPath === false) {
142 142
 			return;
143 143
 		}
144 144
 
145 145
 		// in case someone calls loadApp() directly
146 146
 		self::registerAutoloading($app, $appPath);
147 147
 
148
-		if (is_file($appPath . '/appinfo/app.php')) {
149
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
148
+		if (is_file($appPath.'/appinfo/app.php')) {
149
+			\OC::$server->getEventLogger()->start('load_app_'.$app, 'Load app: '.$app);
150 150
 			self::requireAppFile($app);
151 151
 			if (self::isType($app, array('authentication'))) {
152 152
 				// since authentication apps affect the "is app enabled for group" check,
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 				// enabled for groups
156 156
 				self::$enabledAppsCache = array();
157 157
 			}
158
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
158
+			\OC::$server->getEventLogger()->end('load_app_'.$app);
159 159
 		}
160 160
 
161 161
 		$info = self::getAppInfo($app);
@@ -182,17 +182,17 @@  discard block
 block discarded – undo
182 182
 	 * @param string $path
183 183
 	 */
184 184
 	public static function registerAutoloading($app, $path) {
185
-		$key = $app . '-' . $path;
186
-		if(isset(self::$alreadyRegistered[$key])) {
185
+		$key = $app.'-'.$path;
186
+		if (isset(self::$alreadyRegistered[$key])) {
187 187
 			return;
188 188
 		}
189 189
 		self::$alreadyRegistered[$key] = true;
190 190
 		// Register on PSR-4 composer autoloader
191 191
 		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
192 192
 		\OC::$server->registerNamespace($app, $appNamespace);
193
-		\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
193
+		\OC::$composerAutoloader->addPsr4($appNamespace.'\\', $path.'/lib/', true);
194 194
 		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
195
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
195
+			\OC::$composerAutoloader->addPsr4($appNamespace.'\\Tests\\', $path.'/tests/', true);
196 196
 		}
197 197
 
198 198
 		// Register on legacy autoloader
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 	private static function requireAppFile($app) {
208 208
 		try {
209 209
 			// encapsulated here to avoid variable scope conflicts
210
-			require_once $app . '/appinfo/app.php';
210
+			require_once $app.'/appinfo/app.php';
211 211
 		} catch (Error $ex) {
212 212
 			\OC::$server->getLogger()->logException($ex);
213 213
 			$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 	 */
262 262
 	public static function setAppTypes($app) {
263 263
 		$appData = self::getAppInfo($app);
264
-		if(!is_array($appData)) {
264
+		if (!is_array($appData)) {
265 265
 			return;
266 266
 		}
267 267
 
@@ -325,8 +325,8 @@  discard block
 block discarded – undo
325 325
 		} else {
326 326
 			$apps = $appManager->getEnabledAppsForUser($user);
327 327
 		}
328
-		$apps = array_filter($apps, function ($app) {
329
-			return $app !== 'files';//we add this manually
328
+		$apps = array_filter($apps, function($app) {
329
+			return $app !== 'files'; //we add this manually
330 330
 		});
331 331
 		sort($apps);
332 332
 		array_unshift($apps, 'files');
@@ -370,7 +370,7 @@  discard block
 block discarded – undo
370 370
 		);
371 371
 		$isDownloaded = $installer->isDownloaded($appId);
372 372
 
373
-		if(!$isDownloaded) {
373
+		if (!$isDownloaded) {
374 374
 			$installer->downloadApp($appId);
375 375
 		}
376 376
 
@@ -408,7 +408,7 @@  discard block
 block discarded – undo
408 408
 		}
409 409
 
410 410
 		$info = self::getAppInfo($appId);
411
-		if(isset($info['settings']) && is_array($info['settings'])) {
411
+		if (isset($info['settings']) && is_array($info['settings'])) {
412 412
 			$appPath = self::getAppPath($appId);
413 413
 			self::registerAutoloading($appId, $appPath);
414 414
 			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -487,15 +487,15 @@  discard block
 block discarded – undo
487 487
 		}
488 488
 
489 489
 		$headerIconCount = 7;
490
-		if($activeAppIndex > ($headerIconCount-1)) {
490
+		if ($activeAppIndex > ($headerIconCount - 1)) {
491 491
 			$active = $list[$activeAppIndex];
492
-			$lastInHeader = $list[$headerIconCount-1];
493
-			$list[$headerIconCount-1] = $active;
492
+			$lastInHeader = $list[$headerIconCount - 1];
493
+			$list[$headerIconCount - 1] = $active;
494 494
 			$list[$activeAppIndex] = $lastInHeader;
495 495
 		}
496 496
 
497 497
 		foreach ($list as $index => &$navEntry) {
498
-			if($index >= $headerIconCount) {
498
+			if ($index >= $headerIconCount) {
499 499
 				$navEntry['showInHeader'] = false;
500 500
 			}
501 501
 		}
@@ -524,10 +524,10 @@  discard block
 block discarded – undo
524 524
 
525 525
 		$headerIconCount = 7;
526 526
 		// move active item to last position
527
-		if($activeAppIndex > ($headerIconCount-1)) {
527
+		if ($activeAppIndex > ($headerIconCount - 1)) {
528 528
 			$active = $list[$activeAppIndex];
529
-			$lastInHeader = $list[$headerIconCount-1];
530
-			$list[$headerIconCount-1] = $active;
529
+			$lastInHeader = $list[$headerIconCount - 1];
530
+			$list[$headerIconCount - 1] = $active;
531 531
 			$list[$activeAppIndex] = $lastInHeader;
532 532
 		}
533 533
 		$list = array_slice($list, 0, $headerIconCount);
@@ -564,7 +564,7 @@  discard block
 block discarded – undo
564 564
 	 */
565 565
 	public static function findAppInDirectories($appId) {
566 566
 		$sanitizedAppId = self::cleanAppId($appId);
567
-		if($sanitizedAppId !== $appId) {
567
+		if ($sanitizedAppId !== $appId) {
568 568
 			return false;
569 569
 		}
570 570
 		static $app_dir = array();
@@ -575,7 +575,7 @@  discard block
 block discarded – undo
575 575
 
576 576
 		$possibleApps = array();
577 577
 		foreach (OC::$APPSROOTS as $dir) {
578
-			if (file_exists($dir['path'] . '/' . $appId)) {
578
+			if (file_exists($dir['path'].'/'.$appId)) {
579 579
 				$possibleApps[] = $dir;
580 580
 			}
581 581
 		}
@@ -616,7 +616,7 @@  discard block
 block discarded – undo
616 616
 		}
617 617
 
618 618
 		if (($dir = self::findAppInDirectories($appId)) != false) {
619
-			return $dir['path'] . '/' . $appId;
619
+			return $dir['path'].'/'.$appId;
620 620
 		}
621 621
 		return false;
622 622
 	}
@@ -630,7 +630,7 @@  discard block
 block discarded – undo
630 630
 	 */
631 631
 	public static function getAppWebPath($appId) {
632 632
 		if (($dir = self::findAppInDirectories($appId)) != false) {
633
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
633
+			return OC::$WEBROOT.$dir['url'].'/'.$appId;
634 634
 		}
635 635
 		return false;
636 636
 	}
@@ -643,7 +643,7 @@  discard block
 block discarded – undo
643 643
 	 * @return string
644 644
 	 */
645 645
 	public static function getAppVersion($appId, $useCache = true) {
646
-		if($useCache && isset(self::$appVersion[$appId])) {
646
+		if ($useCache && isset(self::$appVersion[$appId])) {
647 647
 			return self::$appVersion[$appId];
648 648
 		}
649 649
 
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
 	 * @return string
660 660
 	 */
661 661
 	public static function getAppVersionByPath($path) {
662
-		$infoFile = $path . '/appinfo/info.xml';
662
+		$infoFile = $path.'/appinfo/info.xml';
663 663
 		$appData = self::getAppInfo($infoFile, true);
664 664
 		return isset($appData['version']) ? $appData['version'] : '';
665 665
 	}
@@ -682,10 +682,10 @@  discard block
 block discarded – undo
682 682
 				return self::$appInfo[$appId];
683 683
 			}
684 684
 			$appPath = self::getAppPath($appId);
685
-			if($appPath === false) {
685
+			if ($appPath === false) {
686 686
 				return null;
687 687
 			}
688
-			$file = $appPath . '/appinfo/info.xml';
688
+			$file = $appPath.'/appinfo/info.xml';
689 689
 		}
690 690
 
691 691
 		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->create('core.appinfo'));
@@ -694,9 +694,9 @@  discard block
 block discarded – undo
694 694
 		if (is_array($data)) {
695 695
 			$data = OC_App::parseAppInfo($data, $lang);
696 696
 		}
697
-		if(isset($data['ocsid'])) {
697
+		if (isset($data['ocsid'])) {
698 698
 			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
699
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
699
+			if ($storedId !== '' && $storedId !== $data['ocsid']) {
700 700
 				$data['ocsid'] = $storedId;
701 701
 			}
702 702
 		}
@@ -803,7 +803,7 @@  discard block
 block discarded – undo
803 803
 	 * @param string $page
804 804
 	 */
805 805
 	public static function registerAdmin($app, $page) {
806
-		self::$adminForms[] = $app . '/' . $page . '.php';
806
+		self::$adminForms[] = $app.'/'.$page.'.php';
807 807
 	}
808 808
 
809 809
 	/**
@@ -812,7 +812,7 @@  discard block
 block discarded – undo
812 812
 	 * @param string $page
813 813
 	 */
814 814
 	public static function registerPersonal($app, $page) {
815
-		self::$personalForms[] = $app . '/' . $page . '.php';
815
+		self::$personalForms[] = $app.'/'.$page.'.php';
816 816
 	}
817 817
 
818 818
 	/**
@@ -841,7 +841,7 @@  discard block
 block discarded – undo
841 841
 
842 842
 		foreach (OC::$APPSROOTS as $apps_dir) {
843 843
 			if (!is_readable($apps_dir['path'])) {
844
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
844
+				\OCP\Util::writeLog('core', 'unable to read app folder : '.$apps_dir['path'], \OCP\Util::WARN);
845 845
 				continue;
846 846
 			}
847 847
 			$dh = opendir($apps_dir['path']);
@@ -849,7 +849,7 @@  discard block
 block discarded – undo
849 849
 			if (is_resource($dh)) {
850 850
 				while (($file = readdir($dh)) !== false) {
851 851
 
852
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
852
+					if ($file[0] != '.' and is_dir($apps_dir['path'].'/'.$file) and is_file($apps_dir['path'].'/'.$file.'/appinfo/info.xml')) {
853 853
 
854 854
 						$apps[] = $file;
855 855
 					}
@@ -879,12 +879,12 @@  discard block
 block discarded – undo
879 879
 
880 880
 				$info = OC_App::getAppInfo($app, false, $langCode);
881 881
 				if (!is_array($info)) {
882
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
882
+					\OCP\Util::writeLog('core', 'Could not read app info file for app "'.$app.'"', \OCP\Util::ERROR);
883 883
 					continue;
884 884
 				}
885 885
 
886 886
 				if (!isset($info['name'])) {
887
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
887
+					\OCP\Util::writeLog('core', 'App id "'.$app.'" has no name in appinfo', \OCP\Util::ERROR);
888 888
 					continue;
889 889
 				}
890 890
 
@@ -911,13 +911,13 @@  discard block
 block discarded – undo
911 911
 				}
912 912
 
913 913
 				$appPath = self::getAppPath($app);
914
-				if($appPath !== false) {
915
-					$appIcon = $appPath . '/img/' . $app . '.svg';
914
+				if ($appPath !== false) {
915
+					$appIcon = $appPath.'/img/'.$app.'.svg';
916 916
 					if (file_exists($appIcon)) {
917
-						$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app . '.svg');
917
+						$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, $app.'.svg');
918 918
 						$info['previewAsIcon'] = true;
919 919
 					} else {
920
-						$appIcon = $appPath . '/img/app.svg';
920
+						$appIcon = $appPath.'/img/app.svg';
921 921
 						if (file_exists($appIcon)) {
922 922
 							$info['preview'] = \OC::$server->getURLGenerator()->imagePath($app, 'app.svg');
923 923
 							$info['previewAsIcon'] = true;
@@ -951,9 +951,9 @@  discard block
 block discarded – undo
951 951
 	 * @return string|false
952 952
 	 */
953 953
 	public static function getInternalAppIdByOcs($ocsID) {
954
-		if(is_numeric($ocsID)) {
954
+		if (is_numeric($ocsID)) {
955 955
 			$idArray = \OC::$server->getAppConfig()->getValues(false, 'ocsid');
956
-			if(array_search($ocsID, $idArray)) {
956
+			if (array_search($ocsID, $idArray)) {
957 957
 				return array_search($ocsID, $idArray);
958 958
 			}
959 959
 		}
@@ -1057,7 +1057,7 @@  discard block
 block discarded – undo
1057 1057
 	public static function getAppVersions() {
1058 1058
 		static $versions;
1059 1059
 
1060
-		if(!$versions) {
1060
+		if (!$versions) {
1061 1061
 			$appConfig = \OC::$server->getAppConfig();
1062 1062
 			$versions = $appConfig->getValues(false, 'installed_version');
1063 1063
 		}
@@ -1079,7 +1079,7 @@  discard block
 block discarded – undo
1079 1079
 		if ($app !== false) {
1080 1080
 			// check if the app is compatible with this version of ownCloud
1081 1081
 			$info = self::getAppInfo($app);
1082
-			if(!is_array($info)) {
1082
+			if (!is_array($info)) {
1083 1083
 				throw new \Exception(
1084 1084
 					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1085 1085
 						[$info['name']]
@@ -1104,7 +1104,7 @@  discard block
 block discarded – undo
1104 1104
 				$config->setAppValue($app, 'ocsid', $appData['id']);
1105 1105
 			}
1106 1106
 
1107
-			if(isset($info['settings']) && is_array($info['settings'])) {
1107
+			if (isset($info['settings']) && is_array($info['settings'])) {
1108 1108
 				$appPath = self::getAppPath($app);
1109 1109
 				self::registerAutoloading($app, $appPath);
1110 1110
 				\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -1112,7 +1112,7 @@  discard block
 block discarded – undo
1112 1112
 
1113 1113
 			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1114 1114
 		} else {
1115
-			if(empty($appName) ) {
1115
+			if (empty($appName)) {
1116 1116
 				throw new \Exception($l->t("No app name specified"));
1117 1117
 			} else {
1118 1118
 				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
@@ -1130,24 +1130,24 @@  discard block
 block discarded – undo
1130 1130
 	 */
1131 1131
 	public static function updateApp($appId) {
1132 1132
 		$appPath = self::getAppPath($appId);
1133
-		if($appPath === false) {
1133
+		if ($appPath === false) {
1134 1134
 			return false;
1135 1135
 		}
1136 1136
 		$appData = self::getAppInfo($appId);
1137 1137
 		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1138
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1139
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1138
+		if (file_exists($appPath.'/appinfo/database.xml')) {
1139
+			OC_DB::updateDbFromStructure($appPath.'/appinfo/database.xml');
1140 1140
 		}
1141 1141
 		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1142 1142
 		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1143 1143
 		unset(self::$appVersion[$appId]);
1144 1144
 		// run upgrade code
1145
-		if (file_exists($appPath . '/appinfo/update.php')) {
1145
+		if (file_exists($appPath.'/appinfo/update.php')) {
1146 1146
 			self::loadApp($appId);
1147
-			include $appPath . '/appinfo/update.php';
1147
+			include $appPath.'/appinfo/update.php';
1148 1148
 		}
1149 1149
 		self::setupBackgroundJobs($appData['background-jobs']);
1150
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
1150
+		if (isset($appData['settings']) && is_array($appData['settings'])) {
1151 1151
 			$appPath = self::getAppPath($appId);
1152 1152
 			self::registerAutoloading($appId, $appPath);
1153 1153
 			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
@@ -1156,14 +1156,14 @@  discard block
 block discarded – undo
1156 1156
 		//set remote/public handlers
1157 1157
 		if (array_key_exists('ocsid', $appData)) {
1158 1158
 			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1159
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1159
+		} elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1160 1160
 			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1161 1161
 		}
1162 1162
 		foreach ($appData['remote'] as $name => $path) {
1163
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1163
+			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $appId.'/'.$path);
1164 1164
 		}
1165 1165
 		foreach ($appData['public'] as $name => $path) {
1166
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1166
+			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $appId.'/'.$path);
1167 1167
 		}
1168 1168
 
1169 1169
 		self::setAppTypes($appId);
@@ -1233,17 +1233,17 @@  discard block
 block discarded – undo
1233 1233
 	public static function getStorage($appId) {
1234 1234
 		if (OC_App::isEnabled($appId)) { //sanity check
1235 1235
 			if (\OC::$server->getUserSession()->isLoggedIn()) {
1236
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1236
+				$view = new \OC\Files\View('/'.OC_User::getUser());
1237 1237
 				if (!$view->file_exists($appId)) {
1238 1238
 					$view->mkdir($appId);
1239 1239
 				}
1240
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1240
+				return new \OC\Files\View('/'.OC_User::getUser().'/'.$appId);
1241 1241
 			} else {
1242
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1242
+				\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.', user not logged in', \OCP\Util::ERROR);
1243 1243
 				return false;
1244 1244
 			}
1245 1245
 		} else {
1246
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1246
+			\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.' not enabled', \OCP\Util::ERROR);
1247 1247
 			return false;
1248 1248
 		}
1249 1249
 	}
@@ -1275,9 +1275,9 @@  discard block
 block discarded – undo
1275 1275
 
1276 1276
 				if ($attributeLang === $similarLang) {
1277 1277
 					$similarLangFallback = $option['@value'];
1278
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1278
+				} else if (strpos($attributeLang, $similarLang.'_') === 0) {
1279 1279
 					if ($similarLangFallback === false) {
1280
-						$similarLangFallback =  $option['@value'];
1280
+						$similarLangFallback = $option['@value'];
1281 1281
 					}
1282 1282
 				}
1283 1283
 			} else {
@@ -1312,7 +1312,7 @@  discard block
 block discarded – undo
1312 1312
 			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1313 1313
 		} else if (isset($data['description']) && is_string($data['description'])) {
1314 1314
 			$data['description'] = trim($data['description']);
1315
-		} else  {
1315
+		} else {
1316 1316
 			$data['description'] = '';
1317 1317
 		}
1318 1318
 
Please login to merge, or discard this patch.
lib/private/L10N/Factory.php 3 patches
Doc Comments   +5 added lines patch added patch discarded remove patch
@@ -318,6 +318,11 @@
 block discarded – undo
318 318
 	 */
319 319
 	// FIXME This method is only public, until OC_L10N does not need it anymore,
320 320
 	// FIXME This is also the reason, why it is not in the public interface
321
+
322
+	/**
323
+	 * @param string $app
324
+	 * @param string $lang
325
+	 */
321 326
 	public function getL10nFilesForApp($app, $lang) {
322 327
 		$languageFiles = [];
323 328
 
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -131,9 +131,9 @@  discard block
 block discarded – undo
131 131
 		 *
132 132
 		 * @link https://github.com/owncloud/core/issues/21955
133 133
 		 */
134
-		if($this->config->getSystemValue('installed', false)) {
135
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
136
-			if(!is_null($userId)) {
134
+		if ($this->config->getSystemValue('installed', false)) {
135
+			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() : null;
136
+			if (!is_null($userId)) {
137 137
 				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
138 138
 			} else {
139 139
 				$userLang = null;
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 		// merge with translations from theme
203 203
 		$theme = $this->config->getSystemValue('theme');
204 204
 		if (!empty($theme)) {
205
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
205
+			$themeDir = $this->serverRoot.'/themes/'.$theme.substr($dir, strlen($this->serverRoot));
206 206
 
207 207
 			if (is_dir($themeDir)) {
208 208
 				$files = scandir($themeDir);
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
 	 */
298 298
 	private function isSubDirectory($sub, $parent) {
299 299
 		// Check whether $sub contains no ".."
300
-		if(strpos($sub, '..') !== false) {
300
+		if (strpos($sub, '..') !== false) {
301 301
 			return false;
302 302
 		}
303 303
 
@@ -322,12 +322,12 @@  discard block
 block discarded – undo
322 322
 		$languageFiles = [];
323 323
 
324 324
 		$i18nDir = $this->findL10nDir($app);
325
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
325
+		$transFile = strip_tags($i18nDir).strip_tags($lang).'.json';
326 326
 
327
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
328
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
329
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
330
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
327
+		if (($this->isSubDirectory($transFile, $this->serverRoot.'/core/l10n/')
328
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/lib/l10n/')
329
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/settings/l10n/')
330
+				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app).'/l10n/')
331 331
 			)
332 332
 			&& file_exists($transFile)) {
333 333
 			// load the translations file
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
 		// merge with translations from theme
338 338
 		$theme = $this->config->getSystemValue('theme');
339 339
 		if (!empty($theme)) {
340
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
340
+			$transFile = $this->serverRoot.'/themes/'.$theme.substr($transFile, strlen($this->serverRoot));
341 341
 			if (file_exists($transFile)) {
342 342
 				$languageFiles[] = $transFile;
343 343
 			}
@@ -354,14 +354,14 @@  discard block
 block discarded – undo
354 354
 	 */
355 355
 	protected function findL10nDir($app = null) {
356 356
 		if (in_array($app, ['core', 'lib', 'settings'])) {
357
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
358
-				return $this->serverRoot . '/' . $app . '/l10n/';
357
+			if (file_exists($this->serverRoot.'/'.$app.'/l10n/')) {
358
+				return $this->serverRoot.'/'.$app.'/l10n/';
359 359
 			}
360 360
 		} else if ($app && \OC_App::getAppPath($app) !== false) {
361 361
 			// Check if the app is in the app folder
362
-			return \OC_App::getAppPath($app) . '/l10n/';
362
+			return \OC_App::getAppPath($app).'/l10n/';
363 363
 		}
364
-		return $this->serverRoot . '/core/l10n/';
364
+		return $this->serverRoot.'/core/l10n/';
365 365
 	}
366 366
 
367 367
 
@@ -378,15 +378,15 @@  discard block
 block discarded – undo
378 378
 			return $this->pluralFunctions[$string];
379 379
 		}
380 380
 
381
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
381
+		if (preg_match('/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
382 382
 			// sanitize
383
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
384
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
383
+			$nplurals = preg_replace('/[^0-9]/', '', $matches[1]);
384
+			$plural = preg_replace('#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2]);
385 385
 
386 386
 			$body = str_replace(
387
-				array( 'plural', 'n', '$n$plurals', ),
388
-				array( '$plural', '$n', '$nplurals', ),
389
-				'nplurals='. $nplurals . '; plural=' . $plural
387
+				array('plural', 'n', '$n$plurals',),
388
+				array('$plural', '$n', '$nplurals',),
389
+				'nplurals='.$nplurals.'; plural='.$plural
390 390
 			);
391 391
 
392 392
 			// add parents
@@ -394,9 +394,9 @@  discard block
 block discarded – undo
394 394
 			$body .= ';';
395 395
 			$res = '';
396 396
 			$p = 0;
397
-			for($i = 0; $i < strlen($body); $i++) {
397
+			for ($i = 0; $i < strlen($body); $i++) {
398 398
 				$ch = $body[$i];
399
-				switch ( $ch ) {
399
+				switch ($ch) {
400 400
 					case '?':
401 401
 						$res .= ' ? (';
402 402
 						$p++;
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
 						$res .= ') : (';
406 406
 						break;
407 407
 					case ';':
408
-						$res .= str_repeat( ')', $p ) . ';';
408
+						$res .= str_repeat(')', $p).';';
409 409
 						$p = 0;
410 410
 						break;
411 411
 					default:
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 				}
414 414
 			}
415 415
 
416
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
416
+			$body = $res.'return ($plural>=$nplurals?$nplurals-1:$plural);';
417 417
 			$function = create_function('$n', $body);
418 418
 			$this->pluralFunctions[$string] = $function;
419 419
 			return $function;
Please login to merge, or discard this patch.
Indentation   +369 added lines, -369 removed lines patch added patch discarded remove patch
@@ -40,373 +40,373 @@
 block discarded – undo
40 40
  */
41 41
 class Factory implements IFactory {
42 42
 
43
-	/** @var string */
44
-	protected $requestLanguage = '';
45
-
46
-	/**
47
-	 * cached instances
48
-	 * @var array Structure: Lang => App => \OCP\IL10N
49
-	 */
50
-	protected $instances = [];
51
-
52
-	/**
53
-	 * @var array Structure: App => string[]
54
-	 */
55
-	protected $availableLanguages = [];
56
-
57
-	/**
58
-	 * @var array Structure: string => callable
59
-	 */
60
-	protected $pluralFunctions = [];
61
-
62
-	/** @var IConfig */
63
-	protected $config;
64
-
65
-	/** @var IRequest */
66
-	protected $request;
67
-
68
-	/** @var IUserSession */
69
-	protected $userSession;
70
-
71
-	/** @var string */
72
-	protected $serverRoot;
73
-
74
-	/**
75
-	 * @param IConfig $config
76
-	 * @param IRequest $request
77
-	 * @param IUserSession $userSession
78
-	 * @param string $serverRoot
79
-	 */
80
-	public function __construct(IConfig $config,
81
-								IRequest $request,
82
-								IUserSession $userSession,
83
-								$serverRoot) {
84
-		$this->config = $config;
85
-		$this->request = $request;
86
-		$this->userSession = $userSession;
87
-		$this->serverRoot = $serverRoot;
88
-	}
89
-
90
-	/**
91
-	 * Get a language instance
92
-	 *
93
-	 * @param string $app
94
-	 * @param string|null $lang
95
-	 * @return \OCP\IL10N
96
-	 */
97
-	public function get($app, $lang = null) {
98
-		$app = \OC_App::cleanAppId($app);
99
-		if ($lang !== null) {
100
-			$lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
101
-		}
102
-		if ($lang === null || !$this->languageExists($app, $lang)) {
103
-			$lang = $this->findLanguage($app);
104
-		}
105
-
106
-		if (!isset($this->instances[$lang][$app])) {
107
-			$this->instances[$lang][$app] = new L10N(
108
-				$this, $app, $lang,
109
-				$this->getL10nFilesForApp($app, $lang)
110
-			);
111
-		}
112
-
113
-		return $this->instances[$lang][$app];
114
-	}
115
-
116
-	/**
117
-	 * Find the best language
118
-	 *
119
-	 * @param string|null $app App id or null for core
120
-	 * @return string language If nothing works it returns 'en'
121
-	 */
122
-	public function findLanguage($app = null) {
123
-		if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
124
-			return $this->requestLanguage;
125
-		}
126
-
127
-		/**
128
-		 * At this point ownCloud might not yet be installed and thus the lookup
129
-		 * in the preferences table might fail. For this reason we need to check
130
-		 * whether the instance has already been installed
131
-		 *
132
-		 * @link https://github.com/owncloud/core/issues/21955
133
-		 */
134
-		if($this->config->getSystemValue('installed', false)) {
135
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
136
-			if(!is_null($userId)) {
137
-				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
138
-			} else {
139
-				$userLang = null;
140
-			}
141
-		} else {
142
-			$userId = null;
143
-			$userLang = null;
144
-		}
145
-
146
-		if ($userLang) {
147
-			$this->requestLanguage = $userLang;
148
-			if ($this->languageExists($app, $userLang)) {
149
-				return $userLang;
150
-			}
151
-		}
152
-
153
-		try {
154
-			// Try to get the language from the Request
155
-			$lang = $this->getLanguageFromRequest($app);
156
-			if ($userId !== null && $app === null && !$userLang) {
157
-				$this->config->setUserValue($userId, 'core', 'lang', $lang);
158
-			}
159
-			return $lang;
160
-		} catch (LanguageNotFoundException $e) {
161
-			// Finding language from request failed fall back to default language
162
-			$defaultLanguage = $this->config->getSystemValue('default_language', false);
163
-			if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
164
-				return $defaultLanguage;
165
-			}
166
-		}
167
-
168
-		// We could not find any language so fall back to english
169
-		return 'en';
170
-	}
171
-
172
-	/**
173
-	 * Find all available languages for an app
174
-	 *
175
-	 * @param string|null $app App id or null for core
176
-	 * @return array an array of available languages
177
-	 */
178
-	public function findAvailableLanguages($app = null) {
179
-		$key = $app;
180
-		if ($key === null) {
181
-			$key = 'null';
182
-		}
183
-
184
-		// also works with null as key
185
-		if (!empty($this->availableLanguages[$key])) {
186
-			return $this->availableLanguages[$key];
187
-		}
188
-
189
-		$available = ['en']; //english is always available
190
-		$dir = $this->findL10nDir($app);
191
-		if (is_dir($dir)) {
192
-			$files = scandir($dir);
193
-			if ($files !== false) {
194
-				foreach ($files as $file) {
195
-					if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
196
-						$available[] = substr($file, 0, -5);
197
-					}
198
-				}
199
-			}
200
-		}
201
-
202
-		// merge with translations from theme
203
-		$theme = $this->config->getSystemValue('theme');
204
-		if (!empty($theme)) {
205
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
206
-
207
-			if (is_dir($themeDir)) {
208
-				$files = scandir($themeDir);
209
-				if ($files !== false) {
210
-					foreach ($files as $file) {
211
-						if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
212
-							$available[] = substr($file, 0, -5);
213
-						}
214
-					}
215
-				}
216
-			}
217
-		}
218
-
219
-		$this->availableLanguages[$key] = $available;
220
-		return $available;
221
-	}
222
-
223
-	/**
224
-	 * @param string|null $app App id or null for core
225
-	 * @param string $lang
226
-	 * @return bool
227
-	 */
228
-	public function languageExists($app, $lang) {
229
-		if ($lang === 'en') {//english is always available
230
-			return true;
231
-		}
232
-
233
-		$languages = $this->findAvailableLanguages($app);
234
-		return array_search($lang, $languages) !== false;
235
-	}
236
-
237
-	/**
238
-	 * @param string|null $app
239
-	 * @return string
240
-	 * @throws LanguageNotFoundException
241
-	 */
242
-	private function getLanguageFromRequest($app) {
243
-		$header = $this->request->getHeader('ACCEPT_LANGUAGE');
244
-		if ($header) {
245
-			$available = $this->findAvailableLanguages($app);
246
-
247
-			// E.g. make sure that 'de' is before 'de_DE'.
248
-			sort($available);
249
-
250
-			$preferences = preg_split('/,\s*/', strtolower($header));
251
-			foreach ($preferences as $preference) {
252
-				list($preferred_language) = explode(';', $preference);
253
-				$preferred_language = str_replace('-', '_', $preferred_language);
254
-
255
-				foreach ($available as $available_language) {
256
-					if ($preferred_language === strtolower($available_language)) {
257
-						return $available_language;
258
-					}
259
-				}
260
-
261
-				// Fallback from de_De to de
262
-				foreach ($available as $available_language) {
263
-					if (substr($preferred_language, 0, 2) === $available_language) {
264
-						return $available_language;
265
-					}
266
-				}
267
-			}
268
-		}
269
-
270
-		throw new LanguageNotFoundException();
271
-	}
272
-
273
-	/**
274
-	 * Checks if $sub is a subdirectory of $parent
275
-	 *
276
-	 * @param string $sub
277
-	 * @param string $parent
278
-	 * @return bool
279
-	 */
280
-	private function isSubDirectory($sub, $parent) {
281
-		// Check whether $sub contains no ".."
282
-		if(strpos($sub, '..') !== false) {
283
-			return false;
284
-		}
285
-
286
-		// Check whether $sub is a subdirectory of $parent
287
-		if (strpos($sub, $parent) === 0) {
288
-			return true;
289
-		}
290
-
291
-		return false;
292
-	}
293
-
294
-	/**
295
-	 * Get a list of language files that should be loaded
296
-	 *
297
-	 * @param string $app
298
-	 * @param string $lang
299
-	 * @return string[]
300
-	 */
301
-	// FIXME This method is only public, until OC_L10N does not need it anymore,
302
-	// FIXME This is also the reason, why it is not in the public interface
303
-	public function getL10nFilesForApp($app, $lang) {
304
-		$languageFiles = [];
305
-
306
-		$i18nDir = $this->findL10nDir($app);
307
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
308
-
309
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
310
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
311
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
312
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
313
-			)
314
-			&& file_exists($transFile)) {
315
-			// load the translations file
316
-			$languageFiles[] = $transFile;
317
-		}
318
-
319
-		// merge with translations from theme
320
-		$theme = $this->config->getSystemValue('theme');
321
-		if (!empty($theme)) {
322
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
323
-			if (file_exists($transFile)) {
324
-				$languageFiles[] = $transFile;
325
-			}
326
-		}
327
-
328
-		return $languageFiles;
329
-	}
330
-
331
-	/**
332
-	 * find the l10n directory
333
-	 *
334
-	 * @param string $app App id or empty string for core
335
-	 * @return string directory
336
-	 */
337
-	protected function findL10nDir($app = null) {
338
-		if (in_array($app, ['core', 'lib', 'settings'])) {
339
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
340
-				return $this->serverRoot . '/' . $app . '/l10n/';
341
-			}
342
-		} else if ($app && \OC_App::getAppPath($app) !== false) {
343
-			// Check if the app is in the app folder
344
-			return \OC_App::getAppPath($app) . '/l10n/';
345
-		}
346
-		return $this->serverRoot . '/core/l10n/';
347
-	}
348
-
349
-
350
-	/**
351
-	 * Creates a function from the plural string
352
-	 *
353
-	 * Parts of the code is copied from Habari:
354
-	 * https://github.com/habari/system/blob/master/classes/locale.php
355
-	 * @param string $string
356
-	 * @return string
357
-	 */
358
-	public function createPluralFunction($string) {
359
-		if (isset($this->pluralFunctions[$string])) {
360
-			return $this->pluralFunctions[$string];
361
-		}
362
-
363
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
364
-			// sanitize
365
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
366
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
367
-
368
-			$body = str_replace(
369
-				array( 'plural', 'n', '$n$plurals', ),
370
-				array( '$plural', '$n', '$nplurals', ),
371
-				'nplurals='. $nplurals . '; plural=' . $plural
372
-			);
373
-
374
-			// add parents
375
-			// important since PHP's ternary evaluates from left to right
376
-			$body .= ';';
377
-			$res = '';
378
-			$p = 0;
379
-			for($i = 0; $i < strlen($body); $i++) {
380
-				$ch = $body[$i];
381
-				switch ( $ch ) {
382
-					case '?':
383
-						$res .= ' ? (';
384
-						$p++;
385
-						break;
386
-					case ':':
387
-						$res .= ') : (';
388
-						break;
389
-					case ';':
390
-						$res .= str_repeat( ')', $p ) . ';';
391
-						$p = 0;
392
-						break;
393
-					default:
394
-						$res .= $ch;
395
-				}
396
-			}
397
-
398
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
399
-			$function = create_function('$n', $body);
400
-			$this->pluralFunctions[$string] = $function;
401
-			return $function;
402
-		} else {
403
-			// default: one plural form for all cases but n==1 (english)
404
-			$function = create_function(
405
-				'$n',
406
-				'$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
407
-			);
408
-			$this->pluralFunctions[$string] = $function;
409
-			return $function;
410
-		}
411
-	}
43
+    /** @var string */
44
+    protected $requestLanguage = '';
45
+
46
+    /**
47
+     * cached instances
48
+     * @var array Structure: Lang => App => \OCP\IL10N
49
+     */
50
+    protected $instances = [];
51
+
52
+    /**
53
+     * @var array Structure: App => string[]
54
+     */
55
+    protected $availableLanguages = [];
56
+
57
+    /**
58
+     * @var array Structure: string => callable
59
+     */
60
+    protected $pluralFunctions = [];
61
+
62
+    /** @var IConfig */
63
+    protected $config;
64
+
65
+    /** @var IRequest */
66
+    protected $request;
67
+
68
+    /** @var IUserSession */
69
+    protected $userSession;
70
+
71
+    /** @var string */
72
+    protected $serverRoot;
73
+
74
+    /**
75
+     * @param IConfig $config
76
+     * @param IRequest $request
77
+     * @param IUserSession $userSession
78
+     * @param string $serverRoot
79
+     */
80
+    public function __construct(IConfig $config,
81
+                                IRequest $request,
82
+                                IUserSession $userSession,
83
+                                $serverRoot) {
84
+        $this->config = $config;
85
+        $this->request = $request;
86
+        $this->userSession = $userSession;
87
+        $this->serverRoot = $serverRoot;
88
+    }
89
+
90
+    /**
91
+     * Get a language instance
92
+     *
93
+     * @param string $app
94
+     * @param string|null $lang
95
+     * @return \OCP\IL10N
96
+     */
97
+    public function get($app, $lang = null) {
98
+        $app = \OC_App::cleanAppId($app);
99
+        if ($lang !== null) {
100
+            $lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
101
+        }
102
+        if ($lang === null || !$this->languageExists($app, $lang)) {
103
+            $lang = $this->findLanguage($app);
104
+        }
105
+
106
+        if (!isset($this->instances[$lang][$app])) {
107
+            $this->instances[$lang][$app] = new L10N(
108
+                $this, $app, $lang,
109
+                $this->getL10nFilesForApp($app, $lang)
110
+            );
111
+        }
112
+
113
+        return $this->instances[$lang][$app];
114
+    }
115
+
116
+    /**
117
+     * Find the best language
118
+     *
119
+     * @param string|null $app App id or null for core
120
+     * @return string language If nothing works it returns 'en'
121
+     */
122
+    public function findLanguage($app = null) {
123
+        if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
124
+            return $this->requestLanguage;
125
+        }
126
+
127
+        /**
128
+         * At this point ownCloud might not yet be installed and thus the lookup
129
+         * in the preferences table might fail. For this reason we need to check
130
+         * whether the instance has already been installed
131
+         *
132
+         * @link https://github.com/owncloud/core/issues/21955
133
+         */
134
+        if($this->config->getSystemValue('installed', false)) {
135
+            $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
136
+            if(!is_null($userId)) {
137
+                $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
138
+            } else {
139
+                $userLang = null;
140
+            }
141
+        } else {
142
+            $userId = null;
143
+            $userLang = null;
144
+        }
145
+
146
+        if ($userLang) {
147
+            $this->requestLanguage = $userLang;
148
+            if ($this->languageExists($app, $userLang)) {
149
+                return $userLang;
150
+            }
151
+        }
152
+
153
+        try {
154
+            // Try to get the language from the Request
155
+            $lang = $this->getLanguageFromRequest($app);
156
+            if ($userId !== null && $app === null && !$userLang) {
157
+                $this->config->setUserValue($userId, 'core', 'lang', $lang);
158
+            }
159
+            return $lang;
160
+        } catch (LanguageNotFoundException $e) {
161
+            // Finding language from request failed fall back to default language
162
+            $defaultLanguage = $this->config->getSystemValue('default_language', false);
163
+            if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
164
+                return $defaultLanguage;
165
+            }
166
+        }
167
+
168
+        // We could not find any language so fall back to english
169
+        return 'en';
170
+    }
171
+
172
+    /**
173
+     * Find all available languages for an app
174
+     *
175
+     * @param string|null $app App id or null for core
176
+     * @return array an array of available languages
177
+     */
178
+    public function findAvailableLanguages($app = null) {
179
+        $key = $app;
180
+        if ($key === null) {
181
+            $key = 'null';
182
+        }
183
+
184
+        // also works with null as key
185
+        if (!empty($this->availableLanguages[$key])) {
186
+            return $this->availableLanguages[$key];
187
+        }
188
+
189
+        $available = ['en']; //english is always available
190
+        $dir = $this->findL10nDir($app);
191
+        if (is_dir($dir)) {
192
+            $files = scandir($dir);
193
+            if ($files !== false) {
194
+                foreach ($files as $file) {
195
+                    if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
196
+                        $available[] = substr($file, 0, -5);
197
+                    }
198
+                }
199
+            }
200
+        }
201
+
202
+        // merge with translations from theme
203
+        $theme = $this->config->getSystemValue('theme');
204
+        if (!empty($theme)) {
205
+            $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
206
+
207
+            if (is_dir($themeDir)) {
208
+                $files = scandir($themeDir);
209
+                if ($files !== false) {
210
+                    foreach ($files as $file) {
211
+                        if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
212
+                            $available[] = substr($file, 0, -5);
213
+                        }
214
+                    }
215
+                }
216
+            }
217
+        }
218
+
219
+        $this->availableLanguages[$key] = $available;
220
+        return $available;
221
+    }
222
+
223
+    /**
224
+     * @param string|null $app App id or null for core
225
+     * @param string $lang
226
+     * @return bool
227
+     */
228
+    public function languageExists($app, $lang) {
229
+        if ($lang === 'en') {//english is always available
230
+            return true;
231
+        }
232
+
233
+        $languages = $this->findAvailableLanguages($app);
234
+        return array_search($lang, $languages) !== false;
235
+    }
236
+
237
+    /**
238
+     * @param string|null $app
239
+     * @return string
240
+     * @throws LanguageNotFoundException
241
+     */
242
+    private function getLanguageFromRequest($app) {
243
+        $header = $this->request->getHeader('ACCEPT_LANGUAGE');
244
+        if ($header) {
245
+            $available = $this->findAvailableLanguages($app);
246
+
247
+            // E.g. make sure that 'de' is before 'de_DE'.
248
+            sort($available);
249
+
250
+            $preferences = preg_split('/,\s*/', strtolower($header));
251
+            foreach ($preferences as $preference) {
252
+                list($preferred_language) = explode(';', $preference);
253
+                $preferred_language = str_replace('-', '_', $preferred_language);
254
+
255
+                foreach ($available as $available_language) {
256
+                    if ($preferred_language === strtolower($available_language)) {
257
+                        return $available_language;
258
+                    }
259
+                }
260
+
261
+                // Fallback from de_De to de
262
+                foreach ($available as $available_language) {
263
+                    if (substr($preferred_language, 0, 2) === $available_language) {
264
+                        return $available_language;
265
+                    }
266
+                }
267
+            }
268
+        }
269
+
270
+        throw new LanguageNotFoundException();
271
+    }
272
+
273
+    /**
274
+     * Checks if $sub is a subdirectory of $parent
275
+     *
276
+     * @param string $sub
277
+     * @param string $parent
278
+     * @return bool
279
+     */
280
+    private function isSubDirectory($sub, $parent) {
281
+        // Check whether $sub contains no ".."
282
+        if(strpos($sub, '..') !== false) {
283
+            return false;
284
+        }
285
+
286
+        // Check whether $sub is a subdirectory of $parent
287
+        if (strpos($sub, $parent) === 0) {
288
+            return true;
289
+        }
290
+
291
+        return false;
292
+    }
293
+
294
+    /**
295
+     * Get a list of language files that should be loaded
296
+     *
297
+     * @param string $app
298
+     * @param string $lang
299
+     * @return string[]
300
+     */
301
+    // FIXME This method is only public, until OC_L10N does not need it anymore,
302
+    // FIXME This is also the reason, why it is not in the public interface
303
+    public function getL10nFilesForApp($app, $lang) {
304
+        $languageFiles = [];
305
+
306
+        $i18nDir = $this->findL10nDir($app);
307
+        $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
308
+
309
+        if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
310
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
311
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
312
+                || $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
313
+            )
314
+            && file_exists($transFile)) {
315
+            // load the translations file
316
+            $languageFiles[] = $transFile;
317
+        }
318
+
319
+        // merge with translations from theme
320
+        $theme = $this->config->getSystemValue('theme');
321
+        if (!empty($theme)) {
322
+            $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
323
+            if (file_exists($transFile)) {
324
+                $languageFiles[] = $transFile;
325
+            }
326
+        }
327
+
328
+        return $languageFiles;
329
+    }
330
+
331
+    /**
332
+     * find the l10n directory
333
+     *
334
+     * @param string $app App id or empty string for core
335
+     * @return string directory
336
+     */
337
+    protected function findL10nDir($app = null) {
338
+        if (in_array($app, ['core', 'lib', 'settings'])) {
339
+            if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
340
+                return $this->serverRoot . '/' . $app . '/l10n/';
341
+            }
342
+        } else if ($app && \OC_App::getAppPath($app) !== false) {
343
+            // Check if the app is in the app folder
344
+            return \OC_App::getAppPath($app) . '/l10n/';
345
+        }
346
+        return $this->serverRoot . '/core/l10n/';
347
+    }
348
+
349
+
350
+    /**
351
+     * Creates a function from the plural string
352
+     *
353
+     * Parts of the code is copied from Habari:
354
+     * https://github.com/habari/system/blob/master/classes/locale.php
355
+     * @param string $string
356
+     * @return string
357
+     */
358
+    public function createPluralFunction($string) {
359
+        if (isset($this->pluralFunctions[$string])) {
360
+            return $this->pluralFunctions[$string];
361
+        }
362
+
363
+        if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
364
+            // sanitize
365
+            $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
366
+            $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
367
+
368
+            $body = str_replace(
369
+                array( 'plural', 'n', '$n$plurals', ),
370
+                array( '$plural', '$n', '$nplurals', ),
371
+                'nplurals='. $nplurals . '; plural=' . $plural
372
+            );
373
+
374
+            // add parents
375
+            // important since PHP's ternary evaluates from left to right
376
+            $body .= ';';
377
+            $res = '';
378
+            $p = 0;
379
+            for($i = 0; $i < strlen($body); $i++) {
380
+                $ch = $body[$i];
381
+                switch ( $ch ) {
382
+                    case '?':
383
+                        $res .= ' ? (';
384
+                        $p++;
385
+                        break;
386
+                    case ':':
387
+                        $res .= ') : (';
388
+                        break;
389
+                    case ';':
390
+                        $res .= str_repeat( ')', $p ) . ';';
391
+                        $p = 0;
392
+                        break;
393
+                    default:
394
+                        $res .= $ch;
395
+                }
396
+            }
397
+
398
+            $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
399
+            $function = create_function('$n', $body);
400
+            $this->pluralFunctions[$string] = $function;
401
+            return $function;
402
+        } else {
403
+            // default: one plural form for all cases but n==1 (english)
404
+            $function = create_function(
405
+                '$n',
406
+                '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
407
+            );
408
+            $this->pluralFunctions[$string] = $function;
409
+            return $function;
410
+        }
411
+    }
412 412
 }
Please login to merge, or discard this patch.
lib/private/Installer.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -45,7 +45,6 @@
 block discarded – undo
45 45
 use OC\App\CodeChecker\CodeChecker;
46 46
 use OC\App\CodeChecker\EmptyCheck;
47 47
 use OC\App\CodeChecker\PrivateCheck;
48
-use OC\Archive\Archive;
49 48
 use OC\Archive\TAR;
50 49
 use OC_App;
51 50
 use OC_DB;
Please login to merge, or discard this patch.
Indentation   +489 added lines, -489 removed lines patch added patch discarded remove patch
@@ -60,493 +60,493 @@
 block discarded – undo
60 60
  * This class provides the functionality needed to install, update and remove apps
61 61
  */
62 62
 class Installer {
63
-	/** @var AppFetcher */
64
-	private $appFetcher;
65
-	/** @var IClientService */
66
-	private $clientService;
67
-	/** @var ITempManager */
68
-	private $tempManager;
69
-	/** @var ILogger */
70
-	private $logger;
71
-
72
-	/**
73
-	 * @param AppFetcher $appFetcher
74
-	 * @param IClientService $clientService
75
-	 * @param ITempManager $tempManager
76
-	 * @param ILogger $logger
77
-	 */
78
-	public function __construct(AppFetcher $appFetcher,
79
-								IClientService $clientService,
80
-								ITempManager $tempManager,
81
-								ILogger $logger) {
82
-		$this->appFetcher = $appFetcher;
83
-		$this->clientService = $clientService;
84
-		$this->tempManager = $tempManager;
85
-		$this->logger = $logger;
86
-	}
87
-
88
-	/**
89
-	 * Installs an app that is located in one of the app folders already
90
-	 *
91
-	 * @param string $appId App to install
92
-	 * @throws \Exception
93
-	 * @return integer
94
-	 */
95
-	public function installApp($appId) {
96
-		$app = \OC_App::findAppInDirectories($appId);
97
-		if($app === false) {
98
-			throw new \Exception('App not found in any app directory');
99
-		}
100
-
101
-		$basedir = $app['path'].'/'.$appId;
102
-		$info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
103
-
104
-		//install the database
105
-		if(is_file($basedir.'/appinfo/database.xml')) {
106
-			if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
107
-				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
108
-			} else {
109
-				OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
110
-			}
111
-		}
112
-
113
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
114
-
115
-		//run appinfo/install.php
116
-		if((!isset($data['noinstall']) or $data['noinstall']==false)) {
117
-			self::includeAppScript($basedir . '/appinfo/install.php');
118
-		}
119
-
120
-		$appData = OC_App::getAppInfo($appId);
121
-		OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
122
-
123
-		//set the installed version
124
-		\OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
125
-		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
126
-
127
-		//set remote/public handlers
128
-		foreach($info['remote'] as $name=>$path) {
129
-			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
130
-		}
131
-		foreach($info['public'] as $name=>$path) {
132
-			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
133
-		}
134
-
135
-		OC_App::setAppTypes($info['id']);
136
-
137
-		return $info['id'];
138
-	}
139
-
140
-	/**
141
-	 * @brief checks whether or not an app is installed
142
-	 * @param string $app app
143
-	 * @returns bool
144
-	 *
145
-	 * Checks whether or not an app is installed, i.e. registered in apps table.
146
-	 */
147
-	public static function isInstalled( $app ) {
148
-		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
149
-	}
150
-
151
-	/**
152
-	 * Updates the specified app from the appstore
153
-	 *
154
-	 * @param string $appId
155
-	 * @return bool
156
-	 */
157
-	public function updateAppstoreApp($appId) {
158
-		if(self::isUpdateAvailable($appId, $this->appFetcher)) {
159
-			try {
160
-				$this->downloadApp($appId);
161
-			} catch (\Exception $e) {
162
-				$this->logger->error($e->getMessage(), ['app' => 'core']);
163
-				return false;
164
-			}
165
-			return OC_App::updateApp($appId);
166
-		}
167
-
168
-		return false;
169
-	}
170
-
171
-	/**
172
-	 * Downloads an app and puts it into the app directory
173
-	 *
174
-	 * @param string $appId
175
-	 *
176
-	 * @throws \Exception If the installation was not successful
177
-	 */
178
-	public function downloadApp($appId) {
179
-		$appId = strtolower($appId);
180
-
181
-		$apps = $this->appFetcher->get();
182
-		foreach($apps as $app) {
183
-			if($app['id'] === $appId) {
184
-				// Load the certificate
185
-				$certificate = new X509();
186
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
187
-				$loadedCertificate = $certificate->loadX509($app['certificate']);
188
-
189
-				// Verify if the certificate has been revoked
190
-				$crl = new X509();
191
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
192
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
193
-				if($crl->validateSignature() !== true) {
194
-					throw new \Exception('Could not validate CRL signature');
195
-				}
196
-				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
197
-				$revoked = $crl->getRevoked($csn);
198
-				if ($revoked !== false) {
199
-					throw new \Exception(
200
-						sprintf(
201
-							'Certificate "%s" has been revoked',
202
-							$csn
203
-						)
204
-					);
205
-				}
206
-
207
-				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
208
-				if($certificate->validateSignature() !== true) {
209
-					throw new \Exception(
210
-						sprintf(
211
-							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
212
-							$appId
213
-						)
214
-					);
215
-				}
216
-
217
-				// Verify if the certificate is issued for the requested app id
218
-				$certInfo = openssl_x509_parse($app['certificate']);
219
-				if(!isset($certInfo['subject']['CN'])) {
220
-					throw new \Exception(
221
-						sprintf(
222
-							'App with id %s has a cert with no CN',
223
-							$appId
224
-						)
225
-					);
226
-				}
227
-				if($certInfo['subject']['CN'] !== $appId) {
228
-					throw new \Exception(
229
-						sprintf(
230
-							'App with id %s has a cert issued to %s',
231
-							$appId,
232
-							$certInfo['subject']['CN']
233
-						)
234
-					);
235
-				}
236
-
237
-				// Download the release
238
-				$tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
239
-				$client = $this->clientService->newClient();
240
-				$client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
241
-
242
-				// Check if the signature actually matches the downloaded content
243
-				$certificate = openssl_get_publickey($app['certificate']);
244
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
245
-				openssl_free_key($certificate);
246
-
247
-				if($verified === true) {
248
-					// Seems to match, let's proceed
249
-					$extractDir = $this->tempManager->getTemporaryFolder();
250
-					$archive = new TAR($tempFile);
251
-
252
-					if($archive) {
253
-						$archive->extract($extractDir);
254
-						$allFiles = scandir($extractDir);
255
-						$folders = array_diff($allFiles, ['.', '..']);
256
-						$folders = array_values($folders);
257
-
258
-						if(count($folders) > 1) {
259
-							throw new \Exception(
260
-								sprintf(
261
-									'Extracted app %s has more than 1 folder',
262
-									$appId
263
-								)
264
-							);
265
-						}
266
-
267
-						// Check if appinfo/info.xml has the same app ID as well
268
-						$loadEntities = libxml_disable_entity_loader(false);
269
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
270
-						libxml_disable_entity_loader($loadEntities);
271
-						if((string)$xml->id !== $appId) {
272
-							throw new \Exception(
273
-								sprintf(
274
-									'App for id %s has a wrong app ID in info.xml: %s',
275
-									$appId,
276
-									(string)$xml->id
277
-								)
278
-							);
279
-						}
280
-
281
-						// Check if the version is lower than before
282
-						$currentVersion = OC_App::getAppVersion($appId);
283
-						$newVersion = (string)$xml->version;
284
-						if(version_compare($currentVersion, $newVersion) === 1) {
285
-							throw new \Exception(
286
-								sprintf(
287
-									'App for id %s has version %s and tried to update to lower version %s',
288
-									$appId,
289
-									$currentVersion,
290
-									$newVersion
291
-								)
292
-							);
293
-						}
294
-
295
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
296
-						// Remove old app with the ID if existent
297
-						OC_Helper::rmdirr($baseDir);
298
-						// Move to app folder
299
-						if(@mkdir($baseDir)) {
300
-							$extractDir .= '/' . $folders[0];
301
-							OC_Helper::copyr($extractDir, $baseDir);
302
-						}
303
-						OC_Helper::copyr($extractDir, $baseDir);
304
-						OC_Helper::rmdirr($extractDir);
305
-						return;
306
-					} else {
307
-						throw new \Exception(
308
-							sprintf(
309
-								'Could not extract app with ID %s to %s',
310
-								$appId,
311
-								$extractDir
312
-							)
313
-						);
314
-					}
315
-				} else {
316
-					// Signature does not match
317
-					throw new \Exception(
318
-						sprintf(
319
-							'App with id %s has invalid signature',
320
-							$appId
321
-						)
322
-					);
323
-				}
324
-			}
325
-		}
326
-
327
-		throw new \Exception(
328
-			sprintf(
329
-				'Could not download app %s',
330
-				$appId
331
-			)
332
-		);
333
-	}
334
-
335
-	/**
336
-	 * Check if an update for the app is available
337
-	 *
338
-	 * @param string $appId
339
-	 * @param AppFetcher $appFetcher
340
-	 * @return string|false false or the version number of the update
341
-	 */
342
-	public static function isUpdateAvailable($appId,
343
-									  AppFetcher $appFetcher) {
344
-		static $isInstanceReadyForUpdates = null;
345
-
346
-		if ($isInstanceReadyForUpdates === null) {
347
-			$installPath = OC_App::getInstallPath();
348
-			if ($installPath === false || $installPath === null) {
349
-				$isInstanceReadyForUpdates = false;
350
-			} else {
351
-				$isInstanceReadyForUpdates = true;
352
-			}
353
-		}
354
-
355
-		if ($isInstanceReadyForUpdates === false) {
356
-			return false;
357
-		}
358
-
359
-		$apps = $appFetcher->get();
360
-		foreach($apps as $app) {
361
-			if($app['id'] === $appId) {
362
-				$currentVersion = OC_App::getAppVersion($appId);
363
-				$newestVersion = $app['releases'][0]['version'];
364
-				if (version_compare($newestVersion, $currentVersion, '>')) {
365
-					return $newestVersion;
366
-				} else {
367
-					return false;
368
-				}
369
-			}
370
-		}
371
-
372
-		return false;
373
-	}
374
-
375
-	/**
376
-	 * Check if app is already downloaded
377
-	 * @param string $name name of the application to remove
378
-	 * @return boolean
379
-	 *
380
-	 * The function will check if the app is already downloaded in the apps repository
381
-	 */
382
-	public function isDownloaded($name) {
383
-		foreach(\OC::$APPSROOTS as $dir) {
384
-			$dirToTest  = $dir['path'];
385
-			$dirToTest .= '/';
386
-			$dirToTest .= $name;
387
-			$dirToTest .= '/';
388
-
389
-			if (is_dir($dirToTest)) {
390
-				return true;
391
-			}
392
-		}
393
-
394
-		return false;
395
-	}
396
-
397
-	/**
398
-	 * Removes an app
399
-	 * @param string $appId ID of the application to remove
400
-	 * @return boolean
401
-	 *
402
-	 *
403
-	 * This function works as follows
404
-	 *   -# call uninstall repair steps
405
-	 *   -# removing the files
406
-	 *
407
-	 * The function will not delete preferences, tables and the configuration,
408
-	 * this has to be done by the function oc_app_uninstall().
409
-	 */
410
-	public function removeApp($appId) {
411
-		if($this->isDownloaded( $appId )) {
412
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
413
-			OC_Helper::rmdirr($appDir);
414
-			return true;
415
-		}else{
416
-			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
417
-
418
-			return false;
419
-		}
420
-
421
-	}
422
-
423
-	/**
424
-	 * Installs shipped apps
425
-	 *
426
-	 * This function installs all apps found in the 'apps' directory that should be enabled by default;
427
-	 * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
428
-	 *                         working ownCloud at the end instead of an aborted update.
429
-	 * @return array Array of error messages (appid => Exception)
430
-	 */
431
-	public static function installShippedApps($softErrors = false) {
432
-		$errors = [];
433
-		foreach(\OC::$APPSROOTS as $app_dir) {
434
-			if($dir = opendir( $app_dir['path'] )) {
435
-				while( false !== ( $filename = readdir( $dir ))) {
436
-					if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
437
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
438
-							if(!Installer::isInstalled($filename)) {
439
-								$info=OC_App::getAppInfo($filename);
440
-								$enabled = isset($info['default_enable']);
441
-								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
442
-									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
443
-									if ($softErrors) {
444
-										try {
445
-											Installer::installShippedApp($filename);
446
-										} catch (HintException $e) {
447
-											if ($e->getPrevious() instanceof TableExistsException) {
448
-												$errors[$filename] = $e;
449
-												continue;
450
-											}
451
-											throw $e;
452
-										}
453
-									} else {
454
-										Installer::installShippedApp($filename);
455
-									}
456
-									\OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
457
-								}
458
-							}
459
-						}
460
-					}
461
-				}
462
-				closedir( $dir );
463
-			}
464
-		}
465
-
466
-		return $errors;
467
-	}
468
-
469
-	/**
470
-	 * install an app already placed in the app folder
471
-	 * @param string $app id of the app to install
472
-	 * @return integer
473
-	 */
474
-	public static function installShippedApp($app) {
475
-		//install the database
476
-		$appPath = OC_App::getAppPath($app);
477
-		if(is_file("$appPath/appinfo/database.xml")) {
478
-			try {
479
-				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
480
-			} catch (TableExistsException $e) {
481
-				throw new HintException(
482
-					'Failed to enable app ' . $app,
483
-					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer">support channels</a>.',
484
-					0, $e
485
-				);
486
-			}
487
-		}
488
-
489
-		//run appinfo/install.php
490
-		\OC_App::registerAutoloading($app, $appPath);
491
-		self::includeAppScript("$appPath/appinfo/install.php");
492
-
493
-		$info = OC_App::getAppInfo($app);
494
-		if (is_null($info)) {
495
-			return false;
496
-		}
497
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
498
-
499
-		OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
500
-
501
-		$config = \OC::$server->getConfig();
502
-
503
-		$config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
504
-		if (array_key_exists('ocsid', $info)) {
505
-			$config->setAppValue($app, 'ocsid', $info['ocsid']);
506
-		}
507
-
508
-		//set remote/public handlers
509
-		foreach($info['remote'] as $name=>$path) {
510
-			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
511
-		}
512
-		foreach($info['public'] as $name=>$path) {
513
-			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
514
-		}
515
-
516
-		OC_App::setAppTypes($info['id']);
517
-
518
-		if(isset($info['settings']) && is_array($info['settings'])) {
519
-			// requires that autoloading was registered for the app,
520
-			// as happens before running the install.php some lines above
521
-			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
522
-		}
523
-
524
-		return $info['id'];
525
-	}
526
-
527
-	/**
528
-	 * check the code of an app with some static code checks
529
-	 * @param string $folder the folder of the app to check
530
-	 * @return boolean true for app is o.k. and false for app is not o.k.
531
-	 */
532
-	public static function checkCode($folder) {
533
-		// is the code checker enabled?
534
-		if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
535
-			return true;
536
-		}
537
-
538
-		$codeChecker = new CodeChecker(new PrivateCheck(new EmptyCheck()));
539
-		$errors = $codeChecker->analyseFolder(basename($folder), $folder);
540
-
541
-		return empty($errors);
542
-	}
543
-
544
-	/**
545
-	 * @param string $script
546
-	 */
547
-	private static function includeAppScript($script) {
548
-		if ( file_exists($script) ){
549
-			include $script;
550
-		}
551
-	}
63
+    /** @var AppFetcher */
64
+    private $appFetcher;
65
+    /** @var IClientService */
66
+    private $clientService;
67
+    /** @var ITempManager */
68
+    private $tempManager;
69
+    /** @var ILogger */
70
+    private $logger;
71
+
72
+    /**
73
+     * @param AppFetcher $appFetcher
74
+     * @param IClientService $clientService
75
+     * @param ITempManager $tempManager
76
+     * @param ILogger $logger
77
+     */
78
+    public function __construct(AppFetcher $appFetcher,
79
+                                IClientService $clientService,
80
+                                ITempManager $tempManager,
81
+                                ILogger $logger) {
82
+        $this->appFetcher = $appFetcher;
83
+        $this->clientService = $clientService;
84
+        $this->tempManager = $tempManager;
85
+        $this->logger = $logger;
86
+    }
87
+
88
+    /**
89
+     * Installs an app that is located in one of the app folders already
90
+     *
91
+     * @param string $appId App to install
92
+     * @throws \Exception
93
+     * @return integer
94
+     */
95
+    public function installApp($appId) {
96
+        $app = \OC_App::findAppInDirectories($appId);
97
+        if($app === false) {
98
+            throw new \Exception('App not found in any app directory');
99
+        }
100
+
101
+        $basedir = $app['path'].'/'.$appId;
102
+        $info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
103
+
104
+        //install the database
105
+        if(is_file($basedir.'/appinfo/database.xml')) {
106
+            if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
107
+                OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
108
+            } else {
109
+                OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
110
+            }
111
+        }
112
+
113
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
114
+
115
+        //run appinfo/install.php
116
+        if((!isset($data['noinstall']) or $data['noinstall']==false)) {
117
+            self::includeAppScript($basedir . '/appinfo/install.php');
118
+        }
119
+
120
+        $appData = OC_App::getAppInfo($appId);
121
+        OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
122
+
123
+        //set the installed version
124
+        \OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
125
+        \OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
126
+
127
+        //set remote/public handlers
128
+        foreach($info['remote'] as $name=>$path) {
129
+            \OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
130
+        }
131
+        foreach($info['public'] as $name=>$path) {
132
+            \OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
133
+        }
134
+
135
+        OC_App::setAppTypes($info['id']);
136
+
137
+        return $info['id'];
138
+    }
139
+
140
+    /**
141
+     * @brief checks whether or not an app is installed
142
+     * @param string $app app
143
+     * @returns bool
144
+     *
145
+     * Checks whether or not an app is installed, i.e. registered in apps table.
146
+     */
147
+    public static function isInstalled( $app ) {
148
+        return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
149
+    }
150
+
151
+    /**
152
+     * Updates the specified app from the appstore
153
+     *
154
+     * @param string $appId
155
+     * @return bool
156
+     */
157
+    public function updateAppstoreApp($appId) {
158
+        if(self::isUpdateAvailable($appId, $this->appFetcher)) {
159
+            try {
160
+                $this->downloadApp($appId);
161
+            } catch (\Exception $e) {
162
+                $this->logger->error($e->getMessage(), ['app' => 'core']);
163
+                return false;
164
+            }
165
+            return OC_App::updateApp($appId);
166
+        }
167
+
168
+        return false;
169
+    }
170
+
171
+    /**
172
+     * Downloads an app and puts it into the app directory
173
+     *
174
+     * @param string $appId
175
+     *
176
+     * @throws \Exception If the installation was not successful
177
+     */
178
+    public function downloadApp($appId) {
179
+        $appId = strtolower($appId);
180
+
181
+        $apps = $this->appFetcher->get();
182
+        foreach($apps as $app) {
183
+            if($app['id'] === $appId) {
184
+                // Load the certificate
185
+                $certificate = new X509();
186
+                $certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
187
+                $loadedCertificate = $certificate->loadX509($app['certificate']);
188
+
189
+                // Verify if the certificate has been revoked
190
+                $crl = new X509();
191
+                $crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
192
+                $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
193
+                if($crl->validateSignature() !== true) {
194
+                    throw new \Exception('Could not validate CRL signature');
195
+                }
196
+                $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
197
+                $revoked = $crl->getRevoked($csn);
198
+                if ($revoked !== false) {
199
+                    throw new \Exception(
200
+                        sprintf(
201
+                            'Certificate "%s" has been revoked',
202
+                            $csn
203
+                        )
204
+                    );
205
+                }
206
+
207
+                // Verify if the certificate has been issued by the Nextcloud Code Authority CA
208
+                if($certificate->validateSignature() !== true) {
209
+                    throw new \Exception(
210
+                        sprintf(
211
+                            'App with id %s has a certificate not issued by a trusted Code Signing Authority',
212
+                            $appId
213
+                        )
214
+                    );
215
+                }
216
+
217
+                // Verify if the certificate is issued for the requested app id
218
+                $certInfo = openssl_x509_parse($app['certificate']);
219
+                if(!isset($certInfo['subject']['CN'])) {
220
+                    throw new \Exception(
221
+                        sprintf(
222
+                            'App with id %s has a cert with no CN',
223
+                            $appId
224
+                        )
225
+                    );
226
+                }
227
+                if($certInfo['subject']['CN'] !== $appId) {
228
+                    throw new \Exception(
229
+                        sprintf(
230
+                            'App with id %s has a cert issued to %s',
231
+                            $appId,
232
+                            $certInfo['subject']['CN']
233
+                        )
234
+                    );
235
+                }
236
+
237
+                // Download the release
238
+                $tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
239
+                $client = $this->clientService->newClient();
240
+                $client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
241
+
242
+                // Check if the signature actually matches the downloaded content
243
+                $certificate = openssl_get_publickey($app['certificate']);
244
+                $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
245
+                openssl_free_key($certificate);
246
+
247
+                if($verified === true) {
248
+                    // Seems to match, let's proceed
249
+                    $extractDir = $this->tempManager->getTemporaryFolder();
250
+                    $archive = new TAR($tempFile);
251
+
252
+                    if($archive) {
253
+                        $archive->extract($extractDir);
254
+                        $allFiles = scandir($extractDir);
255
+                        $folders = array_diff($allFiles, ['.', '..']);
256
+                        $folders = array_values($folders);
257
+
258
+                        if(count($folders) > 1) {
259
+                            throw new \Exception(
260
+                                sprintf(
261
+                                    'Extracted app %s has more than 1 folder',
262
+                                    $appId
263
+                                )
264
+                            );
265
+                        }
266
+
267
+                        // Check if appinfo/info.xml has the same app ID as well
268
+                        $loadEntities = libxml_disable_entity_loader(false);
269
+                        $xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
270
+                        libxml_disable_entity_loader($loadEntities);
271
+                        if((string)$xml->id !== $appId) {
272
+                            throw new \Exception(
273
+                                sprintf(
274
+                                    'App for id %s has a wrong app ID in info.xml: %s',
275
+                                    $appId,
276
+                                    (string)$xml->id
277
+                                )
278
+                            );
279
+                        }
280
+
281
+                        // Check if the version is lower than before
282
+                        $currentVersion = OC_App::getAppVersion($appId);
283
+                        $newVersion = (string)$xml->version;
284
+                        if(version_compare($currentVersion, $newVersion) === 1) {
285
+                            throw new \Exception(
286
+                                sprintf(
287
+                                    'App for id %s has version %s and tried to update to lower version %s',
288
+                                    $appId,
289
+                                    $currentVersion,
290
+                                    $newVersion
291
+                                )
292
+                            );
293
+                        }
294
+
295
+                        $baseDir = OC_App::getInstallPath() . '/' . $appId;
296
+                        // Remove old app with the ID if existent
297
+                        OC_Helper::rmdirr($baseDir);
298
+                        // Move to app folder
299
+                        if(@mkdir($baseDir)) {
300
+                            $extractDir .= '/' . $folders[0];
301
+                            OC_Helper::copyr($extractDir, $baseDir);
302
+                        }
303
+                        OC_Helper::copyr($extractDir, $baseDir);
304
+                        OC_Helper::rmdirr($extractDir);
305
+                        return;
306
+                    } else {
307
+                        throw new \Exception(
308
+                            sprintf(
309
+                                'Could not extract app with ID %s to %s',
310
+                                $appId,
311
+                                $extractDir
312
+                            )
313
+                        );
314
+                    }
315
+                } else {
316
+                    // Signature does not match
317
+                    throw new \Exception(
318
+                        sprintf(
319
+                            'App with id %s has invalid signature',
320
+                            $appId
321
+                        )
322
+                    );
323
+                }
324
+            }
325
+        }
326
+
327
+        throw new \Exception(
328
+            sprintf(
329
+                'Could not download app %s',
330
+                $appId
331
+            )
332
+        );
333
+    }
334
+
335
+    /**
336
+     * Check if an update for the app is available
337
+     *
338
+     * @param string $appId
339
+     * @param AppFetcher $appFetcher
340
+     * @return string|false false or the version number of the update
341
+     */
342
+    public static function isUpdateAvailable($appId,
343
+                                        AppFetcher $appFetcher) {
344
+        static $isInstanceReadyForUpdates = null;
345
+
346
+        if ($isInstanceReadyForUpdates === null) {
347
+            $installPath = OC_App::getInstallPath();
348
+            if ($installPath === false || $installPath === null) {
349
+                $isInstanceReadyForUpdates = false;
350
+            } else {
351
+                $isInstanceReadyForUpdates = true;
352
+            }
353
+        }
354
+
355
+        if ($isInstanceReadyForUpdates === false) {
356
+            return false;
357
+        }
358
+
359
+        $apps = $appFetcher->get();
360
+        foreach($apps as $app) {
361
+            if($app['id'] === $appId) {
362
+                $currentVersion = OC_App::getAppVersion($appId);
363
+                $newestVersion = $app['releases'][0]['version'];
364
+                if (version_compare($newestVersion, $currentVersion, '>')) {
365
+                    return $newestVersion;
366
+                } else {
367
+                    return false;
368
+                }
369
+            }
370
+        }
371
+
372
+        return false;
373
+    }
374
+
375
+    /**
376
+     * Check if app is already downloaded
377
+     * @param string $name name of the application to remove
378
+     * @return boolean
379
+     *
380
+     * The function will check if the app is already downloaded in the apps repository
381
+     */
382
+    public function isDownloaded($name) {
383
+        foreach(\OC::$APPSROOTS as $dir) {
384
+            $dirToTest  = $dir['path'];
385
+            $dirToTest .= '/';
386
+            $dirToTest .= $name;
387
+            $dirToTest .= '/';
388
+
389
+            if (is_dir($dirToTest)) {
390
+                return true;
391
+            }
392
+        }
393
+
394
+        return false;
395
+    }
396
+
397
+    /**
398
+     * Removes an app
399
+     * @param string $appId ID of the application to remove
400
+     * @return boolean
401
+     *
402
+     *
403
+     * This function works as follows
404
+     *   -# call uninstall repair steps
405
+     *   -# removing the files
406
+     *
407
+     * The function will not delete preferences, tables and the configuration,
408
+     * this has to be done by the function oc_app_uninstall().
409
+     */
410
+    public function removeApp($appId) {
411
+        if($this->isDownloaded( $appId )) {
412
+            $appDir = OC_App::getInstallPath() . '/' . $appId;
413
+            OC_Helper::rmdirr($appDir);
414
+            return true;
415
+        }else{
416
+            \OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
417
+
418
+            return false;
419
+        }
420
+
421
+    }
422
+
423
+    /**
424
+     * Installs shipped apps
425
+     *
426
+     * This function installs all apps found in the 'apps' directory that should be enabled by default;
427
+     * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
428
+     *                         working ownCloud at the end instead of an aborted update.
429
+     * @return array Array of error messages (appid => Exception)
430
+     */
431
+    public static function installShippedApps($softErrors = false) {
432
+        $errors = [];
433
+        foreach(\OC::$APPSROOTS as $app_dir) {
434
+            if($dir = opendir( $app_dir['path'] )) {
435
+                while( false !== ( $filename = readdir( $dir ))) {
436
+                    if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
437
+                        if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
438
+                            if(!Installer::isInstalled($filename)) {
439
+                                $info=OC_App::getAppInfo($filename);
440
+                                $enabled = isset($info['default_enable']);
441
+                                if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
442
+                                      && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
443
+                                    if ($softErrors) {
444
+                                        try {
445
+                                            Installer::installShippedApp($filename);
446
+                                        } catch (HintException $e) {
447
+                                            if ($e->getPrevious() instanceof TableExistsException) {
448
+                                                $errors[$filename] = $e;
449
+                                                continue;
450
+                                            }
451
+                                            throw $e;
452
+                                        }
453
+                                    } else {
454
+                                        Installer::installShippedApp($filename);
455
+                                    }
456
+                                    \OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
457
+                                }
458
+                            }
459
+                        }
460
+                    }
461
+                }
462
+                closedir( $dir );
463
+            }
464
+        }
465
+
466
+        return $errors;
467
+    }
468
+
469
+    /**
470
+     * install an app already placed in the app folder
471
+     * @param string $app id of the app to install
472
+     * @return integer
473
+     */
474
+    public static function installShippedApp($app) {
475
+        //install the database
476
+        $appPath = OC_App::getAppPath($app);
477
+        if(is_file("$appPath/appinfo/database.xml")) {
478
+            try {
479
+                OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
480
+            } catch (TableExistsException $e) {
481
+                throw new HintException(
482
+                    'Failed to enable app ' . $app,
483
+                    'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer">support channels</a>.',
484
+                    0, $e
485
+                );
486
+            }
487
+        }
488
+
489
+        //run appinfo/install.php
490
+        \OC_App::registerAutoloading($app, $appPath);
491
+        self::includeAppScript("$appPath/appinfo/install.php");
492
+
493
+        $info = OC_App::getAppInfo($app);
494
+        if (is_null($info)) {
495
+            return false;
496
+        }
497
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
498
+
499
+        OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
500
+
501
+        $config = \OC::$server->getConfig();
502
+
503
+        $config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
504
+        if (array_key_exists('ocsid', $info)) {
505
+            $config->setAppValue($app, 'ocsid', $info['ocsid']);
506
+        }
507
+
508
+        //set remote/public handlers
509
+        foreach($info['remote'] as $name=>$path) {
510
+            $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
511
+        }
512
+        foreach($info['public'] as $name=>$path) {
513
+            $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
514
+        }
515
+
516
+        OC_App::setAppTypes($info['id']);
517
+
518
+        if(isset($info['settings']) && is_array($info['settings'])) {
519
+            // requires that autoloading was registered for the app,
520
+            // as happens before running the install.php some lines above
521
+            \OC::$server->getSettingsManager()->setupSettings($info['settings']);
522
+        }
523
+
524
+        return $info['id'];
525
+    }
526
+
527
+    /**
528
+     * check the code of an app with some static code checks
529
+     * @param string $folder the folder of the app to check
530
+     * @return boolean true for app is o.k. and false for app is not o.k.
531
+     */
532
+    public static function checkCode($folder) {
533
+        // is the code checker enabled?
534
+        if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
535
+            return true;
536
+        }
537
+
538
+        $codeChecker = new CodeChecker(new PrivateCheck(new EmptyCheck()));
539
+        $errors = $codeChecker->analyseFolder(basename($folder), $folder);
540
+
541
+        return empty($errors);
542
+    }
543
+
544
+    /**
545
+     * @param string $script
546
+     */
547
+    private static function includeAppScript($script) {
548
+        if ( file_exists($script) ){
549
+            include $script;
550
+        }
551
+    }
552 552
 }
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 	 */
95 95
 	public function installApp($appId) {
96 96
 		$app = \OC_App::findAppInDirectories($appId);
97
-		if($app === false) {
97
+		if ($app === false) {
98 98
 			throw new \Exception('App not found in any app directory');
99 99
 		}
100 100
 
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 		$info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
103 103
 
104 104
 		//install the database
105
-		if(is_file($basedir.'/appinfo/database.xml')) {
105
+		if (is_file($basedir.'/appinfo/database.xml')) {
106 106
 			if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) {
107 107
 				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
108 108
 			} else {
@@ -113,8 +113,8 @@  discard block
 block discarded – undo
113 113
 		\OC_App::setupBackgroundJobs($info['background-jobs']);
114 114
 
115 115
 		//run appinfo/install.php
116
-		if((!isset($data['noinstall']) or $data['noinstall']==false)) {
117
-			self::includeAppScript($basedir . '/appinfo/install.php');
116
+		if ((!isset($data['noinstall']) or $data['noinstall'] == false)) {
117
+			self::includeAppScript($basedir.'/appinfo/install.php');
118 118
 		}
119 119
 
120 120
 		$appData = OC_App::getAppInfo($appId);
@@ -125,10 +125,10 @@  discard block
 block discarded – undo
125 125
 		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
126 126
 
127 127
 		//set remote/public handlers
128
-		foreach($info['remote'] as $name=>$path) {
128
+		foreach ($info['remote'] as $name=>$path) {
129 129
 			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
130 130
 		}
131
-		foreach($info['public'] as $name=>$path) {
131
+		foreach ($info['public'] as $name=>$path) {
132 132
 			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
133 133
 		}
134 134
 
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 	 *
145 145
 	 * Checks whether or not an app is installed, i.e. registered in apps table.
146 146
 	 */
147
-	public static function isInstalled( $app ) {
147
+	public static function isInstalled($app) {
148 148
 		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
149 149
 	}
150 150
 
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 	 * @return bool
156 156
 	 */
157 157
 	public function updateAppstoreApp($appId) {
158
-		if(self::isUpdateAvailable($appId, $this->appFetcher)) {
158
+		if (self::isUpdateAvailable($appId, $this->appFetcher)) {
159 159
 			try {
160 160
 				$this->downloadApp($appId);
161 161
 			} catch (\Exception $e) {
@@ -179,18 +179,18 @@  discard block
 block discarded – undo
179 179
 		$appId = strtolower($appId);
180 180
 
181 181
 		$apps = $this->appFetcher->get();
182
-		foreach($apps as $app) {
183
-			if($app['id'] === $appId) {
182
+		foreach ($apps as $app) {
183
+			if ($app['id'] === $appId) {
184 184
 				// Load the certificate
185 185
 				$certificate = new X509();
186
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
186
+				$certificate->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
187 187
 				$loadedCertificate = $certificate->loadX509($app['certificate']);
188 188
 
189 189
 				// Verify if the certificate has been revoked
190 190
 				$crl = new X509();
191
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
192
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
193
-				if($crl->validateSignature() !== true) {
191
+				$crl->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
192
+				$crl->loadCRL(file_get_contents(__DIR__.'/../../resources/codesigning/root.crl'));
193
+				if ($crl->validateSignature() !== true) {
194 194
 					throw new \Exception('Could not validate CRL signature');
195 195
 				}
196 196
 				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 				}
206 206
 
207 207
 				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
208
-				if($certificate->validateSignature() !== true) {
208
+				if ($certificate->validateSignature() !== true) {
209 209
 					throw new \Exception(
210 210
 						sprintf(
211 211
 							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 
217 217
 				// Verify if the certificate is issued for the requested app id
218 218
 				$certInfo = openssl_x509_parse($app['certificate']);
219
-				if(!isset($certInfo['subject']['CN'])) {
219
+				if (!isset($certInfo['subject']['CN'])) {
220 220
 					throw new \Exception(
221 221
 						sprintf(
222 222
 							'App with id %s has a cert with no CN',
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
 						)
225 225
 					);
226 226
 				}
227
-				if($certInfo['subject']['CN'] !== $appId) {
227
+				if ($certInfo['subject']['CN'] !== $appId) {
228 228
 					throw new \Exception(
229 229
 						sprintf(
230 230
 							'App with id %s has a cert issued to %s',
@@ -241,21 +241,21 @@  discard block
 block discarded – undo
241 241
 
242 242
 				// Check if the signature actually matches the downloaded content
243 243
 				$certificate = openssl_get_publickey($app['certificate']);
244
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
244
+				$verified = (bool) openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
245 245
 				openssl_free_key($certificate);
246 246
 
247
-				if($verified === true) {
247
+				if ($verified === true) {
248 248
 					// Seems to match, let's proceed
249 249
 					$extractDir = $this->tempManager->getTemporaryFolder();
250 250
 					$archive = new TAR($tempFile);
251 251
 
252
-					if($archive) {
252
+					if ($archive) {
253 253
 						$archive->extract($extractDir);
254 254
 						$allFiles = scandir($extractDir);
255 255
 						$folders = array_diff($allFiles, ['.', '..']);
256 256
 						$folders = array_values($folders);
257 257
 
258
-						if(count($folders) > 1) {
258
+						if (count($folders) > 1) {
259 259
 							throw new \Exception(
260 260
 								sprintf(
261 261
 									'Extracted app %s has more than 1 folder',
@@ -266,22 +266,22 @@  discard block
 block discarded – undo
266 266
 
267 267
 						// Check if appinfo/info.xml has the same app ID as well
268 268
 						$loadEntities = libxml_disable_entity_loader(false);
269
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
269
+						$xml = simplexml_load_file($extractDir.'/'.$folders[0].'/appinfo/info.xml');
270 270
 						libxml_disable_entity_loader($loadEntities);
271
-						if((string)$xml->id !== $appId) {
271
+						if ((string) $xml->id !== $appId) {
272 272
 							throw new \Exception(
273 273
 								sprintf(
274 274
 									'App for id %s has a wrong app ID in info.xml: %s',
275 275
 									$appId,
276
-									(string)$xml->id
276
+									(string) $xml->id
277 277
 								)
278 278
 							);
279 279
 						}
280 280
 
281 281
 						// Check if the version is lower than before
282 282
 						$currentVersion = OC_App::getAppVersion($appId);
283
-						$newVersion = (string)$xml->version;
284
-						if(version_compare($currentVersion, $newVersion) === 1) {
283
+						$newVersion = (string) $xml->version;
284
+						if (version_compare($currentVersion, $newVersion) === 1) {
285 285
 							throw new \Exception(
286 286
 								sprintf(
287 287
 									'App for id %s has version %s and tried to update to lower version %s',
@@ -292,12 +292,12 @@  discard block
 block discarded – undo
292 292
 							);
293 293
 						}
294 294
 
295
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
295
+						$baseDir = OC_App::getInstallPath().'/'.$appId;
296 296
 						// Remove old app with the ID if existent
297 297
 						OC_Helper::rmdirr($baseDir);
298 298
 						// Move to app folder
299
-						if(@mkdir($baseDir)) {
300
-							$extractDir .= '/' . $folders[0];
299
+						if (@mkdir($baseDir)) {
300
+							$extractDir .= '/'.$folders[0];
301 301
 							OC_Helper::copyr($extractDir, $baseDir);
302 302
 						}
303 303
 						OC_Helper::copyr($extractDir, $baseDir);
@@ -357,8 +357,8 @@  discard block
 block discarded – undo
357 357
 		}
358 358
 
359 359
 		$apps = $appFetcher->get();
360
-		foreach($apps as $app) {
361
-			if($app['id'] === $appId) {
360
+		foreach ($apps as $app) {
361
+			if ($app['id'] === $appId) {
362 362
 				$currentVersion = OC_App::getAppVersion($appId);
363 363
 				$newestVersion = $app['releases'][0]['version'];
364 364
 				if (version_compare($newestVersion, $currentVersion, '>')) {
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 	 * The function will check if the app is already downloaded in the apps repository
381 381
 	 */
382 382
 	public function isDownloaded($name) {
383
-		foreach(\OC::$APPSROOTS as $dir) {
383
+		foreach (\OC::$APPSROOTS as $dir) {
384 384
 			$dirToTest  = $dir['path'];
385 385
 			$dirToTest .= '/';
386 386
 			$dirToTest .= $name;
@@ -408,11 +408,11 @@  discard block
 block discarded – undo
408 408
 	 * this has to be done by the function oc_app_uninstall().
409 409
 	 */
410 410
 	public function removeApp($appId) {
411
-		if($this->isDownloaded( $appId )) {
412
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
411
+		if ($this->isDownloaded($appId)) {
412
+			$appDir = OC_App::getInstallPath().'/'.$appId;
413 413
 			OC_Helper::rmdirr($appDir);
414 414
 			return true;
415
-		}else{
415
+		} else {
416 416
 			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
417 417
 
418 418
 			return false;
@@ -430,13 +430,13 @@  discard block
 block discarded – undo
430 430
 	 */
431 431
 	public static function installShippedApps($softErrors = false) {
432 432
 		$errors = [];
433
-		foreach(\OC::$APPSROOTS as $app_dir) {
434
-			if($dir = opendir( $app_dir['path'] )) {
435
-				while( false !== ( $filename = readdir( $dir ))) {
436
-					if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
437
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
438
-							if(!Installer::isInstalled($filename)) {
439
-								$info=OC_App::getAppInfo($filename);
433
+		foreach (\OC::$APPSROOTS as $app_dir) {
434
+			if ($dir = opendir($app_dir['path'])) {
435
+				while (false !== ($filename = readdir($dir))) {
436
+					if (substr($filename, 0, 1) != '.' and is_dir($app_dir['path']."/$filename")) {
437
+						if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
438
+							if (!Installer::isInstalled($filename)) {
439
+								$info = OC_App::getAppInfo($filename);
440 440
 								$enabled = isset($info['default_enable']);
441 441
 								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
442 442
 									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
@@ -459,7 +459,7 @@  discard block
 block discarded – undo
459 459
 						}
460 460
 					}
461 461
 				}
462
-				closedir( $dir );
462
+				closedir($dir);
463 463
 			}
464 464
 		}
465 465
 
@@ -474,12 +474,12 @@  discard block
 block discarded – undo
474 474
 	public static function installShippedApp($app) {
475 475
 		//install the database
476 476
 		$appPath = OC_App::getAppPath($app);
477
-		if(is_file("$appPath/appinfo/database.xml")) {
477
+		if (is_file("$appPath/appinfo/database.xml")) {
478 478
 			try {
479 479
 				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
480 480
 			} catch (TableExistsException $e) {
481 481
 				throw new HintException(
482
-					'Failed to enable app ' . $app,
482
+					'Failed to enable app '.$app,
483 483
 					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer">support channels</a>.',
484 484
 					0, $e
485 485
 				);
@@ -506,16 +506,16 @@  discard block
 block discarded – undo
506 506
 		}
507 507
 
508 508
 		//set remote/public handlers
509
-		foreach($info['remote'] as $name=>$path) {
509
+		foreach ($info['remote'] as $name=>$path) {
510 510
 			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
511 511
 		}
512
-		foreach($info['public'] as $name=>$path) {
512
+		foreach ($info['public'] as $name=>$path) {
513 513
 			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
514 514
 		}
515 515
 
516 516
 		OC_App::setAppTypes($info['id']);
517 517
 
518
-		if(isset($info['settings']) && is_array($info['settings'])) {
518
+		if (isset($info['settings']) && is_array($info['settings'])) {
519 519
 			// requires that autoloading was registered for the app,
520 520
 			// as happens before running the install.php some lines above
521 521
 			\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 	 */
532 532
 	public static function checkCode($folder) {
533 533
 		// is the code checker enabled?
534
-		if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
534
+		if (!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
535 535
 			return true;
536 536
 		}
537 537
 
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
 	 * @param string $script
546 546
 	 */
547 547
 	private static function includeAppScript($script) {
548
-		if ( file_exists($script) ){
548
+		if (file_exists($script)) {
549 549
 			include $script;
550 550
 		}
551 551
 	}
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -412,7 +412,7 @@
 block discarded – undo
412 412
 			$appDir = OC_App::getInstallPath() . '/' . $appId;
413 413
 			OC_Helper::rmdirr($appDir);
414 414
 			return true;
415
-		}else{
415
+		} else{
416 416
 			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
417 417
 
418 418
 			return false;
Please login to merge, or discard this patch.
apps/dav/lib/HookManager.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -28,7 +28,6 @@
 block discarded – undo
28 28
 use OCP\IUserManager;
29 29
 use OCP\Util;
30 30
 use Symfony\Component\EventDispatcher\EventDispatcher;
31
-use Symfony\Component\EventDispatcher\GenericEvent;
32 31
 
33 32
 class HookManager {
34 33
 
Please login to merge, or discard this patch.
Indentation   +111 added lines, -111 removed lines patch added patch discarded remove patch
@@ -32,115 +32,115 @@
 block discarded – undo
32 32
 
33 33
 class HookManager {
34 34
 
35
-	/** @var IUserManager */
36
-	private $userManager;
37
-
38
-	/** @var SyncService */
39
-	private $syncService;
40
-
41
-	/** @var IUser[] */
42
-	private $usersToDelete;
43
-
44
-	/** @var CalDavBackend */
45
-	private $calDav;
46
-
47
-	/** @var CardDavBackend */
48
-	private $cardDav;
49
-
50
-	/** @var array */
51
-	private $calendarsToDelete;
52
-
53
-	/** @var array */
54
-	private $addressBooksToDelete;
55
-
56
-	/** @var EventDispatcher */
57
-	private $eventDispatcher;
58
-
59
-	public function __construct(IUserManager $userManager,
60
-								SyncService $syncService,
61
-								CalDavBackend $calDav,
62
-								CardDavBackend $cardDav,
63
-								EventDispatcher $eventDispatcher) {
64
-		$this->userManager = $userManager;
65
-		$this->syncService = $syncService;
66
-		$this->calDav = $calDav;
67
-		$this->cardDav = $cardDav;
68
-		$this->eventDispatcher = $eventDispatcher;
69
-	}
70
-
71
-	public function setup() {
72
-		Util::connectHook('OC_User',
73
-			'post_createUser',
74
-			$this,
75
-			'postCreateUser');
76
-		Util::connectHook('OC_User',
77
-			'pre_deleteUser',
78
-			$this,
79
-			'preDeleteUser');
80
-		Util::connectHook('OC_User',
81
-			'post_deleteUser',
82
-			$this,
83
-			'postDeleteUser');
84
-		Util::connectHook('OC_User',
85
-			'changeUser',
86
-			$this,
87
-			'changeUser');
88
-	}
89
-
90
-	public function postCreateUser($params) {
91
-		$user = $this->userManager->get($params['uid']);
92
-		$this->syncService->updateUser($user);
93
-	}
94
-
95
-	public function preDeleteUser($params) {
96
-		$uid = $params['uid'];
97
-		$this->usersToDelete[$uid] = $this->userManager->get($uid);
98
-		$this->calendarsToDelete = $this->calDav->getUsersOwnCalendars('principals/users/' . $uid);
99
-		$this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks('principals/users/' . $uid);
100
-	}
101
-
102
-	public function postDeleteUser($params) {
103
-		$uid = $params['uid'];
104
-		if (isset($this->usersToDelete[$uid])){
105
-			$this->syncService->deleteUser($this->usersToDelete[$uid]);
106
-		}
107
-
108
-		foreach ($this->calendarsToDelete as $calendar) {
109
-			$this->calDav->deleteCalendar($calendar['id']);
110
-		}
111
-		$this->calDav->deleteAllSharesByUser('principals/users/' . $uid);
112
-
113
-		foreach ($this->addressBooksToDelete as $addressBook) {
114
-			$this->cardDav->deleteAddressBook($addressBook['id']);
115
-		}
116
-	}
117
-
118
-	public function changeUser($params) {
119
-		$user = $params['user'];
120
-		$this->syncService->updateUser($user);
121
-	}
122
-
123
-	public function firstLogin(IUser $user = null) {
124
-		if (!is_null($user)) {
125
-			$principal = 'principals/users/' . $user->getUID();
126
-			if ($this->calDav->getCalendarsForUserCount($principal) === 0) {
127
-				try {
128
-					$this->calDav->createCalendar($principal, CalDavBackend::PERSONAL_CALENDAR_URI, [
129
-						'{DAV:}displayname' => CalDavBackend::PERSONAL_CALENDAR_NAME,
130
-					]);
131
-				} catch (\Exception $ex) {
132
-					\OC::$server->getLogger()->logException($ex);
133
-				}
134
-			}
135
-			if ($this->cardDav->getAddressBooksForUserCount($principal) === 0) {
136
-				try {
137
-					$this->cardDav->createAddressBook($principal, CardDavBackend::PERSONAL_ADDRESSBOOK_URI, [
138
-						'{DAV:}displayname' => CardDavBackend::PERSONAL_ADDRESSBOOK_NAME,
139
-					]);
140
-				} catch (\Exception $ex) {
141
-					\OC::$server->getLogger()->logException($ex);
142
-				}
143
-			}
144
-		}
145
-	}
35
+    /** @var IUserManager */
36
+    private $userManager;
37
+
38
+    /** @var SyncService */
39
+    private $syncService;
40
+
41
+    /** @var IUser[] */
42
+    private $usersToDelete;
43
+
44
+    /** @var CalDavBackend */
45
+    private $calDav;
46
+
47
+    /** @var CardDavBackend */
48
+    private $cardDav;
49
+
50
+    /** @var array */
51
+    private $calendarsToDelete;
52
+
53
+    /** @var array */
54
+    private $addressBooksToDelete;
55
+
56
+    /** @var EventDispatcher */
57
+    private $eventDispatcher;
58
+
59
+    public function __construct(IUserManager $userManager,
60
+                                SyncService $syncService,
61
+                                CalDavBackend $calDav,
62
+                                CardDavBackend $cardDav,
63
+                                EventDispatcher $eventDispatcher) {
64
+        $this->userManager = $userManager;
65
+        $this->syncService = $syncService;
66
+        $this->calDav = $calDav;
67
+        $this->cardDav = $cardDav;
68
+        $this->eventDispatcher = $eventDispatcher;
69
+    }
70
+
71
+    public function setup() {
72
+        Util::connectHook('OC_User',
73
+            'post_createUser',
74
+            $this,
75
+            'postCreateUser');
76
+        Util::connectHook('OC_User',
77
+            'pre_deleteUser',
78
+            $this,
79
+            'preDeleteUser');
80
+        Util::connectHook('OC_User',
81
+            'post_deleteUser',
82
+            $this,
83
+            'postDeleteUser');
84
+        Util::connectHook('OC_User',
85
+            'changeUser',
86
+            $this,
87
+            'changeUser');
88
+    }
89
+
90
+    public function postCreateUser($params) {
91
+        $user = $this->userManager->get($params['uid']);
92
+        $this->syncService->updateUser($user);
93
+    }
94
+
95
+    public function preDeleteUser($params) {
96
+        $uid = $params['uid'];
97
+        $this->usersToDelete[$uid] = $this->userManager->get($uid);
98
+        $this->calendarsToDelete = $this->calDav->getUsersOwnCalendars('principals/users/' . $uid);
99
+        $this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks('principals/users/' . $uid);
100
+    }
101
+
102
+    public function postDeleteUser($params) {
103
+        $uid = $params['uid'];
104
+        if (isset($this->usersToDelete[$uid])){
105
+            $this->syncService->deleteUser($this->usersToDelete[$uid]);
106
+        }
107
+
108
+        foreach ($this->calendarsToDelete as $calendar) {
109
+            $this->calDav->deleteCalendar($calendar['id']);
110
+        }
111
+        $this->calDav->deleteAllSharesByUser('principals/users/' . $uid);
112
+
113
+        foreach ($this->addressBooksToDelete as $addressBook) {
114
+            $this->cardDav->deleteAddressBook($addressBook['id']);
115
+        }
116
+    }
117
+
118
+    public function changeUser($params) {
119
+        $user = $params['user'];
120
+        $this->syncService->updateUser($user);
121
+    }
122
+
123
+    public function firstLogin(IUser $user = null) {
124
+        if (!is_null($user)) {
125
+            $principal = 'principals/users/' . $user->getUID();
126
+            if ($this->calDav->getCalendarsForUserCount($principal) === 0) {
127
+                try {
128
+                    $this->calDav->createCalendar($principal, CalDavBackend::PERSONAL_CALENDAR_URI, [
129
+                        '{DAV:}displayname' => CalDavBackend::PERSONAL_CALENDAR_NAME,
130
+                    ]);
131
+                } catch (\Exception $ex) {
132
+                    \OC::$server->getLogger()->logException($ex);
133
+                }
134
+            }
135
+            if ($this->cardDav->getAddressBooksForUserCount($principal) === 0) {
136
+                try {
137
+                    $this->cardDav->createAddressBook($principal, CardDavBackend::PERSONAL_ADDRESSBOOK_URI, [
138
+                        '{DAV:}displayname' => CardDavBackend::PERSONAL_ADDRESSBOOK_NAME,
139
+                    ]);
140
+                } catch (\Exception $ex) {
141
+                    \OC::$server->getLogger()->logException($ex);
142
+                }
143
+            }
144
+        }
145
+    }
146 146
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -95,20 +95,20 @@  discard block
 block discarded – undo
95 95
 	public function preDeleteUser($params) {
96 96
 		$uid = $params['uid'];
97 97
 		$this->usersToDelete[$uid] = $this->userManager->get($uid);
98
-		$this->calendarsToDelete = $this->calDav->getUsersOwnCalendars('principals/users/' . $uid);
99
-		$this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks('principals/users/' . $uid);
98
+		$this->calendarsToDelete = $this->calDav->getUsersOwnCalendars('principals/users/'.$uid);
99
+		$this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks('principals/users/'.$uid);
100 100
 	}
101 101
 
102 102
 	public function postDeleteUser($params) {
103 103
 		$uid = $params['uid'];
104
-		if (isset($this->usersToDelete[$uid])){
104
+		if (isset($this->usersToDelete[$uid])) {
105 105
 			$this->syncService->deleteUser($this->usersToDelete[$uid]);
106 106
 		}
107 107
 
108 108
 		foreach ($this->calendarsToDelete as $calendar) {
109 109
 			$this->calDav->deleteCalendar($calendar['id']);
110 110
 		}
111
-		$this->calDav->deleteAllSharesByUser('principals/users/' . $uid);
111
+		$this->calDav->deleteAllSharesByUser('principals/users/'.$uid);
112 112
 
113 113
 		foreach ($this->addressBooksToDelete as $addressBook) {
114 114
 			$this->cardDav->deleteAddressBook($addressBook['id']);
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
 
123 123
 	public function firstLogin(IUser $user = null) {
124 124
 		if (!is_null($user)) {
125
-			$principal = 'principals/users/' . $user->getUID();
125
+			$principal = 'principals/users/'.$user->getUID();
126 126
 			if ($this->calDav->getCalendarsForUserCount($principal) === 0) {
127 127
 				try {
128 128
 					$this->calDav->createCalendar($principal, CalDavBackend::PERSONAL_CALENDAR_URI, [
Please login to merge, or discard this patch.
apps/files_sharing/lib/Cache.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -110,6 +110,9 @@
 block discarded – undo
110 110
 		return parent::moveFromCache($sourceCache, $sourcePath, $targetPath);
111 111
 	}
112 112
 
113
+	/**
114
+	 * @param ICacheEntry $entry
115
+	 */
113 116
 	protected function formatCacheEntry($entry) {
114 117
 		$path = isset($entry['path']) ? $entry['path'] : '';
115 118
 		$entry = parent::formatCacheEntry($entry);
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -29,7 +29,6 @@
 block discarded – undo
29 29
 
30 30
 use OC\Files\Cache\Wrapper\CacheJail;
31 31
 use OCP\Files\Cache\ICacheEntry;
32
-use OCP\Files\Storage\IStorage;
33 32
 
34 33
 /**
35 34
  * Metadata cache for shared files
Please login to merge, or discard this patch.
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -37,106 +37,106 @@
 block discarded – undo
37 37
  * don't use this class directly if you need to get metadata, use \OC\Files\Filesystem::getFileInfo instead
38 38
  */
39 39
 class Cache extends CacheJail {
40
-	/**
41
-	 * @var \OCA\Files_Sharing\SharedStorage
42
-	 */
43
-	private $storage;
44
-
45
-	/**
46
-	 * @var ICacheEntry
47
-	 */
48
-	private $sourceRootInfo;
49
-
50
-	private $rootUnchanged = true;
51
-
52
-	private $ownerDisplayName;
53
-
54
-	private $numericId;
55
-
56
-	/**
57
-	 * @param \OCA\Files_Sharing\SharedStorage $storage
58
-	 * @param ICacheEntry $sourceRootInfo
59
-	 */
60
-	public function __construct($storage, ICacheEntry $sourceRootInfo) {
61
-		$this->storage = $storage;
62
-		$this->sourceRootInfo = $sourceRootInfo;
63
-		$this->numericId = $sourceRootInfo->getStorageId();
64
-		parent::__construct(
65
-			null,
66
-			$this->sourceRootInfo->getPath()
67
-		);
68
-	}
69
-
70
-	public function getCache() {
71
-		if (is_null($this->cache)) {
72
-			$this->cache = $this->storage->getSourceStorage()->getCache();
73
-		}
74
-		return $this->cache;
75
-	}
76
-
77
-	public function getNumericStorageId() {
78
-		if (isset($this->numericId)) {
79
-			return $this->numericId;
80
-		} else {
81
-			return false;
82
-		}
83
-	}
84
-
85
-	public function get($file) {
86
-		if ($this->rootUnchanged && ($file === '' || $file === $this->sourceRootInfo->getId())) {
87
-			return $this->formatCacheEntry(clone $this->sourceRootInfo);
88
-		}
89
-		return parent::get($file);
90
-	}
91
-
92
-	public function update($id, array $data) {
93
-		$this->rootUnchanged = false;
94
-		parent::update($id, $data);
95
-	}
96
-
97
-	public function insert($file, array $data) {
98
-		$this->rootUnchanged = false;
99
-		return parent::insert($file, $data);
100
-	}
101
-
102
-	public function remove($file) {
103
-		$this->rootUnchanged = false;
104
-		parent::remove($file);
105
-	}
106
-
107
-	public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
108
-		$this->rootUnchanged = false;
109
-		return parent::moveFromCache($sourceCache, $sourcePath, $targetPath);
110
-	}
111
-
112
-	protected function formatCacheEntry($entry) {
113
-		$path = isset($entry['path']) ? $entry['path'] : '';
114
-		$entry = parent::formatCacheEntry($entry);
115
-		$sharePermissions = $this->storage->getPermissions($path);
116
-		if (isset($entry['permissions'])) {
117
-			$entry['permissions'] &= $sharePermissions;
118
-		} else {
119
-			$entry['permissions'] = $sharePermissions;
120
-		}
121
-		$entry['uid_owner'] = $this->storage->getOwner($path);
122
-		$entry['displayname_owner'] = $this->getOwnerDisplayName();
123
-		if ($path === '') {
124
-			$entry['is_share_mount_point'] = true;
125
-		}
126
-		return $entry;
127
-	}
128
-
129
-	private function getOwnerDisplayName() {
130
-		if (!$this->ownerDisplayName) {
131
-			$this->ownerDisplayName = \OC_User::getDisplayName($this->storage->getOwner(''));
132
-		}
133
-		return $this->ownerDisplayName;
134
-	}
135
-
136
-	/**
137
-	 * remove all entries for files that are stored on the storage from the cache
138
-	 */
139
-	public function clear() {
140
-		// Not a valid action for Shared Cache
141
-	}
40
+    /**
41
+     * @var \OCA\Files_Sharing\SharedStorage
42
+     */
43
+    private $storage;
44
+
45
+    /**
46
+     * @var ICacheEntry
47
+     */
48
+    private $sourceRootInfo;
49
+
50
+    private $rootUnchanged = true;
51
+
52
+    private $ownerDisplayName;
53
+
54
+    private $numericId;
55
+
56
+    /**
57
+     * @param \OCA\Files_Sharing\SharedStorage $storage
58
+     * @param ICacheEntry $sourceRootInfo
59
+     */
60
+    public function __construct($storage, ICacheEntry $sourceRootInfo) {
61
+        $this->storage = $storage;
62
+        $this->sourceRootInfo = $sourceRootInfo;
63
+        $this->numericId = $sourceRootInfo->getStorageId();
64
+        parent::__construct(
65
+            null,
66
+            $this->sourceRootInfo->getPath()
67
+        );
68
+    }
69
+
70
+    public function getCache() {
71
+        if (is_null($this->cache)) {
72
+            $this->cache = $this->storage->getSourceStorage()->getCache();
73
+        }
74
+        return $this->cache;
75
+    }
76
+
77
+    public function getNumericStorageId() {
78
+        if (isset($this->numericId)) {
79
+            return $this->numericId;
80
+        } else {
81
+            return false;
82
+        }
83
+    }
84
+
85
+    public function get($file) {
86
+        if ($this->rootUnchanged && ($file === '' || $file === $this->sourceRootInfo->getId())) {
87
+            return $this->formatCacheEntry(clone $this->sourceRootInfo);
88
+        }
89
+        return parent::get($file);
90
+    }
91
+
92
+    public function update($id, array $data) {
93
+        $this->rootUnchanged = false;
94
+        parent::update($id, $data);
95
+    }
96
+
97
+    public function insert($file, array $data) {
98
+        $this->rootUnchanged = false;
99
+        return parent::insert($file, $data);
100
+    }
101
+
102
+    public function remove($file) {
103
+        $this->rootUnchanged = false;
104
+        parent::remove($file);
105
+    }
106
+
107
+    public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
108
+        $this->rootUnchanged = false;
109
+        return parent::moveFromCache($sourceCache, $sourcePath, $targetPath);
110
+    }
111
+
112
+    protected function formatCacheEntry($entry) {
113
+        $path = isset($entry['path']) ? $entry['path'] : '';
114
+        $entry = parent::formatCacheEntry($entry);
115
+        $sharePermissions = $this->storage->getPermissions($path);
116
+        if (isset($entry['permissions'])) {
117
+            $entry['permissions'] &= $sharePermissions;
118
+        } else {
119
+            $entry['permissions'] = $sharePermissions;
120
+        }
121
+        $entry['uid_owner'] = $this->storage->getOwner($path);
122
+        $entry['displayname_owner'] = $this->getOwnerDisplayName();
123
+        if ($path === '') {
124
+            $entry['is_share_mount_point'] = true;
125
+        }
126
+        return $entry;
127
+    }
128
+
129
+    private function getOwnerDisplayName() {
130
+        if (!$this->ownerDisplayName) {
131
+            $this->ownerDisplayName = \OC_User::getDisplayName($this->storage->getOwner(''));
132
+        }
133
+        return $this->ownerDisplayName;
134
+    }
135
+
136
+    /**
137
+     * remove all entries for files that are stored on the storage from the cache
138
+     */
139
+    public function clear() {
140
+        // Not a valid action for Shared Cache
141
+    }
142 142
 }
Please login to merge, or discard this patch.
lib/private/Files/Filesystem.php 4 patches
Doc Comments   +31 added lines, -2 removed lines patch added patch discarded remove patch
@@ -360,6 +360,9 @@  discard block
 block discarded – undo
360 360
 		}
361 361
 	}
362 362
 
363
+	/**
364
+	 * @param string $root
365
+	 */
363 366
 	static public function init($user, $root) {
364 367
 		if (self::$defaultInstance) {
365 368
 			return false;
@@ -528,7 +531,7 @@  discard block
 block discarded – undo
528 531
 	/**
529 532
 	 * mount an \OC\Files\Storage\Storage in our virtual filesystem
530 533
 	 *
531
-	 * @param \OC\Files\Storage\Storage|string $class
534
+	 * @param string $class
532 535
 	 * @param array $arguments
533 536
 	 * @param string $mountpoint
534 537
 	 */
@@ -660,6 +663,9 @@  discard block
 block discarded – undo
660 663
 		return self::$defaultInstance->is_dir($path);
661 664
 	}
662 665
 
666
+	/**
667
+	 * @param string $path
668
+	 */
663 669
 	static public function is_file($path) {
664 670
 		return self::$defaultInstance->is_file($path);
665 671
 	}
@@ -672,6 +678,9 @@  discard block
 block discarded – undo
672 678
 		return self::$defaultInstance->filetype($path);
673 679
 	}
674 680
 
681
+	/**
682
+	 * @param string $path
683
+	 */
675 684
 	static public function filesize($path) {
676 685
 		return self::$defaultInstance->filesize($path);
677 686
 	}
@@ -684,6 +693,9 @@  discard block
 block discarded – undo
684 693
 		return self::$defaultInstance->isCreatable($path);
685 694
 	}
686 695
 
696
+	/**
697
+	 * @param string $path
698
+	 */
687 699
 	static public function isReadable($path) {
688 700
 		return self::$defaultInstance->isReadable($path);
689 701
 	}
@@ -696,6 +708,9 @@  discard block
 block discarded – undo
696 708
 		return self::$defaultInstance->isDeletable($path);
697 709
 	}
698 710
 
711
+	/**
712
+	 * @param string $path
713
+	 */
699 714
 	static public function isSharable($path) {
700 715
 		return self::$defaultInstance->isSharable($path);
701 716
 	}
@@ -704,6 +719,9 @@  discard block
 block discarded – undo
704 719
 		return self::$defaultInstance->file_exists($path);
705 720
 	}
706 721
 
722
+	/**
723
+	 * @param string $path
724
+	 */
707 725
 	static public function filemtime($path) {
708 726
 		return self::$defaultInstance->filemtime($path);
709 727
 	}
@@ -713,6 +731,7 @@  discard block
 block discarded – undo
713 731
 	}
714 732
 
715 733
 	/**
734
+	 * @param string $path
716 735
 	 * @return string
717 736
 	 */
718 737
 	static public function file_get_contents($path) {
@@ -735,6 +754,10 @@  discard block
 block discarded – undo
735 754
 		return self::$defaultInstance->copy($path1, $path2);
736 755
 	}
737 756
 
757
+	/**
758
+	 * @param string $path
759
+	 * @param string $mode
760
+	 */
738 761
 	static public function fopen($path, $mode) {
739 762
 		return self::$defaultInstance->fopen($path, $mode);
740 763
 	}
@@ -750,6 +773,9 @@  discard block
 block discarded – undo
750 773
 		return self::$defaultInstance->fromTmpFile($tmpFile, $path);
751 774
 	}
752 775
 
776
+	/**
777
+	 * @param string $path
778
+	 */
753 779
 	static public function getMimeType($path) {
754 780
 		return self::$defaultInstance->getMimeType($path);
755 781
 	}
@@ -762,6 +788,9 @@  discard block
 block discarded – undo
762 788
 		return self::$defaultInstance->free_space($path);
763 789
 	}
764 790
 
791
+	/**
792
+	 * @param string $query
793
+	 */
765 794
 	static public function search($query) {
766 795
 		return self::$defaultInstance->search($query);
767 796
 	}
@@ -870,7 +899,7 @@  discard block
 block discarded – undo
870 899
 	 * @param string $path
871 900
 	 * @param boolean $includeMountPoints whether to add mountpoint sizes,
872 901
 	 * defaults to true
873
-	 * @return \OC\Files\FileInfo|bool False if file does not exist
902
+	 * @return \OCP\Files\FileInfo|null False if file does not exist
874 903
 	 */
875 904
 	public static function getFileInfo($path, $includeMountPoints = true) {
876 905
 		return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -64,7 +64,6 @@
 block discarded – undo
64 64
 use OC\Files\Storage\StorageFactory;
65 65
 use OC\Lockdown\Filesystem\NullStorage;
66 66
 use OCP\Files\Config\IMountProvider;
67
-use OCP\Files\Mount\IMountPoint;
68 67
 use OCP\Files\NotFoundException;
69 68
 use OCP\IUserManager;
70 69
 
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -409,17 +409,17 @@  discard block
 block discarded – undo
409 409
 		$userObject = $userManager->get($user);
410 410
 
411 411
 		if (is_null($userObject)) {
412
-			\OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, \OCP\Util::ERROR);
412
+			\OCP\Util::writeLog('files', ' Backends provided no user object for '.$user, \OCP\Util::ERROR);
413 413
 			// reset flag, this will make it possible to rethrow the exception if called again
414 414
 			unset(self::$usersSetup[$user]);
415
-			throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
415
+			throw new \OC\User\NoUserException('Backends provided no user object for '.$user);
416 416
 		}
417 417
 
418 418
 		$realUid = $userObject->getUID();
419 419
 		// workaround in case of different casings
420 420
 		if ($user !== $realUid) {
421 421
 			$stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
422
-			\OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "' . $realUid . '" got "' . $user . '". Stack: ' . $stack, \OCP\Util::WARN);
422
+			\OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "'.$realUid.'" got "'.$user.'". Stack: '.$stack, \OCP\Util::WARN);
423 423
 			$user = $realUid;
424 424
 
425 425
 			// again with the correct casing
@@ -453,11 +453,11 @@  discard block
 block discarded – undo
453 453
 		} else {
454 454
 			self::getMountManager()->addMount(new MountPoint(
455 455
 				new NullStorage([]),
456
-				'/' . $user
456
+				'/'.$user
457 457
 			));
458 458
 			self::getMountManager()->addMount(new MountPoint(
459 459
 				new NullStorage([]),
460
-				'/' . $user . '/files'
460
+				'/'.$user.'/files'
461 461
 			));
462 462
 		}
463 463
 		\OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
@@ -472,7 +472,7 @@  discard block
 block discarded – undo
472 472
 	private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
473 473
 		if (!self::$listeningForProviders) {
474 474
 			self::$listeningForProviders = true;
475
-			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
475
+			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function(IMountProvider $provider) use ($userManager) {
476 476
 				foreach (Filesystem::$usersSetup as $user => $setup) {
477 477
 					$userObject = $userManager->get($user);
478 478
 					if ($userObject) {
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
 	 * @return string
568 568
 	 */
569 569
 	static public function getLocalPath($path) {
570
-		$datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
570
+		$datadir = \OC_User::getHome(\OC_User::getUser()).'/files';
571 571
 		$newpath = $path;
572 572
 		if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
573 573
 			$newpath = substr($path, strlen($datadir));
@@ -584,7 +584,7 @@  discard block
 block discarded – undo
584 584
 	static public function isValidPath($path) {
585 585
 		$path = self::normalizePath($path);
586 586
 		if (!$path || $path[0] !== '/') {
587
-			$path = '/' . $path;
587
+			$path = '/'.$path;
588 588
 		}
589 589
 		if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
590 590
 			return false;
@@ -813,7 +813,7 @@  discard block
 block discarded – undo
813 813
 		 *        conversion should get removed as soon as all existing
814 814
 		 *        function calls have been fixed.
815 815
 		 */
816
-		$path = (string)$path;
816
+		$path = (string) $path;
817 817
 
818 818
 		$cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
819 819
 
@@ -835,7 +835,7 @@  discard block
 block discarded – undo
835 835
 
836 836
 		//add leading slash
837 837
 		if ($path[0] !== '/') {
838
-			$path = '/' . $path;
838
+			$path = '/'.$path;
839 839
 		}
840 840
 
841 841
 		// remove '/./'
Please login to merge, or discard this patch.
Indentation   +861 added lines, -861 removed lines patch added patch discarded remove patch
@@ -70,865 +70,865 @@
 block discarded – undo
70 70
 
71 71
 class Filesystem {
72 72
 
73
-	/**
74
-	 * @var Mount\Manager $mounts
75
-	 */
76
-	private static $mounts;
77
-
78
-	public static $loaded = false;
79
-	/**
80
-	 * @var \OC\Files\View $defaultInstance
81
-	 */
82
-	static private $defaultInstance;
83
-
84
-	static private $usersSetup = array();
85
-
86
-	static private $normalizedPathCache = null;
87
-
88
-	static private $listeningForProviders = false;
89
-
90
-	/**
91
-	 * classname which used for hooks handling
92
-	 * used as signalclass in OC_Hooks::emit()
93
-	 */
94
-	const CLASSNAME = 'OC_Filesystem';
95
-
96
-	/**
97
-	 * signalname emitted before file renaming
98
-	 *
99
-	 * @param string $oldpath
100
-	 * @param string $newpath
101
-	 */
102
-	const signal_rename = 'rename';
103
-
104
-	/**
105
-	 * signal emitted after file renaming
106
-	 *
107
-	 * @param string $oldpath
108
-	 * @param string $newpath
109
-	 */
110
-	const signal_post_rename = 'post_rename';
111
-
112
-	/**
113
-	 * signal emitted before file/dir creation
114
-	 *
115
-	 * @param string $path
116
-	 * @param bool $run changing this flag to false in hook handler will cancel event
117
-	 */
118
-	const signal_create = 'create';
119
-
120
-	/**
121
-	 * signal emitted after file/dir creation
122
-	 *
123
-	 * @param string $path
124
-	 * @param bool $run changing this flag to false in hook handler will cancel event
125
-	 */
126
-	const signal_post_create = 'post_create';
127
-
128
-	/**
129
-	 * signal emits before file/dir copy
130
-	 *
131
-	 * @param string $oldpath
132
-	 * @param string $newpath
133
-	 * @param bool $run changing this flag to false in hook handler will cancel event
134
-	 */
135
-	const signal_copy = 'copy';
136
-
137
-	/**
138
-	 * signal emits after file/dir copy
139
-	 *
140
-	 * @param string $oldpath
141
-	 * @param string $newpath
142
-	 */
143
-	const signal_post_copy = 'post_copy';
144
-
145
-	/**
146
-	 * signal emits before file/dir save
147
-	 *
148
-	 * @param string $path
149
-	 * @param bool $run changing this flag to false in hook handler will cancel event
150
-	 */
151
-	const signal_write = 'write';
152
-
153
-	/**
154
-	 * signal emits after file/dir save
155
-	 *
156
-	 * @param string $path
157
-	 */
158
-	const signal_post_write = 'post_write';
159
-
160
-	/**
161
-	 * signal emitted before file/dir update
162
-	 *
163
-	 * @param string $path
164
-	 * @param bool $run changing this flag to false in hook handler will cancel event
165
-	 */
166
-	const signal_update = 'update';
167
-
168
-	/**
169
-	 * signal emitted after file/dir update
170
-	 *
171
-	 * @param string $path
172
-	 * @param bool $run changing this flag to false in hook handler will cancel event
173
-	 */
174
-	const signal_post_update = 'post_update';
175
-
176
-	/**
177
-	 * signal emits when reading file/dir
178
-	 *
179
-	 * @param string $path
180
-	 */
181
-	const signal_read = 'read';
182
-
183
-	/**
184
-	 * signal emits when removing file/dir
185
-	 *
186
-	 * @param string $path
187
-	 */
188
-	const signal_delete = 'delete';
189
-
190
-	/**
191
-	 * parameters definitions for signals
192
-	 */
193
-	const signal_param_path = 'path';
194
-	const signal_param_oldpath = 'oldpath';
195
-	const signal_param_newpath = 'newpath';
196
-
197
-	/**
198
-	 * run - changing this flag to false in hook handler will cancel event
199
-	 */
200
-	const signal_param_run = 'run';
201
-
202
-	const signal_create_mount = 'create_mount';
203
-	const signal_delete_mount = 'delete_mount';
204
-	const signal_param_mount_type = 'mounttype';
205
-	const signal_param_users = 'users';
206
-
207
-	/**
208
-	 * @var \OC\Files\Storage\StorageFactory $loader
209
-	 */
210
-	private static $loader;
211
-
212
-	/** @var bool */
213
-	private static $logWarningWhenAddingStorageWrapper = true;
214
-
215
-	/**
216
-	 * @param bool $shouldLog
217
-	 * @return bool previous value
218
-	 * @internal
219
-	 */
220
-	public static function logWarningWhenAddingStorageWrapper($shouldLog) {
221
-		$previousValue = self::$logWarningWhenAddingStorageWrapper;
222
-		self::$logWarningWhenAddingStorageWrapper = (bool) $shouldLog;
223
-		return $previousValue;
224
-	}
225
-
226
-	/**
227
-	 * @param string $wrapperName
228
-	 * @param callable $wrapper
229
-	 * @param int $priority
230
-	 */
231
-	public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) {
232
-		if (self::$logWarningWhenAddingStorageWrapper) {
233
-			\OC::$server->getLogger()->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [
234
-				'wrapper' => $wrapperName,
235
-				'app' => 'filesystem',
236
-			]);
237
-		}
238
-
239
-		$mounts = self::getMountManager()->getAll();
240
-		if (!self::getLoader()->addStorageWrapper($wrapperName, $wrapper, $priority, $mounts)) {
241
-			// do not re-wrap if storage with this name already existed
242
-			return;
243
-		}
244
-	}
245
-
246
-	/**
247
-	 * Returns the storage factory
248
-	 *
249
-	 * @return \OCP\Files\Storage\IStorageFactory
250
-	 */
251
-	public static function getLoader() {
252
-		if (!self::$loader) {
253
-			self::$loader = new StorageFactory();
254
-		}
255
-		return self::$loader;
256
-	}
257
-
258
-	/**
259
-	 * Returns the mount manager
260
-	 *
261
-	 * @return \OC\Files\Mount\Manager
262
-	 */
263
-	public static function getMountManager($user = '') {
264
-		if (!self::$mounts) {
265
-			\OC_Util::setupFS($user);
266
-		}
267
-		return self::$mounts;
268
-	}
269
-
270
-	/**
271
-	 * get the mountpoint of the storage object for a path
272
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
273
-	 * returned mountpoint is relative to the absolute root of the filesystem
274
-	 * and doesn't take the chroot into account )
275
-	 *
276
-	 * @param string $path
277
-	 * @return string
278
-	 */
279
-	static public function getMountPoint($path) {
280
-		if (!self::$mounts) {
281
-			\OC_Util::setupFS();
282
-		}
283
-		$mount = self::$mounts->find($path);
284
-		if ($mount) {
285
-			return $mount->getMountPoint();
286
-		} else {
287
-			return '';
288
-		}
289
-	}
290
-
291
-	/**
292
-	 * get a list of all mount points in a directory
293
-	 *
294
-	 * @param string $path
295
-	 * @return string[]
296
-	 */
297
-	static public function getMountPoints($path) {
298
-		if (!self::$mounts) {
299
-			\OC_Util::setupFS();
300
-		}
301
-		$result = array();
302
-		$mounts = self::$mounts->findIn($path);
303
-		foreach ($mounts as $mount) {
304
-			$result[] = $mount->getMountPoint();
305
-		}
306
-		return $result;
307
-	}
308
-
309
-	/**
310
-	 * get the storage mounted at $mountPoint
311
-	 *
312
-	 * @param string $mountPoint
313
-	 * @return \OC\Files\Storage\Storage
314
-	 */
315
-	public static function getStorage($mountPoint) {
316
-		if (!self::$mounts) {
317
-			\OC_Util::setupFS();
318
-		}
319
-		$mount = self::$mounts->find($mountPoint);
320
-		return $mount->getStorage();
321
-	}
322
-
323
-	/**
324
-	 * @param string $id
325
-	 * @return Mount\MountPoint[]
326
-	 */
327
-	public static function getMountByStorageId($id) {
328
-		if (!self::$mounts) {
329
-			\OC_Util::setupFS();
330
-		}
331
-		return self::$mounts->findByStorageId($id);
332
-	}
333
-
334
-	/**
335
-	 * @param int $id
336
-	 * @return Mount\MountPoint[]
337
-	 */
338
-	public static function getMountByNumericId($id) {
339
-		if (!self::$mounts) {
340
-			\OC_Util::setupFS();
341
-		}
342
-		return self::$mounts->findByNumericId($id);
343
-	}
344
-
345
-	/**
346
-	 * resolve a path to a storage and internal path
347
-	 *
348
-	 * @param string $path
349
-	 * @return array an array consisting of the storage and the internal path
350
-	 */
351
-	static public function resolvePath($path) {
352
-		if (!self::$mounts) {
353
-			\OC_Util::setupFS();
354
-		}
355
-		$mount = self::$mounts->find($path);
356
-		if ($mount) {
357
-			return array($mount->getStorage(), rtrim($mount->getInternalPath($path), '/'));
358
-		} else {
359
-			return array(null, null);
360
-		}
361
-	}
362
-
363
-	static public function init($user, $root) {
364
-		if (self::$defaultInstance) {
365
-			return false;
366
-		}
367
-		self::getLoader();
368
-		self::$defaultInstance = new View($root);
369
-
370
-		if (!self::$mounts) {
371
-			self::$mounts = \OC::$server->getMountManager();
372
-		}
373
-
374
-		//load custom mount config
375
-		self::initMountPoints($user);
376
-
377
-		self::$loaded = true;
378
-
379
-		return true;
380
-	}
381
-
382
-	static public function initMountManager() {
383
-		if (!self::$mounts) {
384
-			self::$mounts = \OC::$server->getMountManager();
385
-		}
386
-	}
387
-
388
-	/**
389
-	 * Initialize system and personal mount points for a user
390
-	 *
391
-	 * @param string $user
392
-	 * @throws \OC\User\NoUserException if the user is not available
393
-	 */
394
-	public static function initMountPoints($user = '') {
395
-		if ($user == '') {
396
-			$user = \OC_User::getUser();
397
-		}
398
-		if ($user === null || $user === false || $user === '') {
399
-			throw new \OC\User\NoUserException('Attempted to initialize mount points for null user and no user in session');
400
-		}
401
-
402
-		if (isset(self::$usersSetup[$user])) {
403
-			return;
404
-		}
405
-
406
-		self::$usersSetup[$user] = true;
407
-
408
-		$userManager = \OC::$server->getUserManager();
409
-		$userObject = $userManager->get($user);
410
-
411
-		if (is_null($userObject)) {
412
-			\OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, \OCP\Util::ERROR);
413
-			// reset flag, this will make it possible to rethrow the exception if called again
414
-			unset(self::$usersSetup[$user]);
415
-			throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
416
-		}
417
-
418
-		$realUid = $userObject->getUID();
419
-		// workaround in case of different casings
420
-		if ($user !== $realUid) {
421
-			$stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
422
-			\OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "' . $realUid . '" got "' . $user . '". Stack: ' . $stack, \OCP\Util::WARN);
423
-			$user = $realUid;
424
-
425
-			// again with the correct casing
426
-			if (isset(self::$usersSetup[$user])) {
427
-				return;
428
-			}
429
-
430
-			self::$usersSetup[$user] = true;
431
-		}
432
-
433
-		if (\OC::$server->getLockdownManager()->canAccessFilesystem()) {
434
-			/** @var \OC\Files\Config\MountProviderCollection $mountConfigManager */
435
-			$mountConfigManager = \OC::$server->getMountProviderCollection();
436
-
437
-			// home mounts are handled seperate since we need to ensure this is mounted before we call the other mount providers
438
-			$homeMount = $mountConfigManager->getHomeMountForUser($userObject);
439
-
440
-			self::getMountManager()->addMount($homeMount);
441
-
442
-			\OC\Files\Filesystem::getStorage($user);
443
-
444
-			// Chance to mount for other storages
445
-			if ($userObject) {
446
-				$mounts = $mountConfigManager->addMountForUser($userObject, self::getMountManager());
447
-				$mounts[] = $homeMount;
448
-				$mountConfigManager->registerMounts($userObject, $mounts);
449
-			}
450
-
451
-			self::listenForNewMountProviders($mountConfigManager, $userManager);
452
-		} else {
453
-			self::getMountManager()->addMount(new MountPoint(
454
-				new NullStorage([]),
455
-				'/' . $user
456
-			));
457
-			self::getMountManager()->addMount(new MountPoint(
458
-				new NullStorage([]),
459
-				'/' . $user . '/files'
460
-			));
461
-		}
462
-		\OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
463
-	}
464
-
465
-	/**
466
-	 * Get mounts from mount providers that are registered after setup
467
-	 *
468
-	 * @param MountProviderCollection $mountConfigManager
469
-	 * @param IUserManager $userManager
470
-	 */
471
-	private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
472
-		if (!self::$listeningForProviders) {
473
-			self::$listeningForProviders = true;
474
-			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
475
-				foreach (Filesystem::$usersSetup as $user => $setup) {
476
-					$userObject = $userManager->get($user);
477
-					if ($userObject) {
478
-						$mounts = $provider->getMountsForUser($userObject, Filesystem::getLoader());
479
-						array_walk($mounts, array(self::$mounts, 'addMount'));
480
-					}
481
-				}
482
-			});
483
-		}
484
-	}
485
-
486
-	/**
487
-	 * get the default filesystem view
488
-	 *
489
-	 * @return View
490
-	 */
491
-	static public function getView() {
492
-		return self::$defaultInstance;
493
-	}
494
-
495
-	/**
496
-	 * tear down the filesystem, removing all storage providers
497
-	 */
498
-	static public function tearDown() {
499
-		self::clearMounts();
500
-		self::$defaultInstance = null;
501
-	}
502
-
503
-	/**
504
-	 * get the relative path of the root data directory for the current user
505
-	 *
506
-	 * @return string
507
-	 *
508
-	 * Returns path like /admin/files
509
-	 */
510
-	static public function getRoot() {
511
-		if (!self::$defaultInstance) {
512
-			return null;
513
-		}
514
-		return self::$defaultInstance->getRoot();
515
-	}
516
-
517
-	/**
518
-	 * clear all mounts and storage backends
519
-	 */
520
-	public static function clearMounts() {
521
-		if (self::$mounts) {
522
-			self::$usersSetup = array();
523
-			self::$mounts->clear();
524
-		}
525
-	}
526
-
527
-	/**
528
-	 * mount an \OC\Files\Storage\Storage in our virtual filesystem
529
-	 *
530
-	 * @param \OC\Files\Storage\Storage|string $class
531
-	 * @param array $arguments
532
-	 * @param string $mountpoint
533
-	 */
534
-	static public function mount($class, $arguments, $mountpoint) {
535
-		if (!self::$mounts) {
536
-			\OC_Util::setupFS();
537
-		}
538
-		$mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader());
539
-		self::$mounts->addMount($mount);
540
-	}
541
-
542
-	/**
543
-	 * return the path to a local version of the file
544
-	 * we need this because we can't know if a file is stored local or not from
545
-	 * outside the filestorage and for some purposes a local file is needed
546
-	 *
547
-	 * @param string $path
548
-	 * @return string
549
-	 */
550
-	static public function getLocalFile($path) {
551
-		return self::$defaultInstance->getLocalFile($path);
552
-	}
553
-
554
-	/**
555
-	 * @param string $path
556
-	 * @return string
557
-	 */
558
-	static public function getLocalFolder($path) {
559
-		return self::$defaultInstance->getLocalFolder($path);
560
-	}
561
-
562
-	/**
563
-	 * return path to file which reflects one visible in browser
564
-	 *
565
-	 * @param string $path
566
-	 * @return string
567
-	 */
568
-	static public function getLocalPath($path) {
569
-		$datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
570
-		$newpath = $path;
571
-		if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
572
-			$newpath = substr($path, strlen($datadir));
573
-		}
574
-		return $newpath;
575
-	}
576
-
577
-	/**
578
-	 * check if the requested path is valid
579
-	 *
580
-	 * @param string $path
581
-	 * @return bool
582
-	 */
583
-	static public function isValidPath($path) {
584
-		$path = self::normalizePath($path);
585
-		if (!$path || $path[0] !== '/') {
586
-			$path = '/' . $path;
587
-		}
588
-		if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
589
-			return false;
590
-		}
591
-		return true;
592
-	}
593
-
594
-	/**
595
-	 * checks if a file is blacklisted for storage in the filesystem
596
-	 * Listens to write and rename hooks
597
-	 *
598
-	 * @param array $data from hook
599
-	 */
600
-	static public function isBlacklisted($data) {
601
-		if (isset($data['path'])) {
602
-			$path = $data['path'];
603
-		} else if (isset($data['newpath'])) {
604
-			$path = $data['newpath'];
605
-		}
606
-		if (isset($path)) {
607
-			if (self::isFileBlacklisted($path)) {
608
-				$data['run'] = false;
609
-			}
610
-		}
611
-	}
612
-
613
-	/**
614
-	 * @param string $filename
615
-	 * @return bool
616
-	 */
617
-	static public function isFileBlacklisted($filename) {
618
-		$filename = self::normalizePath($filename);
619
-
620
-		$blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array('.htaccess'));
621
-		$filename = strtolower(basename($filename));
622
-		return in_array($filename, $blacklist);
623
-	}
624
-
625
-	/**
626
-	 * check if the directory should be ignored when scanning
627
-	 * NOTE: the special directories . and .. would cause never ending recursion
628
-	 *
629
-	 * @param String $dir
630
-	 * @return boolean
631
-	 */
632
-	static public function isIgnoredDir($dir) {
633
-		if ($dir === '.' || $dir === '..') {
634
-			return true;
635
-		}
636
-		return false;
637
-	}
638
-
639
-	/**
640
-	 * following functions are equivalent to their php builtin equivalents for arguments/return values.
641
-	 */
642
-	static public function mkdir($path) {
643
-		return self::$defaultInstance->mkdir($path);
644
-	}
645
-
646
-	static public function rmdir($path) {
647
-		return self::$defaultInstance->rmdir($path);
648
-	}
649
-
650
-	static public function opendir($path) {
651
-		return self::$defaultInstance->opendir($path);
652
-	}
653
-
654
-	static public function readdir($path) {
655
-		return self::$defaultInstance->readdir($path);
656
-	}
657
-
658
-	static public function is_dir($path) {
659
-		return self::$defaultInstance->is_dir($path);
660
-	}
661
-
662
-	static public function is_file($path) {
663
-		return self::$defaultInstance->is_file($path);
664
-	}
665
-
666
-	static public function stat($path) {
667
-		return self::$defaultInstance->stat($path);
668
-	}
669
-
670
-	static public function filetype($path) {
671
-		return self::$defaultInstance->filetype($path);
672
-	}
673
-
674
-	static public function filesize($path) {
675
-		return self::$defaultInstance->filesize($path);
676
-	}
677
-
678
-	static public function readfile($path) {
679
-		return self::$defaultInstance->readfile($path);
680
-	}
681
-
682
-	static public function isCreatable($path) {
683
-		return self::$defaultInstance->isCreatable($path);
684
-	}
685
-
686
-	static public function isReadable($path) {
687
-		return self::$defaultInstance->isReadable($path);
688
-	}
689
-
690
-	static public function isUpdatable($path) {
691
-		return self::$defaultInstance->isUpdatable($path);
692
-	}
693
-
694
-	static public function isDeletable($path) {
695
-		return self::$defaultInstance->isDeletable($path);
696
-	}
697
-
698
-	static public function isSharable($path) {
699
-		return self::$defaultInstance->isSharable($path);
700
-	}
701
-
702
-	static public function file_exists($path) {
703
-		return self::$defaultInstance->file_exists($path);
704
-	}
705
-
706
-	static public function filemtime($path) {
707
-		return self::$defaultInstance->filemtime($path);
708
-	}
709
-
710
-	static public function touch($path, $mtime = null) {
711
-		return self::$defaultInstance->touch($path, $mtime);
712
-	}
713
-
714
-	/**
715
-	 * @return string
716
-	 */
717
-	static public function file_get_contents($path) {
718
-		return self::$defaultInstance->file_get_contents($path);
719
-	}
720
-
721
-	static public function file_put_contents($path, $data) {
722
-		return self::$defaultInstance->file_put_contents($path, $data);
723
-	}
724
-
725
-	static public function unlink($path) {
726
-		return self::$defaultInstance->unlink($path);
727
-	}
728
-
729
-	static public function rename($path1, $path2) {
730
-		return self::$defaultInstance->rename($path1, $path2);
731
-	}
732
-
733
-	static public function copy($path1, $path2) {
734
-		return self::$defaultInstance->copy($path1, $path2);
735
-	}
736
-
737
-	static public function fopen($path, $mode) {
738
-		return self::$defaultInstance->fopen($path, $mode);
739
-	}
740
-
741
-	/**
742
-	 * @return string
743
-	 */
744
-	static public function toTmpFile($path) {
745
-		return self::$defaultInstance->toTmpFile($path);
746
-	}
747
-
748
-	static public function fromTmpFile($tmpFile, $path) {
749
-		return self::$defaultInstance->fromTmpFile($tmpFile, $path);
750
-	}
751
-
752
-	static public function getMimeType($path) {
753
-		return self::$defaultInstance->getMimeType($path);
754
-	}
755
-
756
-	static public function hash($type, $path, $raw = false) {
757
-		return self::$defaultInstance->hash($type, $path, $raw);
758
-	}
759
-
760
-	static public function free_space($path = '/') {
761
-		return self::$defaultInstance->free_space($path);
762
-	}
763
-
764
-	static public function search($query) {
765
-		return self::$defaultInstance->search($query);
766
-	}
767
-
768
-	/**
769
-	 * @param string $query
770
-	 */
771
-	static public function searchByMime($query) {
772
-		return self::$defaultInstance->searchByMime($query);
773
-	}
774
-
775
-	/**
776
-	 * @param string|int $tag name or tag id
777
-	 * @param string $userId owner of the tags
778
-	 * @return FileInfo[] array or file info
779
-	 */
780
-	static public function searchByTag($tag, $userId) {
781
-		return self::$defaultInstance->searchByTag($tag, $userId);
782
-	}
783
-
784
-	/**
785
-	 * check if a file or folder has been updated since $time
786
-	 *
787
-	 * @param string $path
788
-	 * @param int $time
789
-	 * @return bool
790
-	 */
791
-	static public function hasUpdated($path, $time) {
792
-		return self::$defaultInstance->hasUpdated($path, $time);
793
-	}
794
-
795
-	/**
796
-	 * Fix common problems with a file path
797
-	 *
798
-	 * @param string $path
799
-	 * @param bool $stripTrailingSlash whether to strip the trailing slash
800
-	 * @param bool $isAbsolutePath whether the given path is absolute
801
-	 * @param bool $keepUnicode true to disable unicode normalization
802
-	 * @return string
803
-	 */
804
-	public static function normalizePath($path, $stripTrailingSlash = true, $isAbsolutePath = false, $keepUnicode = false) {
805
-		if (is_null(self::$normalizedPathCache)) {
806
-			self::$normalizedPathCache = new CappedMemoryCache();
807
-		}
808
-
809
-		/**
810
-		 * FIXME: This is a workaround for existing classes and files which call
811
-		 *        this function with another type than a valid string. This
812
-		 *        conversion should get removed as soon as all existing
813
-		 *        function calls have been fixed.
814
-		 */
815
-		$path = (string)$path;
816
-
817
-		$cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
818
-
819
-		if (isset(self::$normalizedPathCache[$cacheKey])) {
820
-			return self::$normalizedPathCache[$cacheKey];
821
-		}
822
-
823
-		if ($path == '') {
824
-			return '/';
825
-		}
826
-
827
-		//normalize unicode if possible
828
-		if (!$keepUnicode) {
829
-			$path = \OC_Util::normalizeUnicode($path);
830
-		}
831
-
832
-		//no windows style slashes
833
-		$path = str_replace('\\', '/', $path);
834
-
835
-		//add leading slash
836
-		if ($path[0] !== '/') {
837
-			$path = '/' . $path;
838
-		}
839
-
840
-		// remove '/./'
841
-		// ugly, but str_replace() can't replace them all in one go
842
-		// as the replacement itself is part of the search string
843
-		// which will only be found during the next iteration
844
-		while (strpos($path, '/./') !== false) {
845
-			$path = str_replace('/./', '/', $path);
846
-		}
847
-		// remove sequences of slashes
848
-		$path = preg_replace('#/{2,}#', '/', $path);
849
-
850
-		//remove trailing slash
851
-		if ($stripTrailingSlash and strlen($path) > 1 and substr($path, -1, 1) === '/') {
852
-			$path = substr($path, 0, -1);
853
-		}
854
-
855
-		// remove trailing '/.'
856
-		if (substr($path, -2) == '/.') {
857
-			$path = substr($path, 0, -2);
858
-		}
859
-
860
-		$normalizedPath = $path;
861
-		self::$normalizedPathCache[$cacheKey] = $normalizedPath;
862
-
863
-		return $normalizedPath;
864
-	}
865
-
866
-	/**
867
-	 * get the filesystem info
868
-	 *
869
-	 * @param string $path
870
-	 * @param boolean $includeMountPoints whether to add mountpoint sizes,
871
-	 * defaults to true
872
-	 * @return \OC\Files\FileInfo|bool False if file does not exist
873
-	 */
874
-	public static function getFileInfo($path, $includeMountPoints = true) {
875
-		return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
876
-	}
877
-
878
-	/**
879
-	 * change file metadata
880
-	 *
881
-	 * @param string $path
882
-	 * @param array $data
883
-	 * @return int
884
-	 *
885
-	 * returns the fileid of the updated file
886
-	 */
887
-	public static function putFileInfo($path, $data) {
888
-		return self::$defaultInstance->putFileInfo($path, $data);
889
-	}
890
-
891
-	/**
892
-	 * get the content of a directory
893
-	 *
894
-	 * @param string $directory path under datadirectory
895
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
896
-	 * @return \OC\Files\FileInfo[]
897
-	 */
898
-	public static function getDirectoryContent($directory, $mimetype_filter = '') {
899
-		return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter);
900
-	}
901
-
902
-	/**
903
-	 * Get the path of a file by id
904
-	 *
905
-	 * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
906
-	 *
907
-	 * @param int $id
908
-	 * @throws NotFoundException
909
-	 * @return string
910
-	 */
911
-	public static function getPath($id) {
912
-		return self::$defaultInstance->getPath($id);
913
-	}
914
-
915
-	/**
916
-	 * Get the owner for a file or folder
917
-	 *
918
-	 * @param string $path
919
-	 * @return string
920
-	 */
921
-	public static function getOwner($path) {
922
-		return self::$defaultInstance->getOwner($path);
923
-	}
924
-
925
-	/**
926
-	 * get the ETag for a file or folder
927
-	 *
928
-	 * @param string $path
929
-	 * @return string
930
-	 */
931
-	static public function getETag($path) {
932
-		return self::$defaultInstance->getETag($path);
933
-	}
73
+    /**
74
+     * @var Mount\Manager $mounts
75
+     */
76
+    private static $mounts;
77
+
78
+    public static $loaded = false;
79
+    /**
80
+     * @var \OC\Files\View $defaultInstance
81
+     */
82
+    static private $defaultInstance;
83
+
84
+    static private $usersSetup = array();
85
+
86
+    static private $normalizedPathCache = null;
87
+
88
+    static private $listeningForProviders = false;
89
+
90
+    /**
91
+     * classname which used for hooks handling
92
+     * used as signalclass in OC_Hooks::emit()
93
+     */
94
+    const CLASSNAME = 'OC_Filesystem';
95
+
96
+    /**
97
+     * signalname emitted before file renaming
98
+     *
99
+     * @param string $oldpath
100
+     * @param string $newpath
101
+     */
102
+    const signal_rename = 'rename';
103
+
104
+    /**
105
+     * signal emitted after file renaming
106
+     *
107
+     * @param string $oldpath
108
+     * @param string $newpath
109
+     */
110
+    const signal_post_rename = 'post_rename';
111
+
112
+    /**
113
+     * signal emitted before file/dir creation
114
+     *
115
+     * @param string $path
116
+     * @param bool $run changing this flag to false in hook handler will cancel event
117
+     */
118
+    const signal_create = 'create';
119
+
120
+    /**
121
+     * signal emitted after file/dir creation
122
+     *
123
+     * @param string $path
124
+     * @param bool $run changing this flag to false in hook handler will cancel event
125
+     */
126
+    const signal_post_create = 'post_create';
127
+
128
+    /**
129
+     * signal emits before file/dir copy
130
+     *
131
+     * @param string $oldpath
132
+     * @param string $newpath
133
+     * @param bool $run changing this flag to false in hook handler will cancel event
134
+     */
135
+    const signal_copy = 'copy';
136
+
137
+    /**
138
+     * signal emits after file/dir copy
139
+     *
140
+     * @param string $oldpath
141
+     * @param string $newpath
142
+     */
143
+    const signal_post_copy = 'post_copy';
144
+
145
+    /**
146
+     * signal emits before file/dir save
147
+     *
148
+     * @param string $path
149
+     * @param bool $run changing this flag to false in hook handler will cancel event
150
+     */
151
+    const signal_write = 'write';
152
+
153
+    /**
154
+     * signal emits after file/dir save
155
+     *
156
+     * @param string $path
157
+     */
158
+    const signal_post_write = 'post_write';
159
+
160
+    /**
161
+     * signal emitted before file/dir update
162
+     *
163
+     * @param string $path
164
+     * @param bool $run changing this flag to false in hook handler will cancel event
165
+     */
166
+    const signal_update = 'update';
167
+
168
+    /**
169
+     * signal emitted after file/dir update
170
+     *
171
+     * @param string $path
172
+     * @param bool $run changing this flag to false in hook handler will cancel event
173
+     */
174
+    const signal_post_update = 'post_update';
175
+
176
+    /**
177
+     * signal emits when reading file/dir
178
+     *
179
+     * @param string $path
180
+     */
181
+    const signal_read = 'read';
182
+
183
+    /**
184
+     * signal emits when removing file/dir
185
+     *
186
+     * @param string $path
187
+     */
188
+    const signal_delete = 'delete';
189
+
190
+    /**
191
+     * parameters definitions for signals
192
+     */
193
+    const signal_param_path = 'path';
194
+    const signal_param_oldpath = 'oldpath';
195
+    const signal_param_newpath = 'newpath';
196
+
197
+    /**
198
+     * run - changing this flag to false in hook handler will cancel event
199
+     */
200
+    const signal_param_run = 'run';
201
+
202
+    const signal_create_mount = 'create_mount';
203
+    const signal_delete_mount = 'delete_mount';
204
+    const signal_param_mount_type = 'mounttype';
205
+    const signal_param_users = 'users';
206
+
207
+    /**
208
+     * @var \OC\Files\Storage\StorageFactory $loader
209
+     */
210
+    private static $loader;
211
+
212
+    /** @var bool */
213
+    private static $logWarningWhenAddingStorageWrapper = true;
214
+
215
+    /**
216
+     * @param bool $shouldLog
217
+     * @return bool previous value
218
+     * @internal
219
+     */
220
+    public static function logWarningWhenAddingStorageWrapper($shouldLog) {
221
+        $previousValue = self::$logWarningWhenAddingStorageWrapper;
222
+        self::$logWarningWhenAddingStorageWrapper = (bool) $shouldLog;
223
+        return $previousValue;
224
+    }
225
+
226
+    /**
227
+     * @param string $wrapperName
228
+     * @param callable $wrapper
229
+     * @param int $priority
230
+     */
231
+    public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) {
232
+        if (self::$logWarningWhenAddingStorageWrapper) {
233
+            \OC::$server->getLogger()->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [
234
+                'wrapper' => $wrapperName,
235
+                'app' => 'filesystem',
236
+            ]);
237
+        }
238
+
239
+        $mounts = self::getMountManager()->getAll();
240
+        if (!self::getLoader()->addStorageWrapper($wrapperName, $wrapper, $priority, $mounts)) {
241
+            // do not re-wrap if storage with this name already existed
242
+            return;
243
+        }
244
+    }
245
+
246
+    /**
247
+     * Returns the storage factory
248
+     *
249
+     * @return \OCP\Files\Storage\IStorageFactory
250
+     */
251
+    public static function getLoader() {
252
+        if (!self::$loader) {
253
+            self::$loader = new StorageFactory();
254
+        }
255
+        return self::$loader;
256
+    }
257
+
258
+    /**
259
+     * Returns the mount manager
260
+     *
261
+     * @return \OC\Files\Mount\Manager
262
+     */
263
+    public static function getMountManager($user = '') {
264
+        if (!self::$mounts) {
265
+            \OC_Util::setupFS($user);
266
+        }
267
+        return self::$mounts;
268
+    }
269
+
270
+    /**
271
+     * get the mountpoint of the storage object for a path
272
+     * ( note: because a storage is not always mounted inside the fakeroot, the
273
+     * returned mountpoint is relative to the absolute root of the filesystem
274
+     * and doesn't take the chroot into account )
275
+     *
276
+     * @param string $path
277
+     * @return string
278
+     */
279
+    static public function getMountPoint($path) {
280
+        if (!self::$mounts) {
281
+            \OC_Util::setupFS();
282
+        }
283
+        $mount = self::$mounts->find($path);
284
+        if ($mount) {
285
+            return $mount->getMountPoint();
286
+        } else {
287
+            return '';
288
+        }
289
+    }
290
+
291
+    /**
292
+     * get a list of all mount points in a directory
293
+     *
294
+     * @param string $path
295
+     * @return string[]
296
+     */
297
+    static public function getMountPoints($path) {
298
+        if (!self::$mounts) {
299
+            \OC_Util::setupFS();
300
+        }
301
+        $result = array();
302
+        $mounts = self::$mounts->findIn($path);
303
+        foreach ($mounts as $mount) {
304
+            $result[] = $mount->getMountPoint();
305
+        }
306
+        return $result;
307
+    }
308
+
309
+    /**
310
+     * get the storage mounted at $mountPoint
311
+     *
312
+     * @param string $mountPoint
313
+     * @return \OC\Files\Storage\Storage
314
+     */
315
+    public static function getStorage($mountPoint) {
316
+        if (!self::$mounts) {
317
+            \OC_Util::setupFS();
318
+        }
319
+        $mount = self::$mounts->find($mountPoint);
320
+        return $mount->getStorage();
321
+    }
322
+
323
+    /**
324
+     * @param string $id
325
+     * @return Mount\MountPoint[]
326
+     */
327
+    public static function getMountByStorageId($id) {
328
+        if (!self::$mounts) {
329
+            \OC_Util::setupFS();
330
+        }
331
+        return self::$mounts->findByStorageId($id);
332
+    }
333
+
334
+    /**
335
+     * @param int $id
336
+     * @return Mount\MountPoint[]
337
+     */
338
+    public static function getMountByNumericId($id) {
339
+        if (!self::$mounts) {
340
+            \OC_Util::setupFS();
341
+        }
342
+        return self::$mounts->findByNumericId($id);
343
+    }
344
+
345
+    /**
346
+     * resolve a path to a storage and internal path
347
+     *
348
+     * @param string $path
349
+     * @return array an array consisting of the storage and the internal path
350
+     */
351
+    static public function resolvePath($path) {
352
+        if (!self::$mounts) {
353
+            \OC_Util::setupFS();
354
+        }
355
+        $mount = self::$mounts->find($path);
356
+        if ($mount) {
357
+            return array($mount->getStorage(), rtrim($mount->getInternalPath($path), '/'));
358
+        } else {
359
+            return array(null, null);
360
+        }
361
+    }
362
+
363
+    static public function init($user, $root) {
364
+        if (self::$defaultInstance) {
365
+            return false;
366
+        }
367
+        self::getLoader();
368
+        self::$defaultInstance = new View($root);
369
+
370
+        if (!self::$mounts) {
371
+            self::$mounts = \OC::$server->getMountManager();
372
+        }
373
+
374
+        //load custom mount config
375
+        self::initMountPoints($user);
376
+
377
+        self::$loaded = true;
378
+
379
+        return true;
380
+    }
381
+
382
+    static public function initMountManager() {
383
+        if (!self::$mounts) {
384
+            self::$mounts = \OC::$server->getMountManager();
385
+        }
386
+    }
387
+
388
+    /**
389
+     * Initialize system and personal mount points for a user
390
+     *
391
+     * @param string $user
392
+     * @throws \OC\User\NoUserException if the user is not available
393
+     */
394
+    public static function initMountPoints($user = '') {
395
+        if ($user == '') {
396
+            $user = \OC_User::getUser();
397
+        }
398
+        if ($user === null || $user === false || $user === '') {
399
+            throw new \OC\User\NoUserException('Attempted to initialize mount points for null user and no user in session');
400
+        }
401
+
402
+        if (isset(self::$usersSetup[$user])) {
403
+            return;
404
+        }
405
+
406
+        self::$usersSetup[$user] = true;
407
+
408
+        $userManager = \OC::$server->getUserManager();
409
+        $userObject = $userManager->get($user);
410
+
411
+        if (is_null($userObject)) {
412
+            \OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, \OCP\Util::ERROR);
413
+            // reset flag, this will make it possible to rethrow the exception if called again
414
+            unset(self::$usersSetup[$user]);
415
+            throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
416
+        }
417
+
418
+        $realUid = $userObject->getUID();
419
+        // workaround in case of different casings
420
+        if ($user !== $realUid) {
421
+            $stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
422
+            \OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "' . $realUid . '" got "' . $user . '". Stack: ' . $stack, \OCP\Util::WARN);
423
+            $user = $realUid;
424
+
425
+            // again with the correct casing
426
+            if (isset(self::$usersSetup[$user])) {
427
+                return;
428
+            }
429
+
430
+            self::$usersSetup[$user] = true;
431
+        }
432
+
433
+        if (\OC::$server->getLockdownManager()->canAccessFilesystem()) {
434
+            /** @var \OC\Files\Config\MountProviderCollection $mountConfigManager */
435
+            $mountConfigManager = \OC::$server->getMountProviderCollection();
436
+
437
+            // home mounts are handled seperate since we need to ensure this is mounted before we call the other mount providers
438
+            $homeMount = $mountConfigManager->getHomeMountForUser($userObject);
439
+
440
+            self::getMountManager()->addMount($homeMount);
441
+
442
+            \OC\Files\Filesystem::getStorage($user);
443
+
444
+            // Chance to mount for other storages
445
+            if ($userObject) {
446
+                $mounts = $mountConfigManager->addMountForUser($userObject, self::getMountManager());
447
+                $mounts[] = $homeMount;
448
+                $mountConfigManager->registerMounts($userObject, $mounts);
449
+            }
450
+
451
+            self::listenForNewMountProviders($mountConfigManager, $userManager);
452
+        } else {
453
+            self::getMountManager()->addMount(new MountPoint(
454
+                new NullStorage([]),
455
+                '/' . $user
456
+            ));
457
+            self::getMountManager()->addMount(new MountPoint(
458
+                new NullStorage([]),
459
+                '/' . $user . '/files'
460
+            ));
461
+        }
462
+        \OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
463
+    }
464
+
465
+    /**
466
+     * Get mounts from mount providers that are registered after setup
467
+     *
468
+     * @param MountProviderCollection $mountConfigManager
469
+     * @param IUserManager $userManager
470
+     */
471
+    private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
472
+        if (!self::$listeningForProviders) {
473
+            self::$listeningForProviders = true;
474
+            $mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
475
+                foreach (Filesystem::$usersSetup as $user => $setup) {
476
+                    $userObject = $userManager->get($user);
477
+                    if ($userObject) {
478
+                        $mounts = $provider->getMountsForUser($userObject, Filesystem::getLoader());
479
+                        array_walk($mounts, array(self::$mounts, 'addMount'));
480
+                    }
481
+                }
482
+            });
483
+        }
484
+    }
485
+
486
+    /**
487
+     * get the default filesystem view
488
+     *
489
+     * @return View
490
+     */
491
+    static public function getView() {
492
+        return self::$defaultInstance;
493
+    }
494
+
495
+    /**
496
+     * tear down the filesystem, removing all storage providers
497
+     */
498
+    static public function tearDown() {
499
+        self::clearMounts();
500
+        self::$defaultInstance = null;
501
+    }
502
+
503
+    /**
504
+     * get the relative path of the root data directory for the current user
505
+     *
506
+     * @return string
507
+     *
508
+     * Returns path like /admin/files
509
+     */
510
+    static public function getRoot() {
511
+        if (!self::$defaultInstance) {
512
+            return null;
513
+        }
514
+        return self::$defaultInstance->getRoot();
515
+    }
516
+
517
+    /**
518
+     * clear all mounts and storage backends
519
+     */
520
+    public static function clearMounts() {
521
+        if (self::$mounts) {
522
+            self::$usersSetup = array();
523
+            self::$mounts->clear();
524
+        }
525
+    }
526
+
527
+    /**
528
+     * mount an \OC\Files\Storage\Storage in our virtual filesystem
529
+     *
530
+     * @param \OC\Files\Storage\Storage|string $class
531
+     * @param array $arguments
532
+     * @param string $mountpoint
533
+     */
534
+    static public function mount($class, $arguments, $mountpoint) {
535
+        if (!self::$mounts) {
536
+            \OC_Util::setupFS();
537
+        }
538
+        $mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader());
539
+        self::$mounts->addMount($mount);
540
+    }
541
+
542
+    /**
543
+     * return the path to a local version of the file
544
+     * we need this because we can't know if a file is stored local or not from
545
+     * outside the filestorage and for some purposes a local file is needed
546
+     *
547
+     * @param string $path
548
+     * @return string
549
+     */
550
+    static public function getLocalFile($path) {
551
+        return self::$defaultInstance->getLocalFile($path);
552
+    }
553
+
554
+    /**
555
+     * @param string $path
556
+     * @return string
557
+     */
558
+    static public function getLocalFolder($path) {
559
+        return self::$defaultInstance->getLocalFolder($path);
560
+    }
561
+
562
+    /**
563
+     * return path to file which reflects one visible in browser
564
+     *
565
+     * @param string $path
566
+     * @return string
567
+     */
568
+    static public function getLocalPath($path) {
569
+        $datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
570
+        $newpath = $path;
571
+        if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
572
+            $newpath = substr($path, strlen($datadir));
573
+        }
574
+        return $newpath;
575
+    }
576
+
577
+    /**
578
+     * check if the requested path is valid
579
+     *
580
+     * @param string $path
581
+     * @return bool
582
+     */
583
+    static public function isValidPath($path) {
584
+        $path = self::normalizePath($path);
585
+        if (!$path || $path[0] !== '/') {
586
+            $path = '/' . $path;
587
+        }
588
+        if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
589
+            return false;
590
+        }
591
+        return true;
592
+    }
593
+
594
+    /**
595
+     * checks if a file is blacklisted for storage in the filesystem
596
+     * Listens to write and rename hooks
597
+     *
598
+     * @param array $data from hook
599
+     */
600
+    static public function isBlacklisted($data) {
601
+        if (isset($data['path'])) {
602
+            $path = $data['path'];
603
+        } else if (isset($data['newpath'])) {
604
+            $path = $data['newpath'];
605
+        }
606
+        if (isset($path)) {
607
+            if (self::isFileBlacklisted($path)) {
608
+                $data['run'] = false;
609
+            }
610
+        }
611
+    }
612
+
613
+    /**
614
+     * @param string $filename
615
+     * @return bool
616
+     */
617
+    static public function isFileBlacklisted($filename) {
618
+        $filename = self::normalizePath($filename);
619
+
620
+        $blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array('.htaccess'));
621
+        $filename = strtolower(basename($filename));
622
+        return in_array($filename, $blacklist);
623
+    }
624
+
625
+    /**
626
+     * check if the directory should be ignored when scanning
627
+     * NOTE: the special directories . and .. would cause never ending recursion
628
+     *
629
+     * @param String $dir
630
+     * @return boolean
631
+     */
632
+    static public function isIgnoredDir($dir) {
633
+        if ($dir === '.' || $dir === '..') {
634
+            return true;
635
+        }
636
+        return false;
637
+    }
638
+
639
+    /**
640
+     * following functions are equivalent to their php builtin equivalents for arguments/return values.
641
+     */
642
+    static public function mkdir($path) {
643
+        return self::$defaultInstance->mkdir($path);
644
+    }
645
+
646
+    static public function rmdir($path) {
647
+        return self::$defaultInstance->rmdir($path);
648
+    }
649
+
650
+    static public function opendir($path) {
651
+        return self::$defaultInstance->opendir($path);
652
+    }
653
+
654
+    static public function readdir($path) {
655
+        return self::$defaultInstance->readdir($path);
656
+    }
657
+
658
+    static public function is_dir($path) {
659
+        return self::$defaultInstance->is_dir($path);
660
+    }
661
+
662
+    static public function is_file($path) {
663
+        return self::$defaultInstance->is_file($path);
664
+    }
665
+
666
+    static public function stat($path) {
667
+        return self::$defaultInstance->stat($path);
668
+    }
669
+
670
+    static public function filetype($path) {
671
+        return self::$defaultInstance->filetype($path);
672
+    }
673
+
674
+    static public function filesize($path) {
675
+        return self::$defaultInstance->filesize($path);
676
+    }
677
+
678
+    static public function readfile($path) {
679
+        return self::$defaultInstance->readfile($path);
680
+    }
681
+
682
+    static public function isCreatable($path) {
683
+        return self::$defaultInstance->isCreatable($path);
684
+    }
685
+
686
+    static public function isReadable($path) {
687
+        return self::$defaultInstance->isReadable($path);
688
+    }
689
+
690
+    static public function isUpdatable($path) {
691
+        return self::$defaultInstance->isUpdatable($path);
692
+    }
693
+
694
+    static public function isDeletable($path) {
695
+        return self::$defaultInstance->isDeletable($path);
696
+    }
697
+
698
+    static public function isSharable($path) {
699
+        return self::$defaultInstance->isSharable($path);
700
+    }
701
+
702
+    static public function file_exists($path) {
703
+        return self::$defaultInstance->file_exists($path);
704
+    }
705
+
706
+    static public function filemtime($path) {
707
+        return self::$defaultInstance->filemtime($path);
708
+    }
709
+
710
+    static public function touch($path, $mtime = null) {
711
+        return self::$defaultInstance->touch($path, $mtime);
712
+    }
713
+
714
+    /**
715
+     * @return string
716
+     */
717
+    static public function file_get_contents($path) {
718
+        return self::$defaultInstance->file_get_contents($path);
719
+    }
720
+
721
+    static public function file_put_contents($path, $data) {
722
+        return self::$defaultInstance->file_put_contents($path, $data);
723
+    }
724
+
725
+    static public function unlink($path) {
726
+        return self::$defaultInstance->unlink($path);
727
+    }
728
+
729
+    static public function rename($path1, $path2) {
730
+        return self::$defaultInstance->rename($path1, $path2);
731
+    }
732
+
733
+    static public function copy($path1, $path2) {
734
+        return self::$defaultInstance->copy($path1, $path2);
735
+    }
736
+
737
+    static public function fopen($path, $mode) {
738
+        return self::$defaultInstance->fopen($path, $mode);
739
+    }
740
+
741
+    /**
742
+     * @return string
743
+     */
744
+    static public function toTmpFile($path) {
745
+        return self::$defaultInstance->toTmpFile($path);
746
+    }
747
+
748
+    static public function fromTmpFile($tmpFile, $path) {
749
+        return self::$defaultInstance->fromTmpFile($tmpFile, $path);
750
+    }
751
+
752
+    static public function getMimeType($path) {
753
+        return self::$defaultInstance->getMimeType($path);
754
+    }
755
+
756
+    static public function hash($type, $path, $raw = false) {
757
+        return self::$defaultInstance->hash($type, $path, $raw);
758
+    }
759
+
760
+    static public function free_space($path = '/') {
761
+        return self::$defaultInstance->free_space($path);
762
+    }
763
+
764
+    static public function search($query) {
765
+        return self::$defaultInstance->search($query);
766
+    }
767
+
768
+    /**
769
+     * @param string $query
770
+     */
771
+    static public function searchByMime($query) {
772
+        return self::$defaultInstance->searchByMime($query);
773
+    }
774
+
775
+    /**
776
+     * @param string|int $tag name or tag id
777
+     * @param string $userId owner of the tags
778
+     * @return FileInfo[] array or file info
779
+     */
780
+    static public function searchByTag($tag, $userId) {
781
+        return self::$defaultInstance->searchByTag($tag, $userId);
782
+    }
783
+
784
+    /**
785
+     * check if a file or folder has been updated since $time
786
+     *
787
+     * @param string $path
788
+     * @param int $time
789
+     * @return bool
790
+     */
791
+    static public function hasUpdated($path, $time) {
792
+        return self::$defaultInstance->hasUpdated($path, $time);
793
+    }
794
+
795
+    /**
796
+     * Fix common problems with a file path
797
+     *
798
+     * @param string $path
799
+     * @param bool $stripTrailingSlash whether to strip the trailing slash
800
+     * @param bool $isAbsolutePath whether the given path is absolute
801
+     * @param bool $keepUnicode true to disable unicode normalization
802
+     * @return string
803
+     */
804
+    public static function normalizePath($path, $stripTrailingSlash = true, $isAbsolutePath = false, $keepUnicode = false) {
805
+        if (is_null(self::$normalizedPathCache)) {
806
+            self::$normalizedPathCache = new CappedMemoryCache();
807
+        }
808
+
809
+        /**
810
+         * FIXME: This is a workaround for existing classes and files which call
811
+         *        this function with another type than a valid string. This
812
+         *        conversion should get removed as soon as all existing
813
+         *        function calls have been fixed.
814
+         */
815
+        $path = (string)$path;
816
+
817
+        $cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
818
+
819
+        if (isset(self::$normalizedPathCache[$cacheKey])) {
820
+            return self::$normalizedPathCache[$cacheKey];
821
+        }
822
+
823
+        if ($path == '') {
824
+            return '/';
825
+        }
826
+
827
+        //normalize unicode if possible
828
+        if (!$keepUnicode) {
829
+            $path = \OC_Util::normalizeUnicode($path);
830
+        }
831
+
832
+        //no windows style slashes
833
+        $path = str_replace('\\', '/', $path);
834
+
835
+        //add leading slash
836
+        if ($path[0] !== '/') {
837
+            $path = '/' . $path;
838
+        }
839
+
840
+        // remove '/./'
841
+        // ugly, but str_replace() can't replace them all in one go
842
+        // as the replacement itself is part of the search string
843
+        // which will only be found during the next iteration
844
+        while (strpos($path, '/./') !== false) {
845
+            $path = str_replace('/./', '/', $path);
846
+        }
847
+        // remove sequences of slashes
848
+        $path = preg_replace('#/{2,}#', '/', $path);
849
+
850
+        //remove trailing slash
851
+        if ($stripTrailingSlash and strlen($path) > 1 and substr($path, -1, 1) === '/') {
852
+            $path = substr($path, 0, -1);
853
+        }
854
+
855
+        // remove trailing '/.'
856
+        if (substr($path, -2) == '/.') {
857
+            $path = substr($path, 0, -2);
858
+        }
859
+
860
+        $normalizedPath = $path;
861
+        self::$normalizedPathCache[$cacheKey] = $normalizedPath;
862
+
863
+        return $normalizedPath;
864
+    }
865
+
866
+    /**
867
+     * get the filesystem info
868
+     *
869
+     * @param string $path
870
+     * @param boolean $includeMountPoints whether to add mountpoint sizes,
871
+     * defaults to true
872
+     * @return \OC\Files\FileInfo|bool False if file does not exist
873
+     */
874
+    public static function getFileInfo($path, $includeMountPoints = true) {
875
+        return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
876
+    }
877
+
878
+    /**
879
+     * change file metadata
880
+     *
881
+     * @param string $path
882
+     * @param array $data
883
+     * @return int
884
+     *
885
+     * returns the fileid of the updated file
886
+     */
887
+    public static function putFileInfo($path, $data) {
888
+        return self::$defaultInstance->putFileInfo($path, $data);
889
+    }
890
+
891
+    /**
892
+     * get the content of a directory
893
+     *
894
+     * @param string $directory path under datadirectory
895
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
896
+     * @return \OC\Files\FileInfo[]
897
+     */
898
+    public static function getDirectoryContent($directory, $mimetype_filter = '') {
899
+        return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter);
900
+    }
901
+
902
+    /**
903
+     * Get the path of a file by id
904
+     *
905
+     * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
906
+     *
907
+     * @param int $id
908
+     * @throws NotFoundException
909
+     * @return string
910
+     */
911
+    public static function getPath($id) {
912
+        return self::$defaultInstance->getPath($id);
913
+    }
914
+
915
+    /**
916
+     * Get the owner for a file or folder
917
+     *
918
+     * @param string $path
919
+     * @return string
920
+     */
921
+    public static function getOwner($path) {
922
+        return self::$defaultInstance->getOwner($path);
923
+    }
924
+
925
+    /**
926
+     * get the ETag for a file or folder
927
+     *
928
+     * @param string $path
929
+     * @return string
930
+     */
931
+    static public function getETag($path) {
932
+        return self::$defaultInstance->getETag($path);
933
+    }
934 934
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Encryption.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -984,7 +984,7 @@  discard block
 block discarded – undo
984 984
 	/**
985 985
 	 * check if path points to a files version
986 986
 	 *
987
-	 * @param $path
987
+	 * @param string $path
988 988
 	 * @return bool
989 989
 	 */
990 990
 	protected function isVersion($path) {
@@ -995,7 +995,7 @@  discard block
 block discarded – undo
995 995
 	/**
996 996
 	 * check if the given storage should be encrypted or not
997 997
 	 *
998
-	 * @param $path
998
+	 * @param string $path
999 999
 	 * @return bool
1000 1000
 	 */
1001 1001
 	protected function shouldEncrypt($path) {
Please login to merge, or discard this patch.
Indentation   +972 added lines, -972 removed lines patch added patch discarded remove patch
@@ -46,977 +46,977 @@
 block discarded – undo
46 46
 
47 47
 class Encryption extends Wrapper {
48 48
 
49
-	use LocalTempFileTrait;
50
-
51
-	/** @var string */
52
-	private $mountPoint;
53
-
54
-	/** @var \OC\Encryption\Util */
55
-	private $util;
56
-
57
-	/** @var \OCP\Encryption\IManager */
58
-	private $encryptionManager;
59
-
60
-	/** @var \OCP\ILogger */
61
-	private $logger;
62
-
63
-	/** @var string */
64
-	private $uid;
65
-
66
-	/** @var array */
67
-	protected $unencryptedSize;
68
-
69
-	/** @var \OCP\Encryption\IFile */
70
-	private $fileHelper;
71
-
72
-	/** @var IMountPoint */
73
-	private $mount;
74
-
75
-	/** @var IStorage */
76
-	private $keyStorage;
77
-
78
-	/** @var Update */
79
-	private $update;
80
-
81
-	/** @var Manager */
82
-	private $mountManager;
83
-
84
-	/** @var array remember for which path we execute the repair step to avoid recursions */
85
-	private $fixUnencryptedSizeOf = array();
86
-
87
-	/** @var  ArrayCache */
88
-	private $arrayCache;
89
-
90
-	/**
91
-	 * @param array $parameters
92
-	 * @param IManager $encryptionManager
93
-	 * @param Util $util
94
-	 * @param ILogger $logger
95
-	 * @param IFile $fileHelper
96
-	 * @param string $uid
97
-	 * @param IStorage $keyStorage
98
-	 * @param Update $update
99
-	 * @param Manager $mountManager
100
-	 * @param ArrayCache $arrayCache
101
-	 */
102
-	public function __construct(
103
-			$parameters,
104
-			IManager $encryptionManager = null,
105
-			Util $util = null,
106
-			ILogger $logger = null,
107
-			IFile $fileHelper = null,
108
-			$uid = null,
109
-			IStorage $keyStorage = null,
110
-			Update $update = null,
111
-			Manager $mountManager = null,
112
-			ArrayCache $arrayCache = null
113
-		) {
114
-
115
-		$this->mountPoint = $parameters['mountPoint'];
116
-		$this->mount = $parameters['mount'];
117
-		$this->encryptionManager = $encryptionManager;
118
-		$this->util = $util;
119
-		$this->logger = $logger;
120
-		$this->uid = $uid;
121
-		$this->fileHelper = $fileHelper;
122
-		$this->keyStorage = $keyStorage;
123
-		$this->unencryptedSize = array();
124
-		$this->update = $update;
125
-		$this->mountManager = $mountManager;
126
-		$this->arrayCache = $arrayCache;
127
-		parent::__construct($parameters);
128
-	}
129
-
130
-	/**
131
-	 * see http://php.net/manual/en/function.filesize.php
132
-	 * The result for filesize when called on a folder is required to be 0
133
-	 *
134
-	 * @param string $path
135
-	 * @return int
136
-	 */
137
-	public function filesize($path) {
138
-		$fullPath = $this->getFullPath($path);
139
-
140
-		/** @var CacheEntry $info */
141
-		$info = $this->getCache()->get($path);
142
-		if (isset($this->unencryptedSize[$fullPath])) {
143
-			$size = $this->unencryptedSize[$fullPath];
144
-			// update file cache
145
-			if ($info instanceof ICacheEntry) {
146
-				$info = $info->getData();
147
-				$info['encrypted'] = $info['encryptedVersion'];
148
-			} else {
149
-				if (!is_array($info)) {
150
-					$info = [];
151
-				}
152
-				$info['encrypted'] = true;
153
-			}
154
-
155
-			$info['size'] = $size;
156
-			$this->getCache()->put($path, $info);
157
-
158
-			return $size;
159
-		}
160
-
161
-		if (isset($info['fileid']) && $info['encrypted']) {
162
-			return $this->verifyUnencryptedSize($path, $info['size']);
163
-		}
164
-
165
-		return $this->storage->filesize($path);
166
-	}
167
-
168
-	/**
169
-	 * @param string $path
170
-	 * @return array
171
-	 */
172
-	public function getMetaData($path) {
173
-		$data = $this->storage->getMetaData($path);
174
-		if (is_null($data)) {
175
-			return null;
176
-		}
177
-		$fullPath = $this->getFullPath($path);
178
-		$info = $this->getCache()->get($path);
179
-
180
-		if (isset($this->unencryptedSize[$fullPath])) {
181
-			$data['encrypted'] = true;
182
-			$data['size'] = $this->unencryptedSize[$fullPath];
183
-		} else {
184
-			if (isset($info['fileid']) && $info['encrypted']) {
185
-				$data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
186
-				$data['encrypted'] = true;
187
-			}
188
-		}
189
-
190
-		if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
191
-			$data['encryptedVersion'] = $info['encryptedVersion'];
192
-		}
193
-
194
-		return $data;
195
-	}
196
-
197
-	/**
198
-	 * see http://php.net/manual/en/function.file_get_contents.php
199
-	 *
200
-	 * @param string $path
201
-	 * @return string
202
-	 */
203
-	public function file_get_contents($path) {
204
-
205
-		$encryptionModule = $this->getEncryptionModule($path);
206
-
207
-		if ($encryptionModule) {
208
-			$handle = $this->fopen($path, "r");
209
-			if (!$handle) {
210
-				return false;
211
-			}
212
-			$data = stream_get_contents($handle);
213
-			fclose($handle);
214
-			return $data;
215
-		}
216
-		return $this->storage->file_get_contents($path);
217
-	}
218
-
219
-	/**
220
-	 * see http://php.net/manual/en/function.file_put_contents.php
221
-	 *
222
-	 * @param string $path
223
-	 * @param string $data
224
-	 * @return bool
225
-	 */
226
-	public function file_put_contents($path, $data) {
227
-		// file put content will always be translated to a stream write
228
-		$handle = $this->fopen($path, 'w');
229
-		if (is_resource($handle)) {
230
-			$written = fwrite($handle, $data);
231
-			fclose($handle);
232
-			return $written;
233
-		}
234
-
235
-		return false;
236
-	}
237
-
238
-	/**
239
-	 * see http://php.net/manual/en/function.unlink.php
240
-	 *
241
-	 * @param string $path
242
-	 * @return bool
243
-	 */
244
-	public function unlink($path) {
245
-		$fullPath = $this->getFullPath($path);
246
-		if ($this->util->isExcluded($fullPath)) {
247
-			return $this->storage->unlink($path);
248
-		}
249
-
250
-		$encryptionModule = $this->getEncryptionModule($path);
251
-		if ($encryptionModule) {
252
-			$this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
253
-		}
254
-
255
-		return $this->storage->unlink($path);
256
-	}
257
-
258
-	/**
259
-	 * see http://php.net/manual/en/function.rename.php
260
-	 *
261
-	 * @param string $path1
262
-	 * @param string $path2
263
-	 * @return bool
264
-	 */
265
-	public function rename($path1, $path2) {
266
-
267
-		$result = $this->storage->rename($path1, $path2);
268
-
269
-		if ($result &&
270
-			// versions always use the keys from the original file, so we can skip
271
-			// this step for versions
272
-			$this->isVersion($path2) === false &&
273
-			$this->encryptionManager->isEnabled()) {
274
-			$source = $this->getFullPath($path1);
275
-			if (!$this->util->isExcluded($source)) {
276
-				$target = $this->getFullPath($path2);
277
-				if (isset($this->unencryptedSize[$source])) {
278
-					$this->unencryptedSize[$target] = $this->unencryptedSize[$source];
279
-				}
280
-				$this->keyStorage->renameKeys($source, $target);
281
-				$module = $this->getEncryptionModule($path2);
282
-				if ($module) {
283
-					$module->update($target, $this->uid, []);
284
-				}
285
-			}
286
-		}
287
-
288
-		return $result;
289
-	}
290
-
291
-	/**
292
-	 * see http://php.net/manual/en/function.rmdir.php
293
-	 *
294
-	 * @param string $path
295
-	 * @return bool
296
-	 */
297
-	public function rmdir($path) {
298
-		$result = $this->storage->rmdir($path);
299
-		$fullPath = $this->getFullPath($path);
300
-		if ($result &&
301
-			$this->util->isExcluded($fullPath) === false &&
302
-			$this->encryptionManager->isEnabled()
303
-		) {
304
-			$this->keyStorage->deleteAllFileKeys($fullPath);
305
-		}
306
-
307
-		return $result;
308
-	}
309
-
310
-	/**
311
-	 * check if a file can be read
312
-	 *
313
-	 * @param string $path
314
-	 * @return bool
315
-	 */
316
-	public function isReadable($path) {
317
-
318
-		$isReadable = true;
319
-
320
-		$metaData = $this->getMetaData($path);
321
-		if (
322
-			!$this->is_dir($path) &&
323
-			isset($metaData['encrypted']) &&
324
-			$metaData['encrypted'] === true
325
-		) {
326
-			$fullPath = $this->getFullPath($path);
327
-			$module = $this->getEncryptionModule($path);
328
-			$isReadable = $module->isReadable($fullPath, $this->uid);
329
-		}
330
-
331
-		return $this->storage->isReadable($path) && $isReadable;
332
-	}
333
-
334
-	/**
335
-	 * see http://php.net/manual/en/function.copy.php
336
-	 *
337
-	 * @param string $path1
338
-	 * @param string $path2
339
-	 * @return bool
340
-	 */
341
-	public function copy($path1, $path2) {
342
-
343
-		$source = $this->getFullPath($path1);
344
-
345
-		if ($this->util->isExcluded($source)) {
346
-			return $this->storage->copy($path1, $path2);
347
-		}
348
-
349
-		// need to stream copy file by file in case we copy between a encrypted
350
-		// and a unencrypted storage
351
-		$this->unlink($path2);
352
-		$result = $this->copyFromStorage($this, $path1, $path2);
353
-
354
-		return $result;
355
-	}
356
-
357
-	/**
358
-	 * see http://php.net/manual/en/function.fopen.php
359
-	 *
360
-	 * @param string $path
361
-	 * @param string $mode
362
-	 * @return resource|bool
363
-	 * @throws GenericEncryptionException
364
-	 * @throws ModuleDoesNotExistsException
365
-	 */
366
-	public function fopen($path, $mode) {
367
-
368
-		// check if the file is stored in the array cache, this means that we
369
-		// copy a file over to the versions folder, in this case we don't want to
370
-		// decrypt it
371
-		if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
372
-			$this->arrayCache->remove('encryption_copy_version_' . $path);
373
-			return $this->storage->fopen($path, $mode);
374
-		}
375
-
376
-		$encryptionEnabled = $this->encryptionManager->isEnabled();
377
-		$shouldEncrypt = false;
378
-		$encryptionModule = null;
379
-		$header = $this->getHeader($path);
380
-		$signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
381
-		$fullPath = $this->getFullPath($path);
382
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
383
-
384
-		if ($this->util->isExcluded($fullPath) === false) {
385
-
386
-			$size = $unencryptedSize = 0;
387
-			$realFile = $this->util->stripPartialFileExtension($path);
388
-			$targetExists = $this->file_exists($realFile) || $this->file_exists($path);
389
-			$targetIsEncrypted = false;
390
-			if ($targetExists) {
391
-				// in case the file exists we require the explicit module as
392
-				// specified in the file header - otherwise we need to fail hard to
393
-				// prevent data loss on client side
394
-				if (!empty($encryptionModuleId)) {
395
-					$targetIsEncrypted = true;
396
-					$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
397
-				}
398
-
399
-				if ($this->file_exists($path)) {
400
-					$size = $this->storage->filesize($path);
401
-					$unencryptedSize = $this->filesize($path);
402
-				} else {
403
-					$size = $unencryptedSize = 0;
404
-				}
405
-			}
406
-
407
-			try {
408
-
409
-				if (
410
-					$mode === 'w'
411
-					|| $mode === 'w+'
412
-					|| $mode === 'wb'
413
-					|| $mode === 'wb+'
414
-				) {
415
-					// don't overwrite encrypted files if encryption is not enabled
416
-					if ($targetIsEncrypted && $encryptionEnabled === false) {
417
-						throw new GenericEncryptionException('Tried to access encrypted file but encryption is not enabled');
418
-					}
419
-					if ($encryptionEnabled) {
420
-						// if $encryptionModuleId is empty, the default module will be used
421
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
422
-						$shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
423
-						$signed = true;
424
-					}
425
-				} else {
426
-					$info = $this->getCache()->get($path);
427
-					// only get encryption module if we found one in the header
428
-					// or if file should be encrypted according to the file cache
429
-					if (!empty($encryptionModuleId)) {
430
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
431
-						$shouldEncrypt = true;
432
-					} else if (empty($encryptionModuleId) && $info['encrypted'] === true) {
433
-						// we come from a old installation. No header and/or no module defined
434
-						// but the file is encrypted. In this case we need to use the
435
-						// OC_DEFAULT_MODULE to read the file
436
-						$encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
437
-						$shouldEncrypt = true;
438
-						$targetIsEncrypted = true;
439
-					}
440
-				}
441
-			} catch (ModuleDoesNotExistsException $e) {
442
-				$this->logger->warning('Encryption module "' . $encryptionModuleId .
443
-					'" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
444
-			}
445
-
446
-			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
447
-			if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
448
-				if (!$targetExists || !$targetIsEncrypted) {
449
-					$shouldEncrypt = false;
450
-				}
451
-			}
452
-
453
-			if ($shouldEncrypt === true && $encryptionModule !== null) {
454
-				$headerSize = $this->getHeaderSize($path);
455
-				$source = $this->storage->fopen($path, $mode);
456
-				if (!is_resource($source)) {
457
-					return false;
458
-				}
459
-				$handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
460
-					$this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
461
-					$size, $unencryptedSize, $headerSize, $signed);
462
-				return $handle;
463
-			}
464
-
465
-		}
466
-
467
-		return $this->storage->fopen($path, $mode);
468
-	}
469
-
470
-
471
-	/**
472
-	 * perform some plausibility checks if the the unencrypted size is correct.
473
-	 * If not, we calculate the correct unencrypted size and return it
474
-	 *
475
-	 * @param string $path internal path relative to the storage root
476
-	 * @param int $unencryptedSize size of the unencrypted file
477
-	 *
478
-	 * @return int unencrypted size
479
-	 */
480
-	protected function verifyUnencryptedSize($path, $unencryptedSize) {
481
-
482
-		$size = $this->storage->filesize($path);
483
-		$result = $unencryptedSize;
484
-
485
-		if ($unencryptedSize < 0 ||
486
-			($size > 0 && $unencryptedSize === $size)
487
-		) {
488
-			// check if we already calculate the unencrypted size for the
489
-			// given path to avoid recursions
490
-			if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
491
-				$this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
492
-				try {
493
-					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
494
-				} catch (\Exception $e) {
495
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
496
-					$this->logger->logException($e);
497
-				}
498
-				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
499
-			}
500
-		}
501
-
502
-		return $result;
503
-	}
504
-
505
-	/**
506
-	 * calculate the unencrypted size
507
-	 *
508
-	 * @param string $path internal path relative to the storage root
509
-	 * @param int $size size of the physical file
510
-	 * @param int $unencryptedSize size of the unencrypted file
511
-	 *
512
-	 * @return int calculated unencrypted size
513
-	 */
514
-	protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
515
-
516
-		$headerSize = $this->getHeaderSize($path);
517
-		$header = $this->getHeader($path);
518
-		$encryptionModule = $this->getEncryptionModule($path);
519
-
520
-		$stream = $this->storage->fopen($path, 'r');
521
-
522
-		// if we couldn't open the file we return the old unencrypted size
523
-		if (!is_resource($stream)) {
524
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
525
-			return $unencryptedSize;
526
-		}
527
-
528
-		$newUnencryptedSize = 0;
529
-		$size -= $headerSize;
530
-		$blockSize = $this->util->getBlockSize();
531
-
532
-		// if a header exists we skip it
533
-		if ($headerSize > 0) {
534
-			fread($stream, $headerSize);
535
-		}
536
-
537
-		// fast path, else the calculation for $lastChunkNr is bogus
538
-		if ($size === 0) {
539
-			return 0;
540
-		}
541
-
542
-		$signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
543
-		$unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
544
-
545
-		// calculate last chunk nr
546
-		// next highest is end of chunks, one subtracted is last one
547
-		// we have to read the last chunk, we can't just calculate it (because of padding etc)
548
-
549
-		$lastChunkNr = ceil($size/ $blockSize)-1;
550
-		// calculate last chunk position
551
-		$lastChunkPos = ($lastChunkNr * $blockSize);
552
-		// try to fseek to the last chunk, if it fails we have to read the whole file
553
-		if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
554
-			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
555
-		}
556
-
557
-		$lastChunkContentEncrypted='';
558
-		$count = $blockSize;
559
-
560
-		while ($count > 0) {
561
-			$data=fread($stream, $blockSize);
562
-			$count=strlen($data);
563
-			$lastChunkContentEncrypted .= $data;
564
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
565
-				$newUnencryptedSize += $unencryptedBlockSize;
566
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
567
-			}
568
-		}
569
-
570
-		fclose($stream);
571
-
572
-		// we have to decrypt the last chunk to get it actual size
573
-		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
574
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
575
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
576
-
577
-		// calc the real file size with the size of the last chunk
578
-		$newUnencryptedSize += strlen($decryptedLastChunk);
579
-
580
-		$this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
581
-
582
-		// write to cache if applicable
583
-		$cache = $this->storage->getCache();
584
-		if ($cache) {
585
-			$entry = $cache->get($path);
586
-			$cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
587
-		}
588
-
589
-		return $newUnencryptedSize;
590
-	}
591
-
592
-	/**
593
-	 * @param Storage $sourceStorage
594
-	 * @param string $sourceInternalPath
595
-	 * @param string $targetInternalPath
596
-	 * @param bool $preserveMtime
597
-	 * @return bool
598
-	 */
599
-	public function moveFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
600
-		if ($sourceStorage === $this) {
601
-			return $this->rename($sourceInternalPath, $targetInternalPath);
602
-		}
603
-
604
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
605
-		// - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
606
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
607
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
608
-		// - remove $this->copyBetweenStorage
609
-
610
-		if (!$sourceStorage->isDeletable($sourceInternalPath)) {
611
-			return false;
612
-		}
613
-
614
-		$result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
615
-		if ($result) {
616
-			if ($sourceStorage->is_dir($sourceInternalPath)) {
617
-				$result &= $sourceStorage->rmdir($sourceInternalPath);
618
-			} else {
619
-				$result &= $sourceStorage->unlink($sourceInternalPath);
620
-			}
621
-		}
622
-		return $result;
623
-	}
624
-
625
-
626
-	/**
627
-	 * @param Storage $sourceStorage
628
-	 * @param string $sourceInternalPath
629
-	 * @param string $targetInternalPath
630
-	 * @param bool $preserveMtime
631
-	 * @param bool $isRename
632
-	 * @return bool
633
-	 */
634
-	public function copyFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
635
-
636
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
637
-		// - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
638
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
639
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
640
-		// - remove $this->copyBetweenStorage
641
-
642
-		return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
643
-	}
644
-
645
-	/**
646
-	 * Update the encrypted cache version in the database
647
-	 *
648
-	 * @param Storage $sourceStorage
649
-	 * @param string $sourceInternalPath
650
-	 * @param string $targetInternalPath
651
-	 * @param bool $isRename
652
-	 */
653
-	private function updateEncryptedVersion(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
654
-		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath) ? 1 : 0;
655
-		$cacheInformation = [
656
-			'encrypted' => (bool)$isEncrypted,
657
-		];
658
-		if($isEncrypted === 1) {
659
-			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
660
-
661
-			// In case of a move operation from an unencrypted to an encrypted
662
-			// storage the old encrypted version would stay with "0" while the
663
-			// correct value would be "1". Thus we manually set the value to "1"
664
-			// for those cases.
665
-			// See also https://github.com/owncloud/core/issues/23078
666
-			if($encryptedVersion === 0) {
667
-				$encryptedVersion = 1;
668
-			}
669
-
670
-			$cacheInformation['encryptedVersion'] = $encryptedVersion;
671
-		}
672
-
673
-		// in case of a rename we need to manipulate the source cache because
674
-		// this information will be kept for the new target
675
-		if ($isRename) {
676
-			$sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
677
-		} else {
678
-			$this->getCache()->put($targetInternalPath, $cacheInformation);
679
-		}
680
-	}
681
-
682
-	/**
683
-	 * copy file between two storages
684
-	 *
685
-	 * @param Storage $sourceStorage
686
-	 * @param string $sourceInternalPath
687
-	 * @param string $targetInternalPath
688
-	 * @param bool $preserveMtime
689
-	 * @param bool $isRename
690
-	 * @return bool
691
-	 * @throws \Exception
692
-	 */
693
-	private function copyBetweenStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
694
-
695
-		// for versions we have nothing to do, because versions should always use the
696
-		// key from the original file. Just create a 1:1 copy and done
697
-		if ($this->isVersion($targetInternalPath) ||
698
-			$this->isVersion($sourceInternalPath)) {
699
-			// remember that we try to create a version so that we can detect it during
700
-			// fopen($sourceInternalPath) and by-pass the encryption in order to
701
-			// create a 1:1 copy of the file
702
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
703
-			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
704
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
705
-			if ($result) {
706
-				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
707
-				// make sure that we update the unencrypted size for the version
708
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
709
-					$this->updateUnencryptedSize(
710
-						$this->getFullPath($targetInternalPath),
711
-						$info['size']
712
-					);
713
-				}
714
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
715
-			}
716
-			return $result;
717
-		}
718
-
719
-		// first copy the keys that we reuse the existing file key on the target location
720
-		// and don't create a new one which would break versions for example.
721
-		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
722
-		if (count($mount) === 1) {
723
-			$mountPoint = $mount[0]->getMountPoint();
724
-			$source = $mountPoint . '/' . $sourceInternalPath;
725
-			$target = $this->getFullPath($targetInternalPath);
726
-			$this->copyKeys($source, $target);
727
-		} else {
728
-			$this->logger->error('Could not find mount point, can\'t keep encryption keys');
729
-		}
730
-
731
-		if ($sourceStorage->is_dir($sourceInternalPath)) {
732
-			$dh = $sourceStorage->opendir($sourceInternalPath);
733
-			$result = $this->mkdir($targetInternalPath);
734
-			if (is_resource($dh)) {
735
-				while ($result and ($file = readdir($dh)) !== false) {
736
-					if (!Filesystem::isIgnoredDir($file)) {
737
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
738
-					}
739
-				}
740
-			}
741
-		} else {
742
-			try {
743
-				$source = $sourceStorage->fopen($sourceInternalPath, 'r');
744
-				$target = $this->fopen($targetInternalPath, 'w');
745
-				list(, $result) = \OC_Helper::streamCopy($source, $target);
746
-				fclose($source);
747
-				fclose($target);
748
-			} catch (\Exception $e) {
749
-				fclose($source);
750
-				fclose($target);
751
-				throw $e;
752
-			}
753
-			if($result) {
754
-				if ($preserveMtime) {
755
-					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
756
-				}
757
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
758
-			} else {
759
-				// delete partially written target file
760
-				$this->unlink($targetInternalPath);
761
-				// delete cache entry that was created by fopen
762
-				$this->getCache()->remove($targetInternalPath);
763
-			}
764
-		}
765
-		return (bool)$result;
766
-
767
-	}
768
-
769
-	/**
770
-	 * get the path to a local version of the file.
771
-	 * The local version of the file can be temporary and doesn't have to be persistent across requests
772
-	 *
773
-	 * @param string $path
774
-	 * @return string
775
-	 */
776
-	public function getLocalFile($path) {
777
-		if ($this->encryptionManager->isEnabled()) {
778
-			$cachedFile = $this->getCachedFile($path);
779
-			if (is_string($cachedFile)) {
780
-				return $cachedFile;
781
-			}
782
-		}
783
-		return $this->storage->getLocalFile($path);
784
-	}
785
-
786
-	/**
787
-	 * Returns the wrapped storage's value for isLocal()
788
-	 *
789
-	 * @return bool wrapped storage's isLocal() value
790
-	 */
791
-	public function isLocal() {
792
-		if ($this->encryptionManager->isEnabled()) {
793
-			return false;
794
-		}
795
-		return $this->storage->isLocal();
796
-	}
797
-
798
-	/**
799
-	 * see http://php.net/manual/en/function.stat.php
800
-	 * only the following keys are required in the result: size and mtime
801
-	 *
802
-	 * @param string $path
803
-	 * @return array
804
-	 */
805
-	public function stat($path) {
806
-		$stat = $this->storage->stat($path);
807
-		$fileSize = $this->filesize($path);
808
-		$stat['size'] = $fileSize;
809
-		$stat[7] = $fileSize;
810
-		return $stat;
811
-	}
812
-
813
-	/**
814
-	 * see http://php.net/manual/en/function.hash.php
815
-	 *
816
-	 * @param string $type
817
-	 * @param string $path
818
-	 * @param bool $raw
819
-	 * @return string
820
-	 */
821
-	public function hash($type, $path, $raw = false) {
822
-		$fh = $this->fopen($path, 'rb');
823
-		$ctx = hash_init($type);
824
-		hash_update_stream($ctx, $fh);
825
-		fclose($fh);
826
-		return hash_final($ctx, $raw);
827
-	}
828
-
829
-	/**
830
-	 * return full path, including mount point
831
-	 *
832
-	 * @param string $path relative to mount point
833
-	 * @return string full path including mount point
834
-	 */
835
-	protected function getFullPath($path) {
836
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
837
-	}
838
-
839
-	/**
840
-	 * read first block of encrypted file, typically this will contain the
841
-	 * encryption header
842
-	 *
843
-	 * @param string $path
844
-	 * @return string
845
-	 */
846
-	protected function readFirstBlock($path) {
847
-		$firstBlock = '';
848
-		if ($this->storage->file_exists($path)) {
849
-			$handle = $this->storage->fopen($path, 'r');
850
-			$firstBlock = fread($handle, $this->util->getHeaderSize());
851
-			fclose($handle);
852
-		}
853
-		return $firstBlock;
854
-	}
855
-
856
-	/**
857
-	 * return header size of given file
858
-	 *
859
-	 * @param string $path
860
-	 * @return int
861
-	 */
862
-	protected function getHeaderSize($path) {
863
-		$headerSize = 0;
864
-		$realFile = $this->util->stripPartialFileExtension($path);
865
-		if ($this->storage->file_exists($realFile)) {
866
-			$path = $realFile;
867
-		}
868
-		$firstBlock = $this->readFirstBlock($path);
869
-
870
-		if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
871
-			$headerSize = $this->util->getHeaderSize();
872
-		}
873
-
874
-		return $headerSize;
875
-	}
876
-
877
-	/**
878
-	 * parse raw header to array
879
-	 *
880
-	 * @param string $rawHeader
881
-	 * @return array
882
-	 */
883
-	protected function parseRawHeader($rawHeader) {
884
-		$result = array();
885
-		if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
886
-			$header = $rawHeader;
887
-			$endAt = strpos($header, Util::HEADER_END);
888
-			if ($endAt !== false) {
889
-				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
890
-
891
-				// +1 to not start with an ':' which would result in empty element at the beginning
892
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
893
-
894
-				$element = array_shift($exploded);
895
-				while ($element !== Util::HEADER_END) {
896
-					$result[$element] = array_shift($exploded);
897
-					$element = array_shift($exploded);
898
-				}
899
-			}
900
-		}
901
-
902
-		return $result;
903
-	}
904
-
905
-	/**
906
-	 * read header from file
907
-	 *
908
-	 * @param string $path
909
-	 * @return array
910
-	 */
911
-	protected function getHeader($path) {
912
-		$realFile = $this->util->stripPartialFileExtension($path);
913
-		if ($this->storage->file_exists($realFile)) {
914
-			$path = $realFile;
915
-		}
916
-
917
-		$firstBlock = $this->readFirstBlock($path);
918
-		$result = $this->parseRawHeader($firstBlock);
919
-
920
-		// if the header doesn't contain a encryption module we check if it is a
921
-		// legacy file. If true, we add the default encryption module
922
-		if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
923
-			if (!empty($result)) {
924
-				$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
925
-			} else {
926
-				// if the header was empty we have to check first if it is a encrypted file at all
927
-				$info = $this->getCache()->get($path);
928
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
929
-					$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
930
-				}
931
-			}
932
-		}
933
-
934
-		return $result;
935
-	}
936
-
937
-	/**
938
-	 * read encryption module needed to read/write the file located at $path
939
-	 *
940
-	 * @param string $path
941
-	 * @return null|\OCP\Encryption\IEncryptionModule
942
-	 * @throws ModuleDoesNotExistsException
943
-	 * @throws \Exception
944
-	 */
945
-	protected function getEncryptionModule($path) {
946
-		$encryptionModule = null;
947
-		$header = $this->getHeader($path);
948
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
949
-		if (!empty($encryptionModuleId)) {
950
-			try {
951
-				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
952
-			} catch (ModuleDoesNotExistsException $e) {
953
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
954
-				throw $e;
955
-			}
956
-		}
957
-
958
-		return $encryptionModule;
959
-	}
960
-
961
-	/**
962
-	 * @param string $path
963
-	 * @param int $unencryptedSize
964
-	 */
965
-	public function updateUnencryptedSize($path, $unencryptedSize) {
966
-		$this->unencryptedSize[$path] = $unencryptedSize;
967
-	}
968
-
969
-	/**
970
-	 * copy keys to new location
971
-	 *
972
-	 * @param string $source path relative to data/
973
-	 * @param string $target path relative to data/
974
-	 * @return bool
975
-	 */
976
-	protected function copyKeys($source, $target) {
977
-		if (!$this->util->isExcluded($source)) {
978
-			return $this->keyStorage->copyKeys($source, $target);
979
-		}
980
-
981
-		return false;
982
-	}
983
-
984
-	/**
985
-	 * check if path points to a files version
986
-	 *
987
-	 * @param $path
988
-	 * @return bool
989
-	 */
990
-	protected function isVersion($path) {
991
-		$normalized = Filesystem::normalizePath($path);
992
-		return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
993
-	}
994
-
995
-	/**
996
-	 * check if the given storage should be encrypted or not
997
-	 *
998
-	 * @param $path
999
-	 * @return bool
1000
-	 */
1001
-	protected function shouldEncrypt($path) {
1002
-		$fullPath = $this->getFullPath($path);
1003
-		$mountPointConfig = $this->mount->getOption('encrypt', true);
1004
-		if ($mountPointConfig === false) {
1005
-			return false;
1006
-		}
1007
-
1008
-		try {
1009
-			$encryptionModule = $this->getEncryptionModule($fullPath);
1010
-		} catch (ModuleDoesNotExistsException $e) {
1011
-			return false;
1012
-		}
1013
-
1014
-		if ($encryptionModule === null) {
1015
-			$encryptionModule = $this->encryptionManager->getEncryptionModule();
1016
-		}
1017
-
1018
-		return $encryptionModule->shouldEncrypt($fullPath);
1019
-
1020
-	}
49
+    use LocalTempFileTrait;
50
+
51
+    /** @var string */
52
+    private $mountPoint;
53
+
54
+    /** @var \OC\Encryption\Util */
55
+    private $util;
56
+
57
+    /** @var \OCP\Encryption\IManager */
58
+    private $encryptionManager;
59
+
60
+    /** @var \OCP\ILogger */
61
+    private $logger;
62
+
63
+    /** @var string */
64
+    private $uid;
65
+
66
+    /** @var array */
67
+    protected $unencryptedSize;
68
+
69
+    /** @var \OCP\Encryption\IFile */
70
+    private $fileHelper;
71
+
72
+    /** @var IMountPoint */
73
+    private $mount;
74
+
75
+    /** @var IStorage */
76
+    private $keyStorage;
77
+
78
+    /** @var Update */
79
+    private $update;
80
+
81
+    /** @var Manager */
82
+    private $mountManager;
83
+
84
+    /** @var array remember for which path we execute the repair step to avoid recursions */
85
+    private $fixUnencryptedSizeOf = array();
86
+
87
+    /** @var  ArrayCache */
88
+    private $arrayCache;
89
+
90
+    /**
91
+     * @param array $parameters
92
+     * @param IManager $encryptionManager
93
+     * @param Util $util
94
+     * @param ILogger $logger
95
+     * @param IFile $fileHelper
96
+     * @param string $uid
97
+     * @param IStorage $keyStorage
98
+     * @param Update $update
99
+     * @param Manager $mountManager
100
+     * @param ArrayCache $arrayCache
101
+     */
102
+    public function __construct(
103
+            $parameters,
104
+            IManager $encryptionManager = null,
105
+            Util $util = null,
106
+            ILogger $logger = null,
107
+            IFile $fileHelper = null,
108
+            $uid = null,
109
+            IStorage $keyStorage = null,
110
+            Update $update = null,
111
+            Manager $mountManager = null,
112
+            ArrayCache $arrayCache = null
113
+        ) {
114
+
115
+        $this->mountPoint = $parameters['mountPoint'];
116
+        $this->mount = $parameters['mount'];
117
+        $this->encryptionManager = $encryptionManager;
118
+        $this->util = $util;
119
+        $this->logger = $logger;
120
+        $this->uid = $uid;
121
+        $this->fileHelper = $fileHelper;
122
+        $this->keyStorage = $keyStorage;
123
+        $this->unencryptedSize = array();
124
+        $this->update = $update;
125
+        $this->mountManager = $mountManager;
126
+        $this->arrayCache = $arrayCache;
127
+        parent::__construct($parameters);
128
+    }
129
+
130
+    /**
131
+     * see http://php.net/manual/en/function.filesize.php
132
+     * The result for filesize when called on a folder is required to be 0
133
+     *
134
+     * @param string $path
135
+     * @return int
136
+     */
137
+    public function filesize($path) {
138
+        $fullPath = $this->getFullPath($path);
139
+
140
+        /** @var CacheEntry $info */
141
+        $info = $this->getCache()->get($path);
142
+        if (isset($this->unencryptedSize[$fullPath])) {
143
+            $size = $this->unencryptedSize[$fullPath];
144
+            // update file cache
145
+            if ($info instanceof ICacheEntry) {
146
+                $info = $info->getData();
147
+                $info['encrypted'] = $info['encryptedVersion'];
148
+            } else {
149
+                if (!is_array($info)) {
150
+                    $info = [];
151
+                }
152
+                $info['encrypted'] = true;
153
+            }
154
+
155
+            $info['size'] = $size;
156
+            $this->getCache()->put($path, $info);
157
+
158
+            return $size;
159
+        }
160
+
161
+        if (isset($info['fileid']) && $info['encrypted']) {
162
+            return $this->verifyUnencryptedSize($path, $info['size']);
163
+        }
164
+
165
+        return $this->storage->filesize($path);
166
+    }
167
+
168
+    /**
169
+     * @param string $path
170
+     * @return array
171
+     */
172
+    public function getMetaData($path) {
173
+        $data = $this->storage->getMetaData($path);
174
+        if (is_null($data)) {
175
+            return null;
176
+        }
177
+        $fullPath = $this->getFullPath($path);
178
+        $info = $this->getCache()->get($path);
179
+
180
+        if (isset($this->unencryptedSize[$fullPath])) {
181
+            $data['encrypted'] = true;
182
+            $data['size'] = $this->unencryptedSize[$fullPath];
183
+        } else {
184
+            if (isset($info['fileid']) && $info['encrypted']) {
185
+                $data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
186
+                $data['encrypted'] = true;
187
+            }
188
+        }
189
+
190
+        if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
191
+            $data['encryptedVersion'] = $info['encryptedVersion'];
192
+        }
193
+
194
+        return $data;
195
+    }
196
+
197
+    /**
198
+     * see http://php.net/manual/en/function.file_get_contents.php
199
+     *
200
+     * @param string $path
201
+     * @return string
202
+     */
203
+    public function file_get_contents($path) {
204
+
205
+        $encryptionModule = $this->getEncryptionModule($path);
206
+
207
+        if ($encryptionModule) {
208
+            $handle = $this->fopen($path, "r");
209
+            if (!$handle) {
210
+                return false;
211
+            }
212
+            $data = stream_get_contents($handle);
213
+            fclose($handle);
214
+            return $data;
215
+        }
216
+        return $this->storage->file_get_contents($path);
217
+    }
218
+
219
+    /**
220
+     * see http://php.net/manual/en/function.file_put_contents.php
221
+     *
222
+     * @param string $path
223
+     * @param string $data
224
+     * @return bool
225
+     */
226
+    public function file_put_contents($path, $data) {
227
+        // file put content will always be translated to a stream write
228
+        $handle = $this->fopen($path, 'w');
229
+        if (is_resource($handle)) {
230
+            $written = fwrite($handle, $data);
231
+            fclose($handle);
232
+            return $written;
233
+        }
234
+
235
+        return false;
236
+    }
237
+
238
+    /**
239
+     * see http://php.net/manual/en/function.unlink.php
240
+     *
241
+     * @param string $path
242
+     * @return bool
243
+     */
244
+    public function unlink($path) {
245
+        $fullPath = $this->getFullPath($path);
246
+        if ($this->util->isExcluded($fullPath)) {
247
+            return $this->storage->unlink($path);
248
+        }
249
+
250
+        $encryptionModule = $this->getEncryptionModule($path);
251
+        if ($encryptionModule) {
252
+            $this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
253
+        }
254
+
255
+        return $this->storage->unlink($path);
256
+    }
257
+
258
+    /**
259
+     * see http://php.net/manual/en/function.rename.php
260
+     *
261
+     * @param string $path1
262
+     * @param string $path2
263
+     * @return bool
264
+     */
265
+    public function rename($path1, $path2) {
266
+
267
+        $result = $this->storage->rename($path1, $path2);
268
+
269
+        if ($result &&
270
+            // versions always use the keys from the original file, so we can skip
271
+            // this step for versions
272
+            $this->isVersion($path2) === false &&
273
+            $this->encryptionManager->isEnabled()) {
274
+            $source = $this->getFullPath($path1);
275
+            if (!$this->util->isExcluded($source)) {
276
+                $target = $this->getFullPath($path2);
277
+                if (isset($this->unencryptedSize[$source])) {
278
+                    $this->unencryptedSize[$target] = $this->unencryptedSize[$source];
279
+                }
280
+                $this->keyStorage->renameKeys($source, $target);
281
+                $module = $this->getEncryptionModule($path2);
282
+                if ($module) {
283
+                    $module->update($target, $this->uid, []);
284
+                }
285
+            }
286
+        }
287
+
288
+        return $result;
289
+    }
290
+
291
+    /**
292
+     * see http://php.net/manual/en/function.rmdir.php
293
+     *
294
+     * @param string $path
295
+     * @return bool
296
+     */
297
+    public function rmdir($path) {
298
+        $result = $this->storage->rmdir($path);
299
+        $fullPath = $this->getFullPath($path);
300
+        if ($result &&
301
+            $this->util->isExcluded($fullPath) === false &&
302
+            $this->encryptionManager->isEnabled()
303
+        ) {
304
+            $this->keyStorage->deleteAllFileKeys($fullPath);
305
+        }
306
+
307
+        return $result;
308
+    }
309
+
310
+    /**
311
+     * check if a file can be read
312
+     *
313
+     * @param string $path
314
+     * @return bool
315
+     */
316
+    public function isReadable($path) {
317
+
318
+        $isReadable = true;
319
+
320
+        $metaData = $this->getMetaData($path);
321
+        if (
322
+            !$this->is_dir($path) &&
323
+            isset($metaData['encrypted']) &&
324
+            $metaData['encrypted'] === true
325
+        ) {
326
+            $fullPath = $this->getFullPath($path);
327
+            $module = $this->getEncryptionModule($path);
328
+            $isReadable = $module->isReadable($fullPath, $this->uid);
329
+        }
330
+
331
+        return $this->storage->isReadable($path) && $isReadable;
332
+    }
333
+
334
+    /**
335
+     * see http://php.net/manual/en/function.copy.php
336
+     *
337
+     * @param string $path1
338
+     * @param string $path2
339
+     * @return bool
340
+     */
341
+    public function copy($path1, $path2) {
342
+
343
+        $source = $this->getFullPath($path1);
344
+
345
+        if ($this->util->isExcluded($source)) {
346
+            return $this->storage->copy($path1, $path2);
347
+        }
348
+
349
+        // need to stream copy file by file in case we copy between a encrypted
350
+        // and a unencrypted storage
351
+        $this->unlink($path2);
352
+        $result = $this->copyFromStorage($this, $path1, $path2);
353
+
354
+        return $result;
355
+    }
356
+
357
+    /**
358
+     * see http://php.net/manual/en/function.fopen.php
359
+     *
360
+     * @param string $path
361
+     * @param string $mode
362
+     * @return resource|bool
363
+     * @throws GenericEncryptionException
364
+     * @throws ModuleDoesNotExistsException
365
+     */
366
+    public function fopen($path, $mode) {
367
+
368
+        // check if the file is stored in the array cache, this means that we
369
+        // copy a file over to the versions folder, in this case we don't want to
370
+        // decrypt it
371
+        if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
372
+            $this->arrayCache->remove('encryption_copy_version_' . $path);
373
+            return $this->storage->fopen($path, $mode);
374
+        }
375
+
376
+        $encryptionEnabled = $this->encryptionManager->isEnabled();
377
+        $shouldEncrypt = false;
378
+        $encryptionModule = null;
379
+        $header = $this->getHeader($path);
380
+        $signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
381
+        $fullPath = $this->getFullPath($path);
382
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
383
+
384
+        if ($this->util->isExcluded($fullPath) === false) {
385
+
386
+            $size = $unencryptedSize = 0;
387
+            $realFile = $this->util->stripPartialFileExtension($path);
388
+            $targetExists = $this->file_exists($realFile) || $this->file_exists($path);
389
+            $targetIsEncrypted = false;
390
+            if ($targetExists) {
391
+                // in case the file exists we require the explicit module as
392
+                // specified in the file header - otherwise we need to fail hard to
393
+                // prevent data loss on client side
394
+                if (!empty($encryptionModuleId)) {
395
+                    $targetIsEncrypted = true;
396
+                    $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
397
+                }
398
+
399
+                if ($this->file_exists($path)) {
400
+                    $size = $this->storage->filesize($path);
401
+                    $unencryptedSize = $this->filesize($path);
402
+                } else {
403
+                    $size = $unencryptedSize = 0;
404
+                }
405
+            }
406
+
407
+            try {
408
+
409
+                if (
410
+                    $mode === 'w'
411
+                    || $mode === 'w+'
412
+                    || $mode === 'wb'
413
+                    || $mode === 'wb+'
414
+                ) {
415
+                    // don't overwrite encrypted files if encryption is not enabled
416
+                    if ($targetIsEncrypted && $encryptionEnabled === false) {
417
+                        throw new GenericEncryptionException('Tried to access encrypted file but encryption is not enabled');
418
+                    }
419
+                    if ($encryptionEnabled) {
420
+                        // if $encryptionModuleId is empty, the default module will be used
421
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
422
+                        $shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
423
+                        $signed = true;
424
+                    }
425
+                } else {
426
+                    $info = $this->getCache()->get($path);
427
+                    // only get encryption module if we found one in the header
428
+                    // or if file should be encrypted according to the file cache
429
+                    if (!empty($encryptionModuleId)) {
430
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
431
+                        $shouldEncrypt = true;
432
+                    } else if (empty($encryptionModuleId) && $info['encrypted'] === true) {
433
+                        // we come from a old installation. No header and/or no module defined
434
+                        // but the file is encrypted. In this case we need to use the
435
+                        // OC_DEFAULT_MODULE to read the file
436
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
437
+                        $shouldEncrypt = true;
438
+                        $targetIsEncrypted = true;
439
+                    }
440
+                }
441
+            } catch (ModuleDoesNotExistsException $e) {
442
+                $this->logger->warning('Encryption module "' . $encryptionModuleId .
443
+                    '" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
444
+            }
445
+
446
+            // encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
447
+            if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
448
+                if (!$targetExists || !$targetIsEncrypted) {
449
+                    $shouldEncrypt = false;
450
+                }
451
+            }
452
+
453
+            if ($shouldEncrypt === true && $encryptionModule !== null) {
454
+                $headerSize = $this->getHeaderSize($path);
455
+                $source = $this->storage->fopen($path, $mode);
456
+                if (!is_resource($source)) {
457
+                    return false;
458
+                }
459
+                $handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
460
+                    $this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
461
+                    $size, $unencryptedSize, $headerSize, $signed);
462
+                return $handle;
463
+            }
464
+
465
+        }
466
+
467
+        return $this->storage->fopen($path, $mode);
468
+    }
469
+
470
+
471
+    /**
472
+     * perform some plausibility checks if the the unencrypted size is correct.
473
+     * If not, we calculate the correct unencrypted size and return it
474
+     *
475
+     * @param string $path internal path relative to the storage root
476
+     * @param int $unencryptedSize size of the unencrypted file
477
+     *
478
+     * @return int unencrypted size
479
+     */
480
+    protected function verifyUnencryptedSize($path, $unencryptedSize) {
481
+
482
+        $size = $this->storage->filesize($path);
483
+        $result = $unencryptedSize;
484
+
485
+        if ($unencryptedSize < 0 ||
486
+            ($size > 0 && $unencryptedSize === $size)
487
+        ) {
488
+            // check if we already calculate the unencrypted size for the
489
+            // given path to avoid recursions
490
+            if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
491
+                $this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
492
+                try {
493
+                    $result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
494
+                } catch (\Exception $e) {
495
+                    $this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
496
+                    $this->logger->logException($e);
497
+                }
498
+                unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
499
+            }
500
+        }
501
+
502
+        return $result;
503
+    }
504
+
505
+    /**
506
+     * calculate the unencrypted size
507
+     *
508
+     * @param string $path internal path relative to the storage root
509
+     * @param int $size size of the physical file
510
+     * @param int $unencryptedSize size of the unencrypted file
511
+     *
512
+     * @return int calculated unencrypted size
513
+     */
514
+    protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
515
+
516
+        $headerSize = $this->getHeaderSize($path);
517
+        $header = $this->getHeader($path);
518
+        $encryptionModule = $this->getEncryptionModule($path);
519
+
520
+        $stream = $this->storage->fopen($path, 'r');
521
+
522
+        // if we couldn't open the file we return the old unencrypted size
523
+        if (!is_resource($stream)) {
524
+            $this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
525
+            return $unencryptedSize;
526
+        }
527
+
528
+        $newUnencryptedSize = 0;
529
+        $size -= $headerSize;
530
+        $blockSize = $this->util->getBlockSize();
531
+
532
+        // if a header exists we skip it
533
+        if ($headerSize > 0) {
534
+            fread($stream, $headerSize);
535
+        }
536
+
537
+        // fast path, else the calculation for $lastChunkNr is bogus
538
+        if ($size === 0) {
539
+            return 0;
540
+        }
541
+
542
+        $signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
543
+        $unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
544
+
545
+        // calculate last chunk nr
546
+        // next highest is end of chunks, one subtracted is last one
547
+        // we have to read the last chunk, we can't just calculate it (because of padding etc)
548
+
549
+        $lastChunkNr = ceil($size/ $blockSize)-1;
550
+        // calculate last chunk position
551
+        $lastChunkPos = ($lastChunkNr * $blockSize);
552
+        // try to fseek to the last chunk, if it fails we have to read the whole file
553
+        if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
554
+            $newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
555
+        }
556
+
557
+        $lastChunkContentEncrypted='';
558
+        $count = $blockSize;
559
+
560
+        while ($count > 0) {
561
+            $data=fread($stream, $blockSize);
562
+            $count=strlen($data);
563
+            $lastChunkContentEncrypted .= $data;
564
+            if(strlen($lastChunkContentEncrypted) > $blockSize) {
565
+                $newUnencryptedSize += $unencryptedBlockSize;
566
+                $lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
567
+            }
568
+        }
569
+
570
+        fclose($stream);
571
+
572
+        // we have to decrypt the last chunk to get it actual size
573
+        $encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
574
+        $decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
575
+        $decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
576
+
577
+        // calc the real file size with the size of the last chunk
578
+        $newUnencryptedSize += strlen($decryptedLastChunk);
579
+
580
+        $this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
581
+
582
+        // write to cache if applicable
583
+        $cache = $this->storage->getCache();
584
+        if ($cache) {
585
+            $entry = $cache->get($path);
586
+            $cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
587
+        }
588
+
589
+        return $newUnencryptedSize;
590
+    }
591
+
592
+    /**
593
+     * @param Storage $sourceStorage
594
+     * @param string $sourceInternalPath
595
+     * @param string $targetInternalPath
596
+     * @param bool $preserveMtime
597
+     * @return bool
598
+     */
599
+    public function moveFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
600
+        if ($sourceStorage === $this) {
601
+            return $this->rename($sourceInternalPath, $targetInternalPath);
602
+        }
603
+
604
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
605
+        // - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
606
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
607
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
608
+        // - remove $this->copyBetweenStorage
609
+
610
+        if (!$sourceStorage->isDeletable($sourceInternalPath)) {
611
+            return false;
612
+        }
613
+
614
+        $result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
615
+        if ($result) {
616
+            if ($sourceStorage->is_dir($sourceInternalPath)) {
617
+                $result &= $sourceStorage->rmdir($sourceInternalPath);
618
+            } else {
619
+                $result &= $sourceStorage->unlink($sourceInternalPath);
620
+            }
621
+        }
622
+        return $result;
623
+    }
624
+
625
+
626
+    /**
627
+     * @param Storage $sourceStorage
628
+     * @param string $sourceInternalPath
629
+     * @param string $targetInternalPath
630
+     * @param bool $preserveMtime
631
+     * @param bool $isRename
632
+     * @return bool
633
+     */
634
+    public function copyFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
635
+
636
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
637
+        // - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
638
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
639
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
640
+        // - remove $this->copyBetweenStorage
641
+
642
+        return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
643
+    }
644
+
645
+    /**
646
+     * Update the encrypted cache version in the database
647
+     *
648
+     * @param Storage $sourceStorage
649
+     * @param string $sourceInternalPath
650
+     * @param string $targetInternalPath
651
+     * @param bool $isRename
652
+     */
653
+    private function updateEncryptedVersion(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
654
+        $isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath) ? 1 : 0;
655
+        $cacheInformation = [
656
+            'encrypted' => (bool)$isEncrypted,
657
+        ];
658
+        if($isEncrypted === 1) {
659
+            $encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
660
+
661
+            // In case of a move operation from an unencrypted to an encrypted
662
+            // storage the old encrypted version would stay with "0" while the
663
+            // correct value would be "1". Thus we manually set the value to "1"
664
+            // for those cases.
665
+            // See also https://github.com/owncloud/core/issues/23078
666
+            if($encryptedVersion === 0) {
667
+                $encryptedVersion = 1;
668
+            }
669
+
670
+            $cacheInformation['encryptedVersion'] = $encryptedVersion;
671
+        }
672
+
673
+        // in case of a rename we need to manipulate the source cache because
674
+        // this information will be kept for the new target
675
+        if ($isRename) {
676
+            $sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
677
+        } else {
678
+            $this->getCache()->put($targetInternalPath, $cacheInformation);
679
+        }
680
+    }
681
+
682
+    /**
683
+     * copy file between two storages
684
+     *
685
+     * @param Storage $sourceStorage
686
+     * @param string $sourceInternalPath
687
+     * @param string $targetInternalPath
688
+     * @param bool $preserveMtime
689
+     * @param bool $isRename
690
+     * @return bool
691
+     * @throws \Exception
692
+     */
693
+    private function copyBetweenStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
694
+
695
+        // for versions we have nothing to do, because versions should always use the
696
+        // key from the original file. Just create a 1:1 copy and done
697
+        if ($this->isVersion($targetInternalPath) ||
698
+            $this->isVersion($sourceInternalPath)) {
699
+            // remember that we try to create a version so that we can detect it during
700
+            // fopen($sourceInternalPath) and by-pass the encryption in order to
701
+            // create a 1:1 copy of the file
702
+            $this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
703
+            $result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
704
+            $this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
705
+            if ($result) {
706
+                $info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
707
+                // make sure that we update the unencrypted size for the version
708
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
709
+                    $this->updateUnencryptedSize(
710
+                        $this->getFullPath($targetInternalPath),
711
+                        $info['size']
712
+                    );
713
+                }
714
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
715
+            }
716
+            return $result;
717
+        }
718
+
719
+        // first copy the keys that we reuse the existing file key on the target location
720
+        // and don't create a new one which would break versions for example.
721
+        $mount = $this->mountManager->findByStorageId($sourceStorage->getId());
722
+        if (count($mount) === 1) {
723
+            $mountPoint = $mount[0]->getMountPoint();
724
+            $source = $mountPoint . '/' . $sourceInternalPath;
725
+            $target = $this->getFullPath($targetInternalPath);
726
+            $this->copyKeys($source, $target);
727
+        } else {
728
+            $this->logger->error('Could not find mount point, can\'t keep encryption keys');
729
+        }
730
+
731
+        if ($sourceStorage->is_dir($sourceInternalPath)) {
732
+            $dh = $sourceStorage->opendir($sourceInternalPath);
733
+            $result = $this->mkdir($targetInternalPath);
734
+            if (is_resource($dh)) {
735
+                while ($result and ($file = readdir($dh)) !== false) {
736
+                    if (!Filesystem::isIgnoredDir($file)) {
737
+                        $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
738
+                    }
739
+                }
740
+            }
741
+        } else {
742
+            try {
743
+                $source = $sourceStorage->fopen($sourceInternalPath, 'r');
744
+                $target = $this->fopen($targetInternalPath, 'w');
745
+                list(, $result) = \OC_Helper::streamCopy($source, $target);
746
+                fclose($source);
747
+                fclose($target);
748
+            } catch (\Exception $e) {
749
+                fclose($source);
750
+                fclose($target);
751
+                throw $e;
752
+            }
753
+            if($result) {
754
+                if ($preserveMtime) {
755
+                    $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
756
+                }
757
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
758
+            } else {
759
+                // delete partially written target file
760
+                $this->unlink($targetInternalPath);
761
+                // delete cache entry that was created by fopen
762
+                $this->getCache()->remove($targetInternalPath);
763
+            }
764
+        }
765
+        return (bool)$result;
766
+
767
+    }
768
+
769
+    /**
770
+     * get the path to a local version of the file.
771
+     * The local version of the file can be temporary and doesn't have to be persistent across requests
772
+     *
773
+     * @param string $path
774
+     * @return string
775
+     */
776
+    public function getLocalFile($path) {
777
+        if ($this->encryptionManager->isEnabled()) {
778
+            $cachedFile = $this->getCachedFile($path);
779
+            if (is_string($cachedFile)) {
780
+                return $cachedFile;
781
+            }
782
+        }
783
+        return $this->storage->getLocalFile($path);
784
+    }
785
+
786
+    /**
787
+     * Returns the wrapped storage's value for isLocal()
788
+     *
789
+     * @return bool wrapped storage's isLocal() value
790
+     */
791
+    public function isLocal() {
792
+        if ($this->encryptionManager->isEnabled()) {
793
+            return false;
794
+        }
795
+        return $this->storage->isLocal();
796
+    }
797
+
798
+    /**
799
+     * see http://php.net/manual/en/function.stat.php
800
+     * only the following keys are required in the result: size and mtime
801
+     *
802
+     * @param string $path
803
+     * @return array
804
+     */
805
+    public function stat($path) {
806
+        $stat = $this->storage->stat($path);
807
+        $fileSize = $this->filesize($path);
808
+        $stat['size'] = $fileSize;
809
+        $stat[7] = $fileSize;
810
+        return $stat;
811
+    }
812
+
813
+    /**
814
+     * see http://php.net/manual/en/function.hash.php
815
+     *
816
+     * @param string $type
817
+     * @param string $path
818
+     * @param bool $raw
819
+     * @return string
820
+     */
821
+    public function hash($type, $path, $raw = false) {
822
+        $fh = $this->fopen($path, 'rb');
823
+        $ctx = hash_init($type);
824
+        hash_update_stream($ctx, $fh);
825
+        fclose($fh);
826
+        return hash_final($ctx, $raw);
827
+    }
828
+
829
+    /**
830
+     * return full path, including mount point
831
+     *
832
+     * @param string $path relative to mount point
833
+     * @return string full path including mount point
834
+     */
835
+    protected function getFullPath($path) {
836
+        return Filesystem::normalizePath($this->mountPoint . '/' . $path);
837
+    }
838
+
839
+    /**
840
+     * read first block of encrypted file, typically this will contain the
841
+     * encryption header
842
+     *
843
+     * @param string $path
844
+     * @return string
845
+     */
846
+    protected function readFirstBlock($path) {
847
+        $firstBlock = '';
848
+        if ($this->storage->file_exists($path)) {
849
+            $handle = $this->storage->fopen($path, 'r');
850
+            $firstBlock = fread($handle, $this->util->getHeaderSize());
851
+            fclose($handle);
852
+        }
853
+        return $firstBlock;
854
+    }
855
+
856
+    /**
857
+     * return header size of given file
858
+     *
859
+     * @param string $path
860
+     * @return int
861
+     */
862
+    protected function getHeaderSize($path) {
863
+        $headerSize = 0;
864
+        $realFile = $this->util->stripPartialFileExtension($path);
865
+        if ($this->storage->file_exists($realFile)) {
866
+            $path = $realFile;
867
+        }
868
+        $firstBlock = $this->readFirstBlock($path);
869
+
870
+        if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
871
+            $headerSize = $this->util->getHeaderSize();
872
+        }
873
+
874
+        return $headerSize;
875
+    }
876
+
877
+    /**
878
+     * parse raw header to array
879
+     *
880
+     * @param string $rawHeader
881
+     * @return array
882
+     */
883
+    protected function parseRawHeader($rawHeader) {
884
+        $result = array();
885
+        if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
886
+            $header = $rawHeader;
887
+            $endAt = strpos($header, Util::HEADER_END);
888
+            if ($endAt !== false) {
889
+                $header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
890
+
891
+                // +1 to not start with an ':' which would result in empty element at the beginning
892
+                $exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
893
+
894
+                $element = array_shift($exploded);
895
+                while ($element !== Util::HEADER_END) {
896
+                    $result[$element] = array_shift($exploded);
897
+                    $element = array_shift($exploded);
898
+                }
899
+            }
900
+        }
901
+
902
+        return $result;
903
+    }
904
+
905
+    /**
906
+     * read header from file
907
+     *
908
+     * @param string $path
909
+     * @return array
910
+     */
911
+    protected function getHeader($path) {
912
+        $realFile = $this->util->stripPartialFileExtension($path);
913
+        if ($this->storage->file_exists($realFile)) {
914
+            $path = $realFile;
915
+        }
916
+
917
+        $firstBlock = $this->readFirstBlock($path);
918
+        $result = $this->parseRawHeader($firstBlock);
919
+
920
+        // if the header doesn't contain a encryption module we check if it is a
921
+        // legacy file. If true, we add the default encryption module
922
+        if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
923
+            if (!empty($result)) {
924
+                $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
925
+            } else {
926
+                // if the header was empty we have to check first if it is a encrypted file at all
927
+                $info = $this->getCache()->get($path);
928
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
929
+                    $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
930
+                }
931
+            }
932
+        }
933
+
934
+        return $result;
935
+    }
936
+
937
+    /**
938
+     * read encryption module needed to read/write the file located at $path
939
+     *
940
+     * @param string $path
941
+     * @return null|\OCP\Encryption\IEncryptionModule
942
+     * @throws ModuleDoesNotExistsException
943
+     * @throws \Exception
944
+     */
945
+    protected function getEncryptionModule($path) {
946
+        $encryptionModule = null;
947
+        $header = $this->getHeader($path);
948
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
949
+        if (!empty($encryptionModuleId)) {
950
+            try {
951
+                $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
952
+            } catch (ModuleDoesNotExistsException $e) {
953
+                $this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
954
+                throw $e;
955
+            }
956
+        }
957
+
958
+        return $encryptionModule;
959
+    }
960
+
961
+    /**
962
+     * @param string $path
963
+     * @param int $unencryptedSize
964
+     */
965
+    public function updateUnencryptedSize($path, $unencryptedSize) {
966
+        $this->unencryptedSize[$path] = $unencryptedSize;
967
+    }
968
+
969
+    /**
970
+     * copy keys to new location
971
+     *
972
+     * @param string $source path relative to data/
973
+     * @param string $target path relative to data/
974
+     * @return bool
975
+     */
976
+    protected function copyKeys($source, $target) {
977
+        if (!$this->util->isExcluded($source)) {
978
+            return $this->keyStorage->copyKeys($source, $target);
979
+        }
980
+
981
+        return false;
982
+    }
983
+
984
+    /**
985
+     * check if path points to a files version
986
+     *
987
+     * @param $path
988
+     * @return bool
989
+     */
990
+    protected function isVersion($path) {
991
+        $normalized = Filesystem::normalizePath($path);
992
+        return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
993
+    }
994
+
995
+    /**
996
+     * check if the given storage should be encrypted or not
997
+     *
998
+     * @param $path
999
+     * @return bool
1000
+     */
1001
+    protected function shouldEncrypt($path) {
1002
+        $fullPath = $this->getFullPath($path);
1003
+        $mountPointConfig = $this->mount->getOption('encrypt', true);
1004
+        if ($mountPointConfig === false) {
1005
+            return false;
1006
+        }
1007
+
1008
+        try {
1009
+            $encryptionModule = $this->getEncryptionModule($fullPath);
1010
+        } catch (ModuleDoesNotExistsException $e) {
1011
+            return false;
1012
+        }
1013
+
1014
+        if ($encryptionModule === null) {
1015
+            $encryptionModule = $this->encryptionManager->getEncryptionModule();
1016
+        }
1017
+
1018
+        return $encryptionModule->shouldEncrypt($fullPath);
1019
+
1020
+    }
1021 1021
 
1022 1022
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -368,8 +368,8 @@  discard block
 block discarded – undo
368 368
 		// check if the file is stored in the array cache, this means that we
369 369
 		// copy a file over to the versions folder, in this case we don't want to
370 370
 		// decrypt it
371
-		if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
372
-			$this->arrayCache->remove('encryption_copy_version_' . $path);
371
+		if ($this->arrayCache->hasKey('encryption_copy_version_'.$path)) {
372
+			$this->arrayCache->remove('encryption_copy_version_'.$path);
373 373
 			return $this->storage->fopen($path, $mode);
374 374
 		}
375 375
 
@@ -439,8 +439,8 @@  discard block
 block discarded – undo
439 439
 					}
440 440
 				}
441 441
 			} catch (ModuleDoesNotExistsException $e) {
442
-				$this->logger->warning('Encryption module "' . $encryptionModuleId .
443
-					'" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
442
+				$this->logger->warning('Encryption module "'.$encryptionModuleId.
443
+					'" not found, file will be stored unencrypted ('.$e->getMessage().')');
444 444
 			}
445 445
 
446 446
 			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
@@ -492,7 +492,7 @@  discard block
 block discarded – undo
492 492
 				try {
493 493
 					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
494 494
 				} catch (\Exception $e) {
495
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
495
+					$this->logger->error('Couldn\'t re-calculate unencrypted size for '.$path);
496 496
 					$this->logger->logException($e);
497 497
 				}
498 498
 				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
@@ -521,7 +521,7 @@  discard block
 block discarded – undo
521 521
 
522 522
 		// if we couldn't open the file we return the old unencrypted size
523 523
 		if (!is_resource($stream)) {
524
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
524
+			$this->logger->error('Could not open '.$path.'. Recalculation of unencrypted size aborted.');
525 525
 			return $unencryptedSize;
526 526
 		}
527 527
 
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
 		// next highest is end of chunks, one subtracted is last one
547 547
 		// we have to read the last chunk, we can't just calculate it (because of padding etc)
548 548
 
549
-		$lastChunkNr = ceil($size/ $blockSize)-1;
549
+		$lastChunkNr = ceil($size / $blockSize) - 1;
550 550
 		// calculate last chunk position
551 551
 		$lastChunkPos = ($lastChunkNr * $blockSize);
552 552
 		// try to fseek to the last chunk, if it fails we have to read the whole file
@@ -554,16 +554,16 @@  discard block
 block discarded – undo
554 554
 			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
555 555
 		}
556 556
 
557
-		$lastChunkContentEncrypted='';
557
+		$lastChunkContentEncrypted = '';
558 558
 		$count = $blockSize;
559 559
 
560 560
 		while ($count > 0) {
561
-			$data=fread($stream, $blockSize);
562
-			$count=strlen($data);
561
+			$data = fread($stream, $blockSize);
562
+			$count = strlen($data);
563 563
 			$lastChunkContentEncrypted .= $data;
564
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
564
+			if (strlen($lastChunkContentEncrypted) > $blockSize) {
565 565
 				$newUnencryptedSize += $unencryptedBlockSize;
566
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
566
+				$lastChunkContentEncrypted = substr($lastChunkContentEncrypted, $blockSize);
567 567
 			}
568 568
 		}
569 569
 
@@ -571,8 +571,8 @@  discard block
 block discarded – undo
571 571
 
572 572
 		// we have to decrypt the last chunk to get it actual size
573 573
 		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
574
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
575
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
574
+		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr.'end');
575
+		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr.'end');
576 576
 
577 577
 		// calc the real file size with the size of the last chunk
578 578
 		$newUnencryptedSize += strlen($decryptedLastChunk);
@@ -653,9 +653,9 @@  discard block
 block discarded – undo
653 653
 	private function updateEncryptedVersion(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
654 654
 		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath) ? 1 : 0;
655 655
 		$cacheInformation = [
656
-			'encrypted' => (bool)$isEncrypted,
656
+			'encrypted' => (bool) $isEncrypted,
657 657
 		];
658
-		if($isEncrypted === 1) {
658
+		if ($isEncrypted === 1) {
659 659
 			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
660 660
 
661 661
 			// In case of a move operation from an unencrypted to an encrypted
@@ -663,7 +663,7 @@  discard block
 block discarded – undo
663 663
 			// correct value would be "1". Thus we manually set the value to "1"
664 664
 			// for those cases.
665 665
 			// See also https://github.com/owncloud/core/issues/23078
666
-			if($encryptedVersion === 0) {
666
+			if ($encryptedVersion === 0) {
667 667
 				$encryptedVersion = 1;
668 668
 			}
669 669
 
@@ -699,9 +699,9 @@  discard block
 block discarded – undo
699 699
 			// remember that we try to create a version so that we can detect it during
700 700
 			// fopen($sourceInternalPath) and by-pass the encryption in order to
701 701
 			// create a 1:1 copy of the file
702
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
702
+			$this->arrayCache->set('encryption_copy_version_'.$sourceInternalPath, true);
703 703
 			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
704
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
704
+			$this->arrayCache->remove('encryption_copy_version_'.$sourceInternalPath);
705 705
 			if ($result) {
706 706
 				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
707 707
 				// make sure that we update the unencrypted size for the version
@@ -721,7 +721,7 @@  discard block
 block discarded – undo
721 721
 		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
722 722
 		if (count($mount) === 1) {
723 723
 			$mountPoint = $mount[0]->getMountPoint();
724
-			$source = $mountPoint . '/' . $sourceInternalPath;
724
+			$source = $mountPoint.'/'.$sourceInternalPath;
725 725
 			$target = $this->getFullPath($targetInternalPath);
726 726
 			$this->copyKeys($source, $target);
727 727
 		} else {
@@ -734,7 +734,7 @@  discard block
 block discarded – undo
734 734
 			if (is_resource($dh)) {
735 735
 				while ($result and ($file = readdir($dh)) !== false) {
736 736
 					if (!Filesystem::isIgnoredDir($file)) {
737
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
737
+						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath.'/'.$file, $targetInternalPath.'/'.$file, false, $isRename);
738 738
 					}
739 739
 				}
740 740
 			}
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
 				fclose($target);
751 751
 				throw $e;
752 752
 			}
753
-			if($result) {
753
+			if ($result) {
754 754
 				if ($preserveMtime) {
755 755
 					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
756 756
 				}
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
 				$this->getCache()->remove($targetInternalPath);
763 763
 			}
764 764
 		}
765
-		return (bool)$result;
765
+		return (bool) $result;
766 766
 
767 767
 	}
768 768
 
@@ -833,7 +833,7 @@  discard block
 block discarded – undo
833 833
 	 * @return string full path including mount point
834 834
 	 */
835 835
 	protected function getFullPath($path) {
836
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
836
+		return Filesystem::normalizePath($this->mountPoint.'/'.$path);
837 837
 	}
838 838
 
839 839
 	/**
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
 				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
890 890
 
891 891
 				// +1 to not start with an ':' which would result in empty element at the beginning
892
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
892
+				$exploded = explode(':', substr($header, strlen(Util::HEADER_START) + 1));
893 893
 
894 894
 				$element = array_shift($exploded);
895 895
 				while ($element !== Util::HEADER_END) {
@@ -950,7 +950,7 @@  discard block
 block discarded – undo
950 950
 			try {
951 951
 				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
952 952
 			} catch (ModuleDoesNotExistsException $e) {
953
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
953
+				$this->logger->critical('Encryption module defined in "'.$path.'" not loaded!');
954 954
 				throw $e;
955 955
 			}
956 956
 		}
Please login to merge, or discard this patch.