Completed
Pull Request — master (#6637)
by Tobia
13: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/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   +400 added lines, -400 removed lines patch added patch discarded remove patch
@@ -40,404 +40,404 @@
 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
-
103
-		$forceLang = $this->config->getSystemValue('force_language', false);
104
-		if (is_string($forceLang)) {
105
-			$lang = $forceLang;
106
-		}
107
-
108
-		if ($lang === null || !$this->languageExists($app, $lang)) {
109
-			$lang = $this->findLanguage($app);
110
-		}
111
-
112
-		if (!isset($this->instances[$lang][$app])) {
113
-			$this->instances[$lang][$app] = new L10N(
114
-				$this, $app, $lang,
115
-				$this->getL10nFilesForApp($app, $lang)
116
-			);
117
-		}
118
-
119
-		return $this->instances[$lang][$app];
120
-	}
121
-
122
-	/**
123
-	 * Find the best language
124
-	 *
125
-	 * @param string|null $app App id or null for core
126
-	 * @return string language If nothing works it returns 'en'
127
-	 */
128
-	public function findLanguage($app = null) {
129
-		if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
130
-			return $this->requestLanguage;
131
-		}
132
-
133
-		/**
134
-		 * At this point Nextcloud might not yet be installed and thus the lookup
135
-		 * in the preferences table might fail. For this reason we need to check
136
-		 * whether the instance has already been installed
137
-		 *
138
-		 * @link https://github.com/owncloud/core/issues/21955
139
-		 */
140
-		if($this->config->getSystemValue('installed', false)) {
141
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
142
-			if(!is_null($userId)) {
143
-				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
144
-			} else {
145
-				$userLang = null;
146
-			}
147
-		} else {
148
-			$userId = null;
149
-			$userLang = null;
150
-		}
151
-
152
-		if ($userLang) {
153
-			$this->requestLanguage = $userLang;
154
-			if ($this->languageExists($app, $userLang)) {
155
-				return $userLang;
156
-			}
157
-		}
158
-
159
-		try {
160
-			// Try to get the language from the Request
161
-			$lang = $this->getLanguageFromRequest($app);
162
-			if ($userId !== null && $app === null && !$userLang) {
163
-				$this->config->setUserValue($userId, 'core', 'lang', $lang);
164
-			}
165
-			return $lang;
166
-		} catch (LanguageNotFoundException $e) {
167
-			// Finding language from request failed fall back to default language
168
-			$defaultLanguage = $this->config->getSystemValue('default_language', false);
169
-			if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
170
-				return $defaultLanguage;
171
-			}
172
-		}
173
-
174
-		// We could not find any language so fall back to english
175
-		return 'en';
176
-	}
177
-
178
-	/**
179
-	 * Find all available languages for an app
180
-	 *
181
-	 * @param string|null $app App id or null for core
182
-	 * @return array an array of available languages
183
-	 */
184
-	public function findAvailableLanguages($app = null) {
185
-		$key = $app;
186
-		if ($key === null) {
187
-			$key = 'null';
188
-		}
189
-
190
-		// also works with null as key
191
-		if (!empty($this->availableLanguages[$key])) {
192
-			return $this->availableLanguages[$key];
193
-		}
194
-
195
-		$available = ['en']; //english is always available
196
-		$dir = $this->findL10nDir($app);
197
-		if (is_dir($dir)) {
198
-			$files = scandir($dir);
199
-			if ($files !== false) {
200
-				foreach ($files as $file) {
201
-					if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
202
-						$available[] = substr($file, 0, -5);
203
-					}
204
-				}
205
-			}
206
-		}
207
-
208
-		// merge with translations from theme
209
-		$theme = $this->config->getSystemValue('theme');
210
-		if (!empty($theme)) {
211
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
212
-
213
-			if (is_dir($themeDir)) {
214
-				$files = scandir($themeDir);
215
-				if ($files !== false) {
216
-					foreach ($files as $file) {
217
-						if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
218
-							$available[] = substr($file, 0, -5);
219
-						}
220
-					}
221
-				}
222
-			}
223
-		}
224
-
225
-		$this->availableLanguages[$key] = $available;
226
-		return $available;
227
-	}
228
-
229
-	/**
230
-	 * @param string|null $app App id or null for core
231
-	 * @param string $lang
232
-	 * @return bool
233
-	 */
234
-	public function languageExists($app, $lang) {
235
-		if ($lang === 'en') {//english is always available
236
-			return true;
237
-		}
238
-
239
-		$languages = $this->findAvailableLanguages($app);
240
-		return array_search($lang, $languages) !== false;
241
-	}
242
-
243
-	/**
244
-	 * @param string|null $app
245
-	 * @return string
246
-	 * @throws LanguageNotFoundException
247
-	 */
248
-	private function getLanguageFromRequest($app) {
249
-		$header = $this->request->getHeader('ACCEPT_LANGUAGE');
250
-		if ($header) {
251
-			$available = $this->findAvailableLanguages($app);
252
-
253
-			// E.g. make sure that 'de' is before 'de_DE'.
254
-			sort($available);
255
-
256
-			$preferences = preg_split('/,\s*/', strtolower($header));
257
-			foreach ($preferences as $preference) {
258
-				list($preferred_language) = explode(';', $preference);
259
-				$preferred_language = str_replace('-', '_', $preferred_language);
260
-
261
-				foreach ($available as $available_language) {
262
-					if ($preferred_language === strtolower($available_language)) {
263
-						return $this->respectDefaultLanguage($app, $available_language);
264
-					}
265
-				}
266
-
267
-				// Fallback from de_De to de
268
-				foreach ($available as $available_language) {
269
-					if (substr($preferred_language, 0, 2) === $available_language) {
270
-						return $available_language;
271
-					}
272
-				}
273
-			}
274
-		}
275
-
276
-		throw new LanguageNotFoundException();
277
-	}
278
-
279
-	/**
280
-	 * if default language is set to de_DE (formal German) this should be
281
-	 * preferred to 'de' (non-formal German) if possible
282
-	 *
283
-	 * @param string|null $app
284
-	 * @param string $lang
285
-	 * @return string
286
-	 */
287
-	protected function respectDefaultLanguage($app, $lang) {
288
-		$result = $lang;
289
-		$defaultLanguage = $this->config->getSystemValue('default_language', false);
290
-
291
-		// use formal version of german ("Sie" instead of "Du") if the default
292
-		// language is set to 'de_DE' if possible
293
-		if (is_string($defaultLanguage) &&
294
-			strtolower($lang) === 'de' &&
295
-			strtolower($defaultLanguage) === 'de_de' &&
296
-			$this->languageExists($app, 'de_DE')
297
-		) {
298
-			$result = 'de_DE';
299
-		}
300
-
301
-		return $result;
302
-	}
303
-
304
-	/**
305
-	 * Checks if $sub is a subdirectory of $parent
306
-	 *
307
-	 * @param string $sub
308
-	 * @param string $parent
309
-	 * @return bool
310
-	 */
311
-	private function isSubDirectory($sub, $parent) {
312
-		// Check whether $sub contains no ".."
313
-		if(strpos($sub, '..') !== false) {
314
-			return false;
315
-		}
316
-
317
-		// Check whether $sub is a subdirectory of $parent
318
-		if (strpos($sub, $parent) === 0) {
319
-			return true;
320
-		}
321
-
322
-		return false;
323
-	}
324
-
325
-	/**
326
-	 * Get a list of language files that should be loaded
327
-	 *
328
-	 * @param string $app
329
-	 * @param string $lang
330
-	 * @return string[]
331
-	 */
332
-	// FIXME This method is only public, until OC_L10N does not need it anymore,
333
-	// FIXME This is also the reason, why it is not in the public interface
334
-	public function getL10nFilesForApp($app, $lang) {
335
-		$languageFiles = [];
336
-
337
-		$i18nDir = $this->findL10nDir($app);
338
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
339
-
340
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
341
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
342
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
343
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
344
-			)
345
-			&& file_exists($transFile)) {
346
-			// load the translations file
347
-			$languageFiles[] = $transFile;
348
-		}
349
-
350
-		// merge with translations from theme
351
-		$theme = $this->config->getSystemValue('theme');
352
-		if (!empty($theme)) {
353
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
354
-			if (file_exists($transFile)) {
355
-				$languageFiles[] = $transFile;
356
-			}
357
-		}
358
-
359
-		return $languageFiles;
360
-	}
361
-
362
-	/**
363
-	 * find the l10n directory
364
-	 *
365
-	 * @param string $app App id or empty string for core
366
-	 * @return string directory
367
-	 */
368
-	protected function findL10nDir($app = null) {
369
-		if (in_array($app, ['core', 'lib', 'settings'])) {
370
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
371
-				return $this->serverRoot . '/' . $app . '/l10n/';
372
-			}
373
-		} else if ($app && \OC_App::getAppPath($app) !== false) {
374
-			// Check if the app is in the app folder
375
-			return \OC_App::getAppPath($app) . '/l10n/';
376
-		}
377
-		return $this->serverRoot . '/core/l10n/';
378
-	}
379
-
380
-
381
-	/**
382
-	 * Creates a function from the plural string
383
-	 *
384
-	 * Parts of the code is copied from Habari:
385
-	 * https://github.com/habari/system/blob/master/classes/locale.php
386
-	 * @param string $string
387
-	 * @return string
388
-	 */
389
-	public function createPluralFunction($string) {
390
-		if (isset($this->pluralFunctions[$string])) {
391
-			return $this->pluralFunctions[$string];
392
-		}
393
-
394
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
395
-			// sanitize
396
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
397
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
398
-
399
-			$body = str_replace(
400
-				array( 'plural', 'n', '$n$plurals', ),
401
-				array( '$plural', '$n', '$nplurals', ),
402
-				'nplurals='. $nplurals . '; plural=' . $plural
403
-			);
404
-
405
-			// add parents
406
-			// important since PHP's ternary evaluates from left to right
407
-			$body .= ';';
408
-			$res = '';
409
-			$p = 0;
410
-			for($i = 0; $i < strlen($body); $i++) {
411
-				$ch = $body[$i];
412
-				switch ( $ch ) {
413
-					case '?':
414
-						$res .= ' ? (';
415
-						$p++;
416
-						break;
417
-					case ':':
418
-						$res .= ') : (';
419
-						break;
420
-					case ';':
421
-						$res .= str_repeat( ')', $p ) . ';';
422
-						$p = 0;
423
-						break;
424
-					default:
425
-						$res .= $ch;
426
-				}
427
-			}
428
-
429
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
430
-			$function = create_function('$n', $body);
431
-			$this->pluralFunctions[$string] = $function;
432
-			return $function;
433
-		} else {
434
-			// default: one plural form for all cases but n==1 (english)
435
-			$function = create_function(
436
-				'$n',
437
-				'$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
438
-			);
439
-			$this->pluralFunctions[$string] = $function;
440
-			return $function;
441
-		}
442
-	}
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
+
103
+        $forceLang = $this->config->getSystemValue('force_language', false);
104
+        if (is_string($forceLang)) {
105
+            $lang = $forceLang;
106
+        }
107
+
108
+        if ($lang === null || !$this->languageExists($app, $lang)) {
109
+            $lang = $this->findLanguage($app);
110
+        }
111
+
112
+        if (!isset($this->instances[$lang][$app])) {
113
+            $this->instances[$lang][$app] = new L10N(
114
+                $this, $app, $lang,
115
+                $this->getL10nFilesForApp($app, $lang)
116
+            );
117
+        }
118
+
119
+        return $this->instances[$lang][$app];
120
+    }
121
+
122
+    /**
123
+     * Find the best language
124
+     *
125
+     * @param string|null $app App id or null for core
126
+     * @return string language If nothing works it returns 'en'
127
+     */
128
+    public function findLanguage($app = null) {
129
+        if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
130
+            return $this->requestLanguage;
131
+        }
132
+
133
+        /**
134
+         * At this point Nextcloud might not yet be installed and thus the lookup
135
+         * in the preferences table might fail. For this reason we need to check
136
+         * whether the instance has already been installed
137
+         *
138
+         * @link https://github.com/owncloud/core/issues/21955
139
+         */
140
+        if($this->config->getSystemValue('installed', false)) {
141
+            $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
142
+            if(!is_null($userId)) {
143
+                $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
144
+            } else {
145
+                $userLang = null;
146
+            }
147
+        } else {
148
+            $userId = null;
149
+            $userLang = null;
150
+        }
151
+
152
+        if ($userLang) {
153
+            $this->requestLanguage = $userLang;
154
+            if ($this->languageExists($app, $userLang)) {
155
+                return $userLang;
156
+            }
157
+        }
158
+
159
+        try {
160
+            // Try to get the language from the Request
161
+            $lang = $this->getLanguageFromRequest($app);
162
+            if ($userId !== null && $app === null && !$userLang) {
163
+                $this->config->setUserValue($userId, 'core', 'lang', $lang);
164
+            }
165
+            return $lang;
166
+        } catch (LanguageNotFoundException $e) {
167
+            // Finding language from request failed fall back to default language
168
+            $defaultLanguage = $this->config->getSystemValue('default_language', false);
169
+            if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
170
+                return $defaultLanguage;
171
+            }
172
+        }
173
+
174
+        // We could not find any language so fall back to english
175
+        return 'en';
176
+    }
177
+
178
+    /**
179
+     * Find all available languages for an app
180
+     *
181
+     * @param string|null $app App id or null for core
182
+     * @return array an array of available languages
183
+     */
184
+    public function findAvailableLanguages($app = null) {
185
+        $key = $app;
186
+        if ($key === null) {
187
+            $key = 'null';
188
+        }
189
+
190
+        // also works with null as key
191
+        if (!empty($this->availableLanguages[$key])) {
192
+            return $this->availableLanguages[$key];
193
+        }
194
+
195
+        $available = ['en']; //english is always available
196
+        $dir = $this->findL10nDir($app);
197
+        if (is_dir($dir)) {
198
+            $files = scandir($dir);
199
+            if ($files !== false) {
200
+                foreach ($files as $file) {
201
+                    if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
202
+                        $available[] = substr($file, 0, -5);
203
+                    }
204
+                }
205
+            }
206
+        }
207
+
208
+        // merge with translations from theme
209
+        $theme = $this->config->getSystemValue('theme');
210
+        if (!empty($theme)) {
211
+            $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
212
+
213
+            if (is_dir($themeDir)) {
214
+                $files = scandir($themeDir);
215
+                if ($files !== false) {
216
+                    foreach ($files as $file) {
217
+                        if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
218
+                            $available[] = substr($file, 0, -5);
219
+                        }
220
+                    }
221
+                }
222
+            }
223
+        }
224
+
225
+        $this->availableLanguages[$key] = $available;
226
+        return $available;
227
+    }
228
+
229
+    /**
230
+     * @param string|null $app App id or null for core
231
+     * @param string $lang
232
+     * @return bool
233
+     */
234
+    public function languageExists($app, $lang) {
235
+        if ($lang === 'en') {//english is always available
236
+            return true;
237
+        }
238
+
239
+        $languages = $this->findAvailableLanguages($app);
240
+        return array_search($lang, $languages) !== false;
241
+    }
242
+
243
+    /**
244
+     * @param string|null $app
245
+     * @return string
246
+     * @throws LanguageNotFoundException
247
+     */
248
+    private function getLanguageFromRequest($app) {
249
+        $header = $this->request->getHeader('ACCEPT_LANGUAGE');
250
+        if ($header) {
251
+            $available = $this->findAvailableLanguages($app);
252
+
253
+            // E.g. make sure that 'de' is before 'de_DE'.
254
+            sort($available);
255
+
256
+            $preferences = preg_split('/,\s*/', strtolower($header));
257
+            foreach ($preferences as $preference) {
258
+                list($preferred_language) = explode(';', $preference);
259
+                $preferred_language = str_replace('-', '_', $preferred_language);
260
+
261
+                foreach ($available as $available_language) {
262
+                    if ($preferred_language === strtolower($available_language)) {
263
+                        return $this->respectDefaultLanguage($app, $available_language);
264
+                    }
265
+                }
266
+
267
+                // Fallback from de_De to de
268
+                foreach ($available as $available_language) {
269
+                    if (substr($preferred_language, 0, 2) === $available_language) {
270
+                        return $available_language;
271
+                    }
272
+                }
273
+            }
274
+        }
275
+
276
+        throw new LanguageNotFoundException();
277
+    }
278
+
279
+    /**
280
+     * if default language is set to de_DE (formal German) this should be
281
+     * preferred to 'de' (non-formal German) if possible
282
+     *
283
+     * @param string|null $app
284
+     * @param string $lang
285
+     * @return string
286
+     */
287
+    protected function respectDefaultLanguage($app, $lang) {
288
+        $result = $lang;
289
+        $defaultLanguage = $this->config->getSystemValue('default_language', false);
290
+
291
+        // use formal version of german ("Sie" instead of "Du") if the default
292
+        // language is set to 'de_DE' if possible
293
+        if (is_string($defaultLanguage) &&
294
+            strtolower($lang) === 'de' &&
295
+            strtolower($defaultLanguage) === 'de_de' &&
296
+            $this->languageExists($app, 'de_DE')
297
+        ) {
298
+            $result = 'de_DE';
299
+        }
300
+
301
+        return $result;
302
+    }
303
+
304
+    /**
305
+     * Checks if $sub is a subdirectory of $parent
306
+     *
307
+     * @param string $sub
308
+     * @param string $parent
309
+     * @return bool
310
+     */
311
+    private function isSubDirectory($sub, $parent) {
312
+        // Check whether $sub contains no ".."
313
+        if(strpos($sub, '..') !== false) {
314
+            return false;
315
+        }
316
+
317
+        // Check whether $sub is a subdirectory of $parent
318
+        if (strpos($sub, $parent) === 0) {
319
+            return true;
320
+        }
321
+
322
+        return false;
323
+    }
324
+
325
+    /**
326
+     * Get a list of language files that should be loaded
327
+     *
328
+     * @param string $app
329
+     * @param string $lang
330
+     * @return string[]
331
+     */
332
+    // FIXME This method is only public, until OC_L10N does not need it anymore,
333
+    // FIXME This is also the reason, why it is not in the public interface
334
+    public function getL10nFilesForApp($app, $lang) {
335
+        $languageFiles = [];
336
+
337
+        $i18nDir = $this->findL10nDir($app);
338
+        $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
339
+
340
+        if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
341
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
342
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
343
+                || $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
344
+            )
345
+            && file_exists($transFile)) {
346
+            // load the translations file
347
+            $languageFiles[] = $transFile;
348
+        }
349
+
350
+        // merge with translations from theme
351
+        $theme = $this->config->getSystemValue('theme');
352
+        if (!empty($theme)) {
353
+            $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
354
+            if (file_exists($transFile)) {
355
+                $languageFiles[] = $transFile;
356
+            }
357
+        }
358
+
359
+        return $languageFiles;
360
+    }
361
+
362
+    /**
363
+     * find the l10n directory
364
+     *
365
+     * @param string $app App id or empty string for core
366
+     * @return string directory
367
+     */
368
+    protected function findL10nDir($app = null) {
369
+        if (in_array($app, ['core', 'lib', 'settings'])) {
370
+            if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
371
+                return $this->serverRoot . '/' . $app . '/l10n/';
372
+            }
373
+        } else if ($app && \OC_App::getAppPath($app) !== false) {
374
+            // Check if the app is in the app folder
375
+            return \OC_App::getAppPath($app) . '/l10n/';
376
+        }
377
+        return $this->serverRoot . '/core/l10n/';
378
+    }
379
+
380
+
381
+    /**
382
+     * Creates a function from the plural string
383
+     *
384
+     * Parts of the code is copied from Habari:
385
+     * https://github.com/habari/system/blob/master/classes/locale.php
386
+     * @param string $string
387
+     * @return string
388
+     */
389
+    public function createPluralFunction($string) {
390
+        if (isset($this->pluralFunctions[$string])) {
391
+            return $this->pluralFunctions[$string];
392
+        }
393
+
394
+        if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
395
+            // sanitize
396
+            $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
397
+            $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
398
+
399
+            $body = str_replace(
400
+                array( 'plural', 'n', '$n$plurals', ),
401
+                array( '$plural', '$n', '$nplurals', ),
402
+                'nplurals='. $nplurals . '; plural=' . $plural
403
+            );
404
+
405
+            // add parents
406
+            // important since PHP's ternary evaluates from left to right
407
+            $body .= ';';
408
+            $res = '';
409
+            $p = 0;
410
+            for($i = 0; $i < strlen($body); $i++) {
411
+                $ch = $body[$i];
412
+                switch ( $ch ) {
413
+                    case '?':
414
+                        $res .= ' ? (';
415
+                        $p++;
416
+                        break;
417
+                    case ':':
418
+                        $res .= ') : (';
419
+                        break;
420
+                    case ';':
421
+                        $res .= str_repeat( ')', $p ) . ';';
422
+                        $p = 0;
423
+                        break;
424
+                    default:
425
+                        $res .= $ch;
426
+                }
427
+            }
428
+
429
+            $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
430
+            $function = create_function('$n', $body);
431
+            $this->pluralFunctions[$string] = $function;
432
+            return $function;
433
+        } else {
434
+            // default: one plural form for all cases but n==1 (english)
435
+            $function = create_function(
436
+                '$n',
437
+                '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
438
+            );
439
+            $this->pluralFunctions[$string] = $function;
440
+            return $function;
441
+        }
442
+    }
443 443
 }
Please login to merge, or discard this patch.
lib/private/Files/Filesystem.php 3 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.
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   +853 added lines, -853 removed lines patch added patch discarded remove patch
@@ -69,857 +69,857 @@
 block discarded – undo
69 69
 
70 70
 class Filesystem {
71 71
 
72
-	/**
73
-	 * @var Mount\Manager $mounts
74
-	 */
75
-	private static $mounts;
76
-
77
-	public static $loaded = false;
78
-	/**
79
-	 * @var \OC\Files\View $defaultInstance
80
-	 */
81
-	static private $defaultInstance;
82
-
83
-	static private $usersSetup = array();
84
-
85
-	static private $normalizedPathCache = null;
86
-
87
-	static private $listeningForProviders = false;
88
-
89
-	/**
90
-	 * classname which used for hooks handling
91
-	 * used as signalclass in OC_Hooks::emit()
92
-	 */
93
-	const CLASSNAME = 'OC_Filesystem';
94
-
95
-	/**
96
-	 * signalname emitted before file renaming
97
-	 *
98
-	 * @param string $oldpath
99
-	 * @param string $newpath
100
-	 */
101
-	const signal_rename = 'rename';
102
-
103
-	/**
104
-	 * signal emitted after file renaming
105
-	 *
106
-	 * @param string $oldpath
107
-	 * @param string $newpath
108
-	 */
109
-	const signal_post_rename = 'post_rename';
110
-
111
-	/**
112
-	 * signal emitted before file/dir creation
113
-	 *
114
-	 * @param string $path
115
-	 * @param bool $run changing this flag to false in hook handler will cancel event
116
-	 */
117
-	const signal_create = 'create';
118
-
119
-	/**
120
-	 * signal emitted after file/dir creation
121
-	 *
122
-	 * @param string $path
123
-	 * @param bool $run changing this flag to false in hook handler will cancel event
124
-	 */
125
-	const signal_post_create = 'post_create';
126
-
127
-	/**
128
-	 * signal emits before file/dir copy
129
-	 *
130
-	 * @param string $oldpath
131
-	 * @param string $newpath
132
-	 * @param bool $run changing this flag to false in hook handler will cancel event
133
-	 */
134
-	const signal_copy = 'copy';
135
-
136
-	/**
137
-	 * signal emits after file/dir copy
138
-	 *
139
-	 * @param string $oldpath
140
-	 * @param string $newpath
141
-	 */
142
-	const signal_post_copy = 'post_copy';
143
-
144
-	/**
145
-	 * signal emits before file/dir save
146
-	 *
147
-	 * @param string $path
148
-	 * @param bool $run changing this flag to false in hook handler will cancel event
149
-	 */
150
-	const signal_write = 'write';
151
-
152
-	/**
153
-	 * signal emits after file/dir save
154
-	 *
155
-	 * @param string $path
156
-	 */
157
-	const signal_post_write = 'post_write';
158
-
159
-	/**
160
-	 * signal emitted before file/dir update
161
-	 *
162
-	 * @param string $path
163
-	 * @param bool $run changing this flag to false in hook handler will cancel event
164
-	 */
165
-	const signal_update = 'update';
166
-
167
-	/**
168
-	 * signal emitted after file/dir update
169
-	 *
170
-	 * @param string $path
171
-	 * @param bool $run changing this flag to false in hook handler will cancel event
172
-	 */
173
-	const signal_post_update = 'post_update';
174
-
175
-	/**
176
-	 * signal emits when reading file/dir
177
-	 *
178
-	 * @param string $path
179
-	 */
180
-	const signal_read = 'read';
181
-
182
-	/**
183
-	 * signal emits when removing file/dir
184
-	 *
185
-	 * @param string $path
186
-	 */
187
-	const signal_delete = 'delete';
188
-
189
-	/**
190
-	 * parameters definitions for signals
191
-	 */
192
-	const signal_param_path = 'path';
193
-	const signal_param_oldpath = 'oldpath';
194
-	const signal_param_newpath = 'newpath';
195
-
196
-	/**
197
-	 * run - changing this flag to false in hook handler will cancel event
198
-	 */
199
-	const signal_param_run = 'run';
200
-
201
-	const signal_create_mount = 'create_mount';
202
-	const signal_delete_mount = 'delete_mount';
203
-	const signal_param_mount_type = 'mounttype';
204
-	const signal_param_users = 'users';
205
-
206
-	/**
207
-	 * @var \OC\Files\Storage\StorageFactory $loader
208
-	 */
209
-	private static $loader;
210
-
211
-	/** @var bool */
212
-	private static $logWarningWhenAddingStorageWrapper = true;
213
-
214
-	/**
215
-	 * @param bool $shouldLog
216
-	 * @return bool previous value
217
-	 * @internal
218
-	 */
219
-	public static function logWarningWhenAddingStorageWrapper($shouldLog) {
220
-		$previousValue = self::$logWarningWhenAddingStorageWrapper;
221
-		self::$logWarningWhenAddingStorageWrapper = (bool) $shouldLog;
222
-		return $previousValue;
223
-	}
224
-
225
-	/**
226
-	 * @param string $wrapperName
227
-	 * @param callable $wrapper
228
-	 * @param int $priority
229
-	 */
230
-	public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) {
231
-		if (self::$logWarningWhenAddingStorageWrapper) {
232
-			\OC::$server->getLogger()->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [
233
-				'wrapper' => $wrapperName,
234
-				'app' => 'filesystem',
235
-			]);
236
-		}
237
-
238
-		$mounts = self::getMountManager()->getAll();
239
-		if (!self::getLoader()->addStorageWrapper($wrapperName, $wrapper, $priority, $mounts)) {
240
-			// do not re-wrap if storage with this name already existed
241
-			return;
242
-		}
243
-	}
244
-
245
-	/**
246
-	 * Returns the storage factory
247
-	 *
248
-	 * @return \OCP\Files\Storage\IStorageFactory
249
-	 */
250
-	public static function getLoader() {
251
-		if (!self::$loader) {
252
-			self::$loader = new StorageFactory();
253
-		}
254
-		return self::$loader;
255
-	}
256
-
257
-	/**
258
-	 * Returns the mount manager
259
-	 *
260
-	 * @return \OC\Files\Mount\Manager
261
-	 */
262
-	public static function getMountManager($user = '') {
263
-		if (!self::$mounts) {
264
-			\OC_Util::setupFS($user);
265
-		}
266
-		return self::$mounts;
267
-	}
268
-
269
-	/**
270
-	 * get the mountpoint of the storage object for a path
271
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
272
-	 * returned mountpoint is relative to the absolute root of the filesystem
273
-	 * and doesn't take the chroot into account )
274
-	 *
275
-	 * @param string $path
276
-	 * @return string
277
-	 */
278
-	static public function getMountPoint($path) {
279
-		if (!self::$mounts) {
280
-			\OC_Util::setupFS();
281
-		}
282
-		$mount = self::$mounts->find($path);
283
-		if ($mount) {
284
-			return $mount->getMountPoint();
285
-		} else {
286
-			return '';
287
-		}
288
-	}
289
-
290
-	/**
291
-	 * get a list of all mount points in a directory
292
-	 *
293
-	 * @param string $path
294
-	 * @return string[]
295
-	 */
296
-	static public function getMountPoints($path) {
297
-		if (!self::$mounts) {
298
-			\OC_Util::setupFS();
299
-		}
300
-		$result = array();
301
-		$mounts = self::$mounts->findIn($path);
302
-		foreach ($mounts as $mount) {
303
-			$result[] = $mount->getMountPoint();
304
-		}
305
-		return $result;
306
-	}
307
-
308
-	/**
309
-	 * get the storage mounted at $mountPoint
310
-	 *
311
-	 * @param string $mountPoint
312
-	 * @return \OC\Files\Storage\Storage
313
-	 */
314
-	public static function getStorage($mountPoint) {
315
-		if (!self::$mounts) {
316
-			\OC_Util::setupFS();
317
-		}
318
-		$mount = self::$mounts->find($mountPoint);
319
-		return $mount->getStorage();
320
-	}
321
-
322
-	/**
323
-	 * @param string $id
324
-	 * @return Mount\MountPoint[]
325
-	 */
326
-	public static function getMountByStorageId($id) {
327
-		if (!self::$mounts) {
328
-			\OC_Util::setupFS();
329
-		}
330
-		return self::$mounts->findByStorageId($id);
331
-	}
332
-
333
-	/**
334
-	 * @param int $id
335
-	 * @return Mount\MountPoint[]
336
-	 */
337
-	public static function getMountByNumericId($id) {
338
-		if (!self::$mounts) {
339
-			\OC_Util::setupFS();
340
-		}
341
-		return self::$mounts->findByNumericId($id);
342
-	}
343
-
344
-	/**
345
-	 * resolve a path to a storage and internal path
346
-	 *
347
-	 * @param string $path
348
-	 * @return array an array consisting of the storage and the internal path
349
-	 */
350
-	static public function resolvePath($path) {
351
-		if (!self::$mounts) {
352
-			\OC_Util::setupFS();
353
-		}
354
-		$mount = self::$mounts->find($path);
355
-		if ($mount) {
356
-			return array($mount->getStorage(), rtrim($mount->getInternalPath($path), '/'));
357
-		} else {
358
-			return array(null, null);
359
-		}
360
-	}
361
-
362
-	static public function init($user, $root) {
363
-		if (self::$defaultInstance) {
364
-			return false;
365
-		}
366
-		self::getLoader();
367
-		self::$defaultInstance = new View($root);
368
-
369
-		if (!self::$mounts) {
370
-			self::$mounts = \OC::$server->getMountManager();
371
-		}
372
-
373
-		//load custom mount config
374
-		self::initMountPoints($user);
375
-
376
-		self::$loaded = true;
377
-
378
-		return true;
379
-	}
380
-
381
-	static public function initMountManager() {
382
-		if (!self::$mounts) {
383
-			self::$mounts = \OC::$server->getMountManager();
384
-		}
385
-	}
386
-
387
-	/**
388
-	 * Initialize system and personal mount points for a user
389
-	 *
390
-	 * @param string $user
391
-	 * @throws \OC\User\NoUserException if the user is not available
392
-	 */
393
-	public static function initMountPoints($user = '') {
394
-		if ($user == '') {
395
-			$user = \OC_User::getUser();
396
-		}
397
-		if ($user === null || $user === false || $user === '') {
398
-			throw new \OC\User\NoUserException('Attempted to initialize mount points for null user and no user in session');
399
-		}
400
-
401
-		if (isset(self::$usersSetup[$user])) {
402
-			return;
403
-		}
404
-
405
-		self::$usersSetup[$user] = true;
406
-
407
-		$userManager = \OC::$server->getUserManager();
408
-		$userObject = $userManager->get($user);
409
-
410
-		if (is_null($userObject)) {
411
-			\OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, \OCP\Util::ERROR);
412
-			// reset flag, this will make it possible to rethrow the exception if called again
413
-			unset(self::$usersSetup[$user]);
414
-			throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
415
-		}
416
-
417
-		$realUid = $userObject->getUID();
418
-		// workaround in case of different casings
419
-		if ($user !== $realUid) {
420
-			$stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
421
-			\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
-			$user = $realUid;
423
-
424
-			// again with the correct casing
425
-			if (isset(self::$usersSetup[$user])) {
426
-				return;
427
-			}
428
-
429
-			self::$usersSetup[$user] = true;
430
-		}
431
-
432
-		if (\OC::$server->getLockdownManager()->canAccessFilesystem()) {
433
-			/** @var \OC\Files\Config\MountProviderCollection $mountConfigManager */
434
-			$mountConfigManager = \OC::$server->getMountProviderCollection();
435
-
436
-			// home mounts are handled seperate since we need to ensure this is mounted before we call the other mount providers
437
-			$homeMount = $mountConfigManager->getHomeMountForUser($userObject);
438
-
439
-			self::getMountManager()->addMount($homeMount);
440
-
441
-			\OC\Files\Filesystem::getStorage($user);
442
-
443
-			// Chance to mount for other storages
444
-			if ($userObject) {
445
-				$mounts = $mountConfigManager->addMountForUser($userObject, self::getMountManager());
446
-				$mounts[] = $homeMount;
447
-				$mountConfigManager->registerMounts($userObject, $mounts);
448
-			}
449
-
450
-			self::listenForNewMountProviders($mountConfigManager, $userManager);
451
-		} else {
452
-			self::getMountManager()->addMount(new MountPoint(
453
-				new NullStorage([]),
454
-				'/' . $user
455
-			));
456
-			self::getMountManager()->addMount(new MountPoint(
457
-				new NullStorage([]),
458
-				'/' . $user . '/files'
459
-			));
460
-		}
461
-		\OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
462
-	}
463
-
464
-	/**
465
-	 * Get mounts from mount providers that are registered after setup
466
-	 *
467
-	 * @param MountProviderCollection $mountConfigManager
468
-	 * @param IUserManager $userManager
469
-	 */
470
-	private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
471
-		if (!self::$listeningForProviders) {
472
-			self::$listeningForProviders = true;
473
-			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
474
-				foreach (Filesystem::$usersSetup as $user => $setup) {
475
-					$userObject = $userManager->get($user);
476
-					if ($userObject) {
477
-						$mounts = $provider->getMountsForUser($userObject, Filesystem::getLoader());
478
-						array_walk($mounts, array(self::$mounts, 'addMount'));
479
-					}
480
-				}
481
-			});
482
-		}
483
-	}
484
-
485
-	/**
486
-	 * get the default filesystem view
487
-	 *
488
-	 * @return View
489
-	 */
490
-	static public function getView() {
491
-		return self::$defaultInstance;
492
-	}
493
-
494
-	/**
495
-	 * tear down the filesystem, removing all storage providers
496
-	 */
497
-	static public function tearDown() {
498
-		self::clearMounts();
499
-		self::$defaultInstance = null;
500
-	}
501
-
502
-	/**
503
-	 * get the relative path of the root data directory for the current user
504
-	 *
505
-	 * @return string
506
-	 *
507
-	 * Returns path like /admin/files
508
-	 */
509
-	static public function getRoot() {
510
-		if (!self::$defaultInstance) {
511
-			return null;
512
-		}
513
-		return self::$defaultInstance->getRoot();
514
-	}
515
-
516
-	/**
517
-	 * clear all mounts and storage backends
518
-	 */
519
-	public static function clearMounts() {
520
-		if (self::$mounts) {
521
-			self::$usersSetup = array();
522
-			self::$mounts->clear();
523
-		}
524
-	}
525
-
526
-	/**
527
-	 * mount an \OC\Files\Storage\Storage in our virtual filesystem
528
-	 *
529
-	 * @param \OC\Files\Storage\Storage|string $class
530
-	 * @param array $arguments
531
-	 * @param string $mountpoint
532
-	 */
533
-	static public function mount($class, $arguments, $mountpoint) {
534
-		if (!self::$mounts) {
535
-			\OC_Util::setupFS();
536
-		}
537
-		$mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader());
538
-		self::$mounts->addMount($mount);
539
-	}
540
-
541
-	/**
542
-	 * return the path to a local version of the file
543
-	 * we need this because we can't know if a file is stored local or not from
544
-	 * outside the filestorage and for some purposes a local file is needed
545
-	 *
546
-	 * @param string $path
547
-	 * @return string
548
-	 */
549
-	static public function getLocalFile($path) {
550
-		return self::$defaultInstance->getLocalFile($path);
551
-	}
552
-
553
-	/**
554
-	 * @param string $path
555
-	 * @return string
556
-	 */
557
-	static public function getLocalFolder($path) {
558
-		return self::$defaultInstance->getLocalFolder($path);
559
-	}
560
-
561
-	/**
562
-	 * return path to file which reflects one visible in browser
563
-	 *
564
-	 * @param string $path
565
-	 * @return string
566
-	 */
567
-	static public function getLocalPath($path) {
568
-		$datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
569
-		$newpath = $path;
570
-		if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
571
-			$newpath = substr($path, strlen($datadir));
572
-		}
573
-		return $newpath;
574
-	}
575
-
576
-	/**
577
-	 * check if the requested path is valid
578
-	 *
579
-	 * @param string $path
580
-	 * @return bool
581
-	 */
582
-	static public function isValidPath($path) {
583
-		$path = self::normalizePath($path);
584
-		if (!$path || $path[0] !== '/') {
585
-			$path = '/' . $path;
586
-		}
587
-		if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
588
-			return false;
589
-		}
590
-		return true;
591
-	}
592
-
593
-	/**
594
-	 * checks if a file is blacklisted for storage in the filesystem
595
-	 * Listens to write and rename hooks
596
-	 *
597
-	 * @param array $data from hook
598
-	 */
599
-	static public function isBlacklisted($data) {
600
-		if (isset($data['path'])) {
601
-			$path = $data['path'];
602
-		} else if (isset($data['newpath'])) {
603
-			$path = $data['newpath'];
604
-		}
605
-		if (isset($path)) {
606
-			if (self::isFileBlacklisted($path)) {
607
-				$data['run'] = false;
608
-			}
609
-		}
610
-	}
611
-
612
-	/**
613
-	 * @param string $filename
614
-	 * @return bool
615
-	 */
616
-	static public function isFileBlacklisted($filename) {
617
-		$filename = self::normalizePath($filename);
618
-
619
-		$blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array('.htaccess'));
620
-		$filename = strtolower(basename($filename));
621
-		return in_array($filename, $blacklist);
622
-	}
623
-
624
-	/**
625
-	 * check if the directory should be ignored when scanning
626
-	 * NOTE: the special directories . and .. would cause never ending recursion
627
-	 *
628
-	 * @param String $dir
629
-	 * @return boolean
630
-	 */
631
-	static public function isIgnoredDir($dir) {
632
-		if ($dir === '.' || $dir === '..') {
633
-			return true;
634
-		}
635
-		return false;
636
-	}
637
-
638
-	/**
639
-	 * following functions are equivalent to their php builtin equivalents for arguments/return values.
640
-	 */
641
-	static public function mkdir($path) {
642
-		return self::$defaultInstance->mkdir($path);
643
-	}
644
-
645
-	static public function rmdir($path) {
646
-		return self::$defaultInstance->rmdir($path);
647
-	}
648
-
649
-	static public function is_dir($path) {
650
-		return self::$defaultInstance->is_dir($path);
651
-	}
652
-
653
-	static public function is_file($path) {
654
-		return self::$defaultInstance->is_file($path);
655
-	}
656
-
657
-	static public function stat($path) {
658
-		return self::$defaultInstance->stat($path);
659
-	}
660
-
661
-	static public function filetype($path) {
662
-		return self::$defaultInstance->filetype($path);
663
-	}
664
-
665
-	static public function filesize($path) {
666
-		return self::$defaultInstance->filesize($path);
667
-	}
668
-
669
-	static public function readfile($path) {
670
-		return self::$defaultInstance->readfile($path);
671
-	}
672
-
673
-	static public function isCreatable($path) {
674
-		return self::$defaultInstance->isCreatable($path);
675
-	}
676
-
677
-	static public function isReadable($path) {
678
-		return self::$defaultInstance->isReadable($path);
679
-	}
680
-
681
-	static public function isUpdatable($path) {
682
-		return self::$defaultInstance->isUpdatable($path);
683
-	}
684
-
685
-	static public function isDeletable($path) {
686
-		return self::$defaultInstance->isDeletable($path);
687
-	}
688
-
689
-	static public function isSharable($path) {
690
-		return self::$defaultInstance->isSharable($path);
691
-	}
692
-
693
-	static public function file_exists($path) {
694
-		return self::$defaultInstance->file_exists($path);
695
-	}
696
-
697
-	static public function filemtime($path) {
698
-		return self::$defaultInstance->filemtime($path);
699
-	}
700
-
701
-	static public function touch($path, $mtime = null) {
702
-		return self::$defaultInstance->touch($path, $mtime);
703
-	}
704
-
705
-	/**
706
-	 * @return string
707
-	 */
708
-	static public function file_get_contents($path) {
709
-		return self::$defaultInstance->file_get_contents($path);
710
-	}
711
-
712
-	static public function file_put_contents($path, $data) {
713
-		return self::$defaultInstance->file_put_contents($path, $data);
714
-	}
715
-
716
-	static public function unlink($path) {
717
-		return self::$defaultInstance->unlink($path);
718
-	}
719
-
720
-	static public function rename($path1, $path2) {
721
-		return self::$defaultInstance->rename($path1, $path2);
722
-	}
723
-
724
-	static public function copy($path1, $path2) {
725
-		return self::$defaultInstance->copy($path1, $path2);
726
-	}
727
-
728
-	static public function fopen($path, $mode) {
729
-		return self::$defaultInstance->fopen($path, $mode);
730
-	}
731
-
732
-	/**
733
-	 * @return string
734
-	 */
735
-	static public function toTmpFile($path) {
736
-		return self::$defaultInstance->toTmpFile($path);
737
-	}
738
-
739
-	static public function fromTmpFile($tmpFile, $path) {
740
-		return self::$defaultInstance->fromTmpFile($tmpFile, $path);
741
-	}
742
-
743
-	static public function getMimeType($path) {
744
-		return self::$defaultInstance->getMimeType($path);
745
-	}
746
-
747
-	static public function hash($type, $path, $raw = false) {
748
-		return self::$defaultInstance->hash($type, $path, $raw);
749
-	}
750
-
751
-	static public function free_space($path = '/') {
752
-		return self::$defaultInstance->free_space($path);
753
-	}
754
-
755
-	static public function search($query) {
756
-		return self::$defaultInstance->search($query);
757
-	}
758
-
759
-	/**
760
-	 * @param string $query
761
-	 */
762
-	static public function searchByMime($query) {
763
-		return self::$defaultInstance->searchByMime($query);
764
-	}
765
-
766
-	/**
767
-	 * @param string|int $tag name or tag id
768
-	 * @param string $userId owner of the tags
769
-	 * @return FileInfo[] array or file info
770
-	 */
771
-	static public function searchByTag($tag, $userId) {
772
-		return self::$defaultInstance->searchByTag($tag, $userId);
773
-	}
774
-
775
-	/**
776
-	 * check if a file or folder has been updated since $time
777
-	 *
778
-	 * @param string $path
779
-	 * @param int $time
780
-	 * @return bool
781
-	 */
782
-	static public function hasUpdated($path, $time) {
783
-		return self::$defaultInstance->hasUpdated($path, $time);
784
-	}
785
-
786
-	/**
787
-	 * Fix common problems with a file path
788
-	 *
789
-	 * @param string $path
790
-	 * @param bool $stripTrailingSlash whether to strip the trailing slash
791
-	 * @param bool $isAbsolutePath whether the given path is absolute
792
-	 * @param bool $keepUnicode true to disable unicode normalization
793
-	 * @return string
794
-	 */
795
-	public static function normalizePath($path, $stripTrailingSlash = true, $isAbsolutePath = false, $keepUnicode = false) {
796
-		if (is_null(self::$normalizedPathCache)) {
797
-			self::$normalizedPathCache = new CappedMemoryCache();
798
-		}
799
-
800
-		/**
801
-		 * FIXME: This is a workaround for existing classes and files which call
802
-		 *        this function with another type than a valid string. This
803
-		 *        conversion should get removed as soon as all existing
804
-		 *        function calls have been fixed.
805
-		 */
806
-		$path = (string)$path;
807
-
808
-		$cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
809
-
810
-		if (isset(self::$normalizedPathCache[$cacheKey])) {
811
-			return self::$normalizedPathCache[$cacheKey];
812
-		}
813
-
814
-		if ($path == '') {
815
-			return '/';
816
-		}
817
-
818
-		//normalize unicode if possible
819
-		if (!$keepUnicode) {
820
-			$path = \OC_Util::normalizeUnicode($path);
821
-		}
822
-
823
-		//no windows style slashes
824
-		$path = str_replace('\\', '/', $path);
825
-
826
-		//add leading slash
827
-		if ($path[0] !== '/') {
828
-			$path = '/' . $path;
829
-		}
830
-
831
-		// remove '/./'
832
-		// ugly, but str_replace() can't replace them all in one go
833
-		// as the replacement itself is part of the search string
834
-		// which will only be found during the next iteration
835
-		while (strpos($path, '/./') !== false) {
836
-			$path = str_replace('/./', '/', $path);
837
-		}
838
-		// remove sequences of slashes
839
-		$path = preg_replace('#/{2,}#', '/', $path);
840
-
841
-		//remove trailing slash
842
-		if ($stripTrailingSlash and strlen($path) > 1 and substr($path, -1, 1) === '/') {
843
-			$path = substr($path, 0, -1);
844
-		}
845
-
846
-		// remove trailing '/.'
847
-		if (substr($path, -2) == '/.') {
848
-			$path = substr($path, 0, -2);
849
-		}
850
-
851
-		$normalizedPath = $path;
852
-		self::$normalizedPathCache[$cacheKey] = $normalizedPath;
853
-
854
-		return $normalizedPath;
855
-	}
856
-
857
-	/**
858
-	 * get the filesystem info
859
-	 *
860
-	 * @param string $path
861
-	 * @param boolean $includeMountPoints whether to add mountpoint sizes,
862
-	 * defaults to true
863
-	 * @return \OC\Files\FileInfo|bool False if file does not exist
864
-	 */
865
-	public static function getFileInfo($path, $includeMountPoints = true) {
866
-		return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
867
-	}
868
-
869
-	/**
870
-	 * change file metadata
871
-	 *
872
-	 * @param string $path
873
-	 * @param array $data
874
-	 * @return int
875
-	 *
876
-	 * returns the fileid of the updated file
877
-	 */
878
-	public static function putFileInfo($path, $data) {
879
-		return self::$defaultInstance->putFileInfo($path, $data);
880
-	}
881
-
882
-	/**
883
-	 * get the content of a directory
884
-	 *
885
-	 * @param string $directory path under datadirectory
886
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
887
-	 * @return \OC\Files\FileInfo[]
888
-	 */
889
-	public static function getDirectoryContent($directory, $mimetype_filter = '') {
890
-		return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter);
891
-	}
892
-
893
-	/**
894
-	 * Get the path of a file by id
895
-	 *
896
-	 * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
897
-	 *
898
-	 * @param int $id
899
-	 * @throws NotFoundException
900
-	 * @return string
901
-	 */
902
-	public static function getPath($id) {
903
-		return self::$defaultInstance->getPath($id);
904
-	}
905
-
906
-	/**
907
-	 * Get the owner for a file or folder
908
-	 *
909
-	 * @param string $path
910
-	 * @return string
911
-	 */
912
-	public static function getOwner($path) {
913
-		return self::$defaultInstance->getOwner($path);
914
-	}
915
-
916
-	/**
917
-	 * get the ETag for a file or folder
918
-	 *
919
-	 * @param string $path
920
-	 * @return string
921
-	 */
922
-	static public function getETag($path) {
923
-		return self::$defaultInstance->getETag($path);
924
-	}
72
+    /**
73
+     * @var Mount\Manager $mounts
74
+     */
75
+    private static $mounts;
76
+
77
+    public static $loaded = false;
78
+    /**
79
+     * @var \OC\Files\View $defaultInstance
80
+     */
81
+    static private $defaultInstance;
82
+
83
+    static private $usersSetup = array();
84
+
85
+    static private $normalizedPathCache = null;
86
+
87
+    static private $listeningForProviders = false;
88
+
89
+    /**
90
+     * classname which used for hooks handling
91
+     * used as signalclass in OC_Hooks::emit()
92
+     */
93
+    const CLASSNAME = 'OC_Filesystem';
94
+
95
+    /**
96
+     * signalname emitted before file renaming
97
+     *
98
+     * @param string $oldpath
99
+     * @param string $newpath
100
+     */
101
+    const signal_rename = 'rename';
102
+
103
+    /**
104
+     * signal emitted after file renaming
105
+     *
106
+     * @param string $oldpath
107
+     * @param string $newpath
108
+     */
109
+    const signal_post_rename = 'post_rename';
110
+
111
+    /**
112
+     * signal emitted before file/dir creation
113
+     *
114
+     * @param string $path
115
+     * @param bool $run changing this flag to false in hook handler will cancel event
116
+     */
117
+    const signal_create = 'create';
118
+
119
+    /**
120
+     * signal emitted after file/dir creation
121
+     *
122
+     * @param string $path
123
+     * @param bool $run changing this flag to false in hook handler will cancel event
124
+     */
125
+    const signal_post_create = 'post_create';
126
+
127
+    /**
128
+     * signal emits before file/dir copy
129
+     *
130
+     * @param string $oldpath
131
+     * @param string $newpath
132
+     * @param bool $run changing this flag to false in hook handler will cancel event
133
+     */
134
+    const signal_copy = 'copy';
135
+
136
+    /**
137
+     * signal emits after file/dir copy
138
+     *
139
+     * @param string $oldpath
140
+     * @param string $newpath
141
+     */
142
+    const signal_post_copy = 'post_copy';
143
+
144
+    /**
145
+     * signal emits before file/dir save
146
+     *
147
+     * @param string $path
148
+     * @param bool $run changing this flag to false in hook handler will cancel event
149
+     */
150
+    const signal_write = 'write';
151
+
152
+    /**
153
+     * signal emits after file/dir save
154
+     *
155
+     * @param string $path
156
+     */
157
+    const signal_post_write = 'post_write';
158
+
159
+    /**
160
+     * signal emitted before file/dir update
161
+     *
162
+     * @param string $path
163
+     * @param bool $run changing this flag to false in hook handler will cancel event
164
+     */
165
+    const signal_update = 'update';
166
+
167
+    /**
168
+     * signal emitted after file/dir update
169
+     *
170
+     * @param string $path
171
+     * @param bool $run changing this flag to false in hook handler will cancel event
172
+     */
173
+    const signal_post_update = 'post_update';
174
+
175
+    /**
176
+     * signal emits when reading file/dir
177
+     *
178
+     * @param string $path
179
+     */
180
+    const signal_read = 'read';
181
+
182
+    /**
183
+     * signal emits when removing file/dir
184
+     *
185
+     * @param string $path
186
+     */
187
+    const signal_delete = 'delete';
188
+
189
+    /**
190
+     * parameters definitions for signals
191
+     */
192
+    const signal_param_path = 'path';
193
+    const signal_param_oldpath = 'oldpath';
194
+    const signal_param_newpath = 'newpath';
195
+
196
+    /**
197
+     * run - changing this flag to false in hook handler will cancel event
198
+     */
199
+    const signal_param_run = 'run';
200
+
201
+    const signal_create_mount = 'create_mount';
202
+    const signal_delete_mount = 'delete_mount';
203
+    const signal_param_mount_type = 'mounttype';
204
+    const signal_param_users = 'users';
205
+
206
+    /**
207
+     * @var \OC\Files\Storage\StorageFactory $loader
208
+     */
209
+    private static $loader;
210
+
211
+    /** @var bool */
212
+    private static $logWarningWhenAddingStorageWrapper = true;
213
+
214
+    /**
215
+     * @param bool $shouldLog
216
+     * @return bool previous value
217
+     * @internal
218
+     */
219
+    public static function logWarningWhenAddingStorageWrapper($shouldLog) {
220
+        $previousValue = self::$logWarningWhenAddingStorageWrapper;
221
+        self::$logWarningWhenAddingStorageWrapper = (bool) $shouldLog;
222
+        return $previousValue;
223
+    }
224
+
225
+    /**
226
+     * @param string $wrapperName
227
+     * @param callable $wrapper
228
+     * @param int $priority
229
+     */
230
+    public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) {
231
+        if (self::$logWarningWhenAddingStorageWrapper) {
232
+            \OC::$server->getLogger()->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [
233
+                'wrapper' => $wrapperName,
234
+                'app' => 'filesystem',
235
+            ]);
236
+        }
237
+
238
+        $mounts = self::getMountManager()->getAll();
239
+        if (!self::getLoader()->addStorageWrapper($wrapperName, $wrapper, $priority, $mounts)) {
240
+            // do not re-wrap if storage with this name already existed
241
+            return;
242
+        }
243
+    }
244
+
245
+    /**
246
+     * Returns the storage factory
247
+     *
248
+     * @return \OCP\Files\Storage\IStorageFactory
249
+     */
250
+    public static function getLoader() {
251
+        if (!self::$loader) {
252
+            self::$loader = new StorageFactory();
253
+        }
254
+        return self::$loader;
255
+    }
256
+
257
+    /**
258
+     * Returns the mount manager
259
+     *
260
+     * @return \OC\Files\Mount\Manager
261
+     */
262
+    public static function getMountManager($user = '') {
263
+        if (!self::$mounts) {
264
+            \OC_Util::setupFS($user);
265
+        }
266
+        return self::$mounts;
267
+    }
268
+
269
+    /**
270
+     * get the mountpoint of the storage object for a path
271
+     * ( note: because a storage is not always mounted inside the fakeroot, the
272
+     * returned mountpoint is relative to the absolute root of the filesystem
273
+     * and doesn't take the chroot into account )
274
+     *
275
+     * @param string $path
276
+     * @return string
277
+     */
278
+    static public function getMountPoint($path) {
279
+        if (!self::$mounts) {
280
+            \OC_Util::setupFS();
281
+        }
282
+        $mount = self::$mounts->find($path);
283
+        if ($mount) {
284
+            return $mount->getMountPoint();
285
+        } else {
286
+            return '';
287
+        }
288
+    }
289
+
290
+    /**
291
+     * get a list of all mount points in a directory
292
+     *
293
+     * @param string $path
294
+     * @return string[]
295
+     */
296
+    static public function getMountPoints($path) {
297
+        if (!self::$mounts) {
298
+            \OC_Util::setupFS();
299
+        }
300
+        $result = array();
301
+        $mounts = self::$mounts->findIn($path);
302
+        foreach ($mounts as $mount) {
303
+            $result[] = $mount->getMountPoint();
304
+        }
305
+        return $result;
306
+    }
307
+
308
+    /**
309
+     * get the storage mounted at $mountPoint
310
+     *
311
+     * @param string $mountPoint
312
+     * @return \OC\Files\Storage\Storage
313
+     */
314
+    public static function getStorage($mountPoint) {
315
+        if (!self::$mounts) {
316
+            \OC_Util::setupFS();
317
+        }
318
+        $mount = self::$mounts->find($mountPoint);
319
+        return $mount->getStorage();
320
+    }
321
+
322
+    /**
323
+     * @param string $id
324
+     * @return Mount\MountPoint[]
325
+     */
326
+    public static function getMountByStorageId($id) {
327
+        if (!self::$mounts) {
328
+            \OC_Util::setupFS();
329
+        }
330
+        return self::$mounts->findByStorageId($id);
331
+    }
332
+
333
+    /**
334
+     * @param int $id
335
+     * @return Mount\MountPoint[]
336
+     */
337
+    public static function getMountByNumericId($id) {
338
+        if (!self::$mounts) {
339
+            \OC_Util::setupFS();
340
+        }
341
+        return self::$mounts->findByNumericId($id);
342
+    }
343
+
344
+    /**
345
+     * resolve a path to a storage and internal path
346
+     *
347
+     * @param string $path
348
+     * @return array an array consisting of the storage and the internal path
349
+     */
350
+    static public function resolvePath($path) {
351
+        if (!self::$mounts) {
352
+            \OC_Util::setupFS();
353
+        }
354
+        $mount = self::$mounts->find($path);
355
+        if ($mount) {
356
+            return array($mount->getStorage(), rtrim($mount->getInternalPath($path), '/'));
357
+        } else {
358
+            return array(null, null);
359
+        }
360
+    }
361
+
362
+    static public function init($user, $root) {
363
+        if (self::$defaultInstance) {
364
+            return false;
365
+        }
366
+        self::getLoader();
367
+        self::$defaultInstance = new View($root);
368
+
369
+        if (!self::$mounts) {
370
+            self::$mounts = \OC::$server->getMountManager();
371
+        }
372
+
373
+        //load custom mount config
374
+        self::initMountPoints($user);
375
+
376
+        self::$loaded = true;
377
+
378
+        return true;
379
+    }
380
+
381
+    static public function initMountManager() {
382
+        if (!self::$mounts) {
383
+            self::$mounts = \OC::$server->getMountManager();
384
+        }
385
+    }
386
+
387
+    /**
388
+     * Initialize system and personal mount points for a user
389
+     *
390
+     * @param string $user
391
+     * @throws \OC\User\NoUserException if the user is not available
392
+     */
393
+    public static function initMountPoints($user = '') {
394
+        if ($user == '') {
395
+            $user = \OC_User::getUser();
396
+        }
397
+        if ($user === null || $user === false || $user === '') {
398
+            throw new \OC\User\NoUserException('Attempted to initialize mount points for null user and no user in session');
399
+        }
400
+
401
+        if (isset(self::$usersSetup[$user])) {
402
+            return;
403
+        }
404
+
405
+        self::$usersSetup[$user] = true;
406
+
407
+        $userManager = \OC::$server->getUserManager();
408
+        $userObject = $userManager->get($user);
409
+
410
+        if (is_null($userObject)) {
411
+            \OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, \OCP\Util::ERROR);
412
+            // reset flag, this will make it possible to rethrow the exception if called again
413
+            unset(self::$usersSetup[$user]);
414
+            throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
415
+        }
416
+
417
+        $realUid = $userObject->getUID();
418
+        // workaround in case of different casings
419
+        if ($user !== $realUid) {
420
+            $stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
421
+            \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
+            $user = $realUid;
423
+
424
+            // again with the correct casing
425
+            if (isset(self::$usersSetup[$user])) {
426
+                return;
427
+            }
428
+
429
+            self::$usersSetup[$user] = true;
430
+        }
431
+
432
+        if (\OC::$server->getLockdownManager()->canAccessFilesystem()) {
433
+            /** @var \OC\Files\Config\MountProviderCollection $mountConfigManager */
434
+            $mountConfigManager = \OC::$server->getMountProviderCollection();
435
+
436
+            // home mounts are handled seperate since we need to ensure this is mounted before we call the other mount providers
437
+            $homeMount = $mountConfigManager->getHomeMountForUser($userObject);
438
+
439
+            self::getMountManager()->addMount($homeMount);
440
+
441
+            \OC\Files\Filesystem::getStorage($user);
442
+
443
+            // Chance to mount for other storages
444
+            if ($userObject) {
445
+                $mounts = $mountConfigManager->addMountForUser($userObject, self::getMountManager());
446
+                $mounts[] = $homeMount;
447
+                $mountConfigManager->registerMounts($userObject, $mounts);
448
+            }
449
+
450
+            self::listenForNewMountProviders($mountConfigManager, $userManager);
451
+        } else {
452
+            self::getMountManager()->addMount(new MountPoint(
453
+                new NullStorage([]),
454
+                '/' . $user
455
+            ));
456
+            self::getMountManager()->addMount(new MountPoint(
457
+                new NullStorage([]),
458
+                '/' . $user . '/files'
459
+            ));
460
+        }
461
+        \OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
462
+    }
463
+
464
+    /**
465
+     * Get mounts from mount providers that are registered after setup
466
+     *
467
+     * @param MountProviderCollection $mountConfigManager
468
+     * @param IUserManager $userManager
469
+     */
470
+    private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
471
+        if (!self::$listeningForProviders) {
472
+            self::$listeningForProviders = true;
473
+            $mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
474
+                foreach (Filesystem::$usersSetup as $user => $setup) {
475
+                    $userObject = $userManager->get($user);
476
+                    if ($userObject) {
477
+                        $mounts = $provider->getMountsForUser($userObject, Filesystem::getLoader());
478
+                        array_walk($mounts, array(self::$mounts, 'addMount'));
479
+                    }
480
+                }
481
+            });
482
+        }
483
+    }
484
+
485
+    /**
486
+     * get the default filesystem view
487
+     *
488
+     * @return View
489
+     */
490
+    static public function getView() {
491
+        return self::$defaultInstance;
492
+    }
493
+
494
+    /**
495
+     * tear down the filesystem, removing all storage providers
496
+     */
497
+    static public function tearDown() {
498
+        self::clearMounts();
499
+        self::$defaultInstance = null;
500
+    }
501
+
502
+    /**
503
+     * get the relative path of the root data directory for the current user
504
+     *
505
+     * @return string
506
+     *
507
+     * Returns path like /admin/files
508
+     */
509
+    static public function getRoot() {
510
+        if (!self::$defaultInstance) {
511
+            return null;
512
+        }
513
+        return self::$defaultInstance->getRoot();
514
+    }
515
+
516
+    /**
517
+     * clear all mounts and storage backends
518
+     */
519
+    public static function clearMounts() {
520
+        if (self::$mounts) {
521
+            self::$usersSetup = array();
522
+            self::$mounts->clear();
523
+        }
524
+    }
525
+
526
+    /**
527
+     * mount an \OC\Files\Storage\Storage in our virtual filesystem
528
+     *
529
+     * @param \OC\Files\Storage\Storage|string $class
530
+     * @param array $arguments
531
+     * @param string $mountpoint
532
+     */
533
+    static public function mount($class, $arguments, $mountpoint) {
534
+        if (!self::$mounts) {
535
+            \OC_Util::setupFS();
536
+        }
537
+        $mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader());
538
+        self::$mounts->addMount($mount);
539
+    }
540
+
541
+    /**
542
+     * return the path to a local version of the file
543
+     * we need this because we can't know if a file is stored local or not from
544
+     * outside the filestorage and for some purposes a local file is needed
545
+     *
546
+     * @param string $path
547
+     * @return string
548
+     */
549
+    static public function getLocalFile($path) {
550
+        return self::$defaultInstance->getLocalFile($path);
551
+    }
552
+
553
+    /**
554
+     * @param string $path
555
+     * @return string
556
+     */
557
+    static public function getLocalFolder($path) {
558
+        return self::$defaultInstance->getLocalFolder($path);
559
+    }
560
+
561
+    /**
562
+     * return path to file which reflects one visible in browser
563
+     *
564
+     * @param string $path
565
+     * @return string
566
+     */
567
+    static public function getLocalPath($path) {
568
+        $datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
569
+        $newpath = $path;
570
+        if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
571
+            $newpath = substr($path, strlen($datadir));
572
+        }
573
+        return $newpath;
574
+    }
575
+
576
+    /**
577
+     * check if the requested path is valid
578
+     *
579
+     * @param string $path
580
+     * @return bool
581
+     */
582
+    static public function isValidPath($path) {
583
+        $path = self::normalizePath($path);
584
+        if (!$path || $path[0] !== '/') {
585
+            $path = '/' . $path;
586
+        }
587
+        if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
588
+            return false;
589
+        }
590
+        return true;
591
+    }
592
+
593
+    /**
594
+     * checks if a file is blacklisted for storage in the filesystem
595
+     * Listens to write and rename hooks
596
+     *
597
+     * @param array $data from hook
598
+     */
599
+    static public function isBlacklisted($data) {
600
+        if (isset($data['path'])) {
601
+            $path = $data['path'];
602
+        } else if (isset($data['newpath'])) {
603
+            $path = $data['newpath'];
604
+        }
605
+        if (isset($path)) {
606
+            if (self::isFileBlacklisted($path)) {
607
+                $data['run'] = false;
608
+            }
609
+        }
610
+    }
611
+
612
+    /**
613
+     * @param string $filename
614
+     * @return bool
615
+     */
616
+    static public function isFileBlacklisted($filename) {
617
+        $filename = self::normalizePath($filename);
618
+
619
+        $blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array('.htaccess'));
620
+        $filename = strtolower(basename($filename));
621
+        return in_array($filename, $blacklist);
622
+    }
623
+
624
+    /**
625
+     * check if the directory should be ignored when scanning
626
+     * NOTE: the special directories . and .. would cause never ending recursion
627
+     *
628
+     * @param String $dir
629
+     * @return boolean
630
+     */
631
+    static public function isIgnoredDir($dir) {
632
+        if ($dir === '.' || $dir === '..') {
633
+            return true;
634
+        }
635
+        return false;
636
+    }
637
+
638
+    /**
639
+     * following functions are equivalent to their php builtin equivalents for arguments/return values.
640
+     */
641
+    static public function mkdir($path) {
642
+        return self::$defaultInstance->mkdir($path);
643
+    }
644
+
645
+    static public function rmdir($path) {
646
+        return self::$defaultInstance->rmdir($path);
647
+    }
648
+
649
+    static public function is_dir($path) {
650
+        return self::$defaultInstance->is_dir($path);
651
+    }
652
+
653
+    static public function is_file($path) {
654
+        return self::$defaultInstance->is_file($path);
655
+    }
656
+
657
+    static public function stat($path) {
658
+        return self::$defaultInstance->stat($path);
659
+    }
660
+
661
+    static public function filetype($path) {
662
+        return self::$defaultInstance->filetype($path);
663
+    }
664
+
665
+    static public function filesize($path) {
666
+        return self::$defaultInstance->filesize($path);
667
+    }
668
+
669
+    static public function readfile($path) {
670
+        return self::$defaultInstance->readfile($path);
671
+    }
672
+
673
+    static public function isCreatable($path) {
674
+        return self::$defaultInstance->isCreatable($path);
675
+    }
676
+
677
+    static public function isReadable($path) {
678
+        return self::$defaultInstance->isReadable($path);
679
+    }
680
+
681
+    static public function isUpdatable($path) {
682
+        return self::$defaultInstance->isUpdatable($path);
683
+    }
684
+
685
+    static public function isDeletable($path) {
686
+        return self::$defaultInstance->isDeletable($path);
687
+    }
688
+
689
+    static public function isSharable($path) {
690
+        return self::$defaultInstance->isSharable($path);
691
+    }
692
+
693
+    static public function file_exists($path) {
694
+        return self::$defaultInstance->file_exists($path);
695
+    }
696
+
697
+    static public function filemtime($path) {
698
+        return self::$defaultInstance->filemtime($path);
699
+    }
700
+
701
+    static public function touch($path, $mtime = null) {
702
+        return self::$defaultInstance->touch($path, $mtime);
703
+    }
704
+
705
+    /**
706
+     * @return string
707
+     */
708
+    static public function file_get_contents($path) {
709
+        return self::$defaultInstance->file_get_contents($path);
710
+    }
711
+
712
+    static public function file_put_contents($path, $data) {
713
+        return self::$defaultInstance->file_put_contents($path, $data);
714
+    }
715
+
716
+    static public function unlink($path) {
717
+        return self::$defaultInstance->unlink($path);
718
+    }
719
+
720
+    static public function rename($path1, $path2) {
721
+        return self::$defaultInstance->rename($path1, $path2);
722
+    }
723
+
724
+    static public function copy($path1, $path2) {
725
+        return self::$defaultInstance->copy($path1, $path2);
726
+    }
727
+
728
+    static public function fopen($path, $mode) {
729
+        return self::$defaultInstance->fopen($path, $mode);
730
+    }
731
+
732
+    /**
733
+     * @return string
734
+     */
735
+    static public function toTmpFile($path) {
736
+        return self::$defaultInstance->toTmpFile($path);
737
+    }
738
+
739
+    static public function fromTmpFile($tmpFile, $path) {
740
+        return self::$defaultInstance->fromTmpFile($tmpFile, $path);
741
+    }
742
+
743
+    static public function getMimeType($path) {
744
+        return self::$defaultInstance->getMimeType($path);
745
+    }
746
+
747
+    static public function hash($type, $path, $raw = false) {
748
+        return self::$defaultInstance->hash($type, $path, $raw);
749
+    }
750
+
751
+    static public function free_space($path = '/') {
752
+        return self::$defaultInstance->free_space($path);
753
+    }
754
+
755
+    static public function search($query) {
756
+        return self::$defaultInstance->search($query);
757
+    }
758
+
759
+    /**
760
+     * @param string $query
761
+     */
762
+    static public function searchByMime($query) {
763
+        return self::$defaultInstance->searchByMime($query);
764
+    }
765
+
766
+    /**
767
+     * @param string|int $tag name or tag id
768
+     * @param string $userId owner of the tags
769
+     * @return FileInfo[] array or file info
770
+     */
771
+    static public function searchByTag($tag, $userId) {
772
+        return self::$defaultInstance->searchByTag($tag, $userId);
773
+    }
774
+
775
+    /**
776
+     * check if a file or folder has been updated since $time
777
+     *
778
+     * @param string $path
779
+     * @param int $time
780
+     * @return bool
781
+     */
782
+    static public function hasUpdated($path, $time) {
783
+        return self::$defaultInstance->hasUpdated($path, $time);
784
+    }
785
+
786
+    /**
787
+     * Fix common problems with a file path
788
+     *
789
+     * @param string $path
790
+     * @param bool $stripTrailingSlash whether to strip the trailing slash
791
+     * @param bool $isAbsolutePath whether the given path is absolute
792
+     * @param bool $keepUnicode true to disable unicode normalization
793
+     * @return string
794
+     */
795
+    public static function normalizePath($path, $stripTrailingSlash = true, $isAbsolutePath = false, $keepUnicode = false) {
796
+        if (is_null(self::$normalizedPathCache)) {
797
+            self::$normalizedPathCache = new CappedMemoryCache();
798
+        }
799
+
800
+        /**
801
+         * FIXME: This is a workaround for existing classes and files which call
802
+         *        this function with another type than a valid string. This
803
+         *        conversion should get removed as soon as all existing
804
+         *        function calls have been fixed.
805
+         */
806
+        $path = (string)$path;
807
+
808
+        $cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
809
+
810
+        if (isset(self::$normalizedPathCache[$cacheKey])) {
811
+            return self::$normalizedPathCache[$cacheKey];
812
+        }
813
+
814
+        if ($path == '') {
815
+            return '/';
816
+        }
817
+
818
+        //normalize unicode if possible
819
+        if (!$keepUnicode) {
820
+            $path = \OC_Util::normalizeUnicode($path);
821
+        }
822
+
823
+        //no windows style slashes
824
+        $path = str_replace('\\', '/', $path);
825
+
826
+        //add leading slash
827
+        if ($path[0] !== '/') {
828
+            $path = '/' . $path;
829
+        }
830
+
831
+        // remove '/./'
832
+        // ugly, but str_replace() can't replace them all in one go
833
+        // as the replacement itself is part of the search string
834
+        // which will only be found during the next iteration
835
+        while (strpos($path, '/./') !== false) {
836
+            $path = str_replace('/./', '/', $path);
837
+        }
838
+        // remove sequences of slashes
839
+        $path = preg_replace('#/{2,}#', '/', $path);
840
+
841
+        //remove trailing slash
842
+        if ($stripTrailingSlash and strlen($path) > 1 and substr($path, -1, 1) === '/') {
843
+            $path = substr($path, 0, -1);
844
+        }
845
+
846
+        // remove trailing '/.'
847
+        if (substr($path, -2) == '/.') {
848
+            $path = substr($path, 0, -2);
849
+        }
850
+
851
+        $normalizedPath = $path;
852
+        self::$normalizedPathCache[$cacheKey] = $normalizedPath;
853
+
854
+        return $normalizedPath;
855
+    }
856
+
857
+    /**
858
+     * get the filesystem info
859
+     *
860
+     * @param string $path
861
+     * @param boolean $includeMountPoints whether to add mountpoint sizes,
862
+     * defaults to true
863
+     * @return \OC\Files\FileInfo|bool False if file does not exist
864
+     */
865
+    public static function getFileInfo($path, $includeMountPoints = true) {
866
+        return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
867
+    }
868
+
869
+    /**
870
+     * change file metadata
871
+     *
872
+     * @param string $path
873
+     * @param array $data
874
+     * @return int
875
+     *
876
+     * returns the fileid of the updated file
877
+     */
878
+    public static function putFileInfo($path, $data) {
879
+        return self::$defaultInstance->putFileInfo($path, $data);
880
+    }
881
+
882
+    /**
883
+     * get the content of a directory
884
+     *
885
+     * @param string $directory path under datadirectory
886
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
887
+     * @return \OC\Files\FileInfo[]
888
+     */
889
+    public static function getDirectoryContent($directory, $mimetype_filter = '') {
890
+        return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter);
891
+    }
892
+
893
+    /**
894
+     * Get the path of a file by id
895
+     *
896
+     * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
897
+     *
898
+     * @param int $id
899
+     * @throws NotFoundException
900
+     * @return string
901
+     */
902
+    public static function getPath($id) {
903
+        return self::$defaultInstance->getPath($id);
904
+    }
905
+
906
+    /**
907
+     * Get the owner for a file or folder
908
+     *
909
+     * @param string $path
910
+     * @return string
911
+     */
912
+    public static function getOwner($path) {
913
+        return self::$defaultInstance->getOwner($path);
914
+    }
915
+
916
+    /**
917
+     * get the ETag for a file or folder
918
+     *
919
+     * @param string $path
920
+     * @return string
921
+     */
922
+    static public function getETag($path) {
923
+        return self::$defaultInstance->getETag($path);
924
+    }
925 925
 }
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   +974 added lines, -974 removed lines patch added patch discarded remove patch
@@ -46,979 +46,979 @@
 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\IStorage $sourceStorage
594
-	 * @param string $sourceInternalPath
595
-	 * @param string $targetInternalPath
596
-	 * @param bool $preserveMtime
597
-	 * @return bool
598
-	 */
599
-	public function moveFromStorage(Storage\IStorage $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\IStorage $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\IStorage $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\IStorage $sourceStorage
649
-	 * @param string $sourceInternalPath
650
-	 * @param string $targetInternalPath
651
-	 * @param bool $isRename
652
-	 */
653
-	private function updateEncryptedVersion(Storage\IStorage $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\IStorage $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\IStorage $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
-		$exists = $this->storage->file_exists($realFile);
914
-		if ($exists) {
915
-			$path = $realFile;
916
-		}
917
-
918
-		$firstBlock = $this->readFirstBlock($path);
919
-		$result = $this->parseRawHeader($firstBlock);
920
-
921
-		// if the header doesn't contain a encryption module we check if it is a
922
-		// legacy file. If true, we add the default encryption module
923
-		if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
924
-			if (!empty($result)) {
925
-				$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
926
-			} else if ($exists) {
927
-				// if the header was empty we have to check first if it is a encrypted file at all
928
-				// We would do query to filecache only if we know that entry in filecache exists
929
-				$info = $this->getCache()->get($path);
930
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
931
-					$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
932
-				}
933
-			}
934
-		}
935
-
936
-		return $result;
937
-	}
938
-
939
-	/**
940
-	 * read encryption module needed to read/write the file located at $path
941
-	 *
942
-	 * @param string $path
943
-	 * @return null|\OCP\Encryption\IEncryptionModule
944
-	 * @throws ModuleDoesNotExistsException
945
-	 * @throws \Exception
946
-	 */
947
-	protected function getEncryptionModule($path) {
948
-		$encryptionModule = null;
949
-		$header = $this->getHeader($path);
950
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
951
-		if (!empty($encryptionModuleId)) {
952
-			try {
953
-				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
954
-			} catch (ModuleDoesNotExistsException $e) {
955
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
956
-				throw $e;
957
-			}
958
-		}
959
-
960
-		return $encryptionModule;
961
-	}
962
-
963
-	/**
964
-	 * @param string $path
965
-	 * @param int $unencryptedSize
966
-	 */
967
-	public function updateUnencryptedSize($path, $unencryptedSize) {
968
-		$this->unencryptedSize[$path] = $unencryptedSize;
969
-	}
970
-
971
-	/**
972
-	 * copy keys to new location
973
-	 *
974
-	 * @param string $source path relative to data/
975
-	 * @param string $target path relative to data/
976
-	 * @return bool
977
-	 */
978
-	protected function copyKeys($source, $target) {
979
-		if (!$this->util->isExcluded($source)) {
980
-			return $this->keyStorage->copyKeys($source, $target);
981
-		}
982
-
983
-		return false;
984
-	}
985
-
986
-	/**
987
-	 * check if path points to a files version
988
-	 *
989
-	 * @param $path
990
-	 * @return bool
991
-	 */
992
-	protected function isVersion($path) {
993
-		$normalized = Filesystem::normalizePath($path);
994
-		return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
995
-	}
996
-
997
-	/**
998
-	 * check if the given storage should be encrypted or not
999
-	 *
1000
-	 * @param $path
1001
-	 * @return bool
1002
-	 */
1003
-	protected function shouldEncrypt($path) {
1004
-		$fullPath = $this->getFullPath($path);
1005
-		$mountPointConfig = $this->mount->getOption('encrypt', true);
1006
-		if ($mountPointConfig === false) {
1007
-			return false;
1008
-		}
1009
-
1010
-		try {
1011
-			$encryptionModule = $this->getEncryptionModule($fullPath);
1012
-		} catch (ModuleDoesNotExistsException $e) {
1013
-			return false;
1014
-		}
1015
-
1016
-		if ($encryptionModule === null) {
1017
-			$encryptionModule = $this->encryptionManager->getEncryptionModule();
1018
-		}
1019
-
1020
-		return $encryptionModule->shouldEncrypt($fullPath);
1021
-
1022
-	}
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\IStorage $sourceStorage
594
+     * @param string $sourceInternalPath
595
+     * @param string $targetInternalPath
596
+     * @param bool $preserveMtime
597
+     * @return bool
598
+     */
599
+    public function moveFromStorage(Storage\IStorage $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\IStorage $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\IStorage $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\IStorage $sourceStorage
649
+     * @param string $sourceInternalPath
650
+     * @param string $targetInternalPath
651
+     * @param bool $isRename
652
+     */
653
+    private function updateEncryptedVersion(Storage\IStorage $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\IStorage $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\IStorage $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
+        $exists = $this->storage->file_exists($realFile);
914
+        if ($exists) {
915
+            $path = $realFile;
916
+        }
917
+
918
+        $firstBlock = $this->readFirstBlock($path);
919
+        $result = $this->parseRawHeader($firstBlock);
920
+
921
+        // if the header doesn't contain a encryption module we check if it is a
922
+        // legacy file. If true, we add the default encryption module
923
+        if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
924
+            if (!empty($result)) {
925
+                $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
926
+            } else if ($exists) {
927
+                // if the header was empty we have to check first if it is a encrypted file at all
928
+                // We would do query to filecache only if we know that entry in filecache exists
929
+                $info = $this->getCache()->get($path);
930
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
931
+                    $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
932
+                }
933
+            }
934
+        }
935
+
936
+        return $result;
937
+    }
938
+
939
+    /**
940
+     * read encryption module needed to read/write the file located at $path
941
+     *
942
+     * @param string $path
943
+     * @return null|\OCP\Encryption\IEncryptionModule
944
+     * @throws ModuleDoesNotExistsException
945
+     * @throws \Exception
946
+     */
947
+    protected function getEncryptionModule($path) {
948
+        $encryptionModule = null;
949
+        $header = $this->getHeader($path);
950
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
951
+        if (!empty($encryptionModuleId)) {
952
+            try {
953
+                $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
954
+            } catch (ModuleDoesNotExistsException $e) {
955
+                $this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
956
+                throw $e;
957
+            }
958
+        }
959
+
960
+        return $encryptionModule;
961
+    }
962
+
963
+    /**
964
+     * @param string $path
965
+     * @param int $unencryptedSize
966
+     */
967
+    public function updateUnencryptedSize($path, $unencryptedSize) {
968
+        $this->unencryptedSize[$path] = $unencryptedSize;
969
+    }
970
+
971
+    /**
972
+     * copy keys to new location
973
+     *
974
+     * @param string $source path relative to data/
975
+     * @param string $target path relative to data/
976
+     * @return bool
977
+     */
978
+    protected function copyKeys($source, $target) {
979
+        if (!$this->util->isExcluded($source)) {
980
+            return $this->keyStorage->copyKeys($source, $target);
981
+        }
982
+
983
+        return false;
984
+    }
985
+
986
+    /**
987
+     * check if path points to a files version
988
+     *
989
+     * @param $path
990
+     * @return bool
991
+     */
992
+    protected function isVersion($path) {
993
+        $normalized = Filesystem::normalizePath($path);
994
+        return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
995
+    }
996
+
997
+    /**
998
+     * check if the given storage should be encrypted or not
999
+     *
1000
+     * @param $path
1001
+     * @return bool
1002
+     */
1003
+    protected function shouldEncrypt($path) {
1004
+        $fullPath = $this->getFullPath($path);
1005
+        $mountPointConfig = $this->mount->getOption('encrypt', true);
1006
+        if ($mountPointConfig === false) {
1007
+            return false;
1008
+        }
1009
+
1010
+        try {
1011
+            $encryptionModule = $this->getEncryptionModule($fullPath);
1012
+        } catch (ModuleDoesNotExistsException $e) {
1013
+            return false;
1014
+        }
1015
+
1016
+        if ($encryptionModule === null) {
1017
+            $encryptionModule = $this->encryptionManager->getEncryptionModule();
1018
+        }
1019
+
1020
+        return $encryptionModule->shouldEncrypt($fullPath);
1021
+
1022
+    }
1023 1023
 
1024 1024
 }
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\IStorage $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) {
@@ -952,7 +952,7 @@  discard block
 block discarded – undo
952 952
 			try {
953 953
 				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
954 954
 			} catch (ModuleDoesNotExistsException $e) {
955
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
955
+				$this->logger->critical('Encryption module defined in "'.$path.'" not loaded!');
956 956
 				throw $e;
957 957
 			}
958 958
 		}
Please login to merge, or discard this patch.
lib/private/Files/ObjectStore/ObjectStoreStorage.php 3 patches
Doc Comments   +6 added lines patch added patch discarded remove patch
@@ -162,6 +162,9 @@  discard block
 block discarded – undo
162 162
 		return true;
163 163
 	}
164 164
 
165
+	/**
166
+	 * @param string $path
167
+	 */
165 168
 	private function rmObjects($path) {
166 169
 		$children = $this->getCache()->getFolderContents($path);
167 170
 		foreach ($children as $child) {
@@ -364,6 +367,9 @@  discard block
 block discarded – undo
364 367
 		return true;
365 368
 	}
366 369
 
370
+	/**
371
+	 * @param string $path
372
+	 */
367 373
 	public function writeBack($tmpFile, $path) {
368 374
 		$stat = $this->stat($path);
369 375
 		if (empty($stat)) {
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -55,9 +55,9 @@  discard block
 block discarded – undo
55 55
 			throw new \Exception('missing IObjectStore instance');
56 56
 		}
57 57
 		if (isset($params['storageid'])) {
58
-			$this->id = 'object::store:' . $params['storageid'];
58
+			$this->id = 'object::store:'.$params['storageid'];
59 59
 		} else {
60
-			$this->id = 'object::store:' . $this->objectStore->getStorageId();
60
+			$this->id = 'object::store:'.$this->objectStore->getStorageId();
61 61
 		}
62 62
 		if (isset($params['objectPrefix'])) {
63 63
 			$this->objectPrefix = $params['objectPrefix'];
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 				if ($ex->getCode() !== 404) {
192 192
 					$this->logger->logException($ex, [
193 193
 						'app' => 'objectstore',
194
-						'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
194
+						'message' => 'Could not delete object '.$this->getURN($stat['fileid']).' for '.$path,
195 195
 					]);
196 196
 					return false;
197 197
 				} else {
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
 	 */
225 225
 	protected function getURN($fileId) {
226 226
 		if (is_numeric($fileId)) {
227
-			return $this->objectPrefix . $fileId;
227
+			return $this->objectPrefix.$fileId;
228 228
 		}
229 229
 		return null;
230 230
 	}
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
 					} catch (\Exception $ex) {
273 273
 						$this->logger->logException($ex, [
274 274
 							'app' => 'objectstore',
275
-							'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
275
+							'message' => 'Count not get object '.$this->getURN($stat['fileid']).' for file '.$path,
276 276
 						]);
277 277
 						return false;
278 278
 					}
@@ -302,7 +302,7 @@  discard block
 block discarded – undo
302 302
 					file_put_contents($tmpFile, $source);
303 303
 				}
304 304
 				$handle = fopen($tmpFile, $mode);
305
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
305
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
306 306
 					$this->writeBack($tmpFile, $path);
307 307
 				});
308 308
 		}
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
 
312 312
 	public function file_exists($path) {
313 313
 		$path = $this->normalizePath($path);
314
-		return (bool)$this->stat($path);
314
+		return (bool) $this->stat($path);
315 315
 	}
316 316
 
317 317
 	public function rename($source, $target) {
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 			} catch (\Exception $ex) {
368 368
 				$this->logger->logException($ex, [
369 369
 					'app' => 'objectstore',
370
-					'message' => 'Could not create object for ' . $path,
370
+					'message' => 'Could not create object for '.$path,
371 371
 				]);
372 372
 				return false;
373 373
 			}
@@ -407,7 +407,7 @@  discard block
 block discarded – undo
407 407
 			$this->getCache()->remove($path);
408 408
 			$this->logger->logException($ex, [
409 409
 				'app' => 'objectstore',
410
-				'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
410
+				'message' => 'Could not create object '.$this->getURN($fileId).' for '.$path,
411 411
 			]);
412 412
 			throw $ex; // make this bubble up
413 413
 		}
Please login to merge, or discard this patch.
Indentation   +393 added lines, -393 removed lines patch added patch discarded remove patch
@@ -31,397 +31,397 @@
 block discarded – undo
31 31
 use OCP\Files\ObjectStore\IObjectStore;
32 32
 
33 33
 class ObjectStoreStorage extends \OC\Files\Storage\Common {
34
-	/**
35
-	 * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
36
-	 */
37
-	protected $objectStore;
38
-	/**
39
-	 * @var string $id
40
-	 */
41
-	protected $id;
42
-	/**
43
-	 * @var \OC\User\User $user
44
-	 */
45
-	protected $user;
46
-
47
-	private $objectPrefix = 'urn:oid:';
48
-
49
-	private $logger;
50
-
51
-	public function __construct($params) {
52
-		if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
53
-			$this->objectStore = $params['objectstore'];
54
-		} else {
55
-			throw new \Exception('missing IObjectStore instance');
56
-		}
57
-		if (isset($params['storageid'])) {
58
-			$this->id = 'object::store:' . $params['storageid'];
59
-		} else {
60
-			$this->id = 'object::store:' . $this->objectStore->getStorageId();
61
-		}
62
-		if (isset($params['objectPrefix'])) {
63
-			$this->objectPrefix = $params['objectPrefix'];
64
-		}
65
-		//initialize cache with root directory in cache
66
-		if (!$this->is_dir('/')) {
67
-			$this->mkdir('/');
68
-		}
69
-
70
-		$this->logger = \OC::$server->getLogger();
71
-	}
72
-
73
-	public function mkdir($path) {
74
-		$path = $this->normalizePath($path);
75
-
76
-		if ($this->file_exists($path)) {
77
-			return false;
78
-		}
79
-
80
-		$mTime = time();
81
-		$data = [
82
-			'mimetype' => 'httpd/unix-directory',
83
-			'size' => 0,
84
-			'mtime' => $mTime,
85
-			'storage_mtime' => $mTime,
86
-			'permissions' => \OCP\Constants::PERMISSION_ALL,
87
-		];
88
-		if ($path === '') {
89
-			//create root on the fly
90
-			$data['etag'] = $this->getETag('');
91
-			$this->getCache()->put('', $data);
92
-			return true;
93
-		} else {
94
-			// if parent does not exist, create it
95
-			$parent = $this->normalizePath(dirname($path));
96
-			$parentType = $this->filetype($parent);
97
-			if ($parentType === false) {
98
-				if (!$this->mkdir($parent)) {
99
-					// something went wrong
100
-					return false;
101
-				}
102
-			} else if ($parentType === 'file') {
103
-				// parent is a file
104
-				return false;
105
-			}
106
-			// finally create the new dir
107
-			$mTime = time(); // update mtime
108
-			$data['mtime'] = $mTime;
109
-			$data['storage_mtime'] = $mTime;
110
-			$data['etag'] = $this->getETag($path);
111
-			$this->getCache()->put($path, $data);
112
-			return true;
113
-		}
114
-	}
115
-
116
-	/**
117
-	 * @param string $path
118
-	 * @return string
119
-	 */
120
-	private function normalizePath($path) {
121
-		$path = trim($path, '/');
122
-		//FIXME why do we sometimes get a path like 'files//username'?
123
-		$path = str_replace('//', '/', $path);
124
-
125
-		// dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
126
-		if (!$path || $path === '.') {
127
-			$path = '';
128
-		}
129
-
130
-		return $path;
131
-	}
132
-
133
-	/**
134
-	 * Object Stores use a NoopScanner because metadata is directly stored in
135
-	 * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
136
-	 *
137
-	 * @param string $path
138
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
139
-	 * @return \OC\Files\ObjectStore\NoopScanner
140
-	 */
141
-	public function getScanner($path = '', $storage = null) {
142
-		if (!$storage) {
143
-			$storage = $this;
144
-		}
145
-		if (!isset($this->scanner)) {
146
-			$this->scanner = new NoopScanner($storage);
147
-		}
148
-		return $this->scanner;
149
-	}
150
-
151
-	public function getId() {
152
-		return $this->id;
153
-	}
154
-
155
-	public function rmdir($path) {
156
-		$path = $this->normalizePath($path);
157
-
158
-		if (!$this->is_dir($path)) {
159
-			return false;
160
-		}
161
-
162
-		$this->rmObjects($path);
163
-
164
-		$this->getCache()->remove($path);
165
-
166
-		return true;
167
-	}
168
-
169
-	private function rmObjects($path) {
170
-		$children = $this->getCache()->getFolderContents($path);
171
-		foreach ($children as $child) {
172
-			if ($child['mimetype'] === 'httpd/unix-directory') {
173
-				$this->rmObjects($child['path']);
174
-			} else {
175
-				$this->unlink($child['path']);
176
-			}
177
-		}
178
-	}
179
-
180
-	public function unlink($path) {
181
-		$path = $this->normalizePath($path);
182
-		$stat = $this->stat($path);
183
-
184
-		if ($stat && isset($stat['fileid'])) {
185
-			if ($stat['mimetype'] === 'httpd/unix-directory') {
186
-				return $this->rmdir($path);
187
-			}
188
-			try {
189
-				$this->objectStore->deleteObject($this->getURN($stat['fileid']));
190
-			} catch (\Exception $ex) {
191
-				if ($ex->getCode() !== 404) {
192
-					$this->logger->logException($ex, [
193
-						'app' => 'objectstore',
194
-						'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
195
-					]);
196
-					return false;
197
-				} else {
198
-					//removing from cache is ok as it does not exist in the objectstore anyway
199
-				}
200
-			}
201
-			$this->getCache()->remove($path);
202
-			return true;
203
-		}
204
-		return false;
205
-	}
206
-
207
-	public function stat($path) {
208
-		$path = $this->normalizePath($path);
209
-		$cacheEntry = $this->getCache()->get($path);
210
-		if ($cacheEntry instanceof CacheEntry) {
211
-			return $cacheEntry->getData();
212
-		} else {
213
-			return false;
214
-		}
215
-	}
216
-
217
-	/**
218
-	 * Override this method if you need a different unique resource identifier for your object storage implementation.
219
-	 * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
220
-	 * You may need a mapping table to store your URN if it cannot be generated from the fileid.
221
-	 *
222
-	 * @param int $fileId the fileid
223
-	 * @return null|string the unified resource name used to identify the object
224
-	 */
225
-	protected function getURN($fileId) {
226
-		if (is_numeric($fileId)) {
227
-			return $this->objectPrefix . $fileId;
228
-		}
229
-		return null;
230
-	}
231
-
232
-	public function opendir($path) {
233
-		$path = $this->normalizePath($path);
234
-
235
-		try {
236
-			$files = array();
237
-			$folderContents = $this->getCache()->getFolderContents($path);
238
-			foreach ($folderContents as $file) {
239
-				$files[] = $file['name'];
240
-			}
241
-
242
-			return IteratorDirectory::wrap($files);
243
-		} catch (\Exception $e) {
244
-			$this->logger->logException($e);
245
-			return false;
246
-		}
247
-	}
248
-
249
-	public function filetype($path) {
250
-		$path = $this->normalizePath($path);
251
-		$stat = $this->stat($path);
252
-		if ($stat) {
253
-			if ($stat['mimetype'] === 'httpd/unix-directory') {
254
-				return 'dir';
255
-			}
256
-			return 'file';
257
-		} else {
258
-			return false;
259
-		}
260
-	}
261
-
262
-	public function fopen($path, $mode) {
263
-		$path = $this->normalizePath($path);
264
-
265
-		switch ($mode) {
266
-			case 'r':
267
-			case 'rb':
268
-				$stat = $this->stat($path);
269
-				if (is_array($stat)) {
270
-					try {
271
-						return $this->objectStore->readObject($this->getURN($stat['fileid']));
272
-					} catch (\Exception $ex) {
273
-						$this->logger->logException($ex, [
274
-							'app' => 'objectstore',
275
-							'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
276
-						]);
277
-						return false;
278
-					}
279
-				} else {
280
-					return false;
281
-				}
282
-			case 'w':
283
-			case 'wb':
284
-			case 'a':
285
-			case 'ab':
286
-			case 'r+':
287
-			case 'w+':
288
-			case 'wb+':
289
-			case 'a+':
290
-			case 'x':
291
-			case 'x+':
292
-			case 'c':
293
-			case 'c+':
294
-				if (strrpos($path, '.') !== false) {
295
-					$ext = substr($path, strrpos($path, '.'));
296
-				} else {
297
-					$ext = '';
298
-				}
299
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
300
-				if ($this->file_exists($path)) {
301
-					$source = $this->fopen($path, 'r');
302
-					file_put_contents($tmpFile, $source);
303
-				}
304
-				$handle = fopen($tmpFile, $mode);
305
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
306
-					$this->writeBack($tmpFile, $path);
307
-				});
308
-		}
309
-		return false;
310
-	}
311
-
312
-	public function file_exists($path) {
313
-		$path = $this->normalizePath($path);
314
-		return (bool)$this->stat($path);
315
-	}
316
-
317
-	public function rename($source, $target) {
318
-		$source = $this->normalizePath($source);
319
-		$target = $this->normalizePath($target);
320
-		$this->remove($target);
321
-		$this->getCache()->move($source, $target);
322
-		$this->touch(dirname($target));
323
-		return true;
324
-	}
325
-
326
-	public function getMimeType($path) {
327
-		$path = $this->normalizePath($path);
328
-		$stat = $this->stat($path);
329
-		if (is_array($stat)) {
330
-			return $stat['mimetype'];
331
-		} else {
332
-			return false;
333
-		}
334
-	}
335
-
336
-	public function touch($path, $mtime = null) {
337
-		if (is_null($mtime)) {
338
-			$mtime = time();
339
-		}
340
-
341
-		$path = $this->normalizePath($path);
342
-		$dirName = dirname($path);
343
-		$parentExists = $this->is_dir($dirName);
344
-		if (!$parentExists) {
345
-			return false;
346
-		}
347
-
348
-		$stat = $this->stat($path);
349
-		if (is_array($stat)) {
350
-			// update existing mtime in db
351
-			$stat['mtime'] = $mtime;
352
-			$this->getCache()->update($stat['fileid'], $stat);
353
-		} else {
354
-			try {
355
-				//create a empty file, need to have at least on char to make it
356
-				// work with all object storage implementations
357
-				$this->file_put_contents($path, ' ');
358
-				$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
359
-				$stat = array(
360
-					'etag' => $this->getETag($path),
361
-					'mimetype' => $mimeType,
362
-					'size' => 0,
363
-					'mtime' => $mtime,
364
-					'storage_mtime' => $mtime,
365
-					'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
366
-				);
367
-				$this->getCache()->put($path, $stat);
368
-			} catch (\Exception $ex) {
369
-				$this->logger->logException($ex, [
370
-					'app' => 'objectstore',
371
-					'message' => 'Could not create object for ' . $path,
372
-				]);
373
-				return false;
374
-			}
375
-		}
376
-		return true;
377
-	}
378
-
379
-	public function writeBack($tmpFile, $path) {
380
-		$stat = $this->stat($path);
381
-		if (empty($stat)) {
382
-			// create new file
383
-			$stat = array(
384
-				'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
385
-			);
386
-		}
387
-		// update stat with new data
388
-		$mTime = time();
389
-		$stat['size'] = filesize($tmpFile);
390
-		$stat['mtime'] = $mTime;
391
-		$stat['storage_mtime'] = $mTime;
392
-
393
-		// run path based detection first, to use file extension because $tmpFile is only a random string
394
-		$mimetypeDetector = \OC::$server->getMimeTypeDetector();
395
-		$mimetype = $mimetypeDetector->detectPath($path);
396
-		if ($mimetype === 'application/octet-stream') {
397
-			$mimetype = $mimetypeDetector->detect($tmpFile);
398
-		}
399
-
400
-		$stat['mimetype'] = $mimetype;
401
-		$stat['etag'] = $this->getETag($path);
402
-
403
-		$fileId = $this->getCache()->put($path, $stat);
404
-		try {
405
-			//upload to object storage
406
-			$this->objectStore->writeObject($this->getURN($fileId), fopen($tmpFile, 'r'));
407
-		} catch (\Exception $ex) {
408
-			$this->getCache()->remove($path);
409
-			$this->logger->logException($ex, [
410
-				'app' => 'objectstore',
411
-				'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
412
-			]);
413
-			throw $ex; // make this bubble up
414
-		}
415
-	}
416
-
417
-	/**
418
-	 * external changes are not supported, exclusive access to the object storage is assumed
419
-	 *
420
-	 * @param string $path
421
-	 * @param int $time
422
-	 * @return false
423
-	 */
424
-	public function hasUpdated($path, $time) {
425
-		return false;
426
-	}
34
+    /**
35
+     * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
36
+     */
37
+    protected $objectStore;
38
+    /**
39
+     * @var string $id
40
+     */
41
+    protected $id;
42
+    /**
43
+     * @var \OC\User\User $user
44
+     */
45
+    protected $user;
46
+
47
+    private $objectPrefix = 'urn:oid:';
48
+
49
+    private $logger;
50
+
51
+    public function __construct($params) {
52
+        if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
53
+            $this->objectStore = $params['objectstore'];
54
+        } else {
55
+            throw new \Exception('missing IObjectStore instance');
56
+        }
57
+        if (isset($params['storageid'])) {
58
+            $this->id = 'object::store:' . $params['storageid'];
59
+        } else {
60
+            $this->id = 'object::store:' . $this->objectStore->getStorageId();
61
+        }
62
+        if (isset($params['objectPrefix'])) {
63
+            $this->objectPrefix = $params['objectPrefix'];
64
+        }
65
+        //initialize cache with root directory in cache
66
+        if (!$this->is_dir('/')) {
67
+            $this->mkdir('/');
68
+        }
69
+
70
+        $this->logger = \OC::$server->getLogger();
71
+    }
72
+
73
+    public function mkdir($path) {
74
+        $path = $this->normalizePath($path);
75
+
76
+        if ($this->file_exists($path)) {
77
+            return false;
78
+        }
79
+
80
+        $mTime = time();
81
+        $data = [
82
+            'mimetype' => 'httpd/unix-directory',
83
+            'size' => 0,
84
+            'mtime' => $mTime,
85
+            'storage_mtime' => $mTime,
86
+            'permissions' => \OCP\Constants::PERMISSION_ALL,
87
+        ];
88
+        if ($path === '') {
89
+            //create root on the fly
90
+            $data['etag'] = $this->getETag('');
91
+            $this->getCache()->put('', $data);
92
+            return true;
93
+        } else {
94
+            // if parent does not exist, create it
95
+            $parent = $this->normalizePath(dirname($path));
96
+            $parentType = $this->filetype($parent);
97
+            if ($parentType === false) {
98
+                if (!$this->mkdir($parent)) {
99
+                    // something went wrong
100
+                    return false;
101
+                }
102
+            } else if ($parentType === 'file') {
103
+                // parent is a file
104
+                return false;
105
+            }
106
+            // finally create the new dir
107
+            $mTime = time(); // update mtime
108
+            $data['mtime'] = $mTime;
109
+            $data['storage_mtime'] = $mTime;
110
+            $data['etag'] = $this->getETag($path);
111
+            $this->getCache()->put($path, $data);
112
+            return true;
113
+        }
114
+    }
115
+
116
+    /**
117
+     * @param string $path
118
+     * @return string
119
+     */
120
+    private function normalizePath($path) {
121
+        $path = trim($path, '/');
122
+        //FIXME why do we sometimes get a path like 'files//username'?
123
+        $path = str_replace('//', '/', $path);
124
+
125
+        // dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
126
+        if (!$path || $path === '.') {
127
+            $path = '';
128
+        }
129
+
130
+        return $path;
131
+    }
132
+
133
+    /**
134
+     * Object Stores use a NoopScanner because metadata is directly stored in
135
+     * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
136
+     *
137
+     * @param string $path
138
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
139
+     * @return \OC\Files\ObjectStore\NoopScanner
140
+     */
141
+    public function getScanner($path = '', $storage = null) {
142
+        if (!$storage) {
143
+            $storage = $this;
144
+        }
145
+        if (!isset($this->scanner)) {
146
+            $this->scanner = new NoopScanner($storage);
147
+        }
148
+        return $this->scanner;
149
+    }
150
+
151
+    public function getId() {
152
+        return $this->id;
153
+    }
154
+
155
+    public function rmdir($path) {
156
+        $path = $this->normalizePath($path);
157
+
158
+        if (!$this->is_dir($path)) {
159
+            return false;
160
+        }
161
+
162
+        $this->rmObjects($path);
163
+
164
+        $this->getCache()->remove($path);
165
+
166
+        return true;
167
+    }
168
+
169
+    private function rmObjects($path) {
170
+        $children = $this->getCache()->getFolderContents($path);
171
+        foreach ($children as $child) {
172
+            if ($child['mimetype'] === 'httpd/unix-directory') {
173
+                $this->rmObjects($child['path']);
174
+            } else {
175
+                $this->unlink($child['path']);
176
+            }
177
+        }
178
+    }
179
+
180
+    public function unlink($path) {
181
+        $path = $this->normalizePath($path);
182
+        $stat = $this->stat($path);
183
+
184
+        if ($stat && isset($stat['fileid'])) {
185
+            if ($stat['mimetype'] === 'httpd/unix-directory') {
186
+                return $this->rmdir($path);
187
+            }
188
+            try {
189
+                $this->objectStore->deleteObject($this->getURN($stat['fileid']));
190
+            } catch (\Exception $ex) {
191
+                if ($ex->getCode() !== 404) {
192
+                    $this->logger->logException($ex, [
193
+                        'app' => 'objectstore',
194
+                        'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
195
+                    ]);
196
+                    return false;
197
+                } else {
198
+                    //removing from cache is ok as it does not exist in the objectstore anyway
199
+                }
200
+            }
201
+            $this->getCache()->remove($path);
202
+            return true;
203
+        }
204
+        return false;
205
+    }
206
+
207
+    public function stat($path) {
208
+        $path = $this->normalizePath($path);
209
+        $cacheEntry = $this->getCache()->get($path);
210
+        if ($cacheEntry instanceof CacheEntry) {
211
+            return $cacheEntry->getData();
212
+        } else {
213
+            return false;
214
+        }
215
+    }
216
+
217
+    /**
218
+     * Override this method if you need a different unique resource identifier for your object storage implementation.
219
+     * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
220
+     * You may need a mapping table to store your URN if it cannot be generated from the fileid.
221
+     *
222
+     * @param int $fileId the fileid
223
+     * @return null|string the unified resource name used to identify the object
224
+     */
225
+    protected function getURN($fileId) {
226
+        if (is_numeric($fileId)) {
227
+            return $this->objectPrefix . $fileId;
228
+        }
229
+        return null;
230
+    }
231
+
232
+    public function opendir($path) {
233
+        $path = $this->normalizePath($path);
234
+
235
+        try {
236
+            $files = array();
237
+            $folderContents = $this->getCache()->getFolderContents($path);
238
+            foreach ($folderContents as $file) {
239
+                $files[] = $file['name'];
240
+            }
241
+
242
+            return IteratorDirectory::wrap($files);
243
+        } catch (\Exception $e) {
244
+            $this->logger->logException($e);
245
+            return false;
246
+        }
247
+    }
248
+
249
+    public function filetype($path) {
250
+        $path = $this->normalizePath($path);
251
+        $stat = $this->stat($path);
252
+        if ($stat) {
253
+            if ($stat['mimetype'] === 'httpd/unix-directory') {
254
+                return 'dir';
255
+            }
256
+            return 'file';
257
+        } else {
258
+            return false;
259
+        }
260
+    }
261
+
262
+    public function fopen($path, $mode) {
263
+        $path = $this->normalizePath($path);
264
+
265
+        switch ($mode) {
266
+            case 'r':
267
+            case 'rb':
268
+                $stat = $this->stat($path);
269
+                if (is_array($stat)) {
270
+                    try {
271
+                        return $this->objectStore->readObject($this->getURN($stat['fileid']));
272
+                    } catch (\Exception $ex) {
273
+                        $this->logger->logException($ex, [
274
+                            'app' => 'objectstore',
275
+                            'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
276
+                        ]);
277
+                        return false;
278
+                    }
279
+                } else {
280
+                    return false;
281
+                }
282
+            case 'w':
283
+            case 'wb':
284
+            case 'a':
285
+            case 'ab':
286
+            case 'r+':
287
+            case 'w+':
288
+            case 'wb+':
289
+            case 'a+':
290
+            case 'x':
291
+            case 'x+':
292
+            case 'c':
293
+            case 'c+':
294
+                if (strrpos($path, '.') !== false) {
295
+                    $ext = substr($path, strrpos($path, '.'));
296
+                } else {
297
+                    $ext = '';
298
+                }
299
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
300
+                if ($this->file_exists($path)) {
301
+                    $source = $this->fopen($path, 'r');
302
+                    file_put_contents($tmpFile, $source);
303
+                }
304
+                $handle = fopen($tmpFile, $mode);
305
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
306
+                    $this->writeBack($tmpFile, $path);
307
+                });
308
+        }
309
+        return false;
310
+    }
311
+
312
+    public function file_exists($path) {
313
+        $path = $this->normalizePath($path);
314
+        return (bool)$this->stat($path);
315
+    }
316
+
317
+    public function rename($source, $target) {
318
+        $source = $this->normalizePath($source);
319
+        $target = $this->normalizePath($target);
320
+        $this->remove($target);
321
+        $this->getCache()->move($source, $target);
322
+        $this->touch(dirname($target));
323
+        return true;
324
+    }
325
+
326
+    public function getMimeType($path) {
327
+        $path = $this->normalizePath($path);
328
+        $stat = $this->stat($path);
329
+        if (is_array($stat)) {
330
+            return $stat['mimetype'];
331
+        } else {
332
+            return false;
333
+        }
334
+    }
335
+
336
+    public function touch($path, $mtime = null) {
337
+        if (is_null($mtime)) {
338
+            $mtime = time();
339
+        }
340
+
341
+        $path = $this->normalizePath($path);
342
+        $dirName = dirname($path);
343
+        $parentExists = $this->is_dir($dirName);
344
+        if (!$parentExists) {
345
+            return false;
346
+        }
347
+
348
+        $stat = $this->stat($path);
349
+        if (is_array($stat)) {
350
+            // update existing mtime in db
351
+            $stat['mtime'] = $mtime;
352
+            $this->getCache()->update($stat['fileid'], $stat);
353
+        } else {
354
+            try {
355
+                //create a empty file, need to have at least on char to make it
356
+                // work with all object storage implementations
357
+                $this->file_put_contents($path, ' ');
358
+                $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
359
+                $stat = array(
360
+                    'etag' => $this->getETag($path),
361
+                    'mimetype' => $mimeType,
362
+                    'size' => 0,
363
+                    'mtime' => $mtime,
364
+                    'storage_mtime' => $mtime,
365
+                    'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
366
+                );
367
+                $this->getCache()->put($path, $stat);
368
+            } catch (\Exception $ex) {
369
+                $this->logger->logException($ex, [
370
+                    'app' => 'objectstore',
371
+                    'message' => 'Could not create object for ' . $path,
372
+                ]);
373
+                return false;
374
+            }
375
+        }
376
+        return true;
377
+    }
378
+
379
+    public function writeBack($tmpFile, $path) {
380
+        $stat = $this->stat($path);
381
+        if (empty($stat)) {
382
+            // create new file
383
+            $stat = array(
384
+                'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
385
+            );
386
+        }
387
+        // update stat with new data
388
+        $mTime = time();
389
+        $stat['size'] = filesize($tmpFile);
390
+        $stat['mtime'] = $mTime;
391
+        $stat['storage_mtime'] = $mTime;
392
+
393
+        // run path based detection first, to use file extension because $tmpFile is only a random string
394
+        $mimetypeDetector = \OC::$server->getMimeTypeDetector();
395
+        $mimetype = $mimetypeDetector->detectPath($path);
396
+        if ($mimetype === 'application/octet-stream') {
397
+            $mimetype = $mimetypeDetector->detect($tmpFile);
398
+        }
399
+
400
+        $stat['mimetype'] = $mimetype;
401
+        $stat['etag'] = $this->getETag($path);
402
+
403
+        $fileId = $this->getCache()->put($path, $stat);
404
+        try {
405
+            //upload to object storage
406
+            $this->objectStore->writeObject($this->getURN($fileId), fopen($tmpFile, 'r'));
407
+        } catch (\Exception $ex) {
408
+            $this->getCache()->remove($path);
409
+            $this->logger->logException($ex, [
410
+                'app' => 'objectstore',
411
+                'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
412
+            ]);
413
+            throw $ex; // make this bubble up
414
+        }
415
+    }
416
+
417
+    /**
418
+     * external changes are not supported, exclusive access to the object storage is assumed
419
+     *
420
+     * @param string $path
421
+     * @param int $time
422
+     * @return false
423
+     */
424
+    public function hasUpdated($path, $time) {
425
+        return false;
426
+    }
427 427
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Notify/SMBNotifyHandler.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -102,7 +102,7 @@
 block discarded – undo
102 102
 
103 103
 	/**
104 104
 	 * @param \Icewind\SMB\Change $change
105
-	 * @return IChange|null
105
+	 * @return null|Change
106 106
 	 */
107 107
 	private function mapChange(\Icewind\SMB\Change $change) {
108 108
 		$path = $this->relativePath($change->getPath());
Please login to merge, or discard this patch.
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -29,122 +29,122 @@
 block discarded – undo
29 29
 use OCP\Files\Notify\INotifyHandler;
30 30
 
31 31
 class SMBNotifyHandler implements INotifyHandler {
32
-	/**
33
-	 * @var \Icewind\SMB\INotifyHandler
34
-	 */
35
-	private $shareNotifyHandler;
32
+    /**
33
+     * @var \Icewind\SMB\INotifyHandler
34
+     */
35
+    private $shareNotifyHandler;
36 36
 
37
-	/**
38
-	 * @var string
39
-	 */
40
-	private $root;
37
+    /**
38
+     * @var string
39
+     */
40
+    private $root;
41 41
 
42
-	private $oldRenamePath = null;
42
+    private $oldRenamePath = null;
43 43
 
44
-	/**
45
-	 * SMBNotifyHandler constructor.
46
-	 *
47
-	 * @param \Icewind\SMB\INotifyHandler $shareNotifyHandler
48
-	 * @param string $root
49
-	 */
50
-	public function __construct(\Icewind\SMB\INotifyHandler $shareNotifyHandler, $root) {
51
-		$this->shareNotifyHandler = $shareNotifyHandler;
52
-		$this->root = $root;
53
-	}
44
+    /**
45
+     * SMBNotifyHandler constructor.
46
+     *
47
+     * @param \Icewind\SMB\INotifyHandler $shareNotifyHandler
48
+     * @param string $root
49
+     */
50
+    public function __construct(\Icewind\SMB\INotifyHandler $shareNotifyHandler, $root) {
51
+        $this->shareNotifyHandler = $shareNotifyHandler;
52
+        $this->root = $root;
53
+    }
54 54
 
55
-	private function relativePath($fullPath) {
56
-		if ($fullPath === $this->root) {
57
-			return '';
58
-		} else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
59
-			return substr($fullPath, strlen($this->root));
60
-		} else {
61
-			return null;
62
-		}
63
-	}
55
+    private function relativePath($fullPath) {
56
+        if ($fullPath === $this->root) {
57
+            return '';
58
+        } else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
59
+            return substr($fullPath, strlen($this->root));
60
+        } else {
61
+            return null;
62
+        }
63
+    }
64 64
 
65
-	public function listen(callable $callback) {
66
-		$oldRenamePath = null;
67
-		$this->shareNotifyHandler->listen(function (\Icewind\SMB\Change $shareChange) use ($callback) {
68
-			$change = $this->mapChange($shareChange);
69
-			if (!is_null($change)) {
70
-				return $callback($change);
71
-			} else {
72
-				return true;
73
-			}
74
-		});
75
-	}
65
+    public function listen(callable $callback) {
66
+        $oldRenamePath = null;
67
+        $this->shareNotifyHandler->listen(function (\Icewind\SMB\Change $shareChange) use ($callback) {
68
+            $change = $this->mapChange($shareChange);
69
+            if (!is_null($change)) {
70
+                return $callback($change);
71
+            } else {
72
+                return true;
73
+            }
74
+        });
75
+    }
76 76
 
77
-	/**
78
-	 * Get all changes detected since the start of the notify process or the last call to getChanges
79
-	 *
80
-	 * @return IChange[]
81
-	 */
82
-	public function getChanges() {
83
-		$shareChanges = $this->shareNotifyHandler->getChanges();
84
-		$changes = [];
85
-		foreach ($shareChanges as $shareChange) {
86
-			$change = $this->mapChange($shareChange);
87
-			if ($change) {
88
-				$changes[] = $change;
89
-			}
90
-		}
91
-		return $changes;
92
-	}
77
+    /**
78
+     * Get all changes detected since the start of the notify process or the last call to getChanges
79
+     *
80
+     * @return IChange[]
81
+     */
82
+    public function getChanges() {
83
+        $shareChanges = $this->shareNotifyHandler->getChanges();
84
+        $changes = [];
85
+        foreach ($shareChanges as $shareChange) {
86
+            $change = $this->mapChange($shareChange);
87
+            if ($change) {
88
+                $changes[] = $change;
89
+            }
90
+        }
91
+        return $changes;
92
+    }
93 93
 
94
-	/**
95
-	 * Stop listening for changes
96
-	 *
97
-	 * Note that any pending changes will be discarded
98
-	 */
99
-	public function stop() {
100
-		$this->shareNotifyHandler->stop();
101
-	}
94
+    /**
95
+     * Stop listening for changes
96
+     *
97
+     * Note that any pending changes will be discarded
98
+     */
99
+    public function stop() {
100
+        $this->shareNotifyHandler->stop();
101
+    }
102 102
 
103
-	/**
104
-	 * @param \Icewind\SMB\Change $change
105
-	 * @return IChange|null
106
-	 */
107
-	private function mapChange(\Icewind\SMB\Change $change) {
108
-		$path = $this->relativePath($change->getPath());
109
-		if (is_null($path)) {
110
-			return null;
111
-		}
112
-		if ($change->getCode() === \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_OLD) {
113
-			$this->oldRenamePath = $path;
114
-			return null;
115
-		}
116
-		$type = $this->mapNotifyType($change->getCode());
117
-		if (is_null($type)) {
118
-			return null;
119
-		}
120
-		if ($type === IChange::RENAMED) {
121
-			if (!is_null($this->oldRenamePath)) {
122
-				$result = new RenameChange($type, $this->oldRenamePath, $path);
123
-				$this->oldRenamePath = null;
124
-			} else {
125
-				$result = null;
126
-			}
127
-		} else {
128
-			$result = new Change($type, $path);
129
-		}
130
-		return $result;
131
-	}
103
+    /**
104
+     * @param \Icewind\SMB\Change $change
105
+     * @return IChange|null
106
+     */
107
+    private function mapChange(\Icewind\SMB\Change $change) {
108
+        $path = $this->relativePath($change->getPath());
109
+        if (is_null($path)) {
110
+            return null;
111
+        }
112
+        if ($change->getCode() === \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_OLD) {
113
+            $this->oldRenamePath = $path;
114
+            return null;
115
+        }
116
+        $type = $this->mapNotifyType($change->getCode());
117
+        if (is_null($type)) {
118
+            return null;
119
+        }
120
+        if ($type === IChange::RENAMED) {
121
+            if (!is_null($this->oldRenamePath)) {
122
+                $result = new RenameChange($type, $this->oldRenamePath, $path);
123
+                $this->oldRenamePath = null;
124
+            } else {
125
+                $result = null;
126
+            }
127
+        } else {
128
+            $result = new Change($type, $path);
129
+        }
130
+        return $result;
131
+    }
132 132
 
133
-	private function mapNotifyType($smbType) {
134
-		switch ($smbType) {
135
-			case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED:
136
-				return IChange::ADDED;
137
-			case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED:
138
-				return IChange::REMOVED;
139
-			case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED:
140
-			case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED_STREAM:
141
-			case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED_STREAM:
142
-			case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED_STREAM:
143
-				return IChange::MODIFIED;
144
-			case \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_NEW:
145
-				return IChange::RENAMED;
146
-			default:
147
-				return null;
148
-		}
149
-	}
133
+    private function mapNotifyType($smbType) {
134
+        switch ($smbType) {
135
+            case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED:
136
+                return IChange::ADDED;
137
+            case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED:
138
+                return IChange::REMOVED;
139
+            case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED:
140
+            case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED_STREAM:
141
+            case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED_STREAM:
142
+            case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED_STREAM:
143
+                return IChange::MODIFIED;
144
+            case \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_NEW:
145
+                return IChange::RENAMED;
146
+            default:
147
+                return null;
148
+        }
149
+    }
150 150
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -64,7 +64,7 @@
 block discarded – undo
64 64
 
65 65
 	public function listen(callable $callback) {
66 66
 		$oldRenamePath = null;
67
-		$this->shareNotifyHandler->listen(function (\Icewind\SMB\Change $shareChange) use ($callback) {
67
+		$this->shareNotifyHandler->listen(function(\Icewind\SMB\Change $shareChange) use ($callback) {
68 68
 			$change = $this->mapChange($shareChange);
69 69
 			if (!is_null($change)) {
70 70
 				return $callback($change);
Please login to merge, or discard this patch.
lib/private/legacy/app.php 3 patches
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   +1180 added lines, -1180 removed lines patch added patch discarded remove patch
@@ -63,1184 +63,1184 @@
 block discarded – undo
63 63
  * upgrading and removing apps.
64 64
  */
65 65
 class OC_App {
66
-	static private $appVersion = [];
67
-	static private $adminForms = array();
68
-	static private $personalForms = array();
69
-	static private $appInfo = array();
70
-	static private $appTypes = array();
71
-	static private $loadedApps = array();
72
-	static private $altLogin = array();
73
-	static private $alreadyRegistered = [];
74
-	const officialApp = 200;
75
-
76
-	/**
77
-	 * clean the appId
78
-	 *
79
-	 * @param string|boolean $app AppId that needs to be cleaned
80
-	 * @return string
81
-	 */
82
-	public static function cleanAppId($app) {
83
-		return str_replace(array('\0', '/', '\\', '..'), '', $app);
84
-	}
85
-
86
-	/**
87
-	 * Check if an app is loaded
88
-	 *
89
-	 * @param string $app
90
-	 * @return bool
91
-	 */
92
-	public static function isAppLoaded($app) {
93
-		return in_array($app, self::$loadedApps, true);
94
-	}
95
-
96
-	/**
97
-	 * loads all apps
98
-	 *
99
-	 * @param string[] | string | null $types
100
-	 * @return bool
101
-	 *
102
-	 * This function walks through the ownCloud directory and loads all apps
103
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
104
-	 * exists.
105
-	 *
106
-	 * if $types is set, only apps of those types will be loaded
107
-	 */
108
-	public static function loadApps($types = null) {
109
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
110
-			return false;
111
-		}
112
-		// Load the enabled apps here
113
-		$apps = self::getEnabledApps();
114
-
115
-		// Add each apps' folder as allowed class path
116
-		foreach($apps as $app) {
117
-			$path = self::getAppPath($app);
118
-			if($path !== false) {
119
-				self::registerAutoloading($app, $path);
120
-			}
121
-		}
122
-
123
-		// prevent app.php from printing output
124
-		ob_start();
125
-		foreach ($apps as $app) {
126
-			if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
127
-				self::loadApp($app);
128
-			}
129
-		}
130
-		ob_end_clean();
131
-
132
-		return true;
133
-	}
134
-
135
-	/**
136
-	 * load a single app
137
-	 *
138
-	 * @param string $app
139
-	 */
140
-	public static function loadApp($app) {
141
-		self::$loadedApps[] = $app;
142
-		$appPath = self::getAppPath($app);
143
-		if($appPath === false) {
144
-			return;
145
-		}
146
-
147
-		// in case someone calls loadApp() directly
148
-		self::registerAutoloading($app, $appPath);
149
-
150
-		if (is_file($appPath . '/appinfo/app.php')) {
151
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
152
-			self::requireAppFile($app);
153
-			if (self::isType($app, array('authentication'))) {
154
-				// since authentication apps affect the "is app enabled for group" check,
155
-				// the enabled apps cache needs to be cleared to make sure that the
156
-				// next time getEnableApps() is called it will also include apps that were
157
-				// enabled for groups
158
-				self::$enabledAppsCache = array();
159
-			}
160
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
161
-		}
162
-
163
-		$info = self::getAppInfo($app);
164
-		if (!empty($info['activity']['filters'])) {
165
-			foreach ($info['activity']['filters'] as $filter) {
166
-				\OC::$server->getActivityManager()->registerFilter($filter);
167
-			}
168
-		}
169
-		if (!empty($info['activity']['settings'])) {
170
-			foreach ($info['activity']['settings'] as $setting) {
171
-				\OC::$server->getActivityManager()->registerSetting($setting);
172
-			}
173
-		}
174
-		if (!empty($info['activity']['providers'])) {
175
-			foreach ($info['activity']['providers'] as $provider) {
176
-				\OC::$server->getActivityManager()->registerProvider($provider);
177
-			}
178
-		}
179
-		if (!empty($info['collaboration']['plugins'])) {
180
-			// deal with one or many plugin entries
181
-			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
182
-				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
183
-			foreach ($plugins as $plugin) {
184
-				if($plugin['@attributes']['type'] === 'collaborator-search') {
185
-					$pluginInfo = [
186
-						'shareType' => $plugin['@attributes']['share-type'],
187
-						'class' => $plugin['@value'],
188
-					];
189
-					\OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
190
-				} else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
191
-					\OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
192
-				}
193
-			}
194
-		}
195
-	}
196
-
197
-	/**
198
-	 * @internal
199
-	 * @param string $app
200
-	 * @param string $path
201
-	 */
202
-	public static function registerAutoloading($app, $path) {
203
-		$key = $app . '-' . $path;
204
-		if(isset(self::$alreadyRegistered[$key])) {
205
-			return;
206
-		}
207
-
208
-		self::$alreadyRegistered[$key] = true;
209
-
210
-		// Register on PSR-4 composer autoloader
211
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
212
-		\OC::$server->registerNamespace($app, $appNamespace);
213
-
214
-		if (file_exists($path . '/composer/autoload.php')) {
215
-			require_once $path . '/composer/autoload.php';
216
-		} else {
217
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
218
-			// Register on legacy autoloader
219
-			\OC::$loader->addValidRoot($path);
220
-		}
221
-
222
-		// Register Test namespace only when testing
223
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
224
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
225
-		}
226
-	}
227
-
228
-	/**
229
-	 * Load app.php from the given app
230
-	 *
231
-	 * @param string $app app name
232
-	 */
233
-	private static function requireAppFile($app) {
234
-		try {
235
-			// encapsulated here to avoid variable scope conflicts
236
-			require_once $app . '/appinfo/app.php';
237
-		} catch (Error $ex) {
238
-			\OC::$server->getLogger()->logException($ex);
239
-			$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
240
-			if (!in_array($app, $blacklist)) {
241
-				self::disable($app);
242
-			}
243
-		}
244
-	}
245
-
246
-	/**
247
-	 * check if an app is of a specific type
248
-	 *
249
-	 * @param string $app
250
-	 * @param string|array $types
251
-	 * @return bool
252
-	 */
253
-	public static function isType($app, $types) {
254
-		if (is_string($types)) {
255
-			$types = array($types);
256
-		}
257
-		$appTypes = self::getAppTypes($app);
258
-		foreach ($types as $type) {
259
-			if (array_search($type, $appTypes) !== false) {
260
-				return true;
261
-			}
262
-		}
263
-		return false;
264
-	}
265
-
266
-	/**
267
-	 * get the types of an app
268
-	 *
269
-	 * @param string $app
270
-	 * @return array
271
-	 */
272
-	private static function getAppTypes($app) {
273
-		//load the cache
274
-		if (count(self::$appTypes) == 0) {
275
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
276
-		}
277
-
278
-		if (isset(self::$appTypes[$app])) {
279
-			return explode(',', self::$appTypes[$app]);
280
-		} else {
281
-			return array();
282
-		}
283
-	}
284
-
285
-	/**
286
-	 * read app types from info.xml and cache them in the database
287
-	 */
288
-	public static function setAppTypes($app) {
289
-		$appData = self::getAppInfo($app);
290
-		if(!is_array($appData)) {
291
-			return;
292
-		}
293
-
294
-		if (isset($appData['types'])) {
295
-			$appTypes = implode(',', $appData['types']);
296
-		} else {
297
-			$appTypes = '';
298
-			$appData['types'] = [];
299
-		}
300
-
301
-		\OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
302
-
303
-		if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
304
-			$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
305
-			if ($enabled !== 'yes' && $enabled !== 'no') {
306
-				\OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
307
-			}
308
-		}
309
-	}
310
-
311
-	/**
312
-	 * get all enabled apps
313
-	 */
314
-	protected static $enabledAppsCache = array();
315
-
316
-	/**
317
-	 * Returns apps enabled for the current user.
318
-	 *
319
-	 * @param bool $forceRefresh whether to refresh the cache
320
-	 * @param bool $all whether to return apps for all users, not only the
321
-	 * currently logged in one
322
-	 * @return string[]
323
-	 */
324
-	public static function getEnabledApps($forceRefresh = false, $all = false) {
325
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
326
-			return array();
327
-		}
328
-		// in incognito mode or when logged out, $user will be false,
329
-		// which is also the case during an upgrade
330
-		$appManager = \OC::$server->getAppManager();
331
-		if ($all) {
332
-			$user = null;
333
-		} else {
334
-			$user = \OC::$server->getUserSession()->getUser();
335
-		}
336
-
337
-		if (is_null($user)) {
338
-			$apps = $appManager->getInstalledApps();
339
-		} else {
340
-			$apps = $appManager->getEnabledAppsForUser($user);
341
-		}
342
-		$apps = array_filter($apps, function ($app) {
343
-			return $app !== 'files';//we add this manually
344
-		});
345
-		sort($apps);
346
-		array_unshift($apps, 'files');
347
-		return $apps;
348
-	}
349
-
350
-	/**
351
-	 * checks whether or not an app is enabled
352
-	 *
353
-	 * @param string $app app
354
-	 * @return bool
355
-	 * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
356
-	 *
357
-	 * This function checks whether or not an app is enabled.
358
-	 */
359
-	public static function isEnabled($app) {
360
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
361
-	}
362
-
363
-	/**
364
-	 * enables an app
365
-	 *
366
-	 * @param string $appId
367
-	 * @param array $groups (optional) when set, only these groups will have access to the app
368
-	 * @throws \Exception
369
-	 * @return void
370
-	 *
371
-	 * This function set an app as enabled in appconfig.
372
-	 */
373
-	public function enable($appId,
374
-						   $groups = null) {
375
-		self::$enabledAppsCache = []; // flush
376
-
377
-		// Check if app is already downloaded
378
-		$installer = \OC::$server->query(Installer::class);
379
-		$isDownloaded = $installer->isDownloaded($appId);
380
-
381
-		if(!$isDownloaded) {
382
-			$installer->downloadApp($appId);
383
-		}
384
-
385
-		$installer->installApp($appId);
386
-
387
-		$appManager = \OC::$server->getAppManager();
388
-		if (!is_null($groups)) {
389
-			$groupManager = \OC::$server->getGroupManager();
390
-			$groupsList = [];
391
-			foreach ($groups as $group) {
392
-				$groupItem = $groupManager->get($group);
393
-				if ($groupItem instanceof \OCP\IGroup) {
394
-					$groupsList[] = $groupManager->get($group);
395
-				}
396
-			}
397
-			$appManager->enableAppForGroups($appId, $groupsList);
398
-		} else {
399
-			$appManager->enableApp($appId);
400
-		}
401
-	}
402
-
403
-	/**
404
-	 * @param string $app
405
-	 * @return bool
406
-	 */
407
-	public static function removeApp($app) {
408
-		if (\OC::$server->getAppManager()->isShipped($app)) {
409
-			return false;
410
-		}
411
-
412
-		$installer = \OC::$server->query(Installer::class);
413
-		return $installer->removeApp($app);
414
-	}
415
-
416
-	/**
417
-	 * This function set an app as disabled in appconfig.
418
-	 *
419
-	 * @param string $app app
420
-	 * @throws Exception
421
-	 */
422
-	public static function disable($app) {
423
-		// flush
424
-		self::$enabledAppsCache = array();
425
-
426
-		// run uninstall steps
427
-		$appData = OC_App::getAppInfo($app);
428
-		if (!is_null($appData)) {
429
-			OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
430
-		}
431
-
432
-		// emit disable hook - needed anymore ?
433
-		\OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
434
-
435
-		// finally disable it
436
-		$appManager = \OC::$server->getAppManager();
437
-		$appManager->disableApp($app);
438
-	}
439
-
440
-	// This is private as well. It simply works, so don't ask for more details
441
-	private static function proceedNavigation($list) {
442
-		usort($list, function($a, $b) {
443
-			if (isset($a['order']) && isset($b['order'])) {
444
-				return ($a['order'] < $b['order']) ? -1 : 1;
445
-			} else if (isset($a['order']) || isset($b['order'])) {
446
-				return isset($a['order']) ? -1 : 1;
447
-			} else {
448
-				return ($a['name'] < $b['name']) ? -1 : 1;
449
-			}
450
-		});
451
-
452
-		$activeApp = OC::$server->getNavigationManager()->getActiveEntry();
453
-		foreach ($list as $index => &$navEntry) {
454
-			if ($navEntry['id'] == $activeApp) {
455
-				$navEntry['active'] = true;
456
-			} else {
457
-				$navEntry['active'] = false;
458
-			}
459
-		}
460
-		unset($navEntry);
461
-
462
-		return $list;
463
-	}
464
-
465
-	/**
466
-	 * Get the path where to install apps
467
-	 *
468
-	 * @return string|false
469
-	 */
470
-	public static function getInstallPath() {
471
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
472
-			return false;
473
-		}
474
-
475
-		foreach (OC::$APPSROOTS as $dir) {
476
-			if (isset($dir['writable']) && $dir['writable'] === true) {
477
-				return $dir['path'];
478
-			}
479
-		}
480
-
481
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
482
-		return null;
483
-	}
484
-
485
-
486
-	/**
487
-	 * search for an app in all app-directories
488
-	 *
489
-	 * @param string $appId
490
-	 * @return false|string
491
-	 */
492
-	public static function findAppInDirectories($appId) {
493
-		$sanitizedAppId = self::cleanAppId($appId);
494
-		if($sanitizedAppId !== $appId) {
495
-			return false;
496
-		}
497
-		static $app_dir = array();
498
-
499
-		if (isset($app_dir[$appId])) {
500
-			return $app_dir[$appId];
501
-		}
502
-
503
-		$possibleApps = array();
504
-		foreach (OC::$APPSROOTS as $dir) {
505
-			if (file_exists($dir['path'] . '/' . $appId)) {
506
-				$possibleApps[] = $dir;
507
-			}
508
-		}
509
-
510
-		if (empty($possibleApps)) {
511
-			return false;
512
-		} elseif (count($possibleApps) === 1) {
513
-			$dir = array_shift($possibleApps);
514
-			$app_dir[$appId] = $dir;
515
-			return $dir;
516
-		} else {
517
-			$versionToLoad = array();
518
-			foreach ($possibleApps as $possibleApp) {
519
-				$version = self::getAppVersionByPath($possibleApp['path']);
520
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
521
-					$versionToLoad = array(
522
-						'dir' => $possibleApp,
523
-						'version' => $version,
524
-					);
525
-				}
526
-			}
527
-			$app_dir[$appId] = $versionToLoad['dir'];
528
-			return $versionToLoad['dir'];
529
-			//TODO - write test
530
-		}
531
-	}
532
-
533
-	/**
534
-	 * Get the directory for the given app.
535
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
536
-	 *
537
-	 * @param string $appId
538
-	 * @return string|false
539
-	 */
540
-	public static function getAppPath($appId) {
541
-		if ($appId === null || trim($appId) === '') {
542
-			return false;
543
-		}
544
-
545
-		if (($dir = self::findAppInDirectories($appId)) != false) {
546
-			return $dir['path'] . '/' . $appId;
547
-		}
548
-		return false;
549
-	}
550
-
551
-	/**
552
-	 * Get the path for the given app on the access
553
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
554
-	 *
555
-	 * @param string $appId
556
-	 * @return string|false
557
-	 */
558
-	public static function getAppWebPath($appId) {
559
-		if (($dir = self::findAppInDirectories($appId)) != false) {
560
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
561
-		}
562
-		return false;
563
-	}
564
-
565
-	/**
566
-	 * get the last version of the app from appinfo/info.xml
567
-	 *
568
-	 * @param string $appId
569
-	 * @param bool $useCache
570
-	 * @return string
571
-	 */
572
-	public static function getAppVersion($appId, $useCache = true) {
573
-		if($useCache && isset(self::$appVersion[$appId])) {
574
-			return self::$appVersion[$appId];
575
-		}
576
-
577
-		$file = self::getAppPath($appId);
578
-		self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
579
-		return self::$appVersion[$appId];
580
-	}
581
-
582
-	/**
583
-	 * get app's version based on it's path
584
-	 *
585
-	 * @param string $path
586
-	 * @return string
587
-	 */
588
-	public static function getAppVersionByPath($path) {
589
-		$infoFile = $path . '/appinfo/info.xml';
590
-		$appData = self::getAppInfo($infoFile, true);
591
-		return isset($appData['version']) ? $appData['version'] : '';
592
-	}
593
-
594
-
595
-	/**
596
-	 * Read all app metadata from the info.xml file
597
-	 *
598
-	 * @param string $appId id of the app or the path of the info.xml file
599
-	 * @param bool $path
600
-	 * @param string $lang
601
-	 * @return array|null
602
-	 * @note all data is read from info.xml, not just pre-defined fields
603
-	 */
604
-	public static function getAppInfo($appId, $path = false, $lang = null) {
605
-		if ($path) {
606
-			$file = $appId;
607
-		} else {
608
-			if ($lang === null && isset(self::$appInfo[$appId])) {
609
-				return self::$appInfo[$appId];
610
-			}
611
-			$appPath = self::getAppPath($appId);
612
-			if($appPath === false) {
613
-				return null;
614
-			}
615
-			$file = $appPath . '/appinfo/info.xml';
616
-		}
617
-
618
-		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->createLocal('core.appinfo'));
619
-		$data = $parser->parse($file);
620
-
621
-		if (is_array($data)) {
622
-			$data = OC_App::parseAppInfo($data, $lang);
623
-		}
624
-		if(isset($data['ocsid'])) {
625
-			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
626
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
627
-				$data['ocsid'] = $storedId;
628
-			}
629
-		}
630
-
631
-		if ($lang === null) {
632
-			self::$appInfo[$appId] = $data;
633
-		}
634
-
635
-		return $data;
636
-	}
637
-
638
-	/**
639
-	 * Returns the navigation
640
-	 *
641
-	 * @return array
642
-	 *
643
-	 * This function returns an array containing all entries added. The
644
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
645
-	 * given for each app the following keys exist:
646
-	 *   - active: boolean, signals if the user is on this navigation entry
647
-	 */
648
-	public static function getNavigation() {
649
-		$entries = OC::$server->getNavigationManager()->getAll();
650
-		return self::proceedNavigation($entries);
651
-	}
652
-
653
-	/**
654
-	 * Returns the Settings Navigation
655
-	 *
656
-	 * @return string[]
657
-	 *
658
-	 * This function returns an array containing all settings pages added. The
659
-	 * entries are sorted by the key 'order' ascending.
660
-	 */
661
-	public static function getSettingsNavigation() {
662
-		$entries = OC::$server->getNavigationManager()->getAll('settings');
663
-		return self::proceedNavigation($entries);
664
-	}
665
-
666
-	/**
667
-	 * get the id of loaded app
668
-	 *
669
-	 * @return string
670
-	 */
671
-	public static function getCurrentApp() {
672
-		$request = \OC::$server->getRequest();
673
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
674
-		$topFolder = substr($script, 0, strpos($script, '/'));
675
-		if (empty($topFolder)) {
676
-			$path_info = $request->getPathInfo();
677
-			if ($path_info) {
678
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
679
-			}
680
-		}
681
-		if ($topFolder == 'apps') {
682
-			$length = strlen($topFolder);
683
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
684
-		} else {
685
-			return $topFolder;
686
-		}
687
-	}
688
-
689
-	/**
690
-	 * @param string $type
691
-	 * @return array
692
-	 */
693
-	public static function getForms($type) {
694
-		$forms = array();
695
-		switch ($type) {
696
-			case 'admin':
697
-				$source = self::$adminForms;
698
-				break;
699
-			case 'personal':
700
-				$source = self::$personalForms;
701
-				break;
702
-			default:
703
-				return array();
704
-		}
705
-		foreach ($source as $form) {
706
-			$forms[] = include $form;
707
-		}
708
-		return $forms;
709
-	}
710
-
711
-	/**
712
-	 * register an admin form to be shown
713
-	 *
714
-	 * @param string $app
715
-	 * @param string $page
716
-	 */
717
-	public static function registerAdmin($app, $page) {
718
-		self::$adminForms[] = $app . '/' . $page . '.php';
719
-	}
720
-
721
-	/**
722
-	 * register a personal form to be shown
723
-	 * @param string $app
724
-	 * @param string $page
725
-	 */
726
-	public static function registerPersonal($app, $page) {
727
-		self::$personalForms[] = $app . '/' . $page . '.php';
728
-	}
729
-
730
-	/**
731
-	 * @param array $entry
732
-	 */
733
-	public static function registerLogIn(array $entry) {
734
-		self::$altLogin[] = $entry;
735
-	}
736
-
737
-	/**
738
-	 * @return array
739
-	 */
740
-	public static function getAlternativeLogIns() {
741
-		return self::$altLogin;
742
-	}
743
-
744
-	/**
745
-	 * get a list of all apps in the apps folder
746
-	 *
747
-	 * @return array an array of app names (string IDs)
748
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
749
-	 */
750
-	public static function getAllApps() {
751
-
752
-		$apps = array();
753
-
754
-		foreach (OC::$APPSROOTS as $apps_dir) {
755
-			if (!is_readable($apps_dir['path'])) {
756
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
757
-				continue;
758
-			}
759
-			$dh = opendir($apps_dir['path']);
760
-
761
-			if (is_resource($dh)) {
762
-				while (($file = readdir($dh)) !== false) {
763
-
764
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
765
-
766
-						$apps[] = $file;
767
-					}
768
-				}
769
-			}
770
-		}
771
-
772
-		$apps = array_unique($apps);
773
-
774
-		return $apps;
775
-	}
776
-
777
-	/**
778
-	 * List all apps, this is used in apps.php
779
-	 *
780
-	 * @return array
781
-	 */
782
-	public function listAllApps() {
783
-		$installedApps = OC_App::getAllApps();
784
-
785
-		$appManager = \OC::$server->getAppManager();
786
-		//we don't want to show configuration for these
787
-		$blacklist = $appManager->getAlwaysEnabledApps();
788
-		$appList = array();
789
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
790
-		$urlGenerator = \OC::$server->getURLGenerator();
791
-
792
-		foreach ($installedApps as $app) {
793
-			if (array_search($app, $blacklist) === false) {
794
-
795
-				$info = OC_App::getAppInfo($app, false, $langCode);
796
-				if (!is_array($info)) {
797
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
798
-					continue;
799
-				}
800
-
801
-				if (!isset($info['name'])) {
802
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
803
-					continue;
804
-				}
805
-
806
-				$enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
807
-				$info['groups'] = null;
808
-				if ($enabled === 'yes') {
809
-					$active = true;
810
-				} else if ($enabled === 'no') {
811
-					$active = false;
812
-				} else {
813
-					$active = true;
814
-					$info['groups'] = $enabled;
815
-				}
816
-
817
-				$info['active'] = $active;
818
-
819
-				if ($appManager->isShipped($app)) {
820
-					$info['internal'] = true;
821
-					$info['level'] = self::officialApp;
822
-					$info['removable'] = false;
823
-				} else {
824
-					$info['internal'] = false;
825
-					$info['removable'] = true;
826
-				}
827
-
828
-				$appPath = self::getAppPath($app);
829
-				if($appPath !== false) {
830
-					$appIcon = $appPath . '/img/' . $app . '.svg';
831
-					if (file_exists($appIcon)) {
832
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
833
-						$info['previewAsIcon'] = true;
834
-					} else {
835
-						$appIcon = $appPath . '/img/app.svg';
836
-						if (file_exists($appIcon)) {
837
-							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
838
-							$info['previewAsIcon'] = true;
839
-						}
840
-					}
841
-				}
842
-				// fix documentation
843
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
844
-					foreach ($info['documentation'] as $key => $url) {
845
-						// If it is not an absolute URL we assume it is a key
846
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
847
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
848
-							$url = $urlGenerator->linkToDocs($url);
849
-						}
850
-
851
-						$info['documentation'][$key] = $url;
852
-					}
853
-				}
854
-
855
-				$info['version'] = OC_App::getAppVersion($app);
856
-				$appList[] = $info;
857
-			}
858
-		}
859
-
860
-		return $appList;
861
-	}
862
-
863
-	public static function shouldUpgrade($app) {
864
-		$versions = self::getAppVersions();
865
-		$currentVersion = OC_App::getAppVersion($app);
866
-		if ($currentVersion && isset($versions[$app])) {
867
-			$installedVersion = $versions[$app];
868
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
869
-				return true;
870
-			}
871
-		}
872
-		return false;
873
-	}
874
-
875
-	/**
876
-	 * Adjust the number of version parts of $version1 to match
877
-	 * the number of version parts of $version2.
878
-	 *
879
-	 * @param string $version1 version to adjust
880
-	 * @param string $version2 version to take the number of parts from
881
-	 * @return string shortened $version1
882
-	 */
883
-	private static function adjustVersionParts($version1, $version2) {
884
-		$version1 = explode('.', $version1);
885
-		$version2 = explode('.', $version2);
886
-		// reduce $version1 to match the number of parts in $version2
887
-		while (count($version1) > count($version2)) {
888
-			array_pop($version1);
889
-		}
890
-		// if $version1 does not have enough parts, add some
891
-		while (count($version1) < count($version2)) {
892
-			$version1[] = '0';
893
-		}
894
-		return implode('.', $version1);
895
-	}
896
-
897
-	/**
898
-	 * Check whether the current ownCloud version matches the given
899
-	 * application's version requirements.
900
-	 *
901
-	 * The comparison is made based on the number of parts that the
902
-	 * app info version has. For example for ownCloud 6.0.3 if the
903
-	 * app info version is expecting version 6.0, the comparison is
904
-	 * made on the first two parts of the ownCloud version.
905
-	 * This means that it's possible to specify "requiremin" => 6
906
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
907
-	 *
908
-	 * @param string $ocVersion ownCloud version to check against
909
-	 * @param array $appInfo app info (from xml)
910
-	 *
911
-	 * @return boolean true if compatible, otherwise false
912
-	 */
913
-	public static function isAppCompatible($ocVersion, $appInfo) {
914
-		$requireMin = '';
915
-		$requireMax = '';
916
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
917
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
918
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
919
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
920
-		} else if (isset($appInfo['requiremin'])) {
921
-			$requireMin = $appInfo['requiremin'];
922
-		} else if (isset($appInfo['require'])) {
923
-			$requireMin = $appInfo['require'];
924
-		}
925
-
926
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
927
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
928
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
929
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
930
-		} else if (isset($appInfo['requiremax'])) {
931
-			$requireMax = $appInfo['requiremax'];
932
-		}
933
-
934
-		if (is_array($ocVersion)) {
935
-			$ocVersion = implode('.', $ocVersion);
936
-		}
937
-
938
-		if (!empty($requireMin)
939
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
940
-		) {
941
-
942
-			return false;
943
-		}
944
-
945
-		if (!empty($requireMax)
946
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
947
-		) {
948
-			return false;
949
-		}
950
-
951
-		return true;
952
-	}
953
-
954
-	/**
955
-	 * get the installed version of all apps
956
-	 */
957
-	public static function getAppVersions() {
958
-		static $versions;
959
-
960
-		if(!$versions) {
961
-			$appConfig = \OC::$server->getAppConfig();
962
-			$versions = $appConfig->getValues(false, 'installed_version');
963
-		}
964
-		return $versions;
965
-	}
966
-
967
-	/**
968
-	 * @param string $app
969
-	 * @param \OCP\IConfig $config
970
-	 * @param \OCP\IL10N $l
971
-	 * @return bool
972
-	 *
973
-	 * @throws Exception if app is not compatible with this version of ownCloud
974
-	 * @throws Exception if no app-name was specified
975
-	 */
976
-	public function installApp($app,
977
-							   \OCP\IConfig $config,
978
-							   \OCP\IL10N $l) {
979
-		if ($app !== false) {
980
-			// check if the app is compatible with this version of ownCloud
981
-			$info = self::getAppInfo($app);
982
-			if(!is_array($info)) {
983
-				throw new \Exception(
984
-					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
985
-						[$info['name']]
986
-					)
987
-				);
988
-			}
989
-
990
-			$version = \OCP\Util::getVersion();
991
-			if (!self::isAppCompatible($version, $info)) {
992
-				throw new \Exception(
993
-					$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
994
-						array($info['name'])
995
-					)
996
-				);
997
-			}
998
-
999
-			// check for required dependencies
1000
-			self::checkAppDependencies($config, $l, $info);
1001
-
1002
-			$config->setAppValue($app, 'enabled', 'yes');
1003
-			if (isset($appData['id'])) {
1004
-				$config->setAppValue($app, 'ocsid', $appData['id']);
1005
-			}
1006
-
1007
-			if(isset($info['settings']) && is_array($info['settings'])) {
1008
-				$appPath = self::getAppPath($app);
1009
-				self::registerAutoloading($app, $appPath);
1010
-				\OC::$server->getSettingsManager()->setupSettings($info['settings']);
1011
-			}
1012
-
1013
-			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1014
-		} else {
1015
-			if(empty($appName) ) {
1016
-				throw new \Exception($l->t("No app name specified"));
1017
-			} else {
1018
-				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1019
-			}
1020
-		}
1021
-
1022
-		return $app;
1023
-	}
1024
-
1025
-	/**
1026
-	 * update the database for the app and call the update script
1027
-	 *
1028
-	 * @param string $appId
1029
-	 * @return bool
1030
-	 */
1031
-	public static function updateApp($appId) {
1032
-		$appPath = self::getAppPath($appId);
1033
-		if($appPath === false) {
1034
-			return false;
1035
-		}
1036
-		self::registerAutoloading($appId, $appPath);
1037
-
1038
-		$appData = self::getAppInfo($appId);
1039
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1040
-
1041
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1042
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1043
-		} else {
1044
-			$ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
1045
-			$ms->migrate();
1046
-		}
1047
-
1048
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1049
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1050
-		unset(self::$appVersion[$appId]);
1051
-
1052
-		// run upgrade code
1053
-		if (file_exists($appPath . '/appinfo/update.php')) {
1054
-			self::loadApp($appId);
1055
-			include $appPath . '/appinfo/update.php';
1056
-		}
1057
-		self::setupBackgroundJobs($appData['background-jobs']);
1058
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
1059
-			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1060
-		}
1061
-
1062
-		//set remote/public handlers
1063
-		if (array_key_exists('ocsid', $appData)) {
1064
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1065
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1066
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1067
-		}
1068
-		foreach ($appData['remote'] as $name => $path) {
1069
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1070
-		}
1071
-		foreach ($appData['public'] as $name => $path) {
1072
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1073
-		}
1074
-
1075
-		self::setAppTypes($appId);
1076
-
1077
-		$version = \OC_App::getAppVersion($appId);
1078
-		\OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1079
-
1080
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1081
-			ManagerEvent::EVENT_APP_UPDATE, $appId
1082
-		));
1083
-
1084
-		return true;
1085
-	}
1086
-
1087
-	/**
1088
-	 * @param string $appId
1089
-	 * @param string[] $steps
1090
-	 * @throws \OC\NeedsUpdateException
1091
-	 */
1092
-	public static function executeRepairSteps($appId, array $steps) {
1093
-		if (empty($steps)) {
1094
-			return;
1095
-		}
1096
-		// load the app
1097
-		self::loadApp($appId);
1098
-
1099
-		$dispatcher = OC::$server->getEventDispatcher();
1100
-
1101
-		// load the steps
1102
-		$r = new Repair([], $dispatcher);
1103
-		foreach ($steps as $step) {
1104
-			try {
1105
-				$r->addStep($step);
1106
-			} catch (Exception $ex) {
1107
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1108
-				\OC::$server->getLogger()->logException($ex);
1109
-			}
1110
-		}
1111
-		// run the steps
1112
-		$r->run();
1113
-	}
1114
-
1115
-	public static function setupBackgroundJobs(array $jobs) {
1116
-		$queue = \OC::$server->getJobList();
1117
-		foreach ($jobs as $job) {
1118
-			$queue->add($job);
1119
-		}
1120
-	}
1121
-
1122
-	/**
1123
-	 * @param string $appId
1124
-	 * @param string[] $steps
1125
-	 */
1126
-	private static function setupLiveMigrations($appId, array $steps) {
1127
-		$queue = \OC::$server->getJobList();
1128
-		foreach ($steps as $step) {
1129
-			$queue->add('OC\Migration\BackgroundRepair', [
1130
-				'app' => $appId,
1131
-				'step' => $step]);
1132
-		}
1133
-	}
1134
-
1135
-	/**
1136
-	 * @param string $appId
1137
-	 * @return \OC\Files\View|false
1138
-	 */
1139
-	public static function getStorage($appId) {
1140
-		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1141
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1142
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1143
-				if (!$view->file_exists($appId)) {
1144
-					$view->mkdir($appId);
1145
-				}
1146
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1147
-			} else {
1148
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1149
-				return false;
1150
-			}
1151
-		} else {
1152
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1153
-			return false;
1154
-		}
1155
-	}
1156
-
1157
-	protected static function findBestL10NOption($options, $lang) {
1158
-		$fallback = $similarLangFallback = $englishFallback = false;
1159
-
1160
-		$lang = strtolower($lang);
1161
-		$similarLang = $lang;
1162
-		if (strpos($similarLang, '_')) {
1163
-			// For "de_DE" we want to find "de" and the other way around
1164
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1165
-		}
1166
-
1167
-		foreach ($options as $option) {
1168
-			if (is_array($option)) {
1169
-				if ($fallback === false) {
1170
-					$fallback = $option['@value'];
1171
-				}
1172
-
1173
-				if (!isset($option['@attributes']['lang'])) {
1174
-					continue;
1175
-				}
1176
-
1177
-				$attributeLang = strtolower($option['@attributes']['lang']);
1178
-				if ($attributeLang === $lang) {
1179
-					return $option['@value'];
1180
-				}
1181
-
1182
-				if ($attributeLang === $similarLang) {
1183
-					$similarLangFallback = $option['@value'];
1184
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1185
-					if ($similarLangFallback === false) {
1186
-						$similarLangFallback =  $option['@value'];
1187
-					}
1188
-				}
1189
-			} else {
1190
-				$englishFallback = $option;
1191
-			}
1192
-		}
1193
-
1194
-		if ($similarLangFallback !== false) {
1195
-			return $similarLangFallback;
1196
-		} else if ($englishFallback !== false) {
1197
-			return $englishFallback;
1198
-		}
1199
-		return (string) $fallback;
1200
-	}
1201
-
1202
-	/**
1203
-	 * parses the app data array and enhanced the 'description' value
1204
-	 *
1205
-	 * @param array $data the app data
1206
-	 * @param string $lang
1207
-	 * @return array improved app data
1208
-	 */
1209
-	public static function parseAppInfo(array $data, $lang = null) {
1210
-
1211
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1212
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1213
-		}
1214
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1215
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1216
-		}
1217
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1218
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1219
-		} else if (isset($data['description']) && is_string($data['description'])) {
1220
-			$data['description'] = trim($data['description']);
1221
-		} else  {
1222
-			$data['description'] = '';
1223
-		}
1224
-
1225
-		return $data;
1226
-	}
1227
-
1228
-	/**
1229
-	 * @param \OCP\IConfig $config
1230
-	 * @param \OCP\IL10N $l
1231
-	 * @param array $info
1232
-	 * @throws \Exception
1233
-	 */
1234
-	public static function checkAppDependencies($config, $l, $info) {
1235
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1236
-		$missing = $dependencyAnalyzer->analyze($info);
1237
-		if (!empty($missing)) {
1238
-			$missingMsg = implode(PHP_EOL, $missing);
1239
-			throw new \Exception(
1240
-				$l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1241
-					[$info['name'], $missingMsg]
1242
-				)
1243
-			);
1244
-		}
1245
-	}
66
+    static private $appVersion = [];
67
+    static private $adminForms = array();
68
+    static private $personalForms = array();
69
+    static private $appInfo = array();
70
+    static private $appTypes = array();
71
+    static private $loadedApps = array();
72
+    static private $altLogin = array();
73
+    static private $alreadyRegistered = [];
74
+    const officialApp = 200;
75
+
76
+    /**
77
+     * clean the appId
78
+     *
79
+     * @param string|boolean $app AppId that needs to be cleaned
80
+     * @return string
81
+     */
82
+    public static function cleanAppId($app) {
83
+        return str_replace(array('\0', '/', '\\', '..'), '', $app);
84
+    }
85
+
86
+    /**
87
+     * Check if an app is loaded
88
+     *
89
+     * @param string $app
90
+     * @return bool
91
+     */
92
+    public static function isAppLoaded($app) {
93
+        return in_array($app, self::$loadedApps, true);
94
+    }
95
+
96
+    /**
97
+     * loads all apps
98
+     *
99
+     * @param string[] | string | null $types
100
+     * @return bool
101
+     *
102
+     * This function walks through the ownCloud directory and loads all apps
103
+     * it can find. A directory contains an app if the file /appinfo/info.xml
104
+     * exists.
105
+     *
106
+     * if $types is set, only apps of those types will be loaded
107
+     */
108
+    public static function loadApps($types = null) {
109
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
110
+            return false;
111
+        }
112
+        // Load the enabled apps here
113
+        $apps = self::getEnabledApps();
114
+
115
+        // Add each apps' folder as allowed class path
116
+        foreach($apps as $app) {
117
+            $path = self::getAppPath($app);
118
+            if($path !== false) {
119
+                self::registerAutoloading($app, $path);
120
+            }
121
+        }
122
+
123
+        // prevent app.php from printing output
124
+        ob_start();
125
+        foreach ($apps as $app) {
126
+            if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
127
+                self::loadApp($app);
128
+            }
129
+        }
130
+        ob_end_clean();
131
+
132
+        return true;
133
+    }
134
+
135
+    /**
136
+     * load a single app
137
+     *
138
+     * @param string $app
139
+     */
140
+    public static function loadApp($app) {
141
+        self::$loadedApps[] = $app;
142
+        $appPath = self::getAppPath($app);
143
+        if($appPath === false) {
144
+            return;
145
+        }
146
+
147
+        // in case someone calls loadApp() directly
148
+        self::registerAutoloading($app, $appPath);
149
+
150
+        if (is_file($appPath . '/appinfo/app.php')) {
151
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
152
+            self::requireAppFile($app);
153
+            if (self::isType($app, array('authentication'))) {
154
+                // since authentication apps affect the "is app enabled for group" check,
155
+                // the enabled apps cache needs to be cleared to make sure that the
156
+                // next time getEnableApps() is called it will also include apps that were
157
+                // enabled for groups
158
+                self::$enabledAppsCache = array();
159
+            }
160
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
161
+        }
162
+
163
+        $info = self::getAppInfo($app);
164
+        if (!empty($info['activity']['filters'])) {
165
+            foreach ($info['activity']['filters'] as $filter) {
166
+                \OC::$server->getActivityManager()->registerFilter($filter);
167
+            }
168
+        }
169
+        if (!empty($info['activity']['settings'])) {
170
+            foreach ($info['activity']['settings'] as $setting) {
171
+                \OC::$server->getActivityManager()->registerSetting($setting);
172
+            }
173
+        }
174
+        if (!empty($info['activity']['providers'])) {
175
+            foreach ($info['activity']['providers'] as $provider) {
176
+                \OC::$server->getActivityManager()->registerProvider($provider);
177
+            }
178
+        }
179
+        if (!empty($info['collaboration']['plugins'])) {
180
+            // deal with one or many plugin entries
181
+            $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
182
+                [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
183
+            foreach ($plugins as $plugin) {
184
+                if($plugin['@attributes']['type'] === 'collaborator-search') {
185
+                    $pluginInfo = [
186
+                        'shareType' => $plugin['@attributes']['share-type'],
187
+                        'class' => $plugin['@value'],
188
+                    ];
189
+                    \OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
190
+                } else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
191
+                    \OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
192
+                }
193
+            }
194
+        }
195
+    }
196
+
197
+    /**
198
+     * @internal
199
+     * @param string $app
200
+     * @param string $path
201
+     */
202
+    public static function registerAutoloading($app, $path) {
203
+        $key = $app . '-' . $path;
204
+        if(isset(self::$alreadyRegistered[$key])) {
205
+            return;
206
+        }
207
+
208
+        self::$alreadyRegistered[$key] = true;
209
+
210
+        // Register on PSR-4 composer autoloader
211
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
212
+        \OC::$server->registerNamespace($app, $appNamespace);
213
+
214
+        if (file_exists($path . '/composer/autoload.php')) {
215
+            require_once $path . '/composer/autoload.php';
216
+        } else {
217
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
218
+            // Register on legacy autoloader
219
+            \OC::$loader->addValidRoot($path);
220
+        }
221
+
222
+        // Register Test namespace only when testing
223
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
224
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
225
+        }
226
+    }
227
+
228
+    /**
229
+     * Load app.php from the given app
230
+     *
231
+     * @param string $app app name
232
+     */
233
+    private static function requireAppFile($app) {
234
+        try {
235
+            // encapsulated here to avoid variable scope conflicts
236
+            require_once $app . '/appinfo/app.php';
237
+        } catch (Error $ex) {
238
+            \OC::$server->getLogger()->logException($ex);
239
+            $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
240
+            if (!in_array($app, $blacklist)) {
241
+                self::disable($app);
242
+            }
243
+        }
244
+    }
245
+
246
+    /**
247
+     * check if an app is of a specific type
248
+     *
249
+     * @param string $app
250
+     * @param string|array $types
251
+     * @return bool
252
+     */
253
+    public static function isType($app, $types) {
254
+        if (is_string($types)) {
255
+            $types = array($types);
256
+        }
257
+        $appTypes = self::getAppTypes($app);
258
+        foreach ($types as $type) {
259
+            if (array_search($type, $appTypes) !== false) {
260
+                return true;
261
+            }
262
+        }
263
+        return false;
264
+    }
265
+
266
+    /**
267
+     * get the types of an app
268
+     *
269
+     * @param string $app
270
+     * @return array
271
+     */
272
+    private static function getAppTypes($app) {
273
+        //load the cache
274
+        if (count(self::$appTypes) == 0) {
275
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
276
+        }
277
+
278
+        if (isset(self::$appTypes[$app])) {
279
+            return explode(',', self::$appTypes[$app]);
280
+        } else {
281
+            return array();
282
+        }
283
+    }
284
+
285
+    /**
286
+     * read app types from info.xml and cache them in the database
287
+     */
288
+    public static function setAppTypes($app) {
289
+        $appData = self::getAppInfo($app);
290
+        if(!is_array($appData)) {
291
+            return;
292
+        }
293
+
294
+        if (isset($appData['types'])) {
295
+            $appTypes = implode(',', $appData['types']);
296
+        } else {
297
+            $appTypes = '';
298
+            $appData['types'] = [];
299
+        }
300
+
301
+        \OC::$server->getAppConfig()->setValue($app, 'types', $appTypes);
302
+
303
+        if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
304
+            $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes');
305
+            if ($enabled !== 'yes' && $enabled !== 'no') {
306
+                \OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes');
307
+            }
308
+        }
309
+    }
310
+
311
+    /**
312
+     * get all enabled apps
313
+     */
314
+    protected static $enabledAppsCache = array();
315
+
316
+    /**
317
+     * Returns apps enabled for the current user.
318
+     *
319
+     * @param bool $forceRefresh whether to refresh the cache
320
+     * @param bool $all whether to return apps for all users, not only the
321
+     * currently logged in one
322
+     * @return string[]
323
+     */
324
+    public static function getEnabledApps($forceRefresh = false, $all = false) {
325
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
326
+            return array();
327
+        }
328
+        // in incognito mode or when logged out, $user will be false,
329
+        // which is also the case during an upgrade
330
+        $appManager = \OC::$server->getAppManager();
331
+        if ($all) {
332
+            $user = null;
333
+        } else {
334
+            $user = \OC::$server->getUserSession()->getUser();
335
+        }
336
+
337
+        if (is_null($user)) {
338
+            $apps = $appManager->getInstalledApps();
339
+        } else {
340
+            $apps = $appManager->getEnabledAppsForUser($user);
341
+        }
342
+        $apps = array_filter($apps, function ($app) {
343
+            return $app !== 'files';//we add this manually
344
+        });
345
+        sort($apps);
346
+        array_unshift($apps, 'files');
347
+        return $apps;
348
+    }
349
+
350
+    /**
351
+     * checks whether or not an app is enabled
352
+     *
353
+     * @param string $app app
354
+     * @return bool
355
+     * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
356
+     *
357
+     * This function checks whether or not an app is enabled.
358
+     */
359
+    public static function isEnabled($app) {
360
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
361
+    }
362
+
363
+    /**
364
+     * enables an app
365
+     *
366
+     * @param string $appId
367
+     * @param array $groups (optional) when set, only these groups will have access to the app
368
+     * @throws \Exception
369
+     * @return void
370
+     *
371
+     * This function set an app as enabled in appconfig.
372
+     */
373
+    public function enable($appId,
374
+                            $groups = null) {
375
+        self::$enabledAppsCache = []; // flush
376
+
377
+        // Check if app is already downloaded
378
+        $installer = \OC::$server->query(Installer::class);
379
+        $isDownloaded = $installer->isDownloaded($appId);
380
+
381
+        if(!$isDownloaded) {
382
+            $installer->downloadApp($appId);
383
+        }
384
+
385
+        $installer->installApp($appId);
386
+
387
+        $appManager = \OC::$server->getAppManager();
388
+        if (!is_null($groups)) {
389
+            $groupManager = \OC::$server->getGroupManager();
390
+            $groupsList = [];
391
+            foreach ($groups as $group) {
392
+                $groupItem = $groupManager->get($group);
393
+                if ($groupItem instanceof \OCP\IGroup) {
394
+                    $groupsList[] = $groupManager->get($group);
395
+                }
396
+            }
397
+            $appManager->enableAppForGroups($appId, $groupsList);
398
+        } else {
399
+            $appManager->enableApp($appId);
400
+        }
401
+    }
402
+
403
+    /**
404
+     * @param string $app
405
+     * @return bool
406
+     */
407
+    public static function removeApp($app) {
408
+        if (\OC::$server->getAppManager()->isShipped($app)) {
409
+            return false;
410
+        }
411
+
412
+        $installer = \OC::$server->query(Installer::class);
413
+        return $installer->removeApp($app);
414
+    }
415
+
416
+    /**
417
+     * This function set an app as disabled in appconfig.
418
+     *
419
+     * @param string $app app
420
+     * @throws Exception
421
+     */
422
+    public static function disable($app) {
423
+        // flush
424
+        self::$enabledAppsCache = array();
425
+
426
+        // run uninstall steps
427
+        $appData = OC_App::getAppInfo($app);
428
+        if (!is_null($appData)) {
429
+            OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
430
+        }
431
+
432
+        // emit disable hook - needed anymore ?
433
+        \OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
434
+
435
+        // finally disable it
436
+        $appManager = \OC::$server->getAppManager();
437
+        $appManager->disableApp($app);
438
+    }
439
+
440
+    // This is private as well. It simply works, so don't ask for more details
441
+    private static function proceedNavigation($list) {
442
+        usort($list, function($a, $b) {
443
+            if (isset($a['order']) && isset($b['order'])) {
444
+                return ($a['order'] < $b['order']) ? -1 : 1;
445
+            } else if (isset($a['order']) || isset($b['order'])) {
446
+                return isset($a['order']) ? -1 : 1;
447
+            } else {
448
+                return ($a['name'] < $b['name']) ? -1 : 1;
449
+            }
450
+        });
451
+
452
+        $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
453
+        foreach ($list as $index => &$navEntry) {
454
+            if ($navEntry['id'] == $activeApp) {
455
+                $navEntry['active'] = true;
456
+            } else {
457
+                $navEntry['active'] = false;
458
+            }
459
+        }
460
+        unset($navEntry);
461
+
462
+        return $list;
463
+    }
464
+
465
+    /**
466
+     * Get the path where to install apps
467
+     *
468
+     * @return string|false
469
+     */
470
+    public static function getInstallPath() {
471
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
472
+            return false;
473
+        }
474
+
475
+        foreach (OC::$APPSROOTS as $dir) {
476
+            if (isset($dir['writable']) && $dir['writable'] === true) {
477
+                return $dir['path'];
478
+            }
479
+        }
480
+
481
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
482
+        return null;
483
+    }
484
+
485
+
486
+    /**
487
+     * search for an app in all app-directories
488
+     *
489
+     * @param string $appId
490
+     * @return false|string
491
+     */
492
+    public static function findAppInDirectories($appId) {
493
+        $sanitizedAppId = self::cleanAppId($appId);
494
+        if($sanitizedAppId !== $appId) {
495
+            return false;
496
+        }
497
+        static $app_dir = array();
498
+
499
+        if (isset($app_dir[$appId])) {
500
+            return $app_dir[$appId];
501
+        }
502
+
503
+        $possibleApps = array();
504
+        foreach (OC::$APPSROOTS as $dir) {
505
+            if (file_exists($dir['path'] . '/' . $appId)) {
506
+                $possibleApps[] = $dir;
507
+            }
508
+        }
509
+
510
+        if (empty($possibleApps)) {
511
+            return false;
512
+        } elseif (count($possibleApps) === 1) {
513
+            $dir = array_shift($possibleApps);
514
+            $app_dir[$appId] = $dir;
515
+            return $dir;
516
+        } else {
517
+            $versionToLoad = array();
518
+            foreach ($possibleApps as $possibleApp) {
519
+                $version = self::getAppVersionByPath($possibleApp['path']);
520
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
521
+                    $versionToLoad = array(
522
+                        'dir' => $possibleApp,
523
+                        'version' => $version,
524
+                    );
525
+                }
526
+            }
527
+            $app_dir[$appId] = $versionToLoad['dir'];
528
+            return $versionToLoad['dir'];
529
+            //TODO - write test
530
+        }
531
+    }
532
+
533
+    /**
534
+     * Get the directory for the given app.
535
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
536
+     *
537
+     * @param string $appId
538
+     * @return string|false
539
+     */
540
+    public static function getAppPath($appId) {
541
+        if ($appId === null || trim($appId) === '') {
542
+            return false;
543
+        }
544
+
545
+        if (($dir = self::findAppInDirectories($appId)) != false) {
546
+            return $dir['path'] . '/' . $appId;
547
+        }
548
+        return false;
549
+    }
550
+
551
+    /**
552
+     * Get the path for the given app on the access
553
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
554
+     *
555
+     * @param string $appId
556
+     * @return string|false
557
+     */
558
+    public static function getAppWebPath($appId) {
559
+        if (($dir = self::findAppInDirectories($appId)) != false) {
560
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
561
+        }
562
+        return false;
563
+    }
564
+
565
+    /**
566
+     * get the last version of the app from appinfo/info.xml
567
+     *
568
+     * @param string $appId
569
+     * @param bool $useCache
570
+     * @return string
571
+     */
572
+    public static function getAppVersion($appId, $useCache = true) {
573
+        if($useCache && isset(self::$appVersion[$appId])) {
574
+            return self::$appVersion[$appId];
575
+        }
576
+
577
+        $file = self::getAppPath($appId);
578
+        self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
579
+        return self::$appVersion[$appId];
580
+    }
581
+
582
+    /**
583
+     * get app's version based on it's path
584
+     *
585
+     * @param string $path
586
+     * @return string
587
+     */
588
+    public static function getAppVersionByPath($path) {
589
+        $infoFile = $path . '/appinfo/info.xml';
590
+        $appData = self::getAppInfo($infoFile, true);
591
+        return isset($appData['version']) ? $appData['version'] : '';
592
+    }
593
+
594
+
595
+    /**
596
+     * Read all app metadata from the info.xml file
597
+     *
598
+     * @param string $appId id of the app or the path of the info.xml file
599
+     * @param bool $path
600
+     * @param string $lang
601
+     * @return array|null
602
+     * @note all data is read from info.xml, not just pre-defined fields
603
+     */
604
+    public static function getAppInfo($appId, $path = false, $lang = null) {
605
+        if ($path) {
606
+            $file = $appId;
607
+        } else {
608
+            if ($lang === null && isset(self::$appInfo[$appId])) {
609
+                return self::$appInfo[$appId];
610
+            }
611
+            $appPath = self::getAppPath($appId);
612
+            if($appPath === false) {
613
+                return null;
614
+            }
615
+            $file = $appPath . '/appinfo/info.xml';
616
+        }
617
+
618
+        $parser = new InfoParser(\OC::$server->getMemCacheFactory()->createLocal('core.appinfo'));
619
+        $data = $parser->parse($file);
620
+
621
+        if (is_array($data)) {
622
+            $data = OC_App::parseAppInfo($data, $lang);
623
+        }
624
+        if(isset($data['ocsid'])) {
625
+            $storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
626
+            if($storedId !== '' && $storedId !== $data['ocsid']) {
627
+                $data['ocsid'] = $storedId;
628
+            }
629
+        }
630
+
631
+        if ($lang === null) {
632
+            self::$appInfo[$appId] = $data;
633
+        }
634
+
635
+        return $data;
636
+    }
637
+
638
+    /**
639
+     * Returns the navigation
640
+     *
641
+     * @return array
642
+     *
643
+     * This function returns an array containing all entries added. The
644
+     * entries are sorted by the key 'order' ascending. Additional to the keys
645
+     * given for each app the following keys exist:
646
+     *   - active: boolean, signals if the user is on this navigation entry
647
+     */
648
+    public static function getNavigation() {
649
+        $entries = OC::$server->getNavigationManager()->getAll();
650
+        return self::proceedNavigation($entries);
651
+    }
652
+
653
+    /**
654
+     * Returns the Settings Navigation
655
+     *
656
+     * @return string[]
657
+     *
658
+     * This function returns an array containing all settings pages added. The
659
+     * entries are sorted by the key 'order' ascending.
660
+     */
661
+    public static function getSettingsNavigation() {
662
+        $entries = OC::$server->getNavigationManager()->getAll('settings');
663
+        return self::proceedNavigation($entries);
664
+    }
665
+
666
+    /**
667
+     * get the id of loaded app
668
+     *
669
+     * @return string
670
+     */
671
+    public static function getCurrentApp() {
672
+        $request = \OC::$server->getRequest();
673
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
674
+        $topFolder = substr($script, 0, strpos($script, '/'));
675
+        if (empty($topFolder)) {
676
+            $path_info = $request->getPathInfo();
677
+            if ($path_info) {
678
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
679
+            }
680
+        }
681
+        if ($topFolder == 'apps') {
682
+            $length = strlen($topFolder);
683
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
684
+        } else {
685
+            return $topFolder;
686
+        }
687
+    }
688
+
689
+    /**
690
+     * @param string $type
691
+     * @return array
692
+     */
693
+    public static function getForms($type) {
694
+        $forms = array();
695
+        switch ($type) {
696
+            case 'admin':
697
+                $source = self::$adminForms;
698
+                break;
699
+            case 'personal':
700
+                $source = self::$personalForms;
701
+                break;
702
+            default:
703
+                return array();
704
+        }
705
+        foreach ($source as $form) {
706
+            $forms[] = include $form;
707
+        }
708
+        return $forms;
709
+    }
710
+
711
+    /**
712
+     * register an admin form to be shown
713
+     *
714
+     * @param string $app
715
+     * @param string $page
716
+     */
717
+    public static function registerAdmin($app, $page) {
718
+        self::$adminForms[] = $app . '/' . $page . '.php';
719
+    }
720
+
721
+    /**
722
+     * register a personal form to be shown
723
+     * @param string $app
724
+     * @param string $page
725
+     */
726
+    public static function registerPersonal($app, $page) {
727
+        self::$personalForms[] = $app . '/' . $page . '.php';
728
+    }
729
+
730
+    /**
731
+     * @param array $entry
732
+     */
733
+    public static function registerLogIn(array $entry) {
734
+        self::$altLogin[] = $entry;
735
+    }
736
+
737
+    /**
738
+     * @return array
739
+     */
740
+    public static function getAlternativeLogIns() {
741
+        return self::$altLogin;
742
+    }
743
+
744
+    /**
745
+     * get a list of all apps in the apps folder
746
+     *
747
+     * @return array an array of app names (string IDs)
748
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
749
+     */
750
+    public static function getAllApps() {
751
+
752
+        $apps = array();
753
+
754
+        foreach (OC::$APPSROOTS as $apps_dir) {
755
+            if (!is_readable($apps_dir['path'])) {
756
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
757
+                continue;
758
+            }
759
+            $dh = opendir($apps_dir['path']);
760
+
761
+            if (is_resource($dh)) {
762
+                while (($file = readdir($dh)) !== false) {
763
+
764
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
765
+
766
+                        $apps[] = $file;
767
+                    }
768
+                }
769
+            }
770
+        }
771
+
772
+        $apps = array_unique($apps);
773
+
774
+        return $apps;
775
+    }
776
+
777
+    /**
778
+     * List all apps, this is used in apps.php
779
+     *
780
+     * @return array
781
+     */
782
+    public function listAllApps() {
783
+        $installedApps = OC_App::getAllApps();
784
+
785
+        $appManager = \OC::$server->getAppManager();
786
+        //we don't want to show configuration for these
787
+        $blacklist = $appManager->getAlwaysEnabledApps();
788
+        $appList = array();
789
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
790
+        $urlGenerator = \OC::$server->getURLGenerator();
791
+
792
+        foreach ($installedApps as $app) {
793
+            if (array_search($app, $blacklist) === false) {
794
+
795
+                $info = OC_App::getAppInfo($app, false, $langCode);
796
+                if (!is_array($info)) {
797
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
798
+                    continue;
799
+                }
800
+
801
+                if (!isset($info['name'])) {
802
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
803
+                    continue;
804
+                }
805
+
806
+                $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no');
807
+                $info['groups'] = null;
808
+                if ($enabled === 'yes') {
809
+                    $active = true;
810
+                } else if ($enabled === 'no') {
811
+                    $active = false;
812
+                } else {
813
+                    $active = true;
814
+                    $info['groups'] = $enabled;
815
+                }
816
+
817
+                $info['active'] = $active;
818
+
819
+                if ($appManager->isShipped($app)) {
820
+                    $info['internal'] = true;
821
+                    $info['level'] = self::officialApp;
822
+                    $info['removable'] = false;
823
+                } else {
824
+                    $info['internal'] = false;
825
+                    $info['removable'] = true;
826
+                }
827
+
828
+                $appPath = self::getAppPath($app);
829
+                if($appPath !== false) {
830
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
831
+                    if (file_exists($appIcon)) {
832
+                        $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
833
+                        $info['previewAsIcon'] = true;
834
+                    } else {
835
+                        $appIcon = $appPath . '/img/app.svg';
836
+                        if (file_exists($appIcon)) {
837
+                            $info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
838
+                            $info['previewAsIcon'] = true;
839
+                        }
840
+                    }
841
+                }
842
+                // fix documentation
843
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
844
+                    foreach ($info['documentation'] as $key => $url) {
845
+                        // If it is not an absolute URL we assume it is a key
846
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
847
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
848
+                            $url = $urlGenerator->linkToDocs($url);
849
+                        }
850
+
851
+                        $info['documentation'][$key] = $url;
852
+                    }
853
+                }
854
+
855
+                $info['version'] = OC_App::getAppVersion($app);
856
+                $appList[] = $info;
857
+            }
858
+        }
859
+
860
+        return $appList;
861
+    }
862
+
863
+    public static function shouldUpgrade($app) {
864
+        $versions = self::getAppVersions();
865
+        $currentVersion = OC_App::getAppVersion($app);
866
+        if ($currentVersion && isset($versions[$app])) {
867
+            $installedVersion = $versions[$app];
868
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
869
+                return true;
870
+            }
871
+        }
872
+        return false;
873
+    }
874
+
875
+    /**
876
+     * Adjust the number of version parts of $version1 to match
877
+     * the number of version parts of $version2.
878
+     *
879
+     * @param string $version1 version to adjust
880
+     * @param string $version2 version to take the number of parts from
881
+     * @return string shortened $version1
882
+     */
883
+    private static function adjustVersionParts($version1, $version2) {
884
+        $version1 = explode('.', $version1);
885
+        $version2 = explode('.', $version2);
886
+        // reduce $version1 to match the number of parts in $version2
887
+        while (count($version1) > count($version2)) {
888
+            array_pop($version1);
889
+        }
890
+        // if $version1 does not have enough parts, add some
891
+        while (count($version1) < count($version2)) {
892
+            $version1[] = '0';
893
+        }
894
+        return implode('.', $version1);
895
+    }
896
+
897
+    /**
898
+     * Check whether the current ownCloud version matches the given
899
+     * application's version requirements.
900
+     *
901
+     * The comparison is made based on the number of parts that the
902
+     * app info version has. For example for ownCloud 6.0.3 if the
903
+     * app info version is expecting version 6.0, the comparison is
904
+     * made on the first two parts of the ownCloud version.
905
+     * This means that it's possible to specify "requiremin" => 6
906
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
907
+     *
908
+     * @param string $ocVersion ownCloud version to check against
909
+     * @param array $appInfo app info (from xml)
910
+     *
911
+     * @return boolean true if compatible, otherwise false
912
+     */
913
+    public static function isAppCompatible($ocVersion, $appInfo) {
914
+        $requireMin = '';
915
+        $requireMax = '';
916
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
917
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
918
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
919
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
920
+        } else if (isset($appInfo['requiremin'])) {
921
+            $requireMin = $appInfo['requiremin'];
922
+        } else if (isset($appInfo['require'])) {
923
+            $requireMin = $appInfo['require'];
924
+        }
925
+
926
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
927
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
928
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
929
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
930
+        } else if (isset($appInfo['requiremax'])) {
931
+            $requireMax = $appInfo['requiremax'];
932
+        }
933
+
934
+        if (is_array($ocVersion)) {
935
+            $ocVersion = implode('.', $ocVersion);
936
+        }
937
+
938
+        if (!empty($requireMin)
939
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
940
+        ) {
941
+
942
+            return false;
943
+        }
944
+
945
+        if (!empty($requireMax)
946
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
947
+        ) {
948
+            return false;
949
+        }
950
+
951
+        return true;
952
+    }
953
+
954
+    /**
955
+     * get the installed version of all apps
956
+     */
957
+    public static function getAppVersions() {
958
+        static $versions;
959
+
960
+        if(!$versions) {
961
+            $appConfig = \OC::$server->getAppConfig();
962
+            $versions = $appConfig->getValues(false, 'installed_version');
963
+        }
964
+        return $versions;
965
+    }
966
+
967
+    /**
968
+     * @param string $app
969
+     * @param \OCP\IConfig $config
970
+     * @param \OCP\IL10N $l
971
+     * @return bool
972
+     *
973
+     * @throws Exception if app is not compatible with this version of ownCloud
974
+     * @throws Exception if no app-name was specified
975
+     */
976
+    public function installApp($app,
977
+                                \OCP\IConfig $config,
978
+                                \OCP\IL10N $l) {
979
+        if ($app !== false) {
980
+            // check if the app is compatible with this version of ownCloud
981
+            $info = self::getAppInfo($app);
982
+            if(!is_array($info)) {
983
+                throw new \Exception(
984
+                    $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
985
+                        [$info['name']]
986
+                    )
987
+                );
988
+            }
989
+
990
+            $version = \OCP\Util::getVersion();
991
+            if (!self::isAppCompatible($version, $info)) {
992
+                throw new \Exception(
993
+                    $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
994
+                        array($info['name'])
995
+                    )
996
+                );
997
+            }
998
+
999
+            // check for required dependencies
1000
+            self::checkAppDependencies($config, $l, $info);
1001
+
1002
+            $config->setAppValue($app, 'enabled', 'yes');
1003
+            if (isset($appData['id'])) {
1004
+                $config->setAppValue($app, 'ocsid', $appData['id']);
1005
+            }
1006
+
1007
+            if(isset($info['settings']) && is_array($info['settings'])) {
1008
+                $appPath = self::getAppPath($app);
1009
+                self::registerAutoloading($app, $appPath);
1010
+                \OC::$server->getSettingsManager()->setupSettings($info['settings']);
1011
+            }
1012
+
1013
+            \OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1014
+        } else {
1015
+            if(empty($appName) ) {
1016
+                throw new \Exception($l->t("No app name specified"));
1017
+            } else {
1018
+                throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1019
+            }
1020
+        }
1021
+
1022
+        return $app;
1023
+    }
1024
+
1025
+    /**
1026
+     * update the database for the app and call the update script
1027
+     *
1028
+     * @param string $appId
1029
+     * @return bool
1030
+     */
1031
+    public static function updateApp($appId) {
1032
+        $appPath = self::getAppPath($appId);
1033
+        if($appPath === false) {
1034
+            return false;
1035
+        }
1036
+        self::registerAutoloading($appId, $appPath);
1037
+
1038
+        $appData = self::getAppInfo($appId);
1039
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1040
+
1041
+        if (file_exists($appPath . '/appinfo/database.xml')) {
1042
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1043
+        } else {
1044
+            $ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
1045
+            $ms->migrate();
1046
+        }
1047
+
1048
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1049
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1050
+        unset(self::$appVersion[$appId]);
1051
+
1052
+        // run upgrade code
1053
+        if (file_exists($appPath . '/appinfo/update.php')) {
1054
+            self::loadApp($appId);
1055
+            include $appPath . '/appinfo/update.php';
1056
+        }
1057
+        self::setupBackgroundJobs($appData['background-jobs']);
1058
+        if(isset($appData['settings']) && is_array($appData['settings'])) {
1059
+            \OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1060
+        }
1061
+
1062
+        //set remote/public handlers
1063
+        if (array_key_exists('ocsid', $appData)) {
1064
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1065
+        } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1066
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1067
+        }
1068
+        foreach ($appData['remote'] as $name => $path) {
1069
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1070
+        }
1071
+        foreach ($appData['public'] as $name => $path) {
1072
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1073
+        }
1074
+
1075
+        self::setAppTypes($appId);
1076
+
1077
+        $version = \OC_App::getAppVersion($appId);
1078
+        \OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version);
1079
+
1080
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1081
+            ManagerEvent::EVENT_APP_UPDATE, $appId
1082
+        ));
1083
+
1084
+        return true;
1085
+    }
1086
+
1087
+    /**
1088
+     * @param string $appId
1089
+     * @param string[] $steps
1090
+     * @throws \OC\NeedsUpdateException
1091
+     */
1092
+    public static function executeRepairSteps($appId, array $steps) {
1093
+        if (empty($steps)) {
1094
+            return;
1095
+        }
1096
+        // load the app
1097
+        self::loadApp($appId);
1098
+
1099
+        $dispatcher = OC::$server->getEventDispatcher();
1100
+
1101
+        // load the steps
1102
+        $r = new Repair([], $dispatcher);
1103
+        foreach ($steps as $step) {
1104
+            try {
1105
+                $r->addStep($step);
1106
+            } catch (Exception $ex) {
1107
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1108
+                \OC::$server->getLogger()->logException($ex);
1109
+            }
1110
+        }
1111
+        // run the steps
1112
+        $r->run();
1113
+    }
1114
+
1115
+    public static function setupBackgroundJobs(array $jobs) {
1116
+        $queue = \OC::$server->getJobList();
1117
+        foreach ($jobs as $job) {
1118
+            $queue->add($job);
1119
+        }
1120
+    }
1121
+
1122
+    /**
1123
+     * @param string $appId
1124
+     * @param string[] $steps
1125
+     */
1126
+    private static function setupLiveMigrations($appId, array $steps) {
1127
+        $queue = \OC::$server->getJobList();
1128
+        foreach ($steps as $step) {
1129
+            $queue->add('OC\Migration\BackgroundRepair', [
1130
+                'app' => $appId,
1131
+                'step' => $step]);
1132
+        }
1133
+    }
1134
+
1135
+    /**
1136
+     * @param string $appId
1137
+     * @return \OC\Files\View|false
1138
+     */
1139
+    public static function getStorage($appId) {
1140
+        if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1141
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1142
+                $view = new \OC\Files\View('/' . OC_User::getUser());
1143
+                if (!$view->file_exists($appId)) {
1144
+                    $view->mkdir($appId);
1145
+                }
1146
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1147
+            } else {
1148
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1149
+                return false;
1150
+            }
1151
+        } else {
1152
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1153
+            return false;
1154
+        }
1155
+    }
1156
+
1157
+    protected static function findBestL10NOption($options, $lang) {
1158
+        $fallback = $similarLangFallback = $englishFallback = false;
1159
+
1160
+        $lang = strtolower($lang);
1161
+        $similarLang = $lang;
1162
+        if (strpos($similarLang, '_')) {
1163
+            // For "de_DE" we want to find "de" and the other way around
1164
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1165
+        }
1166
+
1167
+        foreach ($options as $option) {
1168
+            if (is_array($option)) {
1169
+                if ($fallback === false) {
1170
+                    $fallback = $option['@value'];
1171
+                }
1172
+
1173
+                if (!isset($option['@attributes']['lang'])) {
1174
+                    continue;
1175
+                }
1176
+
1177
+                $attributeLang = strtolower($option['@attributes']['lang']);
1178
+                if ($attributeLang === $lang) {
1179
+                    return $option['@value'];
1180
+                }
1181
+
1182
+                if ($attributeLang === $similarLang) {
1183
+                    $similarLangFallback = $option['@value'];
1184
+                } else if (strpos($attributeLang, $similarLang . '_') === 0) {
1185
+                    if ($similarLangFallback === false) {
1186
+                        $similarLangFallback =  $option['@value'];
1187
+                    }
1188
+                }
1189
+            } else {
1190
+                $englishFallback = $option;
1191
+            }
1192
+        }
1193
+
1194
+        if ($similarLangFallback !== false) {
1195
+            return $similarLangFallback;
1196
+        } else if ($englishFallback !== false) {
1197
+            return $englishFallback;
1198
+        }
1199
+        return (string) $fallback;
1200
+    }
1201
+
1202
+    /**
1203
+     * parses the app data array and enhanced the 'description' value
1204
+     *
1205
+     * @param array $data the app data
1206
+     * @param string $lang
1207
+     * @return array improved app data
1208
+     */
1209
+    public static function parseAppInfo(array $data, $lang = null) {
1210
+
1211
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1212
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1213
+        }
1214
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1215
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1216
+        }
1217
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1218
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1219
+        } else if (isset($data['description']) && is_string($data['description'])) {
1220
+            $data['description'] = trim($data['description']);
1221
+        } else  {
1222
+            $data['description'] = '';
1223
+        }
1224
+
1225
+        return $data;
1226
+    }
1227
+
1228
+    /**
1229
+     * @param \OCP\IConfig $config
1230
+     * @param \OCP\IL10N $l
1231
+     * @param array $info
1232
+     * @throws \Exception
1233
+     */
1234
+    public static function checkAppDependencies($config, $l, $info) {
1235
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1236
+        $missing = $dependencyAnalyzer->analyze($info);
1237
+        if (!empty($missing)) {
1238
+            $missingMsg = implode(PHP_EOL, $missing);
1239
+            throw new \Exception(
1240
+                $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1241
+                    [$info['name'], $missingMsg]
1242
+                )
1243
+            );
1244
+        }
1245
+    }
1246 1246
 }
Please login to merge, or discard this patch.
Spacing   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -113,9 +113,9 @@  discard block
 block discarded – undo
113 113
 		$apps = self::getEnabledApps();
114 114
 
115 115
 		// Add each apps' folder as allowed class path
116
-		foreach($apps as $app) {
116
+		foreach ($apps as $app) {
117 117
 			$path = self::getAppPath($app);
118
-			if($path !== false) {
118
+			if ($path !== false) {
119 119
 				self::registerAutoloading($app, $path);
120 120
 			}
121 121
 		}
@@ -140,15 +140,15 @@  discard block
 block discarded – undo
140 140
 	public static function loadApp($app) {
141 141
 		self::$loadedApps[] = $app;
142 142
 		$appPath = self::getAppPath($app);
143
-		if($appPath === false) {
143
+		if ($appPath === false) {
144 144
 			return;
145 145
 		}
146 146
 
147 147
 		// in case someone calls loadApp() directly
148 148
 		self::registerAutoloading($app, $appPath);
149 149
 
150
-		if (is_file($appPath . '/appinfo/app.php')) {
151
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
+		if (is_file($appPath.'/appinfo/app.php')) {
151
+			\OC::$server->getEventLogger()->start('load_app_'.$app, 'Load app: '.$app);
152 152
 			self::requireAppFile($app);
153 153
 			if (self::isType($app, array('authentication'))) {
154 154
 				// since authentication apps affect the "is app enabled for group" check,
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 				// enabled for groups
158 158
 				self::$enabledAppsCache = array();
159 159
 			}
160
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
160
+			\OC::$server->getEventLogger()->end('load_app_'.$app);
161 161
 		}
162 162
 
163 163
 		$info = self::getAppInfo($app);
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
 			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
182 182
 				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
183 183
 			foreach ($plugins as $plugin) {
184
-				if($plugin['@attributes']['type'] === 'collaborator-search') {
184
+				if ($plugin['@attributes']['type'] === 'collaborator-search') {
185 185
 					$pluginInfo = [
186 186
 						'shareType' => $plugin['@attributes']['share-type'],
187 187
 						'class' => $plugin['@value'],
@@ -200,8 +200,8 @@  discard block
 block discarded – undo
200 200
 	 * @param string $path
201 201
 	 */
202 202
 	public static function registerAutoloading($app, $path) {
203
-		$key = $app . '-' . $path;
204
-		if(isset(self::$alreadyRegistered[$key])) {
203
+		$key = $app.'-'.$path;
204
+		if (isset(self::$alreadyRegistered[$key])) {
205 205
 			return;
206 206
 		}
207 207
 
@@ -211,17 +211,17 @@  discard block
 block discarded – undo
211 211
 		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
212 212
 		\OC::$server->registerNamespace($app, $appNamespace);
213 213
 
214
-		if (file_exists($path . '/composer/autoload.php')) {
215
-			require_once $path . '/composer/autoload.php';
214
+		if (file_exists($path.'/composer/autoload.php')) {
215
+			require_once $path.'/composer/autoload.php';
216 216
 		} else {
217
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
217
+			\OC::$composerAutoloader->addPsr4($appNamespace.'\\', $path.'/lib/', true);
218 218
 			// Register on legacy autoloader
219 219
 			\OC::$loader->addValidRoot($path);
220 220
 		}
221 221
 
222 222
 		// Register Test namespace only when testing
223 223
 		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
224
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
224
+			\OC::$composerAutoloader->addPsr4($appNamespace.'\\Tests\\', $path.'/tests/', true);
225 225
 		}
226 226
 	}
227 227
 
@@ -233,7 +233,7 @@  discard block
 block discarded – undo
233 233
 	private static function requireAppFile($app) {
234 234
 		try {
235 235
 			// encapsulated here to avoid variable scope conflicts
236
-			require_once $app . '/appinfo/app.php';
236
+			require_once $app.'/appinfo/app.php';
237 237
 		} catch (Error $ex) {
238 238
 			\OC::$server->getLogger()->logException($ex);
239 239
 			$blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps();
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
 	 */
288 288
 	public static function setAppTypes($app) {
289 289
 		$appData = self::getAppInfo($app);
290
-		if(!is_array($appData)) {
290
+		if (!is_array($appData)) {
291 291
 			return;
292 292
 		}
293 293
 
@@ -339,8 +339,8 @@  discard block
 block discarded – undo
339 339
 		} else {
340 340
 			$apps = $appManager->getEnabledAppsForUser($user);
341 341
 		}
342
-		$apps = array_filter($apps, function ($app) {
343
-			return $app !== 'files';//we add this manually
342
+		$apps = array_filter($apps, function($app) {
343
+			return $app !== 'files'; //we add this manually
344 344
 		});
345 345
 		sort($apps);
346 346
 		array_unshift($apps, 'files');
@@ -378,7 +378,7 @@  discard block
 block discarded – undo
378 378
 		$installer = \OC::$server->query(Installer::class);
379 379
 		$isDownloaded = $installer->isDownloaded($appId);
380 380
 
381
-		if(!$isDownloaded) {
381
+		if (!$isDownloaded) {
382 382
 			$installer->downloadApp($appId);
383 383
 		}
384 384
 
@@ -491,7 +491,7 @@  discard block
 block discarded – undo
491 491
 	 */
492 492
 	public static function findAppInDirectories($appId) {
493 493
 		$sanitizedAppId = self::cleanAppId($appId);
494
-		if($sanitizedAppId !== $appId) {
494
+		if ($sanitizedAppId !== $appId) {
495 495
 			return false;
496 496
 		}
497 497
 		static $app_dir = array();
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
 
503 503
 		$possibleApps = array();
504 504
 		foreach (OC::$APPSROOTS as $dir) {
505
-			if (file_exists($dir['path'] . '/' . $appId)) {
505
+			if (file_exists($dir['path'].'/'.$appId)) {
506 506
 				$possibleApps[] = $dir;
507 507
 			}
508 508
 		}
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
 		}
544 544
 
545 545
 		if (($dir = self::findAppInDirectories($appId)) != false) {
546
-			return $dir['path'] . '/' . $appId;
546
+			return $dir['path'].'/'.$appId;
547 547
 		}
548 548
 		return false;
549 549
 	}
@@ -557,7 +557,7 @@  discard block
 block discarded – undo
557 557
 	 */
558 558
 	public static function getAppWebPath($appId) {
559 559
 		if (($dir = self::findAppInDirectories($appId)) != false) {
560
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
560
+			return OC::$WEBROOT.$dir['url'].'/'.$appId;
561 561
 		}
562 562
 		return false;
563 563
 	}
@@ -570,7 +570,7 @@  discard block
 block discarded – undo
570 570
 	 * @return string
571 571
 	 */
572 572
 	public static function getAppVersion($appId, $useCache = true) {
573
-		if($useCache && isset(self::$appVersion[$appId])) {
573
+		if ($useCache && isset(self::$appVersion[$appId])) {
574 574
 			return self::$appVersion[$appId];
575 575
 		}
576 576
 
@@ -586,7 +586,7 @@  discard block
 block discarded – undo
586 586
 	 * @return string
587 587
 	 */
588 588
 	public static function getAppVersionByPath($path) {
589
-		$infoFile = $path . '/appinfo/info.xml';
589
+		$infoFile = $path.'/appinfo/info.xml';
590 590
 		$appData = self::getAppInfo($infoFile, true);
591 591
 		return isset($appData['version']) ? $appData['version'] : '';
592 592
 	}
@@ -609,10 +609,10 @@  discard block
 block discarded – undo
609 609
 				return self::$appInfo[$appId];
610 610
 			}
611 611
 			$appPath = self::getAppPath($appId);
612
-			if($appPath === false) {
612
+			if ($appPath === false) {
613 613
 				return null;
614 614
 			}
615
-			$file = $appPath . '/appinfo/info.xml';
615
+			$file = $appPath.'/appinfo/info.xml';
616 616
 		}
617 617
 
618 618
 		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->createLocal('core.appinfo'));
@@ -621,9 +621,9 @@  discard block
 block discarded – undo
621 621
 		if (is_array($data)) {
622 622
 			$data = OC_App::parseAppInfo($data, $lang);
623 623
 		}
624
-		if(isset($data['ocsid'])) {
624
+		if (isset($data['ocsid'])) {
625 625
 			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
626
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
626
+			if ($storedId !== '' && $storedId !== $data['ocsid']) {
627 627
 				$data['ocsid'] = $storedId;
628 628
 			}
629 629
 		}
@@ -715,7 +715,7 @@  discard block
 block discarded – undo
715 715
 	 * @param string $page
716 716
 	 */
717 717
 	public static function registerAdmin($app, $page) {
718
-		self::$adminForms[] = $app . '/' . $page . '.php';
718
+		self::$adminForms[] = $app.'/'.$page.'.php';
719 719
 	}
720 720
 
721 721
 	/**
@@ -724,7 +724,7 @@  discard block
 block discarded – undo
724 724
 	 * @param string $page
725 725
 	 */
726 726
 	public static function registerPersonal($app, $page) {
727
-		self::$personalForms[] = $app . '/' . $page . '.php';
727
+		self::$personalForms[] = $app.'/'.$page.'.php';
728 728
 	}
729 729
 
730 730
 	/**
@@ -753,7 +753,7 @@  discard block
 block discarded – undo
753 753
 
754 754
 		foreach (OC::$APPSROOTS as $apps_dir) {
755 755
 			if (!is_readable($apps_dir['path'])) {
756
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
756
+				\OCP\Util::writeLog('core', 'unable to read app folder : '.$apps_dir['path'], \OCP\Util::WARN);
757 757
 				continue;
758 758
 			}
759 759
 			$dh = opendir($apps_dir['path']);
@@ -761,7 +761,7 @@  discard block
 block discarded – undo
761 761
 			if (is_resource($dh)) {
762 762
 				while (($file = readdir($dh)) !== false) {
763 763
 
764
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
764
+					if ($file[0] != '.' and is_dir($apps_dir['path'].'/'.$file) and is_file($apps_dir['path'].'/'.$file.'/appinfo/info.xml')) {
765 765
 
766 766
 						$apps[] = $file;
767 767
 					}
@@ -794,12 +794,12 @@  discard block
 block discarded – undo
794 794
 
795 795
 				$info = OC_App::getAppInfo($app, false, $langCode);
796 796
 				if (!is_array($info)) {
797
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
797
+					\OCP\Util::writeLog('core', 'Could not read app info file for app "'.$app.'"', \OCP\Util::ERROR);
798 798
 					continue;
799 799
 				}
800 800
 
801 801
 				if (!isset($info['name'])) {
802
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
802
+					\OCP\Util::writeLog('core', 'App id "'.$app.'" has no name in appinfo', \OCP\Util::ERROR);
803 803
 					continue;
804 804
 				}
805 805
 
@@ -826,13 +826,13 @@  discard block
 block discarded – undo
826 826
 				}
827 827
 
828 828
 				$appPath = self::getAppPath($app);
829
-				if($appPath !== false) {
830
-					$appIcon = $appPath . '/img/' . $app . '.svg';
829
+				if ($appPath !== false) {
830
+					$appIcon = $appPath.'/img/'.$app.'.svg';
831 831
 					if (file_exists($appIcon)) {
832
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
832
+						$info['preview'] = $urlGenerator->imagePath($app, $app.'.svg');
833 833
 						$info['previewAsIcon'] = true;
834 834
 					} else {
835
-						$appIcon = $appPath . '/img/app.svg';
835
+						$appIcon = $appPath.'/img/app.svg';
836 836
 						if (file_exists($appIcon)) {
837 837
 							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
838 838
 							$info['previewAsIcon'] = true;
@@ -957,7 +957,7 @@  discard block
 block discarded – undo
957 957
 	public static function getAppVersions() {
958 958
 		static $versions;
959 959
 
960
-		if(!$versions) {
960
+		if (!$versions) {
961 961
 			$appConfig = \OC::$server->getAppConfig();
962 962
 			$versions = $appConfig->getValues(false, 'installed_version');
963 963
 		}
@@ -979,7 +979,7 @@  discard block
 block discarded – undo
979 979
 		if ($app !== false) {
980 980
 			// check if the app is compatible with this version of ownCloud
981 981
 			$info = self::getAppInfo($app);
982
-			if(!is_array($info)) {
982
+			if (!is_array($info)) {
983 983
 				throw new \Exception(
984 984
 					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
985 985
 						[$info['name']]
@@ -1004,7 +1004,7 @@  discard block
 block discarded – undo
1004 1004
 				$config->setAppValue($app, 'ocsid', $appData['id']);
1005 1005
 			}
1006 1006
 
1007
-			if(isset($info['settings']) && is_array($info['settings'])) {
1007
+			if (isset($info['settings']) && is_array($info['settings'])) {
1008 1008
 				$appPath = self::getAppPath($app);
1009 1009
 				self::registerAutoloading($app, $appPath);
1010 1010
 				\OC::$server->getSettingsManager()->setupSettings($info['settings']);
@@ -1012,7 +1012,7 @@  discard block
 block discarded – undo
1012 1012
 
1013 1013
 			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1014 1014
 		} else {
1015
-			if(empty($appName) ) {
1015
+			if (empty($appName)) {
1016 1016
 				throw new \Exception($l->t("No app name specified"));
1017 1017
 			} else {
1018 1018
 				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
@@ -1030,7 +1030,7 @@  discard block
 block discarded – undo
1030 1030
 	 */
1031 1031
 	public static function updateApp($appId) {
1032 1032
 		$appPath = self::getAppPath($appId);
1033
-		if($appPath === false) {
1033
+		if ($appPath === false) {
1034 1034
 			return false;
1035 1035
 		}
1036 1036
 		self::registerAutoloading($appId, $appPath);
@@ -1038,8 +1038,8 @@  discard block
 block discarded – undo
1038 1038
 		$appData = self::getAppInfo($appId);
1039 1039
 		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1040 1040
 
1041
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1042
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1041
+		if (file_exists($appPath.'/appinfo/database.xml')) {
1042
+			OC_DB::updateDbFromStructure($appPath.'/appinfo/database.xml');
1043 1043
 		} else {
1044 1044
 			$ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
1045 1045
 			$ms->migrate();
@@ -1050,26 +1050,26 @@  discard block
 block discarded – undo
1050 1050
 		unset(self::$appVersion[$appId]);
1051 1051
 
1052 1052
 		// run upgrade code
1053
-		if (file_exists($appPath . '/appinfo/update.php')) {
1053
+		if (file_exists($appPath.'/appinfo/update.php')) {
1054 1054
 			self::loadApp($appId);
1055
-			include $appPath . '/appinfo/update.php';
1055
+			include $appPath.'/appinfo/update.php';
1056 1056
 		}
1057 1057
 		self::setupBackgroundJobs($appData['background-jobs']);
1058
-		if(isset($appData['settings']) && is_array($appData['settings'])) {
1058
+		if (isset($appData['settings']) && is_array($appData['settings'])) {
1059 1059
 			\OC::$server->getSettingsManager()->setupSettings($appData['settings']);
1060 1060
 		}
1061 1061
 
1062 1062
 		//set remote/public handlers
1063 1063
 		if (array_key_exists('ocsid', $appData)) {
1064 1064
 			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1065
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1065
+		} elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1066 1066
 			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1067 1067
 		}
1068 1068
 		foreach ($appData['remote'] as $name => $path) {
1069
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1069
+			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $appId.'/'.$path);
1070 1070
 		}
1071 1071
 		foreach ($appData['public'] as $name => $path) {
1072
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1072
+			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $appId.'/'.$path);
1073 1073
 		}
1074 1074
 
1075 1075
 		self::setAppTypes($appId);
@@ -1139,17 +1139,17 @@  discard block
 block discarded – undo
1139 1139
 	public static function getStorage($appId) {
1140 1140
 		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1141 1141
 			if (\OC::$server->getUserSession()->isLoggedIn()) {
1142
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1142
+				$view = new \OC\Files\View('/'.OC_User::getUser());
1143 1143
 				if (!$view->file_exists($appId)) {
1144 1144
 					$view->mkdir($appId);
1145 1145
 				}
1146
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1146
+				return new \OC\Files\View('/'.OC_User::getUser().'/'.$appId);
1147 1147
 			} else {
1148
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1148
+				\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.', user not logged in', \OCP\Util::ERROR);
1149 1149
 				return false;
1150 1150
 			}
1151 1151
 		} else {
1152
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1152
+			\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.' not enabled', \OCP\Util::ERROR);
1153 1153
 			return false;
1154 1154
 		}
1155 1155
 	}
@@ -1181,9 +1181,9 @@  discard block
 block discarded – undo
1181 1181
 
1182 1182
 				if ($attributeLang === $similarLang) {
1183 1183
 					$similarLangFallback = $option['@value'];
1184
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1184
+				} else if (strpos($attributeLang, $similarLang.'_') === 0) {
1185 1185
 					if ($similarLangFallback === false) {
1186
-						$similarLangFallback =  $option['@value'];
1186
+						$similarLangFallback = $option['@value'];
1187 1187
 					}
1188 1188
 				}
1189 1189
 			} else {
@@ -1218,7 +1218,7 @@  discard block
 block discarded – undo
1218 1218
 			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1219 1219
 		} else if (isset($data['description']) && is_string($data['description'])) {
1220 1220
 			$data['description'] = trim($data['description']);
1221
-		} else  {
1221
+		} else {
1222 1222
 			$data['description'] = '';
1223 1223
 		}
1224 1224
 
Please login to merge, or discard this patch.
lib/private/Files/Node/File.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@
 block discarded – undo
31 31
 	 * Creates a Folder that represents a non-existing path
32 32
 	 *
33 33
 	 * @param string $path path
34
-	 * @return string non-existing node class
34
+	 * @return NonExistingFile non-existing node class
35 35
 	 */
36 36
 	protected function createNonExistingNode($path) {
37 37
 		return new NonExistingFile($this->root, $this->view, $path);
Please login to merge, or discard this patch.
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -29,113 +29,113 @@
 block discarded – undo
29 29
 use OCP\Files\NotPermittedException;
30 30
 
31 31
 class File extends Node implements \OCP\Files\File {
32
-	/**
33
-	 * Creates a Folder that represents a non-existing path
34
-	 *
35
-	 * @param string $path path
36
-	 * @return string non-existing node class
37
-	 */
38
-	protected function createNonExistingNode($path) {
39
-		return new NonExistingFile($this->root, $this->view, $path);
40
-	}
32
+    /**
33
+     * Creates a Folder that represents a non-existing path
34
+     *
35
+     * @param string $path path
36
+     * @return string non-existing node class
37
+     */
38
+    protected function createNonExistingNode($path) {
39
+        return new NonExistingFile($this->root, $this->view, $path);
40
+    }
41 41
 
42
-	/**
43
-	 * @return string
44
-	 * @throws \OCP\Files\NotPermittedException
45
-	 */
46
-	public function getContent() {
47
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_READ)) {
48
-			/**
49
-			 * @var \OC\Files\Storage\Storage $storage;
50
-			 */
51
-			return $this->view->file_get_contents($this->path);
52
-		} else {
53
-			throw new NotPermittedException();
54
-		}
55
-	}
42
+    /**
43
+     * @return string
44
+     * @throws \OCP\Files\NotPermittedException
45
+     */
46
+    public function getContent() {
47
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_READ)) {
48
+            /**
49
+             * @var \OC\Files\Storage\Storage $storage;
50
+             */
51
+            return $this->view->file_get_contents($this->path);
52
+        } else {
53
+            throw new NotPermittedException();
54
+        }
55
+    }
56 56
 
57
-	/**
58
-	 * @param string $data
59
-	 * @throws \OCP\Files\NotPermittedException
60
-	 */
61
-	public function putContent($data) {
62
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_UPDATE)) {
63
-			$this->sendHooks(array('preWrite'));
64
-			$this->view->file_put_contents($this->path, $data);
65
-			$this->fileInfo = null;
66
-			$this->sendHooks(array('postWrite'));
67
-		} else {
68
-			throw new NotPermittedException();
69
-		}
70
-	}
57
+    /**
58
+     * @param string $data
59
+     * @throws \OCP\Files\NotPermittedException
60
+     */
61
+    public function putContent($data) {
62
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_UPDATE)) {
63
+            $this->sendHooks(array('preWrite'));
64
+            $this->view->file_put_contents($this->path, $data);
65
+            $this->fileInfo = null;
66
+            $this->sendHooks(array('postWrite'));
67
+        } else {
68
+            throw new NotPermittedException();
69
+        }
70
+    }
71 71
 
72
-	/**
73
-	 * @param string $mode
74
-	 * @return resource
75
-	 * @throws \OCP\Files\NotPermittedException
76
-	 */
77
-	public function fopen($mode) {
78
-		$preHooks = array();
79
-		$postHooks = array();
80
-		$requiredPermissions = \OCP\Constants::PERMISSION_READ;
81
-		switch ($mode) {
82
-			case 'r+':
83
-			case 'rb+':
84
-			case 'w+':
85
-			case 'wb+':
86
-			case 'x+':
87
-			case 'xb+':
88
-			case 'a+':
89
-			case 'ab+':
90
-			case 'w':
91
-			case 'wb':
92
-			case 'x':
93
-			case 'xb':
94
-			case 'a':
95
-			case 'ab':
96
-				$preHooks[] = 'preWrite';
97
-				$postHooks[] = 'postWrite';
98
-				$requiredPermissions |= \OCP\Constants::PERMISSION_UPDATE;
99
-				break;
100
-		}
72
+    /**
73
+     * @param string $mode
74
+     * @return resource
75
+     * @throws \OCP\Files\NotPermittedException
76
+     */
77
+    public function fopen($mode) {
78
+        $preHooks = array();
79
+        $postHooks = array();
80
+        $requiredPermissions = \OCP\Constants::PERMISSION_READ;
81
+        switch ($mode) {
82
+            case 'r+':
83
+            case 'rb+':
84
+            case 'w+':
85
+            case 'wb+':
86
+            case 'x+':
87
+            case 'xb+':
88
+            case 'a+':
89
+            case 'ab+':
90
+            case 'w':
91
+            case 'wb':
92
+            case 'x':
93
+            case 'xb':
94
+            case 'a':
95
+            case 'ab':
96
+                $preHooks[] = 'preWrite';
97
+                $postHooks[] = 'postWrite';
98
+                $requiredPermissions |= \OCP\Constants::PERMISSION_UPDATE;
99
+                break;
100
+        }
101 101
 
102
-		if ($this->checkPermissions($requiredPermissions)) {
103
-			$this->sendHooks($preHooks);
104
-			$result = $this->view->fopen($this->path, $mode);
105
-			$this->sendHooks($postHooks);
106
-			return $result;
107
-		} else {
108
-			throw new NotPermittedException();
109
-		}
110
-	}
102
+        if ($this->checkPermissions($requiredPermissions)) {
103
+            $this->sendHooks($preHooks);
104
+            $result = $this->view->fopen($this->path, $mode);
105
+            $this->sendHooks($postHooks);
106
+            return $result;
107
+        } else {
108
+            throw new NotPermittedException();
109
+        }
110
+    }
111 111
 
112
-	public function delete() {
113
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
114
-			$this->sendHooks(array('preDelete'));
115
-			$fileInfo = $this->getFileInfo();
116
-			$this->view->unlink($this->path);
117
-			$nonExisting = new NonExistingFile($this->root, $this->view, $this->path, $fileInfo);
118
-			$this->root->emit('\OC\Files', 'postDelete', array($nonExisting));
119
-			$this->exists = false;
120
-			$this->fileInfo = null;
121
-		} else {
122
-			throw new NotPermittedException();
123
-		}
124
-	}
112
+    public function delete() {
113
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
114
+            $this->sendHooks(array('preDelete'));
115
+            $fileInfo = $this->getFileInfo();
116
+            $this->view->unlink($this->path);
117
+            $nonExisting = new NonExistingFile($this->root, $this->view, $this->path, $fileInfo);
118
+            $this->root->emit('\OC\Files', 'postDelete', array($nonExisting));
119
+            $this->exists = false;
120
+            $this->fileInfo = null;
121
+        } else {
122
+            throw new NotPermittedException();
123
+        }
124
+    }
125 125
 
126
-	/**
127
-	 * @param string $type
128
-	 * @param bool $raw
129
-	 * @return string
130
-	 */
131
-	public function hash($type, $raw = false) {
132
-		return $this->view->hash($type, $this->path, $raw);
133
-	}
126
+    /**
127
+     * @param string $type
128
+     * @param bool $raw
129
+     * @return string
130
+     */
131
+    public function hash($type, $raw = false) {
132
+        return $this->view->hash($type, $this->path, $raw);
133
+    }
134 134
 
135
-	/**
136
-	 * @inheritdoc
137
-	 */
138
-	public function getChecksum() {
139
-		return $this->getFileInfo()->getChecksum();
140
-	}
135
+    /**
136
+     * @inheritdoc
137
+     */
138
+    public function getChecksum() {
139
+        return $this->getFileInfo()->getChecksum();
140
+    }
141 141
 }
Please login to merge, or discard this patch.