Completed
Push — master ( 8177fd...1ce867 )
by Björn
12:48 queued 10s
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   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 		 * @link https://github.com/owncloud/core/issues/21955
166 166
 		 */
167 167
 		if ($this->config->getSystemValue('installed', false)) {
168
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
168
+			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() : null;
169 169
 			if (!is_null($userId)) {
170 170
 				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
171 171
 			} else {
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
 		}
216 216
 
217 217
 		if ($this->config->getSystemValue('installed', false)) {
218
-			$userId = null !== $this->userSession->getUser() ? $this->userSession->getUser()->getUID() :  null;
218
+			$userId = null !== $this->userSession->getUser() ? $this->userSession->getUser()->getUID() : null;
219 219
 			$userLocale = null;
220 220
 			if (null !== $userId) {
221 221
 				$userLocale = $this->config->getUserValue($userId, 'core', 'locale', null);
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
 		// merge with translations from theme
278 278
 		$theme = $this->config->getSystemValue('theme');
279 279
 		if (!empty($theme)) {
280
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
280
+			$themeDir = $this->serverRoot.'/themes/'.$theme.substr($dir, strlen($this->serverRoot));
281 281
 
282 282
 			if (is_dir($themeDir)) {
283 283
 				$files = scandir($themeDir);
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
 			return $this->availableLocales;
304 304
 		}
305 305
 
306
-		$localeData = file_get_contents(\OC::$SERVERROOT . '/resources/locales.json');
306
+		$localeData = file_get_contents(\OC::$SERVERROOT.'/resources/locales.json');
307 307
 		$this->availableLocales = \json_decode($localeData, true);
308 308
 
309 309
 		return $this->availableLocales;
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
 
326 326
 	public function getLanguageIterator(IUser $user = null): ILanguageIterator {
327 327
 		$user = $user ?? $this->userSession->getUser();
328
-		if($user === null) {
328
+		if ($user === null) {
329 329
 			throw new \RuntimeException('Failed to get an IUser instance');
330 330
 		}
331 331
 		return new LanguageIterator($user, $this->config);
@@ -443,12 +443,12 @@  discard block
 block discarded – undo
443 443
 		$languageFiles = [];
444 444
 
445 445
 		$i18nDir = $this->findL10nDir($app);
446
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
446
+		$transFile = strip_tags($i18nDir).strip_tags($lang).'.json';
447 447
 
448
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
449
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
450
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
451
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
448
+		if (($this->isSubDirectory($transFile, $this->serverRoot.'/core/l10n/')
449
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/lib/l10n/')
450
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/settings/l10n/')
451
+				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app).'/l10n/')
452 452
 			)
453 453
 			&& file_exists($transFile)) {
454 454
 			// load the translations file
@@ -458,7 +458,7 @@  discard block
 block discarded – undo
458 458
 		// merge with translations from theme
459 459
 		$theme = $this->config->getSystemValue('theme');
460 460
 		if (!empty($theme)) {
461
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
461
+			$transFile = $this->serverRoot.'/themes/'.$theme.substr($transFile, strlen($this->serverRoot));
462 462
 			if (file_exists($transFile)) {
463 463
 				$languageFiles[] = $transFile;
464 464
 			}
@@ -475,14 +475,14 @@  discard block
 block discarded – undo
475 475
 	 */
476 476
 	protected function findL10nDir($app = null) {
477 477
 		if (in_array($app, ['core', 'lib', 'settings'])) {
478
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
479
-				return $this->serverRoot . '/' . $app . '/l10n/';
478
+			if (file_exists($this->serverRoot.'/'.$app.'/l10n/')) {
479
+				return $this->serverRoot.'/'.$app.'/l10n/';
480 480
 			}
481 481
 		} else if ($app && \OC_App::getAppPath($app) !== false) {
482 482
 			// Check if the app is in the app folder
483
-			return \OC_App::getAppPath($app) . '/l10n/';
483
+			return \OC_App::getAppPath($app).'/l10n/';
484 484
 		}
485
-		return $this->serverRoot . '/core/l10n/';
485
+		return $this->serverRoot.'/core/l10n/';
486 486
 	}
487 487
 
488 488
 
@@ -499,15 +499,15 @@  discard block
 block discarded – undo
499 499
 			return $this->pluralFunctions[$string];
500 500
 		}
501 501
 
502
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
502
+		if (preg_match('/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
503 503
 			// sanitize
504
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
505
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
504
+			$nplurals = preg_replace('/[^0-9]/', '', $matches[1]);
505
+			$plural = preg_replace('#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2]);
506 506
 
507 507
 			$body = str_replace(
508
-				array( 'plural', 'n', '$n$plurals', ),
509
-				array( '$plural', '$n', '$nplurals', ),
510
-				'nplurals='. $nplurals . '; plural=' . $plural
508
+				array('plural', 'n', '$n$plurals',),
509
+				array('$plural', '$n', '$nplurals',),
510
+				'nplurals='.$nplurals.'; plural='.$plural
511 511
 			);
512 512
 
513 513
 			// add parents
@@ -516,9 +516,9 @@  discard block
 block discarded – undo
516 516
 			$res = '';
517 517
 			$p = 0;
518 518
 			$length = strlen($body);
519
-			for($i = 0; $i < $length; $i++) {
519
+			for ($i = 0; $i < $length; $i++) {
520 520
 				$ch = $body[$i];
521
-				switch ( $ch ) {
521
+				switch ($ch) {
522 522
 					case '?':
523 523
 						$res .= ' ? (';
524 524
 						$p++;
@@ -527,7 +527,7 @@  discard block
 block discarded – undo
527 527
 						$res .= ') : (';
528 528
 						break;
529 529
 					case ';':
530
-						$res .= str_repeat( ')', $p ) . ';';
530
+						$res .= str_repeat(')', $p).';';
531 531
 						$p = 0;
532 532
 						break;
533 533
 					default:
@@ -535,7 +535,7 @@  discard block
 block discarded – undo
535 535
 				}
536 536
 			}
537 537
 
538
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
538
+			$body = $res.'return ($plural>=$nplurals?$nplurals-1:$plural);';
539 539
 			$function = create_function('$n', $body);
540 540
 			$this->pluralFunctions[$string] = $function;
541 541
 			return $function;
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
 		$commonLanguages = [];
568 568
 		$languages = [];
569 569
 
570
-		foreach($languageCodes as $lang) {
570
+		foreach ($languageCodes as $lang) {
571 571
 			$l = $this->get('lib', $lang);
572 572
 			// TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
573 573
 			$potentialName = (string) $l->t('__language_name__');
@@ -600,7 +600,7 @@  discard block
 block discarded – undo
600 600
 		ksort($commonLanguages);
601 601
 
602 602
 		// sort now by displayed language not the iso-code
603
-		usort( $languages, function ($a, $b) {
603
+		usort($languages, function($a, $b) {
604 604
 			if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
605 605
 				// If a doesn't have a name, but b does, list b before a
606 606
 				return 1;
Please login to merge, or discard this patch.
Indentation   +595 added lines, -595 removed lines patch added patch discarded remove patch
@@ -42,600 +42,600 @@
 block discarded – undo
42 42
  */
43 43
 class Factory implements IFactory {
44 44
 
45
-	/** @var string */
46
-	protected $requestLanguage = '';
47
-
48
-	/**
49
-	 * cached instances
50
-	 * @var array Structure: Lang => App => \OCP\IL10N
51
-	 */
52
-	protected $instances = [];
53
-
54
-	/**
55
-	 * @var array Structure: App => string[]
56
-	 */
57
-	protected $availableLanguages = [];
58
-
59
-	/**
60
-	 * @var array
61
-	 */
62
-	protected $availableLocales = [];
63
-
64
-	/**
65
-	 * @var array Structure: string => callable
66
-	 */
67
-	protected $pluralFunctions = [];
68
-
69
-	const COMMON_LANGUAGE_CODES = [
70
-		'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it',
71
-		'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
72
-	];
73
-
74
-	/** @var IConfig */
75
-	protected $config;
76
-
77
-	/** @var IRequest */
78
-	protected $request;
79
-
80
-	/** @var IUserSession */
81
-	protected $userSession;
82
-
83
-	/** @var string */
84
-	protected $serverRoot;
85
-
86
-	/**
87
-	 * @param IConfig $config
88
-	 * @param IRequest $request
89
-	 * @param IUserSession $userSession
90
-	 * @param string $serverRoot
91
-	 */
92
-	public function __construct(IConfig $config,
93
-								IRequest $request,
94
-								IUserSession $userSession,
95
-								$serverRoot) {
96
-		$this->config = $config;
97
-		$this->request = $request;
98
-		$this->userSession = $userSession;
99
-		$this->serverRoot = $serverRoot;
100
-	}
101
-
102
-	/**
103
-	 * Get a language instance
104
-	 *
105
-	 * @param string $app
106
-	 * @param string|null $lang
107
-	 * @param string|null $locale
108
-	 * @return \OCP\IL10N
109
-	 */
110
-	public function get($app, $lang = null, $locale = null) {
111
-		$app = \OC_App::cleanAppId($app);
112
-		if ($lang !== null) {
113
-			$lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
114
-		}
115
-
116
-		$forceLang = $this->config->getSystemValue('force_language', false);
117
-		if (is_string($forceLang)) {
118
-			$lang = $forceLang;
119
-		}
120
-
121
-		$forceLocale = $this->config->getSystemValue('force_locale', false);
122
-		if (is_string($forceLocale)) {
123
-			$locale = $forceLocale;
124
-		}
125
-
126
-		if ($lang === null || !$this->languageExists($app, $lang)) {
127
-			$lang = $this->findLanguage($app);
128
-		}
129
-
130
-		if ($locale === null || !$this->localeExists($locale)) {
131
-			$locale = $this->findLocale($lang);
132
-		}
133
-
134
-		if (!isset($this->instances[$lang][$app])) {
135
-			$this->instances[$lang][$app] = new L10N(
136
-				$this, $app, $lang, $locale,
137
-				$this->getL10nFilesForApp($app, $lang)
138
-			);
139
-		}
140
-
141
-		return $this->instances[$lang][$app];
142
-	}
143
-
144
-	/**
145
-	 * Find the best language
146
-	 *
147
-	 * @param string|null $app App id or null for core
148
-	 * @return string language If nothing works it returns 'en'
149
-	 */
150
-	public function findLanguage($app = null) {
151
-		$forceLang = $this->config->getSystemValue('force_language', false);
152
-		if (is_string($forceLang)) {
153
-			$this->requestLanguage = $forceLang;
154
-		}
155
-
156
-		if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
157
-			return $this->requestLanguage;
158
-		}
159
-
160
-		/**
161
-		 * At this point Nextcloud might not yet be installed and thus the lookup
162
-		 * in the preferences table might fail. For this reason we need to check
163
-		 * whether the instance has already been installed
164
-		 *
165
-		 * @link https://github.com/owncloud/core/issues/21955
166
-		 */
167
-		if ($this->config->getSystemValue('installed', false)) {
168
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
169
-			if (!is_null($userId)) {
170
-				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
171
-			} else {
172
-				$userLang = null;
173
-			}
174
-		} else {
175
-			$userId = null;
176
-			$userLang = null;
177
-		}
178
-
179
-		if ($userLang) {
180
-			$this->requestLanguage = $userLang;
181
-			if ($this->languageExists($app, $userLang)) {
182
-				return $userLang;
183
-			}
184
-		}
185
-
186
-		try {
187
-			// Try to get the language from the Request
188
-			$lang = $this->getLanguageFromRequest($app);
189
-			if ($userId !== null && $app === null && !$userLang) {
190
-				$this->config->setUserValue($userId, 'core', 'lang', $lang);
191
-			}
192
-			return $lang;
193
-		} catch (LanguageNotFoundException $e) {
194
-			// Finding language from request failed fall back to default language
195
-			$defaultLanguage = $this->config->getSystemValue('default_language', false);
196
-			if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
197
-				return $defaultLanguage;
198
-			}
199
-		}
200
-
201
-		// We could not find any language so fall back to english
202
-		return 'en';
203
-	}
204
-
205
-	/**
206
-	 * find the best locale
207
-	 *
208
-	 * @param string $lang
209
-	 * @return null|string
210
-	 */
211
-	public function findLocale($lang = null) {
212
-		$forceLocale = $this->config->getSystemValue('force_locale', false);
213
-		if (is_string($forceLocale) && $this->localeExists($forceLocale)) {
214
-			return $forceLocale;
215
-		}
216
-
217
-		if ($this->config->getSystemValue('installed', false)) {
218
-			$userId = null !== $this->userSession->getUser() ? $this->userSession->getUser()->getUID() :  null;
219
-			$userLocale = null;
220
-			if (null !== $userId) {
221
-				$userLocale = $this->config->getUserValue($userId, 'core', 'locale', null);
222
-			}
223
-		} else {
224
-			$userId = null;
225
-			$userLocale = null;
226
-		}
227
-
228
-		if ($userLocale && $this->localeExists($userLocale)) {
229
-			return $userLocale;
230
-		}
231
-
232
-		// Default : use system default locale
233
-		$defaultLocale = $this->config->getSystemValue('default_locale', false);
234
-		if ($defaultLocale !== false && $this->localeExists($defaultLocale)) {
235
-			return $defaultLocale;
236
-		}
237
-
238
-		// If no user locale set, use lang as locale
239
-		if (null !== $lang && $this->localeExists($lang)) {
240
-			return $lang;
241
-		}
242
-
243
-		// At last, return USA
244
-		return 'en_US';
245
-	}
246
-
247
-	/**
248
-	 * find the matching lang from the locale
249
-	 *
250
-	 * @param string $app
251
-	 * @param string $locale
252
-	 * @return null|string
253
-	 */
254
-	public function findLanguageFromLocale(string $app = 'core', string $locale = null) {
255
-		if ($this->languageExists($app, $locale)) {
256
-			return $locale;
257
-		}
45
+    /** @var string */
46
+    protected $requestLanguage = '';
47
+
48
+    /**
49
+     * cached instances
50
+     * @var array Structure: Lang => App => \OCP\IL10N
51
+     */
52
+    protected $instances = [];
53
+
54
+    /**
55
+     * @var array Structure: App => string[]
56
+     */
57
+    protected $availableLanguages = [];
58
+
59
+    /**
60
+     * @var array
61
+     */
62
+    protected $availableLocales = [];
63
+
64
+    /**
65
+     * @var array Structure: string => callable
66
+     */
67
+    protected $pluralFunctions = [];
68
+
69
+    const COMMON_LANGUAGE_CODES = [
70
+        'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it',
71
+        'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
72
+    ];
73
+
74
+    /** @var IConfig */
75
+    protected $config;
76
+
77
+    /** @var IRequest */
78
+    protected $request;
79
+
80
+    /** @var IUserSession */
81
+    protected $userSession;
82
+
83
+    /** @var string */
84
+    protected $serverRoot;
85
+
86
+    /**
87
+     * @param IConfig $config
88
+     * @param IRequest $request
89
+     * @param IUserSession $userSession
90
+     * @param string $serverRoot
91
+     */
92
+    public function __construct(IConfig $config,
93
+                                IRequest $request,
94
+                                IUserSession $userSession,
95
+                                $serverRoot) {
96
+        $this->config = $config;
97
+        $this->request = $request;
98
+        $this->userSession = $userSession;
99
+        $this->serverRoot = $serverRoot;
100
+    }
101
+
102
+    /**
103
+     * Get a language instance
104
+     *
105
+     * @param string $app
106
+     * @param string|null $lang
107
+     * @param string|null $locale
108
+     * @return \OCP\IL10N
109
+     */
110
+    public function get($app, $lang = null, $locale = null) {
111
+        $app = \OC_App::cleanAppId($app);
112
+        if ($lang !== null) {
113
+            $lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
114
+        }
115
+
116
+        $forceLang = $this->config->getSystemValue('force_language', false);
117
+        if (is_string($forceLang)) {
118
+            $lang = $forceLang;
119
+        }
120
+
121
+        $forceLocale = $this->config->getSystemValue('force_locale', false);
122
+        if (is_string($forceLocale)) {
123
+            $locale = $forceLocale;
124
+        }
125
+
126
+        if ($lang === null || !$this->languageExists($app, $lang)) {
127
+            $lang = $this->findLanguage($app);
128
+        }
129
+
130
+        if ($locale === null || !$this->localeExists($locale)) {
131
+            $locale = $this->findLocale($lang);
132
+        }
133
+
134
+        if (!isset($this->instances[$lang][$app])) {
135
+            $this->instances[$lang][$app] = new L10N(
136
+                $this, $app, $lang, $locale,
137
+                $this->getL10nFilesForApp($app, $lang)
138
+            );
139
+        }
140
+
141
+        return $this->instances[$lang][$app];
142
+    }
143
+
144
+    /**
145
+     * Find the best language
146
+     *
147
+     * @param string|null $app App id or null for core
148
+     * @return string language If nothing works it returns 'en'
149
+     */
150
+    public function findLanguage($app = null) {
151
+        $forceLang = $this->config->getSystemValue('force_language', false);
152
+        if (is_string($forceLang)) {
153
+            $this->requestLanguage = $forceLang;
154
+        }
155
+
156
+        if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
157
+            return $this->requestLanguage;
158
+        }
159
+
160
+        /**
161
+         * At this point Nextcloud might not yet be installed and thus the lookup
162
+         * in the preferences table might fail. For this reason we need to check
163
+         * whether the instance has already been installed
164
+         *
165
+         * @link https://github.com/owncloud/core/issues/21955
166
+         */
167
+        if ($this->config->getSystemValue('installed', false)) {
168
+            $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
169
+            if (!is_null($userId)) {
170
+                $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
171
+            } else {
172
+                $userLang = null;
173
+            }
174
+        } else {
175
+            $userId = null;
176
+            $userLang = null;
177
+        }
178
+
179
+        if ($userLang) {
180
+            $this->requestLanguage = $userLang;
181
+            if ($this->languageExists($app, $userLang)) {
182
+                return $userLang;
183
+            }
184
+        }
185
+
186
+        try {
187
+            // Try to get the language from the Request
188
+            $lang = $this->getLanguageFromRequest($app);
189
+            if ($userId !== null && $app === null && !$userLang) {
190
+                $this->config->setUserValue($userId, 'core', 'lang', $lang);
191
+            }
192
+            return $lang;
193
+        } catch (LanguageNotFoundException $e) {
194
+            // Finding language from request failed fall back to default language
195
+            $defaultLanguage = $this->config->getSystemValue('default_language', false);
196
+            if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
197
+                return $defaultLanguage;
198
+            }
199
+        }
200
+
201
+        // We could not find any language so fall back to english
202
+        return 'en';
203
+    }
204
+
205
+    /**
206
+     * find the best locale
207
+     *
208
+     * @param string $lang
209
+     * @return null|string
210
+     */
211
+    public function findLocale($lang = null) {
212
+        $forceLocale = $this->config->getSystemValue('force_locale', false);
213
+        if (is_string($forceLocale) && $this->localeExists($forceLocale)) {
214
+            return $forceLocale;
215
+        }
216
+
217
+        if ($this->config->getSystemValue('installed', false)) {
218
+            $userId = null !== $this->userSession->getUser() ? $this->userSession->getUser()->getUID() :  null;
219
+            $userLocale = null;
220
+            if (null !== $userId) {
221
+                $userLocale = $this->config->getUserValue($userId, 'core', 'locale', null);
222
+            }
223
+        } else {
224
+            $userId = null;
225
+            $userLocale = null;
226
+        }
227
+
228
+        if ($userLocale && $this->localeExists($userLocale)) {
229
+            return $userLocale;
230
+        }
231
+
232
+        // Default : use system default locale
233
+        $defaultLocale = $this->config->getSystemValue('default_locale', false);
234
+        if ($defaultLocale !== false && $this->localeExists($defaultLocale)) {
235
+            return $defaultLocale;
236
+        }
237
+
238
+        // If no user locale set, use lang as locale
239
+        if (null !== $lang && $this->localeExists($lang)) {
240
+            return $lang;
241
+        }
242
+
243
+        // At last, return USA
244
+        return 'en_US';
245
+    }
246
+
247
+    /**
248
+     * find the matching lang from the locale
249
+     *
250
+     * @param string $app
251
+     * @param string $locale
252
+     * @return null|string
253
+     */
254
+    public function findLanguageFromLocale(string $app = 'core', string $locale = null) {
255
+        if ($this->languageExists($app, $locale)) {
256
+            return $locale;
257
+        }
258 258
 		
259
-		// Try to split e.g: fr_FR => fr
260
-		$locale = explode('_', $locale)[0];
261
-		if ($this->languageExists($app, $locale)) {
262
-			return $locale;
263
-		}
264
-	}
265
-
266
-	/**
267
-	 * Find all available languages for an app
268
-	 *
269
-	 * @param string|null $app App id or null for core
270
-	 * @return array an array of available languages
271
-	 */
272
-	public function findAvailableLanguages($app = null) {
273
-		$key = $app;
274
-		if ($key === null) {
275
-			$key = 'null';
276
-		}
277
-
278
-		// also works with null as key
279
-		if (!empty($this->availableLanguages[$key])) {
280
-			return $this->availableLanguages[$key];
281
-		}
282
-
283
-		$available = ['en']; //english is always available
284
-		$dir = $this->findL10nDir($app);
285
-		if (is_dir($dir)) {
286
-			$files = scandir($dir);
287
-			if ($files !== false) {
288
-				foreach ($files as $file) {
289
-					if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
290
-						$available[] = substr($file, 0, -5);
291
-					}
292
-				}
293
-			}
294
-		}
295
-
296
-		// merge with translations from theme
297
-		$theme = $this->config->getSystemValue('theme');
298
-		if (!empty($theme)) {
299
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
300
-
301
-			if (is_dir($themeDir)) {
302
-				$files = scandir($themeDir);
303
-				if ($files !== false) {
304
-					foreach ($files as $file) {
305
-						if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
306
-							$available[] = substr($file, 0, -5);
307
-						}
308
-					}
309
-				}
310
-			}
311
-		}
312
-
313
-		$this->availableLanguages[$key] = $available;
314
-		return $available;
315
-	}
316
-
317
-	/**
318
-	 * @return array|mixed
319
-	 */
320
-	public function findAvailableLocales() {
321
-		if (!empty($this->availableLocales)) {
322
-			return $this->availableLocales;
323
-		}
324
-
325
-		$localeData = file_get_contents(\OC::$SERVERROOT . '/resources/locales.json');
326
-		$this->availableLocales = \json_decode($localeData, true);
327
-
328
-		return $this->availableLocales;
329
-	}
330
-
331
-	/**
332
-	 * @param string|null $app App id or null for core
333
-	 * @param string $lang
334
-	 * @return bool
335
-	 */
336
-	public function languageExists($app, $lang) {
337
-		if ($lang === 'en') {//english is always available
338
-			return true;
339
-		}
340
-
341
-		$languages = $this->findAvailableLanguages($app);
342
-		return array_search($lang, $languages) !== false;
343
-	}
344
-
345
-	public function getLanguageIterator(IUser $user = null): ILanguageIterator {
346
-		$user = $user ?? $this->userSession->getUser();
347
-		if($user === null) {
348
-			throw new \RuntimeException('Failed to get an IUser instance');
349
-		}
350
-		return new LanguageIterator($user, $this->config);
351
-	}
352
-
353
-	/**
354
-	 * @param string $locale
355
-	 * @return bool
356
-	 */
357
-	public function localeExists($locale) {
358
-		if ($locale === 'en') { //english is always available
359
-			return true;
360
-		}
361
-
362
-		$locales = $this->findAvailableLocales();
363
-		$userLocale = array_filter($locales, function($value) use ($locale) {
364
-			return $locale === $value['code'];
365
-		});
366
-
367
-		return !empty($userLocale);
368
-	}
369
-
370
-	/**
371
-	 * @param string|null $app
372
-	 * @return string
373
-	 * @throws LanguageNotFoundException
374
-	 */
375
-	private function getLanguageFromRequest($app) {
376
-		$header = $this->request->getHeader('ACCEPT_LANGUAGE');
377
-		if ($header !== '') {
378
-			$available = $this->findAvailableLanguages($app);
379
-
380
-			// E.g. make sure that 'de' is before 'de_DE'.
381
-			sort($available);
382
-
383
-			$preferences = preg_split('/,\s*/', strtolower($header));
384
-			foreach ($preferences as $preference) {
385
-				list($preferred_language) = explode(';', $preference);
386
-				$preferred_language = str_replace('-', '_', $preferred_language);
387
-
388
-				foreach ($available as $available_language) {
389
-					if ($preferred_language === strtolower($available_language)) {
390
-						return $this->respectDefaultLanguage($app, $available_language);
391
-					}
392
-				}
393
-
394
-				// Fallback from de_De to de
395
-				foreach ($available as $available_language) {
396
-					if (substr($preferred_language, 0, 2) === $available_language) {
397
-						return $available_language;
398
-					}
399
-				}
400
-			}
401
-		}
402
-
403
-		throw new LanguageNotFoundException();
404
-	}
405
-
406
-	/**
407
-	 * if default language is set to de_DE (formal German) this should be
408
-	 * preferred to 'de' (non-formal German) if possible
409
-	 *
410
-	 * @param string|null $app
411
-	 * @param string $lang
412
-	 * @return string
413
-	 */
414
-	protected function respectDefaultLanguage($app, $lang) {
415
-		$result = $lang;
416
-		$defaultLanguage = $this->config->getSystemValue('default_language', false);
417
-
418
-		// use formal version of german ("Sie" instead of "Du") if the default
419
-		// language is set to 'de_DE' if possible
420
-		if (is_string($defaultLanguage) &&
421
-			strtolower($lang) === 'de' &&
422
-			strtolower($defaultLanguage) === 'de_de' &&
423
-			$this->languageExists($app, 'de_DE')
424
-		) {
425
-			$result = 'de_DE';
426
-		}
427
-
428
-		return $result;
429
-	}
430
-
431
-	/**
432
-	 * Checks if $sub is a subdirectory of $parent
433
-	 *
434
-	 * @param string $sub
435
-	 * @param string $parent
436
-	 * @return bool
437
-	 */
438
-	private function isSubDirectory($sub, $parent) {
439
-		// Check whether $sub contains no ".."
440
-		if (strpos($sub, '..') !== false) {
441
-			return false;
442
-		}
443
-
444
-		// Check whether $sub is a subdirectory of $parent
445
-		if (strpos($sub, $parent) === 0) {
446
-			return true;
447
-		}
448
-
449
-		return false;
450
-	}
451
-
452
-	/**
453
-	 * Get a list of language files that should be loaded
454
-	 *
455
-	 * @param string $app
456
-	 * @param string $lang
457
-	 * @return string[]
458
-	 */
459
-	// FIXME This method is only public, until OC_L10N does not need it anymore,
460
-	// FIXME This is also the reason, why it is not in the public interface
461
-	public function getL10nFilesForApp($app, $lang) {
462
-		$languageFiles = [];
463
-
464
-		$i18nDir = $this->findL10nDir($app);
465
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
466
-
467
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
468
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
469
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
470
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
471
-			)
472
-			&& file_exists($transFile)) {
473
-			// load the translations file
474
-			$languageFiles[] = $transFile;
475
-		}
476
-
477
-		// merge with translations from theme
478
-		$theme = $this->config->getSystemValue('theme');
479
-		if (!empty($theme)) {
480
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
481
-			if (file_exists($transFile)) {
482
-				$languageFiles[] = $transFile;
483
-			}
484
-		}
485
-
486
-		return $languageFiles;
487
-	}
488
-
489
-	/**
490
-	 * find the l10n directory
491
-	 *
492
-	 * @param string $app App id or empty string for core
493
-	 * @return string directory
494
-	 */
495
-	protected function findL10nDir($app = null) {
496
-		if (in_array($app, ['core', 'lib', 'settings'])) {
497
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
498
-				return $this->serverRoot . '/' . $app . '/l10n/';
499
-			}
500
-		} else if ($app && \OC_App::getAppPath($app) !== false) {
501
-			// Check if the app is in the app folder
502
-			return \OC_App::getAppPath($app) . '/l10n/';
503
-		}
504
-		return $this->serverRoot . '/core/l10n/';
505
-	}
506
-
507
-
508
-	/**
509
-	 * Creates a function from the plural string
510
-	 *
511
-	 * Parts of the code is copied from Habari:
512
-	 * https://github.com/habari/system/blob/master/classes/locale.php
513
-	 * @param string $string
514
-	 * @return string
515
-	 */
516
-	public function createPluralFunction($string) {
517
-		if (isset($this->pluralFunctions[$string])) {
518
-			return $this->pluralFunctions[$string];
519
-		}
520
-
521
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
522
-			// sanitize
523
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
524
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
525
-
526
-			$body = str_replace(
527
-				array( 'plural', 'n', '$n$plurals', ),
528
-				array( '$plural', '$n', '$nplurals', ),
529
-				'nplurals='. $nplurals . '; plural=' . $plural
530
-			);
531
-
532
-			// add parents
533
-			// important since PHP's ternary evaluates from left to right
534
-			$body .= ';';
535
-			$res = '';
536
-			$p = 0;
537
-			$length = strlen($body);
538
-			for($i = 0; $i < $length; $i++) {
539
-				$ch = $body[$i];
540
-				switch ( $ch ) {
541
-					case '?':
542
-						$res .= ' ? (';
543
-						$p++;
544
-						break;
545
-					case ':':
546
-						$res .= ') : (';
547
-						break;
548
-					case ';':
549
-						$res .= str_repeat( ')', $p ) . ';';
550
-						$p = 0;
551
-						break;
552
-					default:
553
-						$res .= $ch;
554
-				}
555
-			}
556
-
557
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
558
-			$function = create_function('$n', $body);
559
-			$this->pluralFunctions[$string] = $function;
560
-			return $function;
561
-		} else {
562
-			// default: one plural form for all cases but n==1 (english)
563
-			$function = create_function(
564
-				'$n',
565
-				'$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
566
-			);
567
-			$this->pluralFunctions[$string] = $function;
568
-			return $function;
569
-		}
570
-	}
571
-
572
-	/**
573
-	 * returns the common language and other languages in an
574
-	 * associative array
575
-	 *
576
-	 * @return array
577
-	 */
578
-	public function getLanguages() {
579
-		$forceLanguage = $this->config->getSystemValue('force_language', false);
580
-		if ($forceLanguage !== false) {
581
-			return [];
582
-		}
583
-
584
-		$languageCodes = $this->findAvailableLanguages();
585
-
586
-		$commonLanguages = [];
587
-		$languages = [];
588
-
589
-		foreach($languageCodes as $lang) {
590
-			$l = $this->get('lib', $lang);
591
-			// TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
592
-			$potentialName = (string) $l->t('__language_name__');
593
-			if ($l->getLanguageCode() === $lang && $potentialName[0] !== '_') {//first check if the language name is in the translation file
594
-				$ln = array(
595
-					'code' => $lang,
596
-					'name' => $potentialName
597
-				);
598
-			} else if ($lang === 'en') {
599
-				$ln = array(
600
-					'code' => $lang,
601
-					'name' => 'English (US)'
602
-				);
603
-			} else {//fallback to language code
604
-				$ln = array(
605
-					'code' => $lang,
606
-					'name' => $lang
607
-				);
608
-			}
609
-
610
-			// put appropriate languages into appropriate arrays, to print them sorted
611
-			// common languages -> divider -> other languages
612
-			if (in_array($lang, self::COMMON_LANGUAGE_CODES)) {
613
-				$commonLanguages[array_search($lang, self::COMMON_LANGUAGE_CODES)] = $ln;
614
-			} else {
615
-				$languages[] = $ln;
616
-			}
617
-		}
618
-
619
-		ksort($commonLanguages);
620
-
621
-		// sort now by displayed language not the iso-code
622
-		usort( $languages, function ($a, $b) {
623
-			if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
624
-				// If a doesn't have a name, but b does, list b before a
625
-				return 1;
626
-			}
627
-			if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
628
-				// If a does have a name, but b doesn't, list a before b
629
-				return -1;
630
-			}
631
-			// Otherwise compare the names
632
-			return strcmp($a['name'], $b['name']);
633
-		});
634
-
635
-		return [
636
-			// reset indexes
637
-			'commonlanguages' => array_values($commonLanguages),
638
-			'languages' => $languages
639
-		];
640
-	}
259
+        // Try to split e.g: fr_FR => fr
260
+        $locale = explode('_', $locale)[0];
261
+        if ($this->languageExists($app, $locale)) {
262
+            return $locale;
263
+        }
264
+    }
265
+
266
+    /**
267
+     * Find all available languages for an app
268
+     *
269
+     * @param string|null $app App id or null for core
270
+     * @return array an array of available languages
271
+     */
272
+    public function findAvailableLanguages($app = null) {
273
+        $key = $app;
274
+        if ($key === null) {
275
+            $key = 'null';
276
+        }
277
+
278
+        // also works with null as key
279
+        if (!empty($this->availableLanguages[$key])) {
280
+            return $this->availableLanguages[$key];
281
+        }
282
+
283
+        $available = ['en']; //english is always available
284
+        $dir = $this->findL10nDir($app);
285
+        if (is_dir($dir)) {
286
+            $files = scandir($dir);
287
+            if ($files !== false) {
288
+                foreach ($files as $file) {
289
+                    if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
290
+                        $available[] = substr($file, 0, -5);
291
+                    }
292
+                }
293
+            }
294
+        }
295
+
296
+        // merge with translations from theme
297
+        $theme = $this->config->getSystemValue('theme');
298
+        if (!empty($theme)) {
299
+            $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
300
+
301
+            if (is_dir($themeDir)) {
302
+                $files = scandir($themeDir);
303
+                if ($files !== false) {
304
+                    foreach ($files as $file) {
305
+                        if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
306
+                            $available[] = substr($file, 0, -5);
307
+                        }
308
+                    }
309
+                }
310
+            }
311
+        }
312
+
313
+        $this->availableLanguages[$key] = $available;
314
+        return $available;
315
+    }
316
+
317
+    /**
318
+     * @return array|mixed
319
+     */
320
+    public function findAvailableLocales() {
321
+        if (!empty($this->availableLocales)) {
322
+            return $this->availableLocales;
323
+        }
324
+
325
+        $localeData = file_get_contents(\OC::$SERVERROOT . '/resources/locales.json');
326
+        $this->availableLocales = \json_decode($localeData, true);
327
+
328
+        return $this->availableLocales;
329
+    }
330
+
331
+    /**
332
+     * @param string|null $app App id or null for core
333
+     * @param string $lang
334
+     * @return bool
335
+     */
336
+    public function languageExists($app, $lang) {
337
+        if ($lang === 'en') {//english is always available
338
+            return true;
339
+        }
340
+
341
+        $languages = $this->findAvailableLanguages($app);
342
+        return array_search($lang, $languages) !== false;
343
+    }
344
+
345
+    public function getLanguageIterator(IUser $user = null): ILanguageIterator {
346
+        $user = $user ?? $this->userSession->getUser();
347
+        if($user === null) {
348
+            throw new \RuntimeException('Failed to get an IUser instance');
349
+        }
350
+        return new LanguageIterator($user, $this->config);
351
+    }
352
+
353
+    /**
354
+     * @param string $locale
355
+     * @return bool
356
+     */
357
+    public function localeExists($locale) {
358
+        if ($locale === 'en') { //english is always available
359
+            return true;
360
+        }
361
+
362
+        $locales = $this->findAvailableLocales();
363
+        $userLocale = array_filter($locales, function($value) use ($locale) {
364
+            return $locale === $value['code'];
365
+        });
366
+
367
+        return !empty($userLocale);
368
+    }
369
+
370
+    /**
371
+     * @param string|null $app
372
+     * @return string
373
+     * @throws LanguageNotFoundException
374
+     */
375
+    private function getLanguageFromRequest($app) {
376
+        $header = $this->request->getHeader('ACCEPT_LANGUAGE');
377
+        if ($header !== '') {
378
+            $available = $this->findAvailableLanguages($app);
379
+
380
+            // E.g. make sure that 'de' is before 'de_DE'.
381
+            sort($available);
382
+
383
+            $preferences = preg_split('/,\s*/', strtolower($header));
384
+            foreach ($preferences as $preference) {
385
+                list($preferred_language) = explode(';', $preference);
386
+                $preferred_language = str_replace('-', '_', $preferred_language);
387
+
388
+                foreach ($available as $available_language) {
389
+                    if ($preferred_language === strtolower($available_language)) {
390
+                        return $this->respectDefaultLanguage($app, $available_language);
391
+                    }
392
+                }
393
+
394
+                // Fallback from de_De to de
395
+                foreach ($available as $available_language) {
396
+                    if (substr($preferred_language, 0, 2) === $available_language) {
397
+                        return $available_language;
398
+                    }
399
+                }
400
+            }
401
+        }
402
+
403
+        throw new LanguageNotFoundException();
404
+    }
405
+
406
+    /**
407
+     * if default language is set to de_DE (formal German) this should be
408
+     * preferred to 'de' (non-formal German) if possible
409
+     *
410
+     * @param string|null $app
411
+     * @param string $lang
412
+     * @return string
413
+     */
414
+    protected function respectDefaultLanguage($app, $lang) {
415
+        $result = $lang;
416
+        $defaultLanguage = $this->config->getSystemValue('default_language', false);
417
+
418
+        // use formal version of german ("Sie" instead of "Du") if the default
419
+        // language is set to 'de_DE' if possible
420
+        if (is_string($defaultLanguage) &&
421
+            strtolower($lang) === 'de' &&
422
+            strtolower($defaultLanguage) === 'de_de' &&
423
+            $this->languageExists($app, 'de_DE')
424
+        ) {
425
+            $result = 'de_DE';
426
+        }
427
+
428
+        return $result;
429
+    }
430
+
431
+    /**
432
+     * Checks if $sub is a subdirectory of $parent
433
+     *
434
+     * @param string $sub
435
+     * @param string $parent
436
+     * @return bool
437
+     */
438
+    private function isSubDirectory($sub, $parent) {
439
+        // Check whether $sub contains no ".."
440
+        if (strpos($sub, '..') !== false) {
441
+            return false;
442
+        }
443
+
444
+        // Check whether $sub is a subdirectory of $parent
445
+        if (strpos($sub, $parent) === 0) {
446
+            return true;
447
+        }
448
+
449
+        return false;
450
+    }
451
+
452
+    /**
453
+     * Get a list of language files that should be loaded
454
+     *
455
+     * @param string $app
456
+     * @param string $lang
457
+     * @return string[]
458
+     */
459
+    // FIXME This method is only public, until OC_L10N does not need it anymore,
460
+    // FIXME This is also the reason, why it is not in the public interface
461
+    public function getL10nFilesForApp($app, $lang) {
462
+        $languageFiles = [];
463
+
464
+        $i18nDir = $this->findL10nDir($app);
465
+        $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
466
+
467
+        if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
468
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
469
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
470
+                || $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
471
+            )
472
+            && file_exists($transFile)) {
473
+            // load the translations file
474
+            $languageFiles[] = $transFile;
475
+        }
476
+
477
+        // merge with translations from theme
478
+        $theme = $this->config->getSystemValue('theme');
479
+        if (!empty($theme)) {
480
+            $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
481
+            if (file_exists($transFile)) {
482
+                $languageFiles[] = $transFile;
483
+            }
484
+        }
485
+
486
+        return $languageFiles;
487
+    }
488
+
489
+    /**
490
+     * find the l10n directory
491
+     *
492
+     * @param string $app App id or empty string for core
493
+     * @return string directory
494
+     */
495
+    protected function findL10nDir($app = null) {
496
+        if (in_array($app, ['core', 'lib', 'settings'])) {
497
+            if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
498
+                return $this->serverRoot . '/' . $app . '/l10n/';
499
+            }
500
+        } else if ($app && \OC_App::getAppPath($app) !== false) {
501
+            // Check if the app is in the app folder
502
+            return \OC_App::getAppPath($app) . '/l10n/';
503
+        }
504
+        return $this->serverRoot . '/core/l10n/';
505
+    }
506
+
507
+
508
+    /**
509
+     * Creates a function from the plural string
510
+     *
511
+     * Parts of the code is copied from Habari:
512
+     * https://github.com/habari/system/blob/master/classes/locale.php
513
+     * @param string $string
514
+     * @return string
515
+     */
516
+    public function createPluralFunction($string) {
517
+        if (isset($this->pluralFunctions[$string])) {
518
+            return $this->pluralFunctions[$string];
519
+        }
520
+
521
+        if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
522
+            // sanitize
523
+            $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
524
+            $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
525
+
526
+            $body = str_replace(
527
+                array( 'plural', 'n', '$n$plurals', ),
528
+                array( '$plural', '$n', '$nplurals', ),
529
+                'nplurals='. $nplurals . '; plural=' . $plural
530
+            );
531
+
532
+            // add parents
533
+            // important since PHP's ternary evaluates from left to right
534
+            $body .= ';';
535
+            $res = '';
536
+            $p = 0;
537
+            $length = strlen($body);
538
+            for($i = 0; $i < $length; $i++) {
539
+                $ch = $body[$i];
540
+                switch ( $ch ) {
541
+                    case '?':
542
+                        $res .= ' ? (';
543
+                        $p++;
544
+                        break;
545
+                    case ':':
546
+                        $res .= ') : (';
547
+                        break;
548
+                    case ';':
549
+                        $res .= str_repeat( ')', $p ) . ';';
550
+                        $p = 0;
551
+                        break;
552
+                    default:
553
+                        $res .= $ch;
554
+                }
555
+            }
556
+
557
+            $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
558
+            $function = create_function('$n', $body);
559
+            $this->pluralFunctions[$string] = $function;
560
+            return $function;
561
+        } else {
562
+            // default: one plural form for all cases but n==1 (english)
563
+            $function = create_function(
564
+                '$n',
565
+                '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
566
+            );
567
+            $this->pluralFunctions[$string] = $function;
568
+            return $function;
569
+        }
570
+    }
571
+
572
+    /**
573
+     * returns the common language and other languages in an
574
+     * associative array
575
+     *
576
+     * @return array
577
+     */
578
+    public function getLanguages() {
579
+        $forceLanguage = $this->config->getSystemValue('force_language', false);
580
+        if ($forceLanguage !== false) {
581
+            return [];
582
+        }
583
+
584
+        $languageCodes = $this->findAvailableLanguages();
585
+
586
+        $commonLanguages = [];
587
+        $languages = [];
588
+
589
+        foreach($languageCodes as $lang) {
590
+            $l = $this->get('lib', $lang);
591
+            // TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
592
+            $potentialName = (string) $l->t('__language_name__');
593
+            if ($l->getLanguageCode() === $lang && $potentialName[0] !== '_') {//first check if the language name is in the translation file
594
+                $ln = array(
595
+                    'code' => $lang,
596
+                    'name' => $potentialName
597
+                );
598
+            } else if ($lang === 'en') {
599
+                $ln = array(
600
+                    'code' => $lang,
601
+                    'name' => 'English (US)'
602
+                );
603
+            } else {//fallback to language code
604
+                $ln = array(
605
+                    'code' => $lang,
606
+                    'name' => $lang
607
+                );
608
+            }
609
+
610
+            // put appropriate languages into appropriate arrays, to print them sorted
611
+            // common languages -> divider -> other languages
612
+            if (in_array($lang, self::COMMON_LANGUAGE_CODES)) {
613
+                $commonLanguages[array_search($lang, self::COMMON_LANGUAGE_CODES)] = $ln;
614
+            } else {
615
+                $languages[] = $ln;
616
+            }
617
+        }
618
+
619
+        ksort($commonLanguages);
620
+
621
+        // sort now by displayed language not the iso-code
622
+        usort( $languages, function ($a, $b) {
623
+            if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
624
+                // If a doesn't have a name, but b does, list b before a
625
+                return 1;
626
+            }
627
+            if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
628
+                // If a does have a name, but b doesn't, list a before b
629
+                return -1;
630
+            }
631
+            // Otherwise compare the names
632
+            return strcmp($a['name'], $b['name']);
633
+        });
634
+
635
+        return [
636
+            // reset indexes
637
+            'commonlanguages' => array_values($commonLanguages),
638
+            'languages' => $languages
639
+        ];
640
+    }
641 641
 }
Please login to merge, or discard this patch.
lib/private/Setup/MySQL.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -101,7 +101,7 @@
 block discarded – undo
101 101
 	}
102 102
 
103 103
 	/**
104
-	 * @param $username
104
+	 * @param string $username
105 105
 	 * @param IDBConnection $connection
106 106
 	 * @return array
107 107
 	 */
Please login to merge, or discard this patch.
Indentation   +139 added lines, -139 removed lines patch added patch discarded remove patch
@@ -34,143 +34,143 @@
 block discarded – undo
34 34
 use OCP\ILogger;
35 35
 
36 36
 class MySQL extends AbstractDatabase {
37
-	public $dbprettyname = 'MySQL/MariaDB';
38
-
39
-	public function setupDatabase($username) {
40
-		//check if the database user has admin right
41
-		$connection = $this->connect(['dbname' => null]);
42
-
43
-		// detect mb4
44
-		$tools = new MySqlTools();
45
-		if ($tools->supports4ByteCharset($connection)) {
46
-			$this->config->setValue('mysql.utf8mb4', true);
47
-			$connection = $this->connect(['dbname' => null]);
48
-		}
49
-
50
-		$this->createSpecificUser($username, $connection);
51
-
52
-		//create the database
53
-		$this->createDatabase($connection);
54
-
55
-		//fill the database if needed
56
-		$query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
57
-		$connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
58
-	}
59
-
60
-	/**
61
-	 * @param \OC\DB\Connection $connection
62
-	 */
63
-	private function createDatabase($connection) {
64
-		try{
65
-			$name = $this->dbName;
66
-			$user = $this->dbUser;
67
-			//we can't use OC_DB functions here because we need to connect as the administrative user.
68
-			$characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
69
-			$query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
70
-			$connection->executeUpdate($query);
71
-		} catch (\Exception $ex) {
72
-			$this->logger->logException($ex, [
73
-				'message' => 'Database creation failed.',
74
-				'level' => ILogger::ERROR,
75
-				'app' => 'mysql.setup',
76
-			]);
77
-			return;
78
-		}
79
-
80
-		try {
81
-			//this query will fail if there aren't the right permissions, ignore the error
82
-			$query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
83
-			$connection->executeUpdate($query);
84
-		} catch (\Exception $ex) {
85
-			$this->logger->logException($ex, [
86
-				'message' => 'Could not automatically grant privileges, this can be ignored if database user already had privileges.',
87
-				'level' => ILogger::DEBUG,
88
-				'app' => 'mysql.setup',
89
-			]);
90
-		}
91
-	}
92
-
93
-	/**
94
-	 * @param IDBConnection $connection
95
-	 * @throws \OC\DatabaseSetupException
96
-	 */
97
-	private function createDBUser($connection) {
98
-		try{
99
-			$name = $this->dbUser;
100
-			$password = $this->dbPassword;
101
-			// we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
102
-			// the anonymous user would take precedence when there is one.
103
-			$query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
104
-			$connection->executeUpdate($query);
105
-			$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
106
-			$connection->executeUpdate($query);
107
-		}
108
-		catch (\Exception $ex){
109
-			$this->logger->logException($ex, [
110
-				'message' => 'Database user creation failed.',
111
-				'level' => ILogger::ERROR,
112
-				'app' => 'mysql.setup',
113
-			]);
114
-		}
115
-	}
116
-
117
-	/**
118
-	 * @param $username
119
-	 * @param IDBConnection $connection
120
-	 * @return array
121
-	 */
122
-	private function createSpecificUser($username, $connection) {
123
-		try {
124
-			//user already specified in config
125
-			$oldUser = $this->config->getValue('dbuser', false);
126
-
127
-			//we don't have a dbuser specified in config
128
-			if ($this->dbUser !== $oldUser) {
129
-				//add prefix to the admin username to prevent collisions
130
-				$adminUser = substr('oc_' . $username, 0, 16);
131
-
132
-				$i = 1;
133
-				while (true) {
134
-					//this should be enough to check for admin rights in mysql
135
-					$query = 'SELECT user FROM mysql.user WHERE user=?';
136
-					$result = $connection->executeQuery($query, [$adminUser]);
137
-
138
-					//current dbuser has admin rights
139
-					if ($result) {
140
-						$data = $result->fetchAll();
141
-						//new dbuser does not exist
142
-						if (count($data) === 0) {
143
-							//use the admin login data for the new database user
144
-							$this->dbUser = $adminUser;
145
-
146
-							//create a random password so we don't need to store the admin password in the config file
147
-							$this->dbPassword =  $this->random->generate(30);
148
-
149
-							$this->createDBUser($connection);
150
-
151
-							break;
152
-						} else {
153
-							//repeat with different username
154
-							$length = strlen((string)$i);
155
-							$adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
156
-							$i++;
157
-						}
158
-					} else {
159
-						break;
160
-					}
161
-				}
162
-			}
163
-		} catch (\Exception $ex) {
164
-			$this->logger->logException($ex, [
165
-				'message' => 'Can not create a new MySQL user, will continue with the provided user.',
166
-				'level' => ILogger::INFO,
167
-				'app' => 'mysql.setup',
168
-			]);
169
-		}
170
-
171
-		$this->config->setValues([
172
-			'dbuser' => $this->dbUser,
173
-			'dbpassword' => $this->dbPassword,
174
-		]);
175
-	}
37
+    public $dbprettyname = 'MySQL/MariaDB';
38
+
39
+    public function setupDatabase($username) {
40
+        //check if the database user has admin right
41
+        $connection = $this->connect(['dbname' => null]);
42
+
43
+        // detect mb4
44
+        $tools = new MySqlTools();
45
+        if ($tools->supports4ByteCharset($connection)) {
46
+            $this->config->setValue('mysql.utf8mb4', true);
47
+            $connection = $this->connect(['dbname' => null]);
48
+        }
49
+
50
+        $this->createSpecificUser($username, $connection);
51
+
52
+        //create the database
53
+        $this->createDatabase($connection);
54
+
55
+        //fill the database if needed
56
+        $query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
57
+        $connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
58
+    }
59
+
60
+    /**
61
+     * @param \OC\DB\Connection $connection
62
+     */
63
+    private function createDatabase($connection) {
64
+        try{
65
+            $name = $this->dbName;
66
+            $user = $this->dbUser;
67
+            //we can't use OC_DB functions here because we need to connect as the administrative user.
68
+            $characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
69
+            $query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
70
+            $connection->executeUpdate($query);
71
+        } catch (\Exception $ex) {
72
+            $this->logger->logException($ex, [
73
+                'message' => 'Database creation failed.',
74
+                'level' => ILogger::ERROR,
75
+                'app' => 'mysql.setup',
76
+            ]);
77
+            return;
78
+        }
79
+
80
+        try {
81
+            //this query will fail if there aren't the right permissions, ignore the error
82
+            $query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
83
+            $connection->executeUpdate($query);
84
+        } catch (\Exception $ex) {
85
+            $this->logger->logException($ex, [
86
+                'message' => 'Could not automatically grant privileges, this can be ignored if database user already had privileges.',
87
+                'level' => ILogger::DEBUG,
88
+                'app' => 'mysql.setup',
89
+            ]);
90
+        }
91
+    }
92
+
93
+    /**
94
+     * @param IDBConnection $connection
95
+     * @throws \OC\DatabaseSetupException
96
+     */
97
+    private function createDBUser($connection) {
98
+        try{
99
+            $name = $this->dbUser;
100
+            $password = $this->dbPassword;
101
+            // we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
102
+            // the anonymous user would take precedence when there is one.
103
+            $query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
104
+            $connection->executeUpdate($query);
105
+            $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
106
+            $connection->executeUpdate($query);
107
+        }
108
+        catch (\Exception $ex){
109
+            $this->logger->logException($ex, [
110
+                'message' => 'Database user creation failed.',
111
+                'level' => ILogger::ERROR,
112
+                'app' => 'mysql.setup',
113
+            ]);
114
+        }
115
+    }
116
+
117
+    /**
118
+     * @param $username
119
+     * @param IDBConnection $connection
120
+     * @return array
121
+     */
122
+    private function createSpecificUser($username, $connection) {
123
+        try {
124
+            //user already specified in config
125
+            $oldUser = $this->config->getValue('dbuser', false);
126
+
127
+            //we don't have a dbuser specified in config
128
+            if ($this->dbUser !== $oldUser) {
129
+                //add prefix to the admin username to prevent collisions
130
+                $adminUser = substr('oc_' . $username, 0, 16);
131
+
132
+                $i = 1;
133
+                while (true) {
134
+                    //this should be enough to check for admin rights in mysql
135
+                    $query = 'SELECT user FROM mysql.user WHERE user=?';
136
+                    $result = $connection->executeQuery($query, [$adminUser]);
137
+
138
+                    //current dbuser has admin rights
139
+                    if ($result) {
140
+                        $data = $result->fetchAll();
141
+                        //new dbuser does not exist
142
+                        if (count($data) === 0) {
143
+                            //use the admin login data for the new database user
144
+                            $this->dbUser = $adminUser;
145
+
146
+                            //create a random password so we don't need to store the admin password in the config file
147
+                            $this->dbPassword =  $this->random->generate(30);
148
+
149
+                            $this->createDBUser($connection);
150
+
151
+                            break;
152
+                        } else {
153
+                            //repeat with different username
154
+                            $length = strlen((string)$i);
155
+                            $adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
156
+                            $i++;
157
+                        }
158
+                    } else {
159
+                        break;
160
+                    }
161
+                }
162
+            }
163
+        } catch (\Exception $ex) {
164
+            $this->logger->logException($ex, [
165
+                'message' => 'Can not create a new MySQL user, will continue with the provided user.',
166
+                'level' => ILogger::INFO,
167
+                'app' => 'mysql.setup',
168
+            ]);
169
+        }
170
+
171
+        $this->config->setValues([
172
+            'dbuser' => $this->dbUser,
173
+            'dbpassword' => $this->dbPassword,
174
+        ]);
175
+    }
176 176
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@  discard block
 block discarded – undo
53 53
 		$this->createDatabase($connection);
54 54
 
55 55
 		//fill the database if needed
56
-		$query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
56
+		$query = 'select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
57 57
 		$connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
58 58
 	}
59 59
 
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
 	 * @param \OC\DB\Connection $connection
62 62
 	 */
63 63
 	private function createDatabase($connection) {
64
-		try{
64
+		try {
65 65
 			$name = $this->dbName;
66 66
 			$user = $this->dbUser;
67 67
 			//we can't use OC_DB functions here because we need to connect as the administrative user.
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 
80 80
 		try {
81 81
 			//this query will fail if there aren't the right permissions, ignore the error
82
-			$query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
82
+			$query = "GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
83 83
 			$connection->executeUpdate($query);
84 84
 		} catch (\Exception $ex) {
85 85
 			$this->logger->logException($ex, [
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 	 * @throws \OC\DatabaseSetupException
96 96
 	 */
97 97
 	private function createDBUser($connection) {
98
-		try{
98
+		try {
99 99
 			$name = $this->dbUser;
100 100
 			$password = $this->dbPassword;
101 101
 			// we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 			$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
106 106
 			$connection->executeUpdate($query);
107 107
 		}
108
-		catch (\Exception $ex){
108
+		catch (\Exception $ex) {
109 109
 			$this->logger->logException($ex, [
110 110
 				'message' => 'Database user creation failed.',
111 111
 				'level' => ILogger::ERROR,
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
 			//we don't have a dbuser specified in config
128 128
 			if ($this->dbUser !== $oldUser) {
129 129
 				//add prefix to the admin username to prevent collisions
130
-				$adminUser = substr('oc_' . $username, 0, 16);
130
+				$adminUser = substr('oc_'.$username, 0, 16);
131 131
 
132 132
 				$i = 1;
133 133
 				while (true) {
@@ -144,15 +144,15 @@  discard block
 block discarded – undo
144 144
 							$this->dbUser = $adminUser;
145 145
 
146 146
 							//create a random password so we don't need to store the admin password in the config file
147
-							$this->dbPassword =  $this->random->generate(30);
147
+							$this->dbPassword = $this->random->generate(30);
148 148
 
149 149
 							$this->createDBUser($connection);
150 150
 
151 151
 							break;
152 152
 						} else {
153 153
 							//repeat with different username
154
-							$length = strlen((string)$i);
155
-							$adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
154
+							$length = strlen((string) $i);
155
+							$adminUser = substr('oc_'.$username, 0, 16 - $length).$i;
156 156
 							$i++;
157 157
 						}
158 158
 					} else {
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -104,8 +104,7 @@
 block discarded – undo
104 104
 			$connection->executeUpdate($query);
105 105
 			$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
106 106
 			$connection->executeUpdate($query);
107
-		}
108
-		catch (\Exception $ex){
107
+		} catch (\Exception $ex){
109 108
 			$this->logger->logException($ex, [
110 109
 				'message' => 'Database user creation failed.',
111 110
 				'level' => ILogger::ERROR,
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.
Indentation   +844 added lines, -844 removed lines patch added patch discarded remove patch
@@ -70,848 +70,848 @@
 block discarded – undo
70 70
 
71 71
 class Filesystem {
72 72
 
73
-	/**
74
-	 * @var Mount\Manager $mounts
75
-	 */
76
-	private static $mounts;
77
-
78
-	public static $loaded = false;
79
-	/**
80
-	 * @var \OC\Files\View $defaultInstance
81
-	 */
82
-	static private $defaultInstance;
83
-
84
-	static private $usersSetup = array();
85
-
86
-	static private $normalizedPathCache = null;
87
-
88
-	static private $listeningForProviders = false;
89
-
90
-	/**
91
-	 * classname which used for hooks handling
92
-	 * used as signalclass in OC_Hooks::emit()
93
-	 */
94
-	const CLASSNAME = 'OC_Filesystem';
95
-
96
-	/**
97
-	 * signalname emitted before file renaming
98
-	 *
99
-	 * @param string $oldpath
100
-	 * @param string $newpath
101
-	 */
102
-	const signal_rename = 'rename';
103
-
104
-	/**
105
-	 * signal emitted after file renaming
106
-	 *
107
-	 * @param string $oldpath
108
-	 * @param string $newpath
109
-	 */
110
-	const signal_post_rename = 'post_rename';
111
-
112
-	/**
113
-	 * signal emitted before file/dir creation
114
-	 *
115
-	 * @param string $path
116
-	 * @param bool $run changing this flag to false in hook handler will cancel event
117
-	 */
118
-	const signal_create = 'create';
119
-
120
-	/**
121
-	 * signal emitted after file/dir creation
122
-	 *
123
-	 * @param string $path
124
-	 * @param bool $run changing this flag to false in hook handler will cancel event
125
-	 */
126
-	const signal_post_create = 'post_create';
127
-
128
-	/**
129
-	 * signal emits before file/dir copy
130
-	 *
131
-	 * @param string $oldpath
132
-	 * @param string $newpath
133
-	 * @param bool $run changing this flag to false in hook handler will cancel event
134
-	 */
135
-	const signal_copy = 'copy';
136
-
137
-	/**
138
-	 * signal emits after file/dir copy
139
-	 *
140
-	 * @param string $oldpath
141
-	 * @param string $newpath
142
-	 */
143
-	const signal_post_copy = 'post_copy';
144
-
145
-	/**
146
-	 * signal emits before file/dir save
147
-	 *
148
-	 * @param string $path
149
-	 * @param bool $run changing this flag to false in hook handler will cancel event
150
-	 */
151
-	const signal_write = 'write';
152
-
153
-	/**
154
-	 * signal emits after file/dir save
155
-	 *
156
-	 * @param string $path
157
-	 */
158
-	const signal_post_write = 'post_write';
159
-
160
-	/**
161
-	 * signal emitted before file/dir update
162
-	 *
163
-	 * @param string $path
164
-	 * @param bool $run changing this flag to false in hook handler will cancel event
165
-	 */
166
-	const signal_update = 'update';
167
-
168
-	/**
169
-	 * signal emitted after file/dir update
170
-	 *
171
-	 * @param string $path
172
-	 * @param bool $run changing this flag to false in hook handler will cancel event
173
-	 */
174
-	const signal_post_update = 'post_update';
175
-
176
-	/**
177
-	 * signal emits when reading file/dir
178
-	 *
179
-	 * @param string $path
180
-	 */
181
-	const signal_read = 'read';
182
-
183
-	/**
184
-	 * signal emits when removing file/dir
185
-	 *
186
-	 * @param string $path
187
-	 */
188
-	const signal_delete = 'delete';
189
-
190
-	/**
191
-	 * parameters definitions for signals
192
-	 */
193
-	const signal_param_path = 'path';
194
-	const signal_param_oldpath = 'oldpath';
195
-	const signal_param_newpath = 'newpath';
196
-
197
-	/**
198
-	 * run - changing this flag to false in hook handler will cancel event
199
-	 */
200
-	const signal_param_run = 'run';
201
-
202
-	const signal_create_mount = 'create_mount';
203
-	const signal_delete_mount = 'delete_mount';
204
-	const signal_param_mount_type = 'mounttype';
205
-	const signal_param_users = 'users';
206
-
207
-	/**
208
-	 * @var \OC\Files\Storage\StorageFactory $loader
209
-	 */
210
-	private static $loader;
211
-
212
-	/** @var bool */
213
-	private static $logWarningWhenAddingStorageWrapper = true;
214
-
215
-	/**
216
-	 * @param bool $shouldLog
217
-	 * @return bool previous value
218
-	 * @internal
219
-	 */
220
-	public static function logWarningWhenAddingStorageWrapper($shouldLog) {
221
-		$previousValue = self::$logWarningWhenAddingStorageWrapper;
222
-		self::$logWarningWhenAddingStorageWrapper = (bool) $shouldLog;
223
-		return $previousValue;
224
-	}
225
-
226
-	/**
227
-	 * @param string $wrapperName
228
-	 * @param callable $wrapper
229
-	 * @param int $priority
230
-	 */
231
-	public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) {
232
-		if (self::$logWarningWhenAddingStorageWrapper) {
233
-			\OC::$server->getLogger()->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [
234
-				'wrapper' => $wrapperName,
235
-				'app' => 'filesystem',
236
-			]);
237
-		}
238
-
239
-		$mounts = self::getMountManager()->getAll();
240
-		if (!self::getLoader()->addStorageWrapper($wrapperName, $wrapper, $priority, $mounts)) {
241
-			// do not re-wrap if storage with this name already existed
242
-			return;
243
-		}
244
-	}
245
-
246
-	/**
247
-	 * Returns the storage factory
248
-	 *
249
-	 * @return \OCP\Files\Storage\IStorageFactory
250
-	 */
251
-	public static function getLoader() {
252
-		if (!self::$loader) {
253
-			self::$loader = new StorageFactory();
254
-		}
255
-		return self::$loader;
256
-	}
257
-
258
-	/**
259
-	 * Returns the mount manager
260
-	 *
261
-	 * @return \OC\Files\Mount\Manager
262
-	 */
263
-	public static function getMountManager($user = '') {
264
-		if (!self::$mounts) {
265
-			\OC_Util::setupFS($user);
266
-		}
267
-		return self::$mounts;
268
-	}
269
-
270
-	/**
271
-	 * get the mountpoint of the storage object for a path
272
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
273
-	 * returned mountpoint is relative to the absolute root of the filesystem
274
-	 * and doesn't take the chroot into account )
275
-	 *
276
-	 * @param string $path
277
-	 * @return string
278
-	 */
279
-	static public function getMountPoint($path) {
280
-		if (!self::$mounts) {
281
-			\OC_Util::setupFS();
282
-		}
283
-		$mount = self::$mounts->find($path);
284
-		if ($mount) {
285
-			return $mount->getMountPoint();
286
-		} else {
287
-			return '';
288
-		}
289
-	}
290
-
291
-	/**
292
-	 * get a list of all mount points in a directory
293
-	 *
294
-	 * @param string $path
295
-	 * @return string[]
296
-	 */
297
-	static public function getMountPoints($path) {
298
-		if (!self::$mounts) {
299
-			\OC_Util::setupFS();
300
-		}
301
-		$result = array();
302
-		$mounts = self::$mounts->findIn($path);
303
-		foreach ($mounts as $mount) {
304
-			$result[] = $mount->getMountPoint();
305
-		}
306
-		return $result;
307
-	}
308
-
309
-	/**
310
-	 * get the storage mounted at $mountPoint
311
-	 *
312
-	 * @param string $mountPoint
313
-	 * @return \OC\Files\Storage\Storage
314
-	 */
315
-	public static function getStorage($mountPoint) {
316
-		if (!self::$mounts) {
317
-			\OC_Util::setupFS();
318
-		}
319
-		$mount = self::$mounts->find($mountPoint);
320
-		return $mount->getStorage();
321
-	}
322
-
323
-	/**
324
-	 * @param string $id
325
-	 * @return Mount\MountPoint[]
326
-	 */
327
-	public static function getMountByStorageId($id) {
328
-		if (!self::$mounts) {
329
-			\OC_Util::setupFS();
330
-		}
331
-		return self::$mounts->findByStorageId($id);
332
-	}
333
-
334
-	/**
335
-	 * @param int $id
336
-	 * @return Mount\MountPoint[]
337
-	 */
338
-	public static function getMountByNumericId($id) {
339
-		if (!self::$mounts) {
340
-			\OC_Util::setupFS();
341
-		}
342
-		return self::$mounts->findByNumericId($id);
343
-	}
344
-
345
-	/**
346
-	 * resolve a path to a storage and internal path
347
-	 *
348
-	 * @param string $path
349
-	 * @return array an array consisting of the storage and the internal path
350
-	 */
351
-	static public function resolvePath($path) {
352
-		if (!self::$mounts) {
353
-			\OC_Util::setupFS();
354
-		}
355
-		$mount = self::$mounts->find($path);
356
-		if ($mount) {
357
-			return array($mount->getStorage(), rtrim($mount->getInternalPath($path), '/'));
358
-		} else {
359
-			return array(null, null);
360
-		}
361
-	}
362
-
363
-	static public function init($user, $root) {
364
-		if (self::$defaultInstance) {
365
-			return false;
366
-		}
367
-		self::getLoader();
368
-		self::$defaultInstance = new View($root);
369
-
370
-		if (!self::$mounts) {
371
-			self::$mounts = \OC::$server->getMountManager();
372
-		}
373
-
374
-		//load custom mount config
375
-		self::initMountPoints($user);
376
-
377
-		self::$loaded = true;
378
-
379
-		return true;
380
-	}
381
-
382
-	static public function initMountManager() {
383
-		if (!self::$mounts) {
384
-			self::$mounts = \OC::$server->getMountManager();
385
-		}
386
-	}
387
-
388
-	/**
389
-	 * Initialize system and personal mount points for a user
390
-	 *
391
-	 * @param string $user
392
-	 * @throws \OC\User\NoUserException if the user is not available
393
-	 */
394
-	public static function initMountPoints($user = '') {
395
-		if ($user == '') {
396
-			$user = \OC_User::getUser();
397
-		}
398
-		if ($user === null || $user === false || $user === '') {
399
-			throw new \OC\User\NoUserException('Attempted to initialize mount points for null user and no user in session');
400
-		}
401
-
402
-		if (isset(self::$usersSetup[$user])) {
403
-			return;
404
-		}
405
-
406
-		self::$usersSetup[$user] = true;
407
-
408
-		$userManager = \OC::$server->getUserManager();
409
-		$userObject = $userManager->get($user);
410
-
411
-		if (is_null($userObject)) {
412
-			\OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, ILogger::ERROR);
413
-			// reset flag, this will make it possible to rethrow the exception if called again
414
-			unset(self::$usersSetup[$user]);
415
-			throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
416
-		}
417
-
418
-		$realUid = $userObject->getUID();
419
-		// workaround in case of different casings
420
-		if ($user !== $realUid) {
421
-			$stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
422
-			\OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "' . $realUid . '" got "' . $user . '". Stack: ' . $stack, ILogger::WARN);
423
-			$user = $realUid;
424
-
425
-			// again with the correct casing
426
-			if (isset(self::$usersSetup[$user])) {
427
-				return;
428
-			}
429
-
430
-			self::$usersSetup[$user] = true;
431
-		}
432
-
433
-		if (\OC::$server->getLockdownManager()->canAccessFilesystem()) {
434
-			/** @var \OC\Files\Config\MountProviderCollection $mountConfigManager */
435
-			$mountConfigManager = \OC::$server->getMountProviderCollection();
436
-
437
-			// home mounts are handled seperate since we need to ensure this is mounted before we call the other mount providers
438
-			$homeMount = $mountConfigManager->getHomeMountForUser($userObject);
439
-
440
-			self::getMountManager()->addMount($homeMount);
441
-
442
-			\OC\Files\Filesystem::getStorage($user);
443
-
444
-			// Chance to mount for other storages
445
-			if ($userObject) {
446
-				$mounts = $mountConfigManager->addMountForUser($userObject, self::getMountManager());
447
-				$mounts[] = $homeMount;
448
-				$mountConfigManager->registerMounts($userObject, $mounts);
449
-			}
450
-
451
-			self::listenForNewMountProviders($mountConfigManager, $userManager);
452
-		} else {
453
-			self::getMountManager()->addMount(new MountPoint(
454
-				new NullStorage([]),
455
-				'/' . $user
456
-			));
457
-			self::getMountManager()->addMount(new MountPoint(
458
-				new NullStorage([]),
459
-				'/' . $user . '/files'
460
-			));
461
-		}
462
-		\OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
463
-	}
464
-
465
-	/**
466
-	 * Get mounts from mount providers that are registered after setup
467
-	 *
468
-	 * @param MountProviderCollection $mountConfigManager
469
-	 * @param IUserManager $userManager
470
-	 */
471
-	private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
472
-		if (!self::$listeningForProviders) {
473
-			self::$listeningForProviders = true;
474
-			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
475
-				foreach (Filesystem::$usersSetup as $user => $setup) {
476
-					$userObject = $userManager->get($user);
477
-					if ($userObject) {
478
-						$mounts = $provider->getMountsForUser($userObject, Filesystem::getLoader());
479
-						array_walk($mounts, array(self::$mounts, 'addMount'));
480
-					}
481
-				}
482
-			});
483
-		}
484
-	}
485
-
486
-	/**
487
-	 * get the default filesystem view
488
-	 *
489
-	 * @return View
490
-	 */
491
-	static public function getView() {
492
-		return self::$defaultInstance;
493
-	}
494
-
495
-	/**
496
-	 * tear down the filesystem, removing all storage providers
497
-	 */
498
-	static public function tearDown() {
499
-		self::clearMounts();
500
-		self::$defaultInstance = null;
501
-	}
502
-
503
-	/**
504
-	 * get the relative path of the root data directory for the current user
505
-	 *
506
-	 * @return string
507
-	 *
508
-	 * Returns path like /admin/files
509
-	 */
510
-	static public function getRoot() {
511
-		if (!self::$defaultInstance) {
512
-			return null;
513
-		}
514
-		return self::$defaultInstance->getRoot();
515
-	}
516
-
517
-	/**
518
-	 * clear all mounts and storage backends
519
-	 */
520
-	public static function clearMounts() {
521
-		if (self::$mounts) {
522
-			self::$usersSetup = array();
523
-			self::$mounts->clear();
524
-		}
525
-	}
526
-
527
-	/**
528
-	 * mount an \OC\Files\Storage\Storage in our virtual filesystem
529
-	 *
530
-	 * @param \OC\Files\Storage\Storage|string $class
531
-	 * @param array $arguments
532
-	 * @param string $mountpoint
533
-	 */
534
-	static public function mount($class, $arguments, $mountpoint) {
535
-		if (!self::$mounts) {
536
-			\OC_Util::setupFS();
537
-		}
538
-		$mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader());
539
-		self::$mounts->addMount($mount);
540
-	}
541
-
542
-	/**
543
-	 * return the path to a local version of the file
544
-	 * we need this because we can't know if a file is stored local or not from
545
-	 * outside the filestorage and for some purposes a local file is needed
546
-	 *
547
-	 * @param string $path
548
-	 * @return string
549
-	 */
550
-	static public function getLocalFile($path) {
551
-		return self::$defaultInstance->getLocalFile($path);
552
-	}
553
-
554
-	/**
555
-	 * @param string $path
556
-	 * @return string
557
-	 */
558
-	static public function getLocalFolder($path) {
559
-		return self::$defaultInstance->getLocalFolder($path);
560
-	}
561
-
562
-	/**
563
-	 * return path to file which reflects one visible in browser
564
-	 *
565
-	 * @param string $path
566
-	 * @return string
567
-	 */
568
-	static public function getLocalPath($path) {
569
-		$datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
570
-		$newpath = $path;
571
-		if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
572
-			$newpath = substr($path, strlen($datadir));
573
-		}
574
-		return $newpath;
575
-	}
576
-
577
-	/**
578
-	 * check if the requested path is valid
579
-	 *
580
-	 * @param string $path
581
-	 * @return bool
582
-	 */
583
-	static public function isValidPath($path) {
584
-		$path = self::normalizePath($path);
585
-		if (!$path || $path[0] !== '/') {
586
-			$path = '/' . $path;
587
-		}
588
-		if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
589
-			return false;
590
-		}
591
-		return true;
592
-	}
593
-
594
-	/**
595
-	 * checks if a file is blacklisted for storage in the filesystem
596
-	 * Listens to write and rename hooks
597
-	 *
598
-	 * @param array $data from hook
599
-	 */
600
-	static public function isBlacklisted($data) {
601
-		if (isset($data['path'])) {
602
-			$path = $data['path'];
603
-		} else if (isset($data['newpath'])) {
604
-			$path = $data['newpath'];
605
-		}
606
-		if (isset($path)) {
607
-			if (self::isFileBlacklisted($path)) {
608
-				$data['run'] = false;
609
-			}
610
-		}
611
-	}
612
-
613
-	/**
614
-	 * @param string $filename
615
-	 * @return bool
616
-	 */
617
-	static public function isFileBlacklisted($filename) {
618
-		$filename = self::normalizePath($filename);
619
-
620
-		$blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array('.htaccess'));
621
-		$filename = strtolower(basename($filename));
622
-		return in_array($filename, $blacklist);
623
-	}
624
-
625
-	/**
626
-	 * check if the directory should be ignored when scanning
627
-	 * NOTE: the special directories . and .. would cause never ending recursion
628
-	 *
629
-	 * @param String $dir
630
-	 * @return boolean
631
-	 */
632
-	static public function isIgnoredDir($dir) {
633
-		if ($dir === '.' || $dir === '..') {
634
-			return true;
635
-		}
636
-		return false;
637
-	}
638
-
639
-	/**
640
-	 * following functions are equivalent to their php builtin equivalents for arguments/return values.
641
-	 */
642
-	static public function mkdir($path) {
643
-		return self::$defaultInstance->mkdir($path);
644
-	}
645
-
646
-	static public function rmdir($path) {
647
-		return self::$defaultInstance->rmdir($path);
648
-	}
649
-
650
-	static public function is_dir($path) {
651
-		return self::$defaultInstance->is_dir($path);
652
-	}
653
-
654
-	static public function is_file($path) {
655
-		return self::$defaultInstance->is_file($path);
656
-	}
657
-
658
-	static public function stat($path) {
659
-		return self::$defaultInstance->stat($path);
660
-	}
661
-
662
-	static public function filetype($path) {
663
-		return self::$defaultInstance->filetype($path);
664
-	}
665
-
666
-	static public function filesize($path) {
667
-		return self::$defaultInstance->filesize($path);
668
-	}
669
-
670
-	static public function readfile($path) {
671
-		return self::$defaultInstance->readfile($path);
672
-	}
673
-
674
-	static public function isCreatable($path) {
675
-		return self::$defaultInstance->isCreatable($path);
676
-	}
677
-
678
-	static public function isReadable($path) {
679
-		return self::$defaultInstance->isReadable($path);
680
-	}
681
-
682
-	static public function isUpdatable($path) {
683
-		return self::$defaultInstance->isUpdatable($path);
684
-	}
685
-
686
-	static public function isDeletable($path) {
687
-		return self::$defaultInstance->isDeletable($path);
688
-	}
689
-
690
-	static public function isSharable($path) {
691
-		return self::$defaultInstance->isSharable($path);
692
-	}
693
-
694
-	static public function file_exists($path) {
695
-		return self::$defaultInstance->file_exists($path);
696
-	}
697
-
698
-	static public function filemtime($path) {
699
-		return self::$defaultInstance->filemtime($path);
700
-	}
701
-
702
-	static public function touch($path, $mtime = null) {
703
-		return self::$defaultInstance->touch($path, $mtime);
704
-	}
705
-
706
-	/**
707
-	 * @return string
708
-	 */
709
-	static public function file_get_contents($path) {
710
-		return self::$defaultInstance->file_get_contents($path);
711
-	}
712
-
713
-	static public function file_put_contents($path, $data) {
714
-		return self::$defaultInstance->file_put_contents($path, $data);
715
-	}
716
-
717
-	static public function unlink($path) {
718
-		return self::$defaultInstance->unlink($path);
719
-	}
720
-
721
-	static public function rename($path1, $path2) {
722
-		return self::$defaultInstance->rename($path1, $path2);
723
-	}
724
-
725
-	static public function copy($path1, $path2) {
726
-		return self::$defaultInstance->copy($path1, $path2);
727
-	}
728
-
729
-	static public function fopen($path, $mode) {
730
-		return self::$defaultInstance->fopen($path, $mode);
731
-	}
732
-
733
-	/**
734
-	 * @return string
735
-	 */
736
-	static public function toTmpFile($path) {
737
-		return self::$defaultInstance->toTmpFile($path);
738
-	}
739
-
740
-	static public function fromTmpFile($tmpFile, $path) {
741
-		return self::$defaultInstance->fromTmpFile($tmpFile, $path);
742
-	}
743
-
744
-	static public function getMimeType($path) {
745
-		return self::$defaultInstance->getMimeType($path);
746
-	}
747
-
748
-	static public function hash($type, $path, $raw = false) {
749
-		return self::$defaultInstance->hash($type, $path, $raw);
750
-	}
751
-
752
-	static public function free_space($path = '/') {
753
-		return self::$defaultInstance->free_space($path);
754
-	}
755
-
756
-	static public function search($query) {
757
-		return self::$defaultInstance->search($query);
758
-	}
759
-
760
-	/**
761
-	 * @param string $query
762
-	 */
763
-	static public function searchByMime($query) {
764
-		return self::$defaultInstance->searchByMime($query);
765
-	}
766
-
767
-	/**
768
-	 * @param string|int $tag name or tag id
769
-	 * @param string $userId owner of the tags
770
-	 * @return FileInfo[] array or file info
771
-	 */
772
-	static public function searchByTag($tag, $userId) {
773
-		return self::$defaultInstance->searchByTag($tag, $userId);
774
-	}
775
-
776
-	/**
777
-	 * check if a file or folder has been updated since $time
778
-	 *
779
-	 * @param string $path
780
-	 * @param int $time
781
-	 * @return bool
782
-	 */
783
-	static public function hasUpdated($path, $time) {
784
-		return self::$defaultInstance->hasUpdated($path, $time);
785
-	}
786
-
787
-	/**
788
-	 * Fix common problems with a file path
789
-	 *
790
-	 * @param string $path
791
-	 * @param bool $stripTrailingSlash whether to strip the trailing slash
792
-	 * @param bool $isAbsolutePath whether the given path is absolute
793
-	 * @param bool $keepUnicode true to disable unicode normalization
794
-	 * @return string
795
-	 */
796
-	public static function normalizePath($path, $stripTrailingSlash = true, $isAbsolutePath = false, $keepUnicode = false) {
797
-		if (is_null(self::$normalizedPathCache)) {
798
-			self::$normalizedPathCache = new CappedMemoryCache(2048);
799
-		}
800
-
801
-		/**
802
-		 * FIXME: This is a workaround for existing classes and files which call
803
-		 *        this function with another type than a valid string. This
804
-		 *        conversion should get removed as soon as all existing
805
-		 *        function calls have been fixed.
806
-		 */
807
-		$path = (string)$path;
808
-
809
-		$cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
810
-
811
-		if (isset(self::$normalizedPathCache[$cacheKey])) {
812
-			return self::$normalizedPathCache[$cacheKey];
813
-		}
814
-
815
-		if ($path === '') {
816
-			return '/';
817
-		}
818
-
819
-		//normalize unicode if possible
820
-		if (!$keepUnicode) {
821
-			$path = \OC_Util::normalizeUnicode($path);
822
-		}
823
-
824
-		//add leading slash, if it is already there we strip it anyway
825
-		$path = '/' . $path;
826
-
827
-		$patterns = [
828
-			'/\\\\/s',          // no windows style slashes
829
-			'/\/\.(\/\.)?\//s', // remove '/./'
830
-			'/\/{2,}/s',        // remove squence of slashes
831
-			'/\/\.$/s',         // remove trailing /.
832
-		];
833
-
834
-		do {
835
-			$count = 0;
836
-			$path = preg_replace($patterns, '/', $path, -1, $count);
837
-		} while ($count > 0);
838
-
839
-		//remove trailing slash
840
-		if ($stripTrailingSlash && strlen($path) > 1) {
841
-			$path = rtrim($path, '/');
842
-		}
843
-
844
-		self::$normalizedPathCache[$cacheKey] = $path;
845
-
846
-		return $path;
847
-	}
848
-
849
-	/**
850
-	 * get the filesystem info
851
-	 *
852
-	 * @param string $path
853
-	 * @param boolean $includeMountPoints whether to add mountpoint sizes,
854
-	 * defaults to true
855
-	 * @return \OC\Files\FileInfo|bool False if file does not exist
856
-	 */
857
-	public static function getFileInfo($path, $includeMountPoints = true) {
858
-		return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
859
-	}
860
-
861
-	/**
862
-	 * change file metadata
863
-	 *
864
-	 * @param string $path
865
-	 * @param array $data
866
-	 * @return int
867
-	 *
868
-	 * returns the fileid of the updated file
869
-	 */
870
-	public static function putFileInfo($path, $data) {
871
-		return self::$defaultInstance->putFileInfo($path, $data);
872
-	}
873
-
874
-	/**
875
-	 * get the content of a directory
876
-	 *
877
-	 * @param string $directory path under datadirectory
878
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
879
-	 * @return \OC\Files\FileInfo[]
880
-	 */
881
-	public static function getDirectoryContent($directory, $mimetype_filter = '') {
882
-		return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter);
883
-	}
884
-
885
-	/**
886
-	 * Get the path of a file by id
887
-	 *
888
-	 * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
889
-	 *
890
-	 * @param int $id
891
-	 * @throws NotFoundException
892
-	 * @return string
893
-	 */
894
-	public static function getPath($id) {
895
-		return self::$defaultInstance->getPath($id);
896
-	}
897
-
898
-	/**
899
-	 * Get the owner for a file or folder
900
-	 *
901
-	 * @param string $path
902
-	 * @return string
903
-	 */
904
-	public static function getOwner($path) {
905
-		return self::$defaultInstance->getOwner($path);
906
-	}
907
-
908
-	/**
909
-	 * get the ETag for a file or folder
910
-	 *
911
-	 * @param string $path
912
-	 * @return string
913
-	 */
914
-	static public function getETag($path) {
915
-		return self::$defaultInstance->getETag($path);
916
-	}
73
+    /**
74
+     * @var Mount\Manager $mounts
75
+     */
76
+    private static $mounts;
77
+
78
+    public static $loaded = false;
79
+    /**
80
+     * @var \OC\Files\View $defaultInstance
81
+     */
82
+    static private $defaultInstance;
83
+
84
+    static private $usersSetup = array();
85
+
86
+    static private $normalizedPathCache = null;
87
+
88
+    static private $listeningForProviders = false;
89
+
90
+    /**
91
+     * classname which used for hooks handling
92
+     * used as signalclass in OC_Hooks::emit()
93
+     */
94
+    const CLASSNAME = 'OC_Filesystem';
95
+
96
+    /**
97
+     * signalname emitted before file renaming
98
+     *
99
+     * @param string $oldpath
100
+     * @param string $newpath
101
+     */
102
+    const signal_rename = 'rename';
103
+
104
+    /**
105
+     * signal emitted after file renaming
106
+     *
107
+     * @param string $oldpath
108
+     * @param string $newpath
109
+     */
110
+    const signal_post_rename = 'post_rename';
111
+
112
+    /**
113
+     * signal emitted before file/dir creation
114
+     *
115
+     * @param string $path
116
+     * @param bool $run changing this flag to false in hook handler will cancel event
117
+     */
118
+    const signal_create = 'create';
119
+
120
+    /**
121
+     * signal emitted after file/dir creation
122
+     *
123
+     * @param string $path
124
+     * @param bool $run changing this flag to false in hook handler will cancel event
125
+     */
126
+    const signal_post_create = 'post_create';
127
+
128
+    /**
129
+     * signal emits before file/dir copy
130
+     *
131
+     * @param string $oldpath
132
+     * @param string $newpath
133
+     * @param bool $run changing this flag to false in hook handler will cancel event
134
+     */
135
+    const signal_copy = 'copy';
136
+
137
+    /**
138
+     * signal emits after file/dir copy
139
+     *
140
+     * @param string $oldpath
141
+     * @param string $newpath
142
+     */
143
+    const signal_post_copy = 'post_copy';
144
+
145
+    /**
146
+     * signal emits before file/dir save
147
+     *
148
+     * @param string $path
149
+     * @param bool $run changing this flag to false in hook handler will cancel event
150
+     */
151
+    const signal_write = 'write';
152
+
153
+    /**
154
+     * signal emits after file/dir save
155
+     *
156
+     * @param string $path
157
+     */
158
+    const signal_post_write = 'post_write';
159
+
160
+    /**
161
+     * signal emitted before file/dir update
162
+     *
163
+     * @param string $path
164
+     * @param bool $run changing this flag to false in hook handler will cancel event
165
+     */
166
+    const signal_update = 'update';
167
+
168
+    /**
169
+     * signal emitted after file/dir update
170
+     *
171
+     * @param string $path
172
+     * @param bool $run changing this flag to false in hook handler will cancel event
173
+     */
174
+    const signal_post_update = 'post_update';
175
+
176
+    /**
177
+     * signal emits when reading file/dir
178
+     *
179
+     * @param string $path
180
+     */
181
+    const signal_read = 'read';
182
+
183
+    /**
184
+     * signal emits when removing file/dir
185
+     *
186
+     * @param string $path
187
+     */
188
+    const signal_delete = 'delete';
189
+
190
+    /**
191
+     * parameters definitions for signals
192
+     */
193
+    const signal_param_path = 'path';
194
+    const signal_param_oldpath = 'oldpath';
195
+    const signal_param_newpath = 'newpath';
196
+
197
+    /**
198
+     * run - changing this flag to false in hook handler will cancel event
199
+     */
200
+    const signal_param_run = 'run';
201
+
202
+    const signal_create_mount = 'create_mount';
203
+    const signal_delete_mount = 'delete_mount';
204
+    const signal_param_mount_type = 'mounttype';
205
+    const signal_param_users = 'users';
206
+
207
+    /**
208
+     * @var \OC\Files\Storage\StorageFactory $loader
209
+     */
210
+    private static $loader;
211
+
212
+    /** @var bool */
213
+    private static $logWarningWhenAddingStorageWrapper = true;
214
+
215
+    /**
216
+     * @param bool $shouldLog
217
+     * @return bool previous value
218
+     * @internal
219
+     */
220
+    public static function logWarningWhenAddingStorageWrapper($shouldLog) {
221
+        $previousValue = self::$logWarningWhenAddingStorageWrapper;
222
+        self::$logWarningWhenAddingStorageWrapper = (bool) $shouldLog;
223
+        return $previousValue;
224
+    }
225
+
226
+    /**
227
+     * @param string $wrapperName
228
+     * @param callable $wrapper
229
+     * @param int $priority
230
+     */
231
+    public static function addStorageWrapper($wrapperName, $wrapper, $priority = 50) {
232
+        if (self::$logWarningWhenAddingStorageWrapper) {
233
+            \OC::$server->getLogger()->warning("Storage wrapper '{wrapper}' was not registered via the 'OC_Filesystem - preSetup' hook which could cause potential problems.", [
234
+                'wrapper' => $wrapperName,
235
+                'app' => 'filesystem',
236
+            ]);
237
+        }
238
+
239
+        $mounts = self::getMountManager()->getAll();
240
+        if (!self::getLoader()->addStorageWrapper($wrapperName, $wrapper, $priority, $mounts)) {
241
+            // do not re-wrap if storage with this name already existed
242
+            return;
243
+        }
244
+    }
245
+
246
+    /**
247
+     * Returns the storage factory
248
+     *
249
+     * @return \OCP\Files\Storage\IStorageFactory
250
+     */
251
+    public static function getLoader() {
252
+        if (!self::$loader) {
253
+            self::$loader = new StorageFactory();
254
+        }
255
+        return self::$loader;
256
+    }
257
+
258
+    /**
259
+     * Returns the mount manager
260
+     *
261
+     * @return \OC\Files\Mount\Manager
262
+     */
263
+    public static function getMountManager($user = '') {
264
+        if (!self::$mounts) {
265
+            \OC_Util::setupFS($user);
266
+        }
267
+        return self::$mounts;
268
+    }
269
+
270
+    /**
271
+     * get the mountpoint of the storage object for a path
272
+     * ( note: because a storage is not always mounted inside the fakeroot, the
273
+     * returned mountpoint is relative to the absolute root of the filesystem
274
+     * and doesn't take the chroot into account )
275
+     *
276
+     * @param string $path
277
+     * @return string
278
+     */
279
+    static public function getMountPoint($path) {
280
+        if (!self::$mounts) {
281
+            \OC_Util::setupFS();
282
+        }
283
+        $mount = self::$mounts->find($path);
284
+        if ($mount) {
285
+            return $mount->getMountPoint();
286
+        } else {
287
+            return '';
288
+        }
289
+    }
290
+
291
+    /**
292
+     * get a list of all mount points in a directory
293
+     *
294
+     * @param string $path
295
+     * @return string[]
296
+     */
297
+    static public function getMountPoints($path) {
298
+        if (!self::$mounts) {
299
+            \OC_Util::setupFS();
300
+        }
301
+        $result = array();
302
+        $mounts = self::$mounts->findIn($path);
303
+        foreach ($mounts as $mount) {
304
+            $result[] = $mount->getMountPoint();
305
+        }
306
+        return $result;
307
+    }
308
+
309
+    /**
310
+     * get the storage mounted at $mountPoint
311
+     *
312
+     * @param string $mountPoint
313
+     * @return \OC\Files\Storage\Storage
314
+     */
315
+    public static function getStorage($mountPoint) {
316
+        if (!self::$mounts) {
317
+            \OC_Util::setupFS();
318
+        }
319
+        $mount = self::$mounts->find($mountPoint);
320
+        return $mount->getStorage();
321
+    }
322
+
323
+    /**
324
+     * @param string $id
325
+     * @return Mount\MountPoint[]
326
+     */
327
+    public static function getMountByStorageId($id) {
328
+        if (!self::$mounts) {
329
+            \OC_Util::setupFS();
330
+        }
331
+        return self::$mounts->findByStorageId($id);
332
+    }
333
+
334
+    /**
335
+     * @param int $id
336
+     * @return Mount\MountPoint[]
337
+     */
338
+    public static function getMountByNumericId($id) {
339
+        if (!self::$mounts) {
340
+            \OC_Util::setupFS();
341
+        }
342
+        return self::$mounts->findByNumericId($id);
343
+    }
344
+
345
+    /**
346
+     * resolve a path to a storage and internal path
347
+     *
348
+     * @param string $path
349
+     * @return array an array consisting of the storage and the internal path
350
+     */
351
+    static public function resolvePath($path) {
352
+        if (!self::$mounts) {
353
+            \OC_Util::setupFS();
354
+        }
355
+        $mount = self::$mounts->find($path);
356
+        if ($mount) {
357
+            return array($mount->getStorage(), rtrim($mount->getInternalPath($path), '/'));
358
+        } else {
359
+            return array(null, null);
360
+        }
361
+    }
362
+
363
+    static public function init($user, $root) {
364
+        if (self::$defaultInstance) {
365
+            return false;
366
+        }
367
+        self::getLoader();
368
+        self::$defaultInstance = new View($root);
369
+
370
+        if (!self::$mounts) {
371
+            self::$mounts = \OC::$server->getMountManager();
372
+        }
373
+
374
+        //load custom mount config
375
+        self::initMountPoints($user);
376
+
377
+        self::$loaded = true;
378
+
379
+        return true;
380
+    }
381
+
382
+    static public function initMountManager() {
383
+        if (!self::$mounts) {
384
+            self::$mounts = \OC::$server->getMountManager();
385
+        }
386
+    }
387
+
388
+    /**
389
+     * Initialize system and personal mount points for a user
390
+     *
391
+     * @param string $user
392
+     * @throws \OC\User\NoUserException if the user is not available
393
+     */
394
+    public static function initMountPoints($user = '') {
395
+        if ($user == '') {
396
+            $user = \OC_User::getUser();
397
+        }
398
+        if ($user === null || $user === false || $user === '') {
399
+            throw new \OC\User\NoUserException('Attempted to initialize mount points for null user and no user in session');
400
+        }
401
+
402
+        if (isset(self::$usersSetup[$user])) {
403
+            return;
404
+        }
405
+
406
+        self::$usersSetup[$user] = true;
407
+
408
+        $userManager = \OC::$server->getUserManager();
409
+        $userObject = $userManager->get($user);
410
+
411
+        if (is_null($userObject)) {
412
+            \OCP\Util::writeLog('files', ' Backends provided no user object for ' . $user, ILogger::ERROR);
413
+            // reset flag, this will make it possible to rethrow the exception if called again
414
+            unset(self::$usersSetup[$user]);
415
+            throw new \OC\User\NoUserException('Backends provided no user object for ' . $user);
416
+        }
417
+
418
+        $realUid = $userObject->getUID();
419
+        // workaround in case of different casings
420
+        if ($user !== $realUid) {
421
+            $stack = json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 50));
422
+            \OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "' . $realUid . '" got "' . $user . '". Stack: ' . $stack, ILogger::WARN);
423
+            $user = $realUid;
424
+
425
+            // again with the correct casing
426
+            if (isset(self::$usersSetup[$user])) {
427
+                return;
428
+            }
429
+
430
+            self::$usersSetup[$user] = true;
431
+        }
432
+
433
+        if (\OC::$server->getLockdownManager()->canAccessFilesystem()) {
434
+            /** @var \OC\Files\Config\MountProviderCollection $mountConfigManager */
435
+            $mountConfigManager = \OC::$server->getMountProviderCollection();
436
+
437
+            // home mounts are handled seperate since we need to ensure this is mounted before we call the other mount providers
438
+            $homeMount = $mountConfigManager->getHomeMountForUser($userObject);
439
+
440
+            self::getMountManager()->addMount($homeMount);
441
+
442
+            \OC\Files\Filesystem::getStorage($user);
443
+
444
+            // Chance to mount for other storages
445
+            if ($userObject) {
446
+                $mounts = $mountConfigManager->addMountForUser($userObject, self::getMountManager());
447
+                $mounts[] = $homeMount;
448
+                $mountConfigManager->registerMounts($userObject, $mounts);
449
+            }
450
+
451
+            self::listenForNewMountProviders($mountConfigManager, $userManager);
452
+        } else {
453
+            self::getMountManager()->addMount(new MountPoint(
454
+                new NullStorage([]),
455
+                '/' . $user
456
+            ));
457
+            self::getMountManager()->addMount(new MountPoint(
458
+                new NullStorage([]),
459
+                '/' . $user . '/files'
460
+            ));
461
+        }
462
+        \OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
463
+    }
464
+
465
+    /**
466
+     * Get mounts from mount providers that are registered after setup
467
+     *
468
+     * @param MountProviderCollection $mountConfigManager
469
+     * @param IUserManager $userManager
470
+     */
471
+    private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
472
+        if (!self::$listeningForProviders) {
473
+            self::$listeningForProviders = true;
474
+            $mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
475
+                foreach (Filesystem::$usersSetup as $user => $setup) {
476
+                    $userObject = $userManager->get($user);
477
+                    if ($userObject) {
478
+                        $mounts = $provider->getMountsForUser($userObject, Filesystem::getLoader());
479
+                        array_walk($mounts, array(self::$mounts, 'addMount'));
480
+                    }
481
+                }
482
+            });
483
+        }
484
+    }
485
+
486
+    /**
487
+     * get the default filesystem view
488
+     *
489
+     * @return View
490
+     */
491
+    static public function getView() {
492
+        return self::$defaultInstance;
493
+    }
494
+
495
+    /**
496
+     * tear down the filesystem, removing all storage providers
497
+     */
498
+    static public function tearDown() {
499
+        self::clearMounts();
500
+        self::$defaultInstance = null;
501
+    }
502
+
503
+    /**
504
+     * get the relative path of the root data directory for the current user
505
+     *
506
+     * @return string
507
+     *
508
+     * Returns path like /admin/files
509
+     */
510
+    static public function getRoot() {
511
+        if (!self::$defaultInstance) {
512
+            return null;
513
+        }
514
+        return self::$defaultInstance->getRoot();
515
+    }
516
+
517
+    /**
518
+     * clear all mounts and storage backends
519
+     */
520
+    public static function clearMounts() {
521
+        if (self::$mounts) {
522
+            self::$usersSetup = array();
523
+            self::$mounts->clear();
524
+        }
525
+    }
526
+
527
+    /**
528
+     * mount an \OC\Files\Storage\Storage in our virtual filesystem
529
+     *
530
+     * @param \OC\Files\Storage\Storage|string $class
531
+     * @param array $arguments
532
+     * @param string $mountpoint
533
+     */
534
+    static public function mount($class, $arguments, $mountpoint) {
535
+        if (!self::$mounts) {
536
+            \OC_Util::setupFS();
537
+        }
538
+        $mount = new Mount\MountPoint($class, $mountpoint, $arguments, self::getLoader());
539
+        self::$mounts->addMount($mount);
540
+    }
541
+
542
+    /**
543
+     * return the path to a local version of the file
544
+     * we need this because we can't know if a file is stored local or not from
545
+     * outside the filestorage and for some purposes a local file is needed
546
+     *
547
+     * @param string $path
548
+     * @return string
549
+     */
550
+    static public function getLocalFile($path) {
551
+        return self::$defaultInstance->getLocalFile($path);
552
+    }
553
+
554
+    /**
555
+     * @param string $path
556
+     * @return string
557
+     */
558
+    static public function getLocalFolder($path) {
559
+        return self::$defaultInstance->getLocalFolder($path);
560
+    }
561
+
562
+    /**
563
+     * return path to file which reflects one visible in browser
564
+     *
565
+     * @param string $path
566
+     * @return string
567
+     */
568
+    static public function getLocalPath($path) {
569
+        $datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
570
+        $newpath = $path;
571
+        if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
572
+            $newpath = substr($path, strlen($datadir));
573
+        }
574
+        return $newpath;
575
+    }
576
+
577
+    /**
578
+     * check if the requested path is valid
579
+     *
580
+     * @param string $path
581
+     * @return bool
582
+     */
583
+    static public function isValidPath($path) {
584
+        $path = self::normalizePath($path);
585
+        if (!$path || $path[0] !== '/') {
586
+            $path = '/' . $path;
587
+        }
588
+        if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
589
+            return false;
590
+        }
591
+        return true;
592
+    }
593
+
594
+    /**
595
+     * checks if a file is blacklisted for storage in the filesystem
596
+     * Listens to write and rename hooks
597
+     *
598
+     * @param array $data from hook
599
+     */
600
+    static public function isBlacklisted($data) {
601
+        if (isset($data['path'])) {
602
+            $path = $data['path'];
603
+        } else if (isset($data['newpath'])) {
604
+            $path = $data['newpath'];
605
+        }
606
+        if (isset($path)) {
607
+            if (self::isFileBlacklisted($path)) {
608
+                $data['run'] = false;
609
+            }
610
+        }
611
+    }
612
+
613
+    /**
614
+     * @param string $filename
615
+     * @return bool
616
+     */
617
+    static public function isFileBlacklisted($filename) {
618
+        $filename = self::normalizePath($filename);
619
+
620
+        $blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array('.htaccess'));
621
+        $filename = strtolower(basename($filename));
622
+        return in_array($filename, $blacklist);
623
+    }
624
+
625
+    /**
626
+     * check if the directory should be ignored when scanning
627
+     * NOTE: the special directories . and .. would cause never ending recursion
628
+     *
629
+     * @param String $dir
630
+     * @return boolean
631
+     */
632
+    static public function isIgnoredDir($dir) {
633
+        if ($dir === '.' || $dir === '..') {
634
+            return true;
635
+        }
636
+        return false;
637
+    }
638
+
639
+    /**
640
+     * following functions are equivalent to their php builtin equivalents for arguments/return values.
641
+     */
642
+    static public function mkdir($path) {
643
+        return self::$defaultInstance->mkdir($path);
644
+    }
645
+
646
+    static public function rmdir($path) {
647
+        return self::$defaultInstance->rmdir($path);
648
+    }
649
+
650
+    static public function is_dir($path) {
651
+        return self::$defaultInstance->is_dir($path);
652
+    }
653
+
654
+    static public function is_file($path) {
655
+        return self::$defaultInstance->is_file($path);
656
+    }
657
+
658
+    static public function stat($path) {
659
+        return self::$defaultInstance->stat($path);
660
+    }
661
+
662
+    static public function filetype($path) {
663
+        return self::$defaultInstance->filetype($path);
664
+    }
665
+
666
+    static public function filesize($path) {
667
+        return self::$defaultInstance->filesize($path);
668
+    }
669
+
670
+    static public function readfile($path) {
671
+        return self::$defaultInstance->readfile($path);
672
+    }
673
+
674
+    static public function isCreatable($path) {
675
+        return self::$defaultInstance->isCreatable($path);
676
+    }
677
+
678
+    static public function isReadable($path) {
679
+        return self::$defaultInstance->isReadable($path);
680
+    }
681
+
682
+    static public function isUpdatable($path) {
683
+        return self::$defaultInstance->isUpdatable($path);
684
+    }
685
+
686
+    static public function isDeletable($path) {
687
+        return self::$defaultInstance->isDeletable($path);
688
+    }
689
+
690
+    static public function isSharable($path) {
691
+        return self::$defaultInstance->isSharable($path);
692
+    }
693
+
694
+    static public function file_exists($path) {
695
+        return self::$defaultInstance->file_exists($path);
696
+    }
697
+
698
+    static public function filemtime($path) {
699
+        return self::$defaultInstance->filemtime($path);
700
+    }
701
+
702
+    static public function touch($path, $mtime = null) {
703
+        return self::$defaultInstance->touch($path, $mtime);
704
+    }
705
+
706
+    /**
707
+     * @return string
708
+     */
709
+    static public function file_get_contents($path) {
710
+        return self::$defaultInstance->file_get_contents($path);
711
+    }
712
+
713
+    static public function file_put_contents($path, $data) {
714
+        return self::$defaultInstance->file_put_contents($path, $data);
715
+    }
716
+
717
+    static public function unlink($path) {
718
+        return self::$defaultInstance->unlink($path);
719
+    }
720
+
721
+    static public function rename($path1, $path2) {
722
+        return self::$defaultInstance->rename($path1, $path2);
723
+    }
724
+
725
+    static public function copy($path1, $path2) {
726
+        return self::$defaultInstance->copy($path1, $path2);
727
+    }
728
+
729
+    static public function fopen($path, $mode) {
730
+        return self::$defaultInstance->fopen($path, $mode);
731
+    }
732
+
733
+    /**
734
+     * @return string
735
+     */
736
+    static public function toTmpFile($path) {
737
+        return self::$defaultInstance->toTmpFile($path);
738
+    }
739
+
740
+    static public function fromTmpFile($tmpFile, $path) {
741
+        return self::$defaultInstance->fromTmpFile($tmpFile, $path);
742
+    }
743
+
744
+    static public function getMimeType($path) {
745
+        return self::$defaultInstance->getMimeType($path);
746
+    }
747
+
748
+    static public function hash($type, $path, $raw = false) {
749
+        return self::$defaultInstance->hash($type, $path, $raw);
750
+    }
751
+
752
+    static public function free_space($path = '/') {
753
+        return self::$defaultInstance->free_space($path);
754
+    }
755
+
756
+    static public function search($query) {
757
+        return self::$defaultInstance->search($query);
758
+    }
759
+
760
+    /**
761
+     * @param string $query
762
+     */
763
+    static public function searchByMime($query) {
764
+        return self::$defaultInstance->searchByMime($query);
765
+    }
766
+
767
+    /**
768
+     * @param string|int $tag name or tag id
769
+     * @param string $userId owner of the tags
770
+     * @return FileInfo[] array or file info
771
+     */
772
+    static public function searchByTag($tag, $userId) {
773
+        return self::$defaultInstance->searchByTag($tag, $userId);
774
+    }
775
+
776
+    /**
777
+     * check if a file or folder has been updated since $time
778
+     *
779
+     * @param string $path
780
+     * @param int $time
781
+     * @return bool
782
+     */
783
+    static public function hasUpdated($path, $time) {
784
+        return self::$defaultInstance->hasUpdated($path, $time);
785
+    }
786
+
787
+    /**
788
+     * Fix common problems with a file path
789
+     *
790
+     * @param string $path
791
+     * @param bool $stripTrailingSlash whether to strip the trailing slash
792
+     * @param bool $isAbsolutePath whether the given path is absolute
793
+     * @param bool $keepUnicode true to disable unicode normalization
794
+     * @return string
795
+     */
796
+    public static function normalizePath($path, $stripTrailingSlash = true, $isAbsolutePath = false, $keepUnicode = false) {
797
+        if (is_null(self::$normalizedPathCache)) {
798
+            self::$normalizedPathCache = new CappedMemoryCache(2048);
799
+        }
800
+
801
+        /**
802
+         * FIXME: This is a workaround for existing classes and files which call
803
+         *        this function with another type than a valid string. This
804
+         *        conversion should get removed as soon as all existing
805
+         *        function calls have been fixed.
806
+         */
807
+        $path = (string)$path;
808
+
809
+        $cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
810
+
811
+        if (isset(self::$normalizedPathCache[$cacheKey])) {
812
+            return self::$normalizedPathCache[$cacheKey];
813
+        }
814
+
815
+        if ($path === '') {
816
+            return '/';
817
+        }
818
+
819
+        //normalize unicode if possible
820
+        if (!$keepUnicode) {
821
+            $path = \OC_Util::normalizeUnicode($path);
822
+        }
823
+
824
+        //add leading slash, if it is already there we strip it anyway
825
+        $path = '/' . $path;
826
+
827
+        $patterns = [
828
+            '/\\\\/s',          // no windows style slashes
829
+            '/\/\.(\/\.)?\//s', // remove '/./'
830
+            '/\/{2,}/s',        // remove squence of slashes
831
+            '/\/\.$/s',         // remove trailing /.
832
+        ];
833
+
834
+        do {
835
+            $count = 0;
836
+            $path = preg_replace($patterns, '/', $path, -1, $count);
837
+        } while ($count > 0);
838
+
839
+        //remove trailing slash
840
+        if ($stripTrailingSlash && strlen($path) > 1) {
841
+            $path = rtrim($path, '/');
842
+        }
843
+
844
+        self::$normalizedPathCache[$cacheKey] = $path;
845
+
846
+        return $path;
847
+    }
848
+
849
+    /**
850
+     * get the filesystem info
851
+     *
852
+     * @param string $path
853
+     * @param boolean $includeMountPoints whether to add mountpoint sizes,
854
+     * defaults to true
855
+     * @return \OC\Files\FileInfo|bool False if file does not exist
856
+     */
857
+    public static function getFileInfo($path, $includeMountPoints = true) {
858
+        return self::$defaultInstance->getFileInfo($path, $includeMountPoints);
859
+    }
860
+
861
+    /**
862
+     * change file metadata
863
+     *
864
+     * @param string $path
865
+     * @param array $data
866
+     * @return int
867
+     *
868
+     * returns the fileid of the updated file
869
+     */
870
+    public static function putFileInfo($path, $data) {
871
+        return self::$defaultInstance->putFileInfo($path, $data);
872
+    }
873
+
874
+    /**
875
+     * get the content of a directory
876
+     *
877
+     * @param string $directory path under datadirectory
878
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
879
+     * @return \OC\Files\FileInfo[]
880
+     */
881
+    public static function getDirectoryContent($directory, $mimetype_filter = '') {
882
+        return self::$defaultInstance->getDirectoryContent($directory, $mimetype_filter);
883
+    }
884
+
885
+    /**
886
+     * Get the path of a file by id
887
+     *
888
+     * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
889
+     *
890
+     * @param int $id
891
+     * @throws NotFoundException
892
+     * @return string
893
+     */
894
+    public static function getPath($id) {
895
+        return self::$defaultInstance->getPath($id);
896
+    }
897
+
898
+    /**
899
+     * Get the owner for a file or folder
900
+     *
901
+     * @param string $path
902
+     * @return string
903
+     */
904
+    public static function getOwner($path) {
905
+        return self::$defaultInstance->getOwner($path);
906
+    }
907
+
908
+    /**
909
+     * get the ETag for a file or folder
910
+     *
911
+     * @param string $path
912
+     * @return string
913
+     */
914
+    static public function getETag($path) {
915
+        return self::$defaultInstance->getETag($path);
916
+    }
917 917
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 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, ILogger::ERROR);
412
+			\OCP\Util::writeLog('files', ' Backends provided no user object for '.$user, ILogger::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, ILogger::WARN);
422
+			\OCP\Util::writeLog('files', 'initMountPoints() called with wrong user casing. This could be a bug. Expected: "'.$realUid.'" got "'.$user.'". Stack: '.$stack, ILogger::WARN);
423 423
 			$user = $realUid;
424 424
 
425 425
 			// again with the correct casing
@@ -452,11 +452,11 @@  discard block
 block discarded – undo
452 452
 		} else {
453 453
 			self::getMountManager()->addMount(new MountPoint(
454 454
 				new NullStorage([]),
455
-				'/' . $user
455
+				'/'.$user
456 456
 			));
457 457
 			self::getMountManager()->addMount(new MountPoint(
458 458
 				new NullStorage([]),
459
-				'/' . $user . '/files'
459
+				'/'.$user.'/files'
460 460
 			));
461 461
 		}
462 462
 		\OC_Hook::emit('OC_Filesystem', 'post_initMountPoints', array('user' => $user));
@@ -471,7 +471,7 @@  discard block
 block discarded – undo
471 471
 	private static function listenForNewMountProviders(MountProviderCollection $mountConfigManager, IUserManager $userManager) {
472 472
 		if (!self::$listeningForProviders) {
473 473
 			self::$listeningForProviders = true;
474
-			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function (IMountProvider $provider) use ($userManager) {
474
+			$mountConfigManager->listen('\OC\Files\Config', 'registerMountProvider', function(IMountProvider $provider) use ($userManager) {
475 475
 				foreach (Filesystem::$usersSetup as $user => $setup) {
476 476
 					$userObject = $userManager->get($user);
477 477
 					if ($userObject) {
@@ -566,7 +566,7 @@  discard block
 block discarded – undo
566 566
 	 * @return string
567 567
 	 */
568 568
 	static public function getLocalPath($path) {
569
-		$datadir = \OC_User::getHome(\OC_User::getUser()) . '/files';
569
+		$datadir = \OC_User::getHome(\OC_User::getUser()).'/files';
570 570
 		$newpath = $path;
571 571
 		if (strncmp($newpath, $datadir, strlen($datadir)) == 0) {
572 572
 			$newpath = substr($path, strlen($datadir));
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
 	static public function isValidPath($path) {
584 584
 		$path = self::normalizePath($path);
585 585
 		if (!$path || $path[0] !== '/') {
586
-			$path = '/' . $path;
586
+			$path = '/'.$path;
587 587
 		}
588 588
 		if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
589 589
 			return false;
@@ -804,7 +804,7 @@  discard block
 block discarded – undo
804 804
 		 *        conversion should get removed as soon as all existing
805 805
 		 *        function calls have been fixed.
806 806
 		 */
807
-		$path = (string)$path;
807
+		$path = (string) $path;
808 808
 
809 809
 		$cacheKey = json_encode([$path, $stripTrailingSlash, $isAbsolutePath, $keepUnicode]);
810 810
 
@@ -822,13 +822,13 @@  discard block
 block discarded – undo
822 822
 		}
823 823
 
824 824
 		//add leading slash, if it is already there we strip it anyway
825
-		$path = '/' . $path;
825
+		$path = '/'.$path;
826 826
 
827 827
 		$patterns = [
828
-			'/\\\\/s',          // no windows style slashes
828
+			'/\\\\/s', // no windows style slashes
829 829
 			'/\/\.(\/\.)?\//s', // remove '/./'
830
-			'/\/{2,}/s',        // remove squence of slashes
831
-			'/\/\.$/s',         // remove trailing /.
830
+			'/\/{2,}/s', // remove squence of slashes
831
+			'/\/\.$/s', // remove trailing /.
832 832
 		];
833 833
 
834 834
 		do {
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.
Spacing   +24 added lines, -24 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
 
@@ -440,7 +440,7 @@  discard block
 block discarded – undo
440 440
 				}
441 441
 			} catch (ModuleDoesNotExistsException $e) {
442 442
 				$this->logger->logException($e, [
443
-					'message' => 'Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted',
443
+					'message' => 'Encryption module "'.$encryptionModuleId.'" not found, file will be stored unencrypted',
444 444
 					'level' => ILogger::WARN,
445 445
 					'app' => 'core',
446 446
 				]);
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
 				try {
496 496
 					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
497 497
 				} catch (\Exception $e) {
498
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
498
+					$this->logger->error('Couldn\'t re-calculate unencrypted size for '.$path);
499 499
 					$this->logger->logException($e);
500 500
 				}
501 501
 				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
@@ -524,7 +524,7 @@  discard block
 block discarded – undo
524 524
 
525 525
 		// if we couldn't open the file we return the old unencrypted size
526 526
 		if (!is_resource($stream)) {
527
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
527
+			$this->logger->error('Could not open '.$path.'. Recalculation of unencrypted size aborted.');
528 528
 			return $unencryptedSize;
529 529
 		}
530 530
 
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
 		// next highest is end of chunks, one subtracted is last one
550 550
 		// we have to read the last chunk, we can't just calculate it (because of padding etc)
551 551
 
552
-		$lastChunkNr = ceil($size/ $blockSize)-1;
552
+		$lastChunkNr = ceil($size / $blockSize) - 1;
553 553
 		// calculate last chunk position
554 554
 		$lastChunkPos = ($lastChunkNr * $blockSize);
555 555
 		// try to fseek to the last chunk, if it fails we have to read the whole file
@@ -557,16 +557,16 @@  discard block
 block discarded – undo
557 557
 			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
558 558
 		}
559 559
 
560
-		$lastChunkContentEncrypted='';
560
+		$lastChunkContentEncrypted = '';
561 561
 		$count = $blockSize;
562 562
 
563 563
 		while ($count > 0) {
564
-			$data=fread($stream, $blockSize);
565
-			$count=strlen($data);
564
+			$data = fread($stream, $blockSize);
565
+			$count = strlen($data);
566 566
 			$lastChunkContentEncrypted .= $data;
567
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
567
+			if (strlen($lastChunkContentEncrypted) > $blockSize) {
568 568
 				$newUnencryptedSize += $unencryptedBlockSize;
569
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
569
+				$lastChunkContentEncrypted = substr($lastChunkContentEncrypted, $blockSize);
570 570
 			}
571 571
 		}
572 572
 
@@ -574,8 +574,8 @@  discard block
 block discarded – undo
574 574
 
575 575
 		// we have to decrypt the last chunk to get it actual size
576 576
 		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
577
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
578
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
577
+		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr.'end');
578
+		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr.'end');
579 579
 
580 580
 		// calc the real file size with the size of the last chunk
581 581
 		$newUnencryptedSize += strlen($decryptedLastChunk);
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
 		$cacheInformation = [
660 660
 			'encrypted' => $isEncrypted,
661 661
 		];
662
-		if($isEncrypted) {
662
+		if ($isEncrypted) {
663 663
 			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
664 664
 
665 665
 			// In case of a move operation from an unencrypted to an encrypted
@@ -667,7 +667,7 @@  discard block
 block discarded – undo
667 667
 			// correct value would be "1". Thus we manually set the value to "1"
668 668
 			// for those cases.
669 669
 			// See also https://github.com/owncloud/core/issues/23078
670
-			if($encryptedVersion === 0 || !$keepEncryptionVersion) {
670
+			if ($encryptedVersion === 0 || !$keepEncryptionVersion) {
671 671
 				$encryptedVersion = 1;
672 672
 			}
673 673
 
@@ -703,9 +703,9 @@  discard block
 block discarded – undo
703 703
 			// remember that we try to create a version so that we can detect it during
704 704
 			// fopen($sourceInternalPath) and by-pass the encryption in order to
705 705
 			// create a 1:1 copy of the file
706
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
706
+			$this->arrayCache->set('encryption_copy_version_'.$sourceInternalPath, true);
707 707
 			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
708
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
708
+			$this->arrayCache->remove('encryption_copy_version_'.$sourceInternalPath);
709 709
 			if ($result) {
710 710
 				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
711 711
 				// make sure that we update the unencrypted size for the version
@@ -725,7 +725,7 @@  discard block
 block discarded – undo
725 725
 		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
726 726
 		if (count($mount) === 1) {
727 727
 			$mountPoint = $mount[0]->getMountPoint();
728
-			$source = $mountPoint . '/' . $sourceInternalPath;
728
+			$source = $mountPoint.'/'.$sourceInternalPath;
729 729
 			$target = $this->getFullPath($targetInternalPath);
730 730
 			$this->copyKeys($source, $target);
731 731
 		} else {
@@ -738,7 +738,7 @@  discard block
 block discarded – undo
738 738
 			if (is_resource($dh)) {
739 739
 				while ($result and ($file = readdir($dh)) !== false) {
740 740
 					if (!Filesystem::isIgnoredDir($file)) {
741
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
741
+						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath.'/'.$file, $targetInternalPath.'/'.$file, false, $isRename);
742 742
 					}
743 743
 				}
744 744
 			}
@@ -754,7 +754,7 @@  discard block
 block discarded – undo
754 754
 				fclose($target);
755 755
 				throw $e;
756 756
 			}
757
-			if($result) {
757
+			if ($result) {
758 758
 				if ($preserveMtime) {
759 759
 					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
760 760
 				}
@@ -766,7 +766,7 @@  discard block
 block discarded – undo
766 766
 				$this->getCache()->remove($targetInternalPath);
767 767
 			}
768 768
 		}
769
-		return (bool)$result;
769
+		return (bool) $result;
770 770
 
771 771
 	}
772 772
 
@@ -837,7 +837,7 @@  discard block
 block discarded – undo
837 837
 	 * @return string full path including mount point
838 838
 	 */
839 839
 	protected function getFullPath($path) {
840
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
840
+		return Filesystem::normalizePath($this->mountPoint.'/'.$path);
841 841
 	}
842 842
 
843 843
 	/**
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
 				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
894 894
 
895 895
 				// +1 to not start with an ':' which would result in empty element at the beginning
896
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
896
+				$exploded = explode(':', substr($header, strlen(Util::HEADER_START) + 1));
897 897
 
898 898
 				$element = array_shift($exploded);
899 899
 				while ($element !== Util::HEADER_END) {
@@ -956,7 +956,7 @@  discard block
 block discarded – undo
956 956
 			try {
957 957
 				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
958 958
 			} catch (ModuleDoesNotExistsException $e) {
959
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
959
+				$this->logger->critical('Encryption module defined in "'.$path.'" not loaded!');
960 960
 				throw $e;
961 961
 			}
962 962
 		}
Please login to merge, or discard this patch.
Indentation   +980 added lines, -980 removed lines patch added patch discarded remove patch
@@ -48,985 +48,985 @@
 block discarded – undo
48 48
 
49 49
 class Encryption extends Wrapper {
50 50
 
51
-	use LocalTempFileTrait;
52
-
53
-	/** @var string */
54
-	private $mountPoint;
55
-
56
-	/** @var \OC\Encryption\Util */
57
-	private $util;
58
-
59
-	/** @var \OCP\Encryption\IManager */
60
-	private $encryptionManager;
61
-
62
-	/** @var \OCP\ILogger */
63
-	private $logger;
64
-
65
-	/** @var string */
66
-	private $uid;
67
-
68
-	/** @var array */
69
-	protected $unencryptedSize;
70
-
71
-	/** @var \OCP\Encryption\IFile */
72
-	private $fileHelper;
73
-
74
-	/** @var IMountPoint */
75
-	private $mount;
76
-
77
-	/** @var IStorage */
78
-	private $keyStorage;
79
-
80
-	/** @var Update */
81
-	private $update;
82
-
83
-	/** @var Manager */
84
-	private $mountManager;
85
-
86
-	/** @var array remember for which path we execute the repair step to avoid recursions */
87
-	private $fixUnencryptedSizeOf = array();
88
-
89
-	/** @var  ArrayCache */
90
-	private $arrayCache;
91
-
92
-	/**
93
-	 * @param array $parameters
94
-	 * @param IManager $encryptionManager
95
-	 * @param Util $util
96
-	 * @param ILogger $logger
97
-	 * @param IFile $fileHelper
98
-	 * @param string $uid
99
-	 * @param IStorage $keyStorage
100
-	 * @param Update $update
101
-	 * @param Manager $mountManager
102
-	 * @param ArrayCache $arrayCache
103
-	 */
104
-	public function __construct(
105
-			$parameters,
106
-			IManager $encryptionManager = null,
107
-			Util $util = null,
108
-			ILogger $logger = null,
109
-			IFile $fileHelper = null,
110
-			$uid = null,
111
-			IStorage $keyStorage = null,
112
-			Update $update = null,
113
-			Manager $mountManager = null,
114
-			ArrayCache $arrayCache = null
115
-		) {
116
-
117
-		$this->mountPoint = $parameters['mountPoint'];
118
-		$this->mount = $parameters['mount'];
119
-		$this->encryptionManager = $encryptionManager;
120
-		$this->util = $util;
121
-		$this->logger = $logger;
122
-		$this->uid = $uid;
123
-		$this->fileHelper = $fileHelper;
124
-		$this->keyStorage = $keyStorage;
125
-		$this->unencryptedSize = array();
126
-		$this->update = $update;
127
-		$this->mountManager = $mountManager;
128
-		$this->arrayCache = $arrayCache;
129
-		parent::__construct($parameters);
130
-	}
131
-
132
-	/**
133
-	 * see http://php.net/manual/en/function.filesize.php
134
-	 * The result for filesize when called on a folder is required to be 0
135
-	 *
136
-	 * @param string $path
137
-	 * @return int
138
-	 */
139
-	public function filesize($path) {
140
-		$fullPath = $this->getFullPath($path);
141
-
142
-		/** @var CacheEntry $info */
143
-		$info = $this->getCache()->get($path);
144
-		if (isset($this->unencryptedSize[$fullPath])) {
145
-			$size = $this->unencryptedSize[$fullPath];
146
-			// update file cache
147
-			if ($info instanceof ICacheEntry) {
148
-				$info = $info->getData();
149
-				$info['encrypted'] = $info['encryptedVersion'];
150
-			} else {
151
-				if (!is_array($info)) {
152
-					$info = [];
153
-				}
154
-				$info['encrypted'] = true;
155
-			}
156
-
157
-			$info['size'] = $size;
158
-			$this->getCache()->put($path, $info);
159
-
160
-			return $size;
161
-		}
162
-
163
-		if (isset($info['fileid']) && $info['encrypted']) {
164
-			return $this->verifyUnencryptedSize($path, $info['size']);
165
-		}
166
-
167
-		return $this->storage->filesize($path);
168
-	}
169
-
170
-	/**
171
-	 * @param string $path
172
-	 * @return array
173
-	 */
174
-	public function getMetaData($path) {
175
-		$data = $this->storage->getMetaData($path);
176
-		if (is_null($data)) {
177
-			return null;
178
-		}
179
-		$fullPath = $this->getFullPath($path);
180
-		$info = $this->getCache()->get($path);
181
-
182
-		if (isset($this->unencryptedSize[$fullPath])) {
183
-			$data['encrypted'] = true;
184
-			$data['size'] = $this->unencryptedSize[$fullPath];
185
-		} else {
186
-			if (isset($info['fileid']) && $info['encrypted']) {
187
-				$data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
188
-				$data['encrypted'] = true;
189
-			}
190
-		}
191
-
192
-		if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
193
-			$data['encryptedVersion'] = $info['encryptedVersion'];
194
-		}
195
-
196
-		return $data;
197
-	}
198
-
199
-	/**
200
-	 * see http://php.net/manual/en/function.file_get_contents.php
201
-	 *
202
-	 * @param string $path
203
-	 * @return string
204
-	 */
205
-	public function file_get_contents($path) {
206
-
207
-		$encryptionModule = $this->getEncryptionModule($path);
208
-
209
-		if ($encryptionModule) {
210
-			$handle = $this->fopen($path, "r");
211
-			if (!$handle) {
212
-				return false;
213
-			}
214
-			$data = stream_get_contents($handle);
215
-			fclose($handle);
216
-			return $data;
217
-		}
218
-		return $this->storage->file_get_contents($path);
219
-	}
220
-
221
-	/**
222
-	 * see http://php.net/manual/en/function.file_put_contents.php
223
-	 *
224
-	 * @param string $path
225
-	 * @param string $data
226
-	 * @return bool
227
-	 */
228
-	public function file_put_contents($path, $data) {
229
-		// file put content will always be translated to a stream write
230
-		$handle = $this->fopen($path, 'w');
231
-		if (is_resource($handle)) {
232
-			$written = fwrite($handle, $data);
233
-			fclose($handle);
234
-			return $written;
235
-		}
236
-
237
-		return false;
238
-	}
239
-
240
-	/**
241
-	 * see http://php.net/manual/en/function.unlink.php
242
-	 *
243
-	 * @param string $path
244
-	 * @return bool
245
-	 */
246
-	public function unlink($path) {
247
-		$fullPath = $this->getFullPath($path);
248
-		if ($this->util->isExcluded($fullPath)) {
249
-			return $this->storage->unlink($path);
250
-		}
251
-
252
-		$encryptionModule = $this->getEncryptionModule($path);
253
-		if ($encryptionModule) {
254
-			$this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
255
-		}
256
-
257
-		return $this->storage->unlink($path);
258
-	}
259
-
260
-	/**
261
-	 * see http://php.net/manual/en/function.rename.php
262
-	 *
263
-	 * @param string $path1
264
-	 * @param string $path2
265
-	 * @return bool
266
-	 */
267
-	public function rename($path1, $path2) {
268
-
269
-		$result = $this->storage->rename($path1, $path2);
270
-
271
-		if ($result &&
272
-			// versions always use the keys from the original file, so we can skip
273
-			// this step for versions
274
-			$this->isVersion($path2) === false &&
275
-			$this->encryptionManager->isEnabled()) {
276
-			$source = $this->getFullPath($path1);
277
-			if (!$this->util->isExcluded($source)) {
278
-				$target = $this->getFullPath($path2);
279
-				if (isset($this->unencryptedSize[$source])) {
280
-					$this->unencryptedSize[$target] = $this->unencryptedSize[$source];
281
-				}
282
-				$this->keyStorage->renameKeys($source, $target);
283
-				$module = $this->getEncryptionModule($path2);
284
-				if ($module) {
285
-					$module->update($target, $this->uid, []);
286
-				}
287
-			}
288
-		}
289
-
290
-		return $result;
291
-	}
292
-
293
-	/**
294
-	 * see http://php.net/manual/en/function.rmdir.php
295
-	 *
296
-	 * @param string $path
297
-	 * @return bool
298
-	 */
299
-	public function rmdir($path) {
300
-		$result = $this->storage->rmdir($path);
301
-		$fullPath = $this->getFullPath($path);
302
-		if ($result &&
303
-			$this->util->isExcluded($fullPath) === false &&
304
-			$this->encryptionManager->isEnabled()
305
-		) {
306
-			$this->keyStorage->deleteAllFileKeys($fullPath);
307
-		}
308
-
309
-		return $result;
310
-	}
311
-
312
-	/**
313
-	 * check if a file can be read
314
-	 *
315
-	 * @param string $path
316
-	 * @return bool
317
-	 */
318
-	public function isReadable($path) {
319
-
320
-		$isReadable = true;
321
-
322
-		$metaData = $this->getMetaData($path);
323
-		if (
324
-			!$this->is_dir($path) &&
325
-			isset($metaData['encrypted']) &&
326
-			$metaData['encrypted'] === true
327
-		) {
328
-			$fullPath = $this->getFullPath($path);
329
-			$module = $this->getEncryptionModule($path);
330
-			$isReadable = $module->isReadable($fullPath, $this->uid);
331
-		}
332
-
333
-		return $this->storage->isReadable($path) && $isReadable;
334
-	}
335
-
336
-	/**
337
-	 * see http://php.net/manual/en/function.copy.php
338
-	 *
339
-	 * @param string $path1
340
-	 * @param string $path2
341
-	 * @return bool
342
-	 */
343
-	public function copy($path1, $path2) {
344
-
345
-		$source = $this->getFullPath($path1);
346
-
347
-		if ($this->util->isExcluded($source)) {
348
-			return $this->storage->copy($path1, $path2);
349
-		}
350
-
351
-		// need to stream copy file by file in case we copy between a encrypted
352
-		// and a unencrypted storage
353
-		$this->unlink($path2);
354
-		return $this->copyFromStorage($this, $path1, $path2);
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';
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
-					// if we update a encrypted file with a un-encrypted one we change the db flag
416
-					if ($targetIsEncrypted && $encryptionEnabled === false) {
417
-						$cache = $this->storage->getCache();
418
-						if ($cache) {
419
-							$entry = $cache->get($path);
420
-							$cache->update($entry->getId(), ['encrypted' => 0]);
421
-						}
422
-					}
423
-					if ($encryptionEnabled) {
424
-						// if $encryptionModuleId is empty, the default module will be used
425
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
426
-						$shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
427
-						$signed = true;
428
-					}
429
-				} else {
430
-					$info = $this->getCache()->get($path);
431
-					// only get encryption module if we found one in the header
432
-					// or if file should be encrypted according to the file cache
433
-					if (!empty($encryptionModuleId)) {
434
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
435
-						$shouldEncrypt = true;
436
-					} else if (empty($encryptionModuleId) && $info['encrypted'] === true) {
437
-						// we come from a old installation. No header and/or no module defined
438
-						// but the file is encrypted. In this case we need to use the
439
-						// OC_DEFAULT_MODULE to read the file
440
-						$encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
441
-						$shouldEncrypt = true;
442
-						$targetIsEncrypted = true;
443
-					}
444
-				}
445
-			} catch (ModuleDoesNotExistsException $e) {
446
-				$this->logger->logException($e, [
447
-					'message' => 'Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted',
448
-					'level' => ILogger::WARN,
449
-					'app' => 'core',
450
-				]);
451
-			}
452
-
453
-			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
454
-			if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
455
-				if (!$targetExists || !$targetIsEncrypted) {
456
-					$shouldEncrypt = false;
457
-				}
458
-			}
459
-
460
-			if ($shouldEncrypt === true && $encryptionModule !== null) {
461
-				$headerSize = $this->getHeaderSize($path);
462
-				$source = $this->storage->fopen($path, $mode);
463
-				if (!is_resource($source)) {
464
-					return false;
465
-				}
466
-				$handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
467
-					$this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
468
-					$size, $unencryptedSize, $headerSize, $signed);
469
-				return $handle;
470
-			}
471
-
472
-		}
473
-
474
-		return $this->storage->fopen($path, $mode);
475
-	}
476
-
477
-
478
-	/**
479
-	 * perform some plausibility checks if the the unencrypted size is correct.
480
-	 * If not, we calculate the correct unencrypted size and return it
481
-	 *
482
-	 * @param string $path internal path relative to the storage root
483
-	 * @param int $unencryptedSize size of the unencrypted file
484
-	 *
485
-	 * @return int unencrypted size
486
-	 */
487
-	protected function verifyUnencryptedSize($path, $unencryptedSize) {
488
-
489
-		$size = $this->storage->filesize($path);
490
-		$result = $unencryptedSize;
491
-
492
-		if ($unencryptedSize < 0 ||
493
-			($size > 0 && $unencryptedSize === $size)
494
-		) {
495
-			// check if we already calculate the unencrypted size for the
496
-			// given path to avoid recursions
497
-			if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
498
-				$this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
499
-				try {
500
-					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
501
-				} catch (\Exception $e) {
502
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
503
-					$this->logger->logException($e);
504
-				}
505
-				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
506
-			}
507
-		}
508
-
509
-		return $result;
510
-	}
511
-
512
-	/**
513
-	 * calculate the unencrypted size
514
-	 *
515
-	 * @param string $path internal path relative to the storage root
516
-	 * @param int $size size of the physical file
517
-	 * @param int $unencryptedSize size of the unencrypted file
518
-	 *
519
-	 * @return int calculated unencrypted size
520
-	 */
521
-	protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
522
-
523
-		$headerSize = $this->getHeaderSize($path);
524
-		$header = $this->getHeader($path);
525
-		$encryptionModule = $this->getEncryptionModule($path);
526
-
527
-		$stream = $this->storage->fopen($path, 'r');
528
-
529
-		// if we couldn't open the file we return the old unencrypted size
530
-		if (!is_resource($stream)) {
531
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
532
-			return $unencryptedSize;
533
-		}
534
-
535
-		$newUnencryptedSize = 0;
536
-		$size -= $headerSize;
537
-		$blockSize = $this->util->getBlockSize();
538
-
539
-		// if a header exists we skip it
540
-		if ($headerSize > 0) {
541
-			fread($stream, $headerSize);
542
-		}
543
-
544
-		// fast path, else the calculation for $lastChunkNr is bogus
545
-		if ($size === 0) {
546
-			return 0;
547
-		}
548
-
549
-		$signed = isset($header['signed']) && $header['signed'] === 'true';
550
-		$unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
551
-
552
-		// calculate last chunk nr
553
-		// next highest is end of chunks, one subtracted is last one
554
-		// we have to read the last chunk, we can't just calculate it (because of padding etc)
555
-
556
-		$lastChunkNr = ceil($size/ $blockSize)-1;
557
-		// calculate last chunk position
558
-		$lastChunkPos = ($lastChunkNr * $blockSize);
559
-		// try to fseek to the last chunk, if it fails we have to read the whole file
560
-		if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
561
-			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
562
-		}
563
-
564
-		$lastChunkContentEncrypted='';
565
-		$count = $blockSize;
566
-
567
-		while ($count > 0) {
568
-			$data=fread($stream, $blockSize);
569
-			$count=strlen($data);
570
-			$lastChunkContentEncrypted .= $data;
571
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
572
-				$newUnencryptedSize += $unencryptedBlockSize;
573
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
574
-			}
575
-		}
576
-
577
-		fclose($stream);
578
-
579
-		// we have to decrypt the last chunk to get it actual size
580
-		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
581
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
582
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
583
-
584
-		// calc the real file size with the size of the last chunk
585
-		$newUnencryptedSize += strlen($decryptedLastChunk);
586
-
587
-		$this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
588
-
589
-		// write to cache if applicable
590
-		$cache = $this->storage->getCache();
591
-		if ($cache) {
592
-			$entry = $cache->get($path);
593
-			$cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
594
-		}
595
-
596
-		return $newUnencryptedSize;
597
-	}
598
-
599
-	/**
600
-	 * @param Storage\IStorage $sourceStorage
601
-	 * @param string $sourceInternalPath
602
-	 * @param string $targetInternalPath
603
-	 * @param bool $preserveMtime
604
-	 * @return bool
605
-	 */
606
-	public function moveFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
607
-		if ($sourceStorage === $this) {
608
-			return $this->rename($sourceInternalPath, $targetInternalPath);
609
-		}
610
-
611
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
612
-		// - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
613
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
614
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
615
-		// - remove $this->copyBetweenStorage
616
-
617
-		if (!$sourceStorage->isDeletable($sourceInternalPath)) {
618
-			return false;
619
-		}
620
-
621
-		$result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
622
-		if ($result) {
623
-			if ($sourceStorage->is_dir($sourceInternalPath)) {
624
-				$result &= $sourceStorage->rmdir($sourceInternalPath);
625
-			} else {
626
-				$result &= $sourceStorage->unlink($sourceInternalPath);
627
-			}
628
-		}
629
-		return $result;
630
-	}
631
-
632
-
633
-	/**
634
-	 * @param Storage\IStorage $sourceStorage
635
-	 * @param string $sourceInternalPath
636
-	 * @param string $targetInternalPath
637
-	 * @param bool $preserveMtime
638
-	 * @param bool $isRename
639
-	 * @return bool
640
-	 */
641
-	public function copyFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
642
-
643
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
644
-		// - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
645
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
646
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
647
-		// - remove $this->copyBetweenStorage
648
-
649
-		return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
650
-	}
651
-
652
-	/**
653
-	 * Update the encrypted cache version in the database
654
-	 *
655
-	 * @param Storage\IStorage $sourceStorage
656
-	 * @param string $sourceInternalPath
657
-	 * @param string $targetInternalPath
658
-	 * @param bool $isRename
659
-	 * @param bool $keepEncryptionVersion
660
-	 */
661
-	private function updateEncryptedVersion(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, $keepEncryptionVersion) {
662
-		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath);
663
-		$cacheInformation = [
664
-			'encrypted' => $isEncrypted,
665
-		];
666
-		if($isEncrypted) {
667
-			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
668
-
669
-			// In case of a move operation from an unencrypted to an encrypted
670
-			// storage the old encrypted version would stay with "0" while the
671
-			// correct value would be "1". Thus we manually set the value to "1"
672
-			// for those cases.
673
-			// See also https://github.com/owncloud/core/issues/23078
674
-			if($encryptedVersion === 0 || !$keepEncryptionVersion) {
675
-				$encryptedVersion = 1;
676
-			}
677
-
678
-			$cacheInformation['encryptedVersion'] = $encryptedVersion;
679
-		}
680
-
681
-		// in case of a rename we need to manipulate the source cache because
682
-		// this information will be kept for the new target
683
-		if ($isRename) {
684
-			$sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
685
-		} else {
686
-			$this->getCache()->put($targetInternalPath, $cacheInformation);
687
-		}
688
-	}
689
-
690
-	/**
691
-	 * copy file between two storages
692
-	 *
693
-	 * @param Storage\IStorage $sourceStorage
694
-	 * @param string $sourceInternalPath
695
-	 * @param string $targetInternalPath
696
-	 * @param bool $preserveMtime
697
-	 * @param bool $isRename
698
-	 * @return bool
699
-	 * @throws \Exception
700
-	 */
701
-	private function copyBetweenStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
702
-
703
-		// for versions we have nothing to do, because versions should always use the
704
-		// key from the original file. Just create a 1:1 copy and done
705
-		if ($this->isVersion($targetInternalPath) ||
706
-			$this->isVersion($sourceInternalPath)) {
707
-			// remember that we try to create a version so that we can detect it during
708
-			// fopen($sourceInternalPath) and by-pass the encryption in order to
709
-			// create a 1:1 copy of the file
710
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
711
-			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
712
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
713
-			if ($result) {
714
-				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
715
-				// make sure that we update the unencrypted size for the version
716
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
717
-					$this->updateUnencryptedSize(
718
-						$this->getFullPath($targetInternalPath),
719
-						$info['size']
720
-					);
721
-				}
722
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, true);
723
-			}
724
-			return $result;
725
-		}
726
-
727
-		// first copy the keys that we reuse the existing file key on the target location
728
-		// and don't create a new one which would break versions for example.
729
-		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
730
-		if (count($mount) === 1) {
731
-			$mountPoint = $mount[0]->getMountPoint();
732
-			$source = $mountPoint . '/' . $sourceInternalPath;
733
-			$target = $this->getFullPath($targetInternalPath);
734
-			$this->copyKeys($source, $target);
735
-		} else {
736
-			$this->logger->error('Could not find mount point, can\'t keep encryption keys');
737
-		}
738
-
739
-		if ($sourceStorage->is_dir($sourceInternalPath)) {
740
-			$dh = $sourceStorage->opendir($sourceInternalPath);
741
-			$result = $this->mkdir($targetInternalPath);
742
-			if (is_resource($dh)) {
743
-				while ($result and ($file = readdir($dh)) !== false) {
744
-					if (!Filesystem::isIgnoredDir($file)) {
745
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
746
-					}
747
-				}
748
-			}
749
-		} else {
750
-			try {
751
-				$source = $sourceStorage->fopen($sourceInternalPath, 'r');
752
-				$target = $this->fopen($targetInternalPath, 'w');
753
-				list(, $result) = \OC_Helper::streamCopy($source, $target);
754
-				fclose($source);
755
-				fclose($target);
756
-			} catch (\Exception $e) {
757
-				fclose($source);
758
-				fclose($target);
759
-				throw $e;
760
-			}
761
-			if($result) {
762
-				if ($preserveMtime) {
763
-					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
764
-				}
765
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, false);
766
-			} else {
767
-				// delete partially written target file
768
-				$this->unlink($targetInternalPath);
769
-				// delete cache entry that was created by fopen
770
-				$this->getCache()->remove($targetInternalPath);
771
-			}
772
-		}
773
-		return (bool)$result;
774
-
775
-	}
776
-
777
-	/**
778
-	 * get the path to a local version of the file.
779
-	 * The local version of the file can be temporary and doesn't have to be persistent across requests
780
-	 *
781
-	 * @param string $path
782
-	 * @return string
783
-	 */
784
-	public function getLocalFile($path) {
785
-		if ($this->encryptionManager->isEnabled()) {
786
-			$cachedFile = $this->getCachedFile($path);
787
-			if (is_string($cachedFile)) {
788
-				return $cachedFile;
789
-			}
790
-		}
791
-		return $this->storage->getLocalFile($path);
792
-	}
793
-
794
-	/**
795
-	 * Returns the wrapped storage's value for isLocal()
796
-	 *
797
-	 * @return bool wrapped storage's isLocal() value
798
-	 */
799
-	public function isLocal() {
800
-		if ($this->encryptionManager->isEnabled()) {
801
-			return false;
802
-		}
803
-		return $this->storage->isLocal();
804
-	}
805
-
806
-	/**
807
-	 * see http://php.net/manual/en/function.stat.php
808
-	 * only the following keys are required in the result: size and mtime
809
-	 *
810
-	 * @param string $path
811
-	 * @return array
812
-	 */
813
-	public function stat($path) {
814
-		$stat = $this->storage->stat($path);
815
-		$fileSize = $this->filesize($path);
816
-		$stat['size'] = $fileSize;
817
-		$stat[7] = $fileSize;
818
-		return $stat;
819
-	}
820
-
821
-	/**
822
-	 * see http://php.net/manual/en/function.hash.php
823
-	 *
824
-	 * @param string $type
825
-	 * @param string $path
826
-	 * @param bool $raw
827
-	 * @return string
828
-	 */
829
-	public function hash($type, $path, $raw = false) {
830
-		$fh = $this->fopen($path, 'rb');
831
-		$ctx = hash_init($type);
832
-		hash_update_stream($ctx, $fh);
833
-		fclose($fh);
834
-		return hash_final($ctx, $raw);
835
-	}
836
-
837
-	/**
838
-	 * return full path, including mount point
839
-	 *
840
-	 * @param string $path relative to mount point
841
-	 * @return string full path including mount point
842
-	 */
843
-	protected function getFullPath($path) {
844
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
845
-	}
846
-
847
-	/**
848
-	 * read first block of encrypted file, typically this will contain the
849
-	 * encryption header
850
-	 *
851
-	 * @param string $path
852
-	 * @return string
853
-	 */
854
-	protected function readFirstBlock($path) {
855
-		$firstBlock = '';
856
-		if ($this->storage->file_exists($path)) {
857
-			$handle = $this->storage->fopen($path, 'r');
858
-			$firstBlock = fread($handle, $this->util->getHeaderSize());
859
-			fclose($handle);
860
-		}
861
-		return $firstBlock;
862
-	}
863
-
864
-	/**
865
-	 * return header size of given file
866
-	 *
867
-	 * @param string $path
868
-	 * @return int
869
-	 */
870
-	protected function getHeaderSize($path) {
871
-		$headerSize = 0;
872
-		$realFile = $this->util->stripPartialFileExtension($path);
873
-		if ($this->storage->file_exists($realFile)) {
874
-			$path = $realFile;
875
-		}
876
-		$firstBlock = $this->readFirstBlock($path);
877
-
878
-		if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
879
-			$headerSize = $this->util->getHeaderSize();
880
-		}
881
-
882
-		return $headerSize;
883
-	}
884
-
885
-	/**
886
-	 * parse raw header to array
887
-	 *
888
-	 * @param string $rawHeader
889
-	 * @return array
890
-	 */
891
-	protected function parseRawHeader($rawHeader) {
892
-		$result = array();
893
-		if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
894
-			$header = $rawHeader;
895
-			$endAt = strpos($header, Util::HEADER_END);
896
-			if ($endAt !== false) {
897
-				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
898
-
899
-				// +1 to not start with an ':' which would result in empty element at the beginning
900
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
901
-
902
-				$element = array_shift($exploded);
903
-				while ($element !== Util::HEADER_END) {
904
-					$result[$element] = array_shift($exploded);
905
-					$element = array_shift($exploded);
906
-				}
907
-			}
908
-		}
909
-
910
-		return $result;
911
-	}
912
-
913
-	/**
914
-	 * read header from file
915
-	 *
916
-	 * @param string $path
917
-	 * @return array
918
-	 */
919
-	protected function getHeader($path) {
920
-		$realFile = $this->util->stripPartialFileExtension($path);
921
-		$exists = $this->storage->file_exists($realFile);
922
-		if ($exists) {
923
-			$path = $realFile;
924
-		}
925
-
926
-		$firstBlock = $this->readFirstBlock($path);
927
-		$result = $this->parseRawHeader($firstBlock);
928
-
929
-		// if the header doesn't contain a encryption module we check if it is a
930
-		// legacy file. If true, we add the default encryption module
931
-		if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
932
-			if (!empty($result)) {
933
-				$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
934
-			} else if ($exists) {
935
-				// if the header was empty we have to check first if it is a encrypted file at all
936
-				// We would do query to filecache only if we know that entry in filecache exists
937
-				$info = $this->getCache()->get($path);
938
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
939
-					$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
940
-				}
941
-			}
942
-		}
943
-
944
-		return $result;
945
-	}
946
-
947
-	/**
948
-	 * read encryption module needed to read/write the file located at $path
949
-	 *
950
-	 * @param string $path
951
-	 * @return null|\OCP\Encryption\IEncryptionModule
952
-	 * @throws ModuleDoesNotExistsException
953
-	 * @throws \Exception
954
-	 */
955
-	protected function getEncryptionModule($path) {
956
-		$encryptionModule = null;
957
-		$header = $this->getHeader($path);
958
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
959
-		if (!empty($encryptionModuleId)) {
960
-			try {
961
-				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
962
-			} catch (ModuleDoesNotExistsException $e) {
963
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
964
-				throw $e;
965
-			}
966
-		}
967
-
968
-		return $encryptionModule;
969
-	}
970
-
971
-	/**
972
-	 * @param string $path
973
-	 * @param int $unencryptedSize
974
-	 */
975
-	public function updateUnencryptedSize($path, $unencryptedSize) {
976
-		$this->unencryptedSize[$path] = $unencryptedSize;
977
-	}
978
-
979
-	/**
980
-	 * copy keys to new location
981
-	 *
982
-	 * @param string $source path relative to data/
983
-	 * @param string $target path relative to data/
984
-	 * @return bool
985
-	 */
986
-	protected function copyKeys($source, $target) {
987
-		if (!$this->util->isExcluded($source)) {
988
-			return $this->keyStorage->copyKeys($source, $target);
989
-		}
990
-
991
-		return false;
992
-	}
993
-
994
-	/**
995
-	 * check if path points to a files version
996
-	 *
997
-	 * @param $path
998
-	 * @return bool
999
-	 */
1000
-	protected function isVersion($path) {
1001
-		$normalized = Filesystem::normalizePath($path);
1002
-		return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
1003
-	}
1004
-
1005
-	/**
1006
-	 * check if the given storage should be encrypted or not
1007
-	 *
1008
-	 * @param $path
1009
-	 * @return bool
1010
-	 */
1011
-	protected function shouldEncrypt($path) {
1012
-		$fullPath = $this->getFullPath($path);
1013
-		$mountPointConfig = $this->mount->getOption('encrypt', true);
1014
-		if ($mountPointConfig === false) {
1015
-			return false;
1016
-		}
1017
-
1018
-		try {
1019
-			$encryptionModule = $this->getEncryptionModule($fullPath);
1020
-		} catch (ModuleDoesNotExistsException $e) {
1021
-			return false;
1022
-		}
1023
-
1024
-		if ($encryptionModule === null) {
1025
-			$encryptionModule = $this->encryptionManager->getEncryptionModule();
1026
-		}
1027
-
1028
-		return $encryptionModule->shouldEncrypt($fullPath);
1029
-
1030
-	}
51
+    use LocalTempFileTrait;
52
+
53
+    /** @var string */
54
+    private $mountPoint;
55
+
56
+    /** @var \OC\Encryption\Util */
57
+    private $util;
58
+
59
+    /** @var \OCP\Encryption\IManager */
60
+    private $encryptionManager;
61
+
62
+    /** @var \OCP\ILogger */
63
+    private $logger;
64
+
65
+    /** @var string */
66
+    private $uid;
67
+
68
+    /** @var array */
69
+    protected $unencryptedSize;
70
+
71
+    /** @var \OCP\Encryption\IFile */
72
+    private $fileHelper;
73
+
74
+    /** @var IMountPoint */
75
+    private $mount;
76
+
77
+    /** @var IStorage */
78
+    private $keyStorage;
79
+
80
+    /** @var Update */
81
+    private $update;
82
+
83
+    /** @var Manager */
84
+    private $mountManager;
85
+
86
+    /** @var array remember for which path we execute the repair step to avoid recursions */
87
+    private $fixUnencryptedSizeOf = array();
88
+
89
+    /** @var  ArrayCache */
90
+    private $arrayCache;
91
+
92
+    /**
93
+     * @param array $parameters
94
+     * @param IManager $encryptionManager
95
+     * @param Util $util
96
+     * @param ILogger $logger
97
+     * @param IFile $fileHelper
98
+     * @param string $uid
99
+     * @param IStorage $keyStorage
100
+     * @param Update $update
101
+     * @param Manager $mountManager
102
+     * @param ArrayCache $arrayCache
103
+     */
104
+    public function __construct(
105
+            $parameters,
106
+            IManager $encryptionManager = null,
107
+            Util $util = null,
108
+            ILogger $logger = null,
109
+            IFile $fileHelper = null,
110
+            $uid = null,
111
+            IStorage $keyStorage = null,
112
+            Update $update = null,
113
+            Manager $mountManager = null,
114
+            ArrayCache $arrayCache = null
115
+        ) {
116
+
117
+        $this->mountPoint = $parameters['mountPoint'];
118
+        $this->mount = $parameters['mount'];
119
+        $this->encryptionManager = $encryptionManager;
120
+        $this->util = $util;
121
+        $this->logger = $logger;
122
+        $this->uid = $uid;
123
+        $this->fileHelper = $fileHelper;
124
+        $this->keyStorage = $keyStorage;
125
+        $this->unencryptedSize = array();
126
+        $this->update = $update;
127
+        $this->mountManager = $mountManager;
128
+        $this->arrayCache = $arrayCache;
129
+        parent::__construct($parameters);
130
+    }
131
+
132
+    /**
133
+     * see http://php.net/manual/en/function.filesize.php
134
+     * The result for filesize when called on a folder is required to be 0
135
+     *
136
+     * @param string $path
137
+     * @return int
138
+     */
139
+    public function filesize($path) {
140
+        $fullPath = $this->getFullPath($path);
141
+
142
+        /** @var CacheEntry $info */
143
+        $info = $this->getCache()->get($path);
144
+        if (isset($this->unencryptedSize[$fullPath])) {
145
+            $size = $this->unencryptedSize[$fullPath];
146
+            // update file cache
147
+            if ($info instanceof ICacheEntry) {
148
+                $info = $info->getData();
149
+                $info['encrypted'] = $info['encryptedVersion'];
150
+            } else {
151
+                if (!is_array($info)) {
152
+                    $info = [];
153
+                }
154
+                $info['encrypted'] = true;
155
+            }
156
+
157
+            $info['size'] = $size;
158
+            $this->getCache()->put($path, $info);
159
+
160
+            return $size;
161
+        }
162
+
163
+        if (isset($info['fileid']) && $info['encrypted']) {
164
+            return $this->verifyUnencryptedSize($path, $info['size']);
165
+        }
166
+
167
+        return $this->storage->filesize($path);
168
+    }
169
+
170
+    /**
171
+     * @param string $path
172
+     * @return array
173
+     */
174
+    public function getMetaData($path) {
175
+        $data = $this->storage->getMetaData($path);
176
+        if (is_null($data)) {
177
+            return null;
178
+        }
179
+        $fullPath = $this->getFullPath($path);
180
+        $info = $this->getCache()->get($path);
181
+
182
+        if (isset($this->unencryptedSize[$fullPath])) {
183
+            $data['encrypted'] = true;
184
+            $data['size'] = $this->unencryptedSize[$fullPath];
185
+        } else {
186
+            if (isset($info['fileid']) && $info['encrypted']) {
187
+                $data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
188
+                $data['encrypted'] = true;
189
+            }
190
+        }
191
+
192
+        if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
193
+            $data['encryptedVersion'] = $info['encryptedVersion'];
194
+        }
195
+
196
+        return $data;
197
+    }
198
+
199
+    /**
200
+     * see http://php.net/manual/en/function.file_get_contents.php
201
+     *
202
+     * @param string $path
203
+     * @return string
204
+     */
205
+    public function file_get_contents($path) {
206
+
207
+        $encryptionModule = $this->getEncryptionModule($path);
208
+
209
+        if ($encryptionModule) {
210
+            $handle = $this->fopen($path, "r");
211
+            if (!$handle) {
212
+                return false;
213
+            }
214
+            $data = stream_get_contents($handle);
215
+            fclose($handle);
216
+            return $data;
217
+        }
218
+        return $this->storage->file_get_contents($path);
219
+    }
220
+
221
+    /**
222
+     * see http://php.net/manual/en/function.file_put_contents.php
223
+     *
224
+     * @param string $path
225
+     * @param string $data
226
+     * @return bool
227
+     */
228
+    public function file_put_contents($path, $data) {
229
+        // file put content will always be translated to a stream write
230
+        $handle = $this->fopen($path, 'w');
231
+        if (is_resource($handle)) {
232
+            $written = fwrite($handle, $data);
233
+            fclose($handle);
234
+            return $written;
235
+        }
236
+
237
+        return false;
238
+    }
239
+
240
+    /**
241
+     * see http://php.net/manual/en/function.unlink.php
242
+     *
243
+     * @param string $path
244
+     * @return bool
245
+     */
246
+    public function unlink($path) {
247
+        $fullPath = $this->getFullPath($path);
248
+        if ($this->util->isExcluded($fullPath)) {
249
+            return $this->storage->unlink($path);
250
+        }
251
+
252
+        $encryptionModule = $this->getEncryptionModule($path);
253
+        if ($encryptionModule) {
254
+            $this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
255
+        }
256
+
257
+        return $this->storage->unlink($path);
258
+    }
259
+
260
+    /**
261
+     * see http://php.net/manual/en/function.rename.php
262
+     *
263
+     * @param string $path1
264
+     * @param string $path2
265
+     * @return bool
266
+     */
267
+    public function rename($path1, $path2) {
268
+
269
+        $result = $this->storage->rename($path1, $path2);
270
+
271
+        if ($result &&
272
+            // versions always use the keys from the original file, so we can skip
273
+            // this step for versions
274
+            $this->isVersion($path2) === false &&
275
+            $this->encryptionManager->isEnabled()) {
276
+            $source = $this->getFullPath($path1);
277
+            if (!$this->util->isExcluded($source)) {
278
+                $target = $this->getFullPath($path2);
279
+                if (isset($this->unencryptedSize[$source])) {
280
+                    $this->unencryptedSize[$target] = $this->unencryptedSize[$source];
281
+                }
282
+                $this->keyStorage->renameKeys($source, $target);
283
+                $module = $this->getEncryptionModule($path2);
284
+                if ($module) {
285
+                    $module->update($target, $this->uid, []);
286
+                }
287
+            }
288
+        }
289
+
290
+        return $result;
291
+    }
292
+
293
+    /**
294
+     * see http://php.net/manual/en/function.rmdir.php
295
+     *
296
+     * @param string $path
297
+     * @return bool
298
+     */
299
+    public function rmdir($path) {
300
+        $result = $this->storage->rmdir($path);
301
+        $fullPath = $this->getFullPath($path);
302
+        if ($result &&
303
+            $this->util->isExcluded($fullPath) === false &&
304
+            $this->encryptionManager->isEnabled()
305
+        ) {
306
+            $this->keyStorage->deleteAllFileKeys($fullPath);
307
+        }
308
+
309
+        return $result;
310
+    }
311
+
312
+    /**
313
+     * check if a file can be read
314
+     *
315
+     * @param string $path
316
+     * @return bool
317
+     */
318
+    public function isReadable($path) {
319
+
320
+        $isReadable = true;
321
+
322
+        $metaData = $this->getMetaData($path);
323
+        if (
324
+            !$this->is_dir($path) &&
325
+            isset($metaData['encrypted']) &&
326
+            $metaData['encrypted'] === true
327
+        ) {
328
+            $fullPath = $this->getFullPath($path);
329
+            $module = $this->getEncryptionModule($path);
330
+            $isReadable = $module->isReadable($fullPath, $this->uid);
331
+        }
332
+
333
+        return $this->storage->isReadable($path) && $isReadable;
334
+    }
335
+
336
+    /**
337
+     * see http://php.net/manual/en/function.copy.php
338
+     *
339
+     * @param string $path1
340
+     * @param string $path2
341
+     * @return bool
342
+     */
343
+    public function copy($path1, $path2) {
344
+
345
+        $source = $this->getFullPath($path1);
346
+
347
+        if ($this->util->isExcluded($source)) {
348
+            return $this->storage->copy($path1, $path2);
349
+        }
350
+
351
+        // need to stream copy file by file in case we copy between a encrypted
352
+        // and a unencrypted storage
353
+        $this->unlink($path2);
354
+        return $this->copyFromStorage($this, $path1, $path2);
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';
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
+                    // if we update a encrypted file with a un-encrypted one we change the db flag
416
+                    if ($targetIsEncrypted && $encryptionEnabled === false) {
417
+                        $cache = $this->storage->getCache();
418
+                        if ($cache) {
419
+                            $entry = $cache->get($path);
420
+                            $cache->update($entry->getId(), ['encrypted' => 0]);
421
+                        }
422
+                    }
423
+                    if ($encryptionEnabled) {
424
+                        // if $encryptionModuleId is empty, the default module will be used
425
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
426
+                        $shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
427
+                        $signed = true;
428
+                    }
429
+                } else {
430
+                    $info = $this->getCache()->get($path);
431
+                    // only get encryption module if we found one in the header
432
+                    // or if file should be encrypted according to the file cache
433
+                    if (!empty($encryptionModuleId)) {
434
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
435
+                        $shouldEncrypt = true;
436
+                    } else if (empty($encryptionModuleId) && $info['encrypted'] === true) {
437
+                        // we come from a old installation. No header and/or no module defined
438
+                        // but the file is encrypted. In this case we need to use the
439
+                        // OC_DEFAULT_MODULE to read the file
440
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
441
+                        $shouldEncrypt = true;
442
+                        $targetIsEncrypted = true;
443
+                    }
444
+                }
445
+            } catch (ModuleDoesNotExistsException $e) {
446
+                $this->logger->logException($e, [
447
+                    'message' => 'Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted',
448
+                    'level' => ILogger::WARN,
449
+                    'app' => 'core',
450
+                ]);
451
+            }
452
+
453
+            // encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
454
+            if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
455
+                if (!$targetExists || !$targetIsEncrypted) {
456
+                    $shouldEncrypt = false;
457
+                }
458
+            }
459
+
460
+            if ($shouldEncrypt === true && $encryptionModule !== null) {
461
+                $headerSize = $this->getHeaderSize($path);
462
+                $source = $this->storage->fopen($path, $mode);
463
+                if (!is_resource($source)) {
464
+                    return false;
465
+                }
466
+                $handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
467
+                    $this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
468
+                    $size, $unencryptedSize, $headerSize, $signed);
469
+                return $handle;
470
+            }
471
+
472
+        }
473
+
474
+        return $this->storage->fopen($path, $mode);
475
+    }
476
+
477
+
478
+    /**
479
+     * perform some plausibility checks if the the unencrypted size is correct.
480
+     * If not, we calculate the correct unencrypted size and return it
481
+     *
482
+     * @param string $path internal path relative to the storage root
483
+     * @param int $unencryptedSize size of the unencrypted file
484
+     *
485
+     * @return int unencrypted size
486
+     */
487
+    protected function verifyUnencryptedSize($path, $unencryptedSize) {
488
+
489
+        $size = $this->storage->filesize($path);
490
+        $result = $unencryptedSize;
491
+
492
+        if ($unencryptedSize < 0 ||
493
+            ($size > 0 && $unencryptedSize === $size)
494
+        ) {
495
+            // check if we already calculate the unencrypted size for the
496
+            // given path to avoid recursions
497
+            if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
498
+                $this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
499
+                try {
500
+                    $result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
501
+                } catch (\Exception $e) {
502
+                    $this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
503
+                    $this->logger->logException($e);
504
+                }
505
+                unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
506
+            }
507
+        }
508
+
509
+        return $result;
510
+    }
511
+
512
+    /**
513
+     * calculate the unencrypted size
514
+     *
515
+     * @param string $path internal path relative to the storage root
516
+     * @param int $size size of the physical file
517
+     * @param int $unencryptedSize size of the unencrypted file
518
+     *
519
+     * @return int calculated unencrypted size
520
+     */
521
+    protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
522
+
523
+        $headerSize = $this->getHeaderSize($path);
524
+        $header = $this->getHeader($path);
525
+        $encryptionModule = $this->getEncryptionModule($path);
526
+
527
+        $stream = $this->storage->fopen($path, 'r');
528
+
529
+        // if we couldn't open the file we return the old unencrypted size
530
+        if (!is_resource($stream)) {
531
+            $this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
532
+            return $unencryptedSize;
533
+        }
534
+
535
+        $newUnencryptedSize = 0;
536
+        $size -= $headerSize;
537
+        $blockSize = $this->util->getBlockSize();
538
+
539
+        // if a header exists we skip it
540
+        if ($headerSize > 0) {
541
+            fread($stream, $headerSize);
542
+        }
543
+
544
+        // fast path, else the calculation for $lastChunkNr is bogus
545
+        if ($size === 0) {
546
+            return 0;
547
+        }
548
+
549
+        $signed = isset($header['signed']) && $header['signed'] === 'true';
550
+        $unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
551
+
552
+        // calculate last chunk nr
553
+        // next highest is end of chunks, one subtracted is last one
554
+        // we have to read the last chunk, we can't just calculate it (because of padding etc)
555
+
556
+        $lastChunkNr = ceil($size/ $blockSize)-1;
557
+        // calculate last chunk position
558
+        $lastChunkPos = ($lastChunkNr * $blockSize);
559
+        // try to fseek to the last chunk, if it fails we have to read the whole file
560
+        if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
561
+            $newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
562
+        }
563
+
564
+        $lastChunkContentEncrypted='';
565
+        $count = $blockSize;
566
+
567
+        while ($count > 0) {
568
+            $data=fread($stream, $blockSize);
569
+            $count=strlen($data);
570
+            $lastChunkContentEncrypted .= $data;
571
+            if(strlen($lastChunkContentEncrypted) > $blockSize) {
572
+                $newUnencryptedSize += $unencryptedBlockSize;
573
+                $lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
574
+            }
575
+        }
576
+
577
+        fclose($stream);
578
+
579
+        // we have to decrypt the last chunk to get it actual size
580
+        $encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
581
+        $decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
582
+        $decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
583
+
584
+        // calc the real file size with the size of the last chunk
585
+        $newUnencryptedSize += strlen($decryptedLastChunk);
586
+
587
+        $this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
588
+
589
+        // write to cache if applicable
590
+        $cache = $this->storage->getCache();
591
+        if ($cache) {
592
+            $entry = $cache->get($path);
593
+            $cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
594
+        }
595
+
596
+        return $newUnencryptedSize;
597
+    }
598
+
599
+    /**
600
+     * @param Storage\IStorage $sourceStorage
601
+     * @param string $sourceInternalPath
602
+     * @param string $targetInternalPath
603
+     * @param bool $preserveMtime
604
+     * @return bool
605
+     */
606
+    public function moveFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
607
+        if ($sourceStorage === $this) {
608
+            return $this->rename($sourceInternalPath, $targetInternalPath);
609
+        }
610
+
611
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
612
+        // - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
613
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
614
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
615
+        // - remove $this->copyBetweenStorage
616
+
617
+        if (!$sourceStorage->isDeletable($sourceInternalPath)) {
618
+            return false;
619
+        }
620
+
621
+        $result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
622
+        if ($result) {
623
+            if ($sourceStorage->is_dir($sourceInternalPath)) {
624
+                $result &= $sourceStorage->rmdir($sourceInternalPath);
625
+            } else {
626
+                $result &= $sourceStorage->unlink($sourceInternalPath);
627
+            }
628
+        }
629
+        return $result;
630
+    }
631
+
632
+
633
+    /**
634
+     * @param Storage\IStorage $sourceStorage
635
+     * @param string $sourceInternalPath
636
+     * @param string $targetInternalPath
637
+     * @param bool $preserveMtime
638
+     * @param bool $isRename
639
+     * @return bool
640
+     */
641
+    public function copyFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
642
+
643
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
644
+        // - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
645
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
646
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
647
+        // - remove $this->copyBetweenStorage
648
+
649
+        return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
650
+    }
651
+
652
+    /**
653
+     * Update the encrypted cache version in the database
654
+     *
655
+     * @param Storage\IStorage $sourceStorage
656
+     * @param string $sourceInternalPath
657
+     * @param string $targetInternalPath
658
+     * @param bool $isRename
659
+     * @param bool $keepEncryptionVersion
660
+     */
661
+    private function updateEncryptedVersion(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, $keepEncryptionVersion) {
662
+        $isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath);
663
+        $cacheInformation = [
664
+            'encrypted' => $isEncrypted,
665
+        ];
666
+        if($isEncrypted) {
667
+            $encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
668
+
669
+            // In case of a move operation from an unencrypted to an encrypted
670
+            // storage the old encrypted version would stay with "0" while the
671
+            // correct value would be "1". Thus we manually set the value to "1"
672
+            // for those cases.
673
+            // See also https://github.com/owncloud/core/issues/23078
674
+            if($encryptedVersion === 0 || !$keepEncryptionVersion) {
675
+                $encryptedVersion = 1;
676
+            }
677
+
678
+            $cacheInformation['encryptedVersion'] = $encryptedVersion;
679
+        }
680
+
681
+        // in case of a rename we need to manipulate the source cache because
682
+        // this information will be kept for the new target
683
+        if ($isRename) {
684
+            $sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
685
+        } else {
686
+            $this->getCache()->put($targetInternalPath, $cacheInformation);
687
+        }
688
+    }
689
+
690
+    /**
691
+     * copy file between two storages
692
+     *
693
+     * @param Storage\IStorage $sourceStorage
694
+     * @param string $sourceInternalPath
695
+     * @param string $targetInternalPath
696
+     * @param bool $preserveMtime
697
+     * @param bool $isRename
698
+     * @return bool
699
+     * @throws \Exception
700
+     */
701
+    private function copyBetweenStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
702
+
703
+        // for versions we have nothing to do, because versions should always use the
704
+        // key from the original file. Just create a 1:1 copy and done
705
+        if ($this->isVersion($targetInternalPath) ||
706
+            $this->isVersion($sourceInternalPath)) {
707
+            // remember that we try to create a version so that we can detect it during
708
+            // fopen($sourceInternalPath) and by-pass the encryption in order to
709
+            // create a 1:1 copy of the file
710
+            $this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
711
+            $result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
712
+            $this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
713
+            if ($result) {
714
+                $info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
715
+                // make sure that we update the unencrypted size for the version
716
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
717
+                    $this->updateUnencryptedSize(
718
+                        $this->getFullPath($targetInternalPath),
719
+                        $info['size']
720
+                    );
721
+                }
722
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, true);
723
+            }
724
+            return $result;
725
+        }
726
+
727
+        // first copy the keys that we reuse the existing file key on the target location
728
+        // and don't create a new one which would break versions for example.
729
+        $mount = $this->mountManager->findByStorageId($sourceStorage->getId());
730
+        if (count($mount) === 1) {
731
+            $mountPoint = $mount[0]->getMountPoint();
732
+            $source = $mountPoint . '/' . $sourceInternalPath;
733
+            $target = $this->getFullPath($targetInternalPath);
734
+            $this->copyKeys($source, $target);
735
+        } else {
736
+            $this->logger->error('Could not find mount point, can\'t keep encryption keys');
737
+        }
738
+
739
+        if ($sourceStorage->is_dir($sourceInternalPath)) {
740
+            $dh = $sourceStorage->opendir($sourceInternalPath);
741
+            $result = $this->mkdir($targetInternalPath);
742
+            if (is_resource($dh)) {
743
+                while ($result and ($file = readdir($dh)) !== false) {
744
+                    if (!Filesystem::isIgnoredDir($file)) {
745
+                        $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
746
+                    }
747
+                }
748
+            }
749
+        } else {
750
+            try {
751
+                $source = $sourceStorage->fopen($sourceInternalPath, 'r');
752
+                $target = $this->fopen($targetInternalPath, 'w');
753
+                list(, $result) = \OC_Helper::streamCopy($source, $target);
754
+                fclose($source);
755
+                fclose($target);
756
+            } catch (\Exception $e) {
757
+                fclose($source);
758
+                fclose($target);
759
+                throw $e;
760
+            }
761
+            if($result) {
762
+                if ($preserveMtime) {
763
+                    $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
764
+                }
765
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, false);
766
+            } else {
767
+                // delete partially written target file
768
+                $this->unlink($targetInternalPath);
769
+                // delete cache entry that was created by fopen
770
+                $this->getCache()->remove($targetInternalPath);
771
+            }
772
+        }
773
+        return (bool)$result;
774
+
775
+    }
776
+
777
+    /**
778
+     * get the path to a local version of the file.
779
+     * The local version of the file can be temporary and doesn't have to be persistent across requests
780
+     *
781
+     * @param string $path
782
+     * @return string
783
+     */
784
+    public function getLocalFile($path) {
785
+        if ($this->encryptionManager->isEnabled()) {
786
+            $cachedFile = $this->getCachedFile($path);
787
+            if (is_string($cachedFile)) {
788
+                return $cachedFile;
789
+            }
790
+        }
791
+        return $this->storage->getLocalFile($path);
792
+    }
793
+
794
+    /**
795
+     * Returns the wrapped storage's value for isLocal()
796
+     *
797
+     * @return bool wrapped storage's isLocal() value
798
+     */
799
+    public function isLocal() {
800
+        if ($this->encryptionManager->isEnabled()) {
801
+            return false;
802
+        }
803
+        return $this->storage->isLocal();
804
+    }
805
+
806
+    /**
807
+     * see http://php.net/manual/en/function.stat.php
808
+     * only the following keys are required in the result: size and mtime
809
+     *
810
+     * @param string $path
811
+     * @return array
812
+     */
813
+    public function stat($path) {
814
+        $stat = $this->storage->stat($path);
815
+        $fileSize = $this->filesize($path);
816
+        $stat['size'] = $fileSize;
817
+        $stat[7] = $fileSize;
818
+        return $stat;
819
+    }
820
+
821
+    /**
822
+     * see http://php.net/manual/en/function.hash.php
823
+     *
824
+     * @param string $type
825
+     * @param string $path
826
+     * @param bool $raw
827
+     * @return string
828
+     */
829
+    public function hash($type, $path, $raw = false) {
830
+        $fh = $this->fopen($path, 'rb');
831
+        $ctx = hash_init($type);
832
+        hash_update_stream($ctx, $fh);
833
+        fclose($fh);
834
+        return hash_final($ctx, $raw);
835
+    }
836
+
837
+    /**
838
+     * return full path, including mount point
839
+     *
840
+     * @param string $path relative to mount point
841
+     * @return string full path including mount point
842
+     */
843
+    protected function getFullPath($path) {
844
+        return Filesystem::normalizePath($this->mountPoint . '/' . $path);
845
+    }
846
+
847
+    /**
848
+     * read first block of encrypted file, typically this will contain the
849
+     * encryption header
850
+     *
851
+     * @param string $path
852
+     * @return string
853
+     */
854
+    protected function readFirstBlock($path) {
855
+        $firstBlock = '';
856
+        if ($this->storage->file_exists($path)) {
857
+            $handle = $this->storage->fopen($path, 'r');
858
+            $firstBlock = fread($handle, $this->util->getHeaderSize());
859
+            fclose($handle);
860
+        }
861
+        return $firstBlock;
862
+    }
863
+
864
+    /**
865
+     * return header size of given file
866
+     *
867
+     * @param string $path
868
+     * @return int
869
+     */
870
+    protected function getHeaderSize($path) {
871
+        $headerSize = 0;
872
+        $realFile = $this->util->stripPartialFileExtension($path);
873
+        if ($this->storage->file_exists($realFile)) {
874
+            $path = $realFile;
875
+        }
876
+        $firstBlock = $this->readFirstBlock($path);
877
+
878
+        if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
879
+            $headerSize = $this->util->getHeaderSize();
880
+        }
881
+
882
+        return $headerSize;
883
+    }
884
+
885
+    /**
886
+     * parse raw header to array
887
+     *
888
+     * @param string $rawHeader
889
+     * @return array
890
+     */
891
+    protected function parseRawHeader($rawHeader) {
892
+        $result = array();
893
+        if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
894
+            $header = $rawHeader;
895
+            $endAt = strpos($header, Util::HEADER_END);
896
+            if ($endAt !== false) {
897
+                $header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
898
+
899
+                // +1 to not start with an ':' which would result in empty element at the beginning
900
+                $exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
901
+
902
+                $element = array_shift($exploded);
903
+                while ($element !== Util::HEADER_END) {
904
+                    $result[$element] = array_shift($exploded);
905
+                    $element = array_shift($exploded);
906
+                }
907
+            }
908
+        }
909
+
910
+        return $result;
911
+    }
912
+
913
+    /**
914
+     * read header from file
915
+     *
916
+     * @param string $path
917
+     * @return array
918
+     */
919
+    protected function getHeader($path) {
920
+        $realFile = $this->util->stripPartialFileExtension($path);
921
+        $exists = $this->storage->file_exists($realFile);
922
+        if ($exists) {
923
+            $path = $realFile;
924
+        }
925
+
926
+        $firstBlock = $this->readFirstBlock($path);
927
+        $result = $this->parseRawHeader($firstBlock);
928
+
929
+        // if the header doesn't contain a encryption module we check if it is a
930
+        // legacy file. If true, we add the default encryption module
931
+        if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
932
+            if (!empty($result)) {
933
+                $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
934
+            } else if ($exists) {
935
+                // if the header was empty we have to check first if it is a encrypted file at all
936
+                // We would do query to filecache only if we know that entry in filecache exists
937
+                $info = $this->getCache()->get($path);
938
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
939
+                    $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
940
+                }
941
+            }
942
+        }
943
+
944
+        return $result;
945
+    }
946
+
947
+    /**
948
+     * read encryption module needed to read/write the file located at $path
949
+     *
950
+     * @param string $path
951
+     * @return null|\OCP\Encryption\IEncryptionModule
952
+     * @throws ModuleDoesNotExistsException
953
+     * @throws \Exception
954
+     */
955
+    protected function getEncryptionModule($path) {
956
+        $encryptionModule = null;
957
+        $header = $this->getHeader($path);
958
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
959
+        if (!empty($encryptionModuleId)) {
960
+            try {
961
+                $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
962
+            } catch (ModuleDoesNotExistsException $e) {
963
+                $this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
964
+                throw $e;
965
+            }
966
+        }
967
+
968
+        return $encryptionModule;
969
+    }
970
+
971
+    /**
972
+     * @param string $path
973
+     * @param int $unencryptedSize
974
+     */
975
+    public function updateUnencryptedSize($path, $unencryptedSize) {
976
+        $this->unencryptedSize[$path] = $unencryptedSize;
977
+    }
978
+
979
+    /**
980
+     * copy keys to new location
981
+     *
982
+     * @param string $source path relative to data/
983
+     * @param string $target path relative to data/
984
+     * @return bool
985
+     */
986
+    protected function copyKeys($source, $target) {
987
+        if (!$this->util->isExcluded($source)) {
988
+            return $this->keyStorage->copyKeys($source, $target);
989
+        }
990
+
991
+        return false;
992
+    }
993
+
994
+    /**
995
+     * check if path points to a files version
996
+     *
997
+     * @param $path
998
+     * @return bool
999
+     */
1000
+    protected function isVersion($path) {
1001
+        $normalized = Filesystem::normalizePath($path);
1002
+        return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
1003
+    }
1004
+
1005
+    /**
1006
+     * check if the given storage should be encrypted or not
1007
+     *
1008
+     * @param $path
1009
+     * @return bool
1010
+     */
1011
+    protected function shouldEncrypt($path) {
1012
+        $fullPath = $this->getFullPath($path);
1013
+        $mountPointConfig = $this->mount->getOption('encrypt', true);
1014
+        if ($mountPointConfig === false) {
1015
+            return false;
1016
+        }
1017
+
1018
+        try {
1019
+            $encryptionModule = $this->getEncryptionModule($fullPath);
1020
+        } catch (ModuleDoesNotExistsException $e) {
1021
+            return false;
1022
+        }
1023
+
1024
+        if ($encryptionModule === null) {
1025
+            $encryptionModule = $this->encryptionManager->getEncryptionModule();
1026
+        }
1027
+
1028
+        return $encryptionModule->shouldEncrypt($fullPath);
1029
+
1030
+    }
1031 1031
 
1032 1032
 }
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   +10 added lines, -10 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
 				}
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 	 */
224 224
 	protected function getURN($fileId) {
225 225
 		if (is_numeric($fileId)) {
226
-			return $this->objectPrefix . $fileId;
226
+			return $this->objectPrefix.$fileId;
227 227
 		}
228 228
 		return null;
229 229
 	}
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
 					} catch (\Exception $ex) {
278 278
 						$this->logger->logException($ex, [
279 279
 							'app' => 'objectstore',
280
-							'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
280
+							'message' => 'Count not get object '.$this->getURN($stat['fileid']).' for file '.$path,
281 281
 						]);
282 282
 						return false;
283 283
 					}
@@ -290,7 +290,7 @@  discard block
 block discarded – undo
290 290
 			case 'wb+':
291 291
 				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
292 292
 				$handle = fopen($tmpFile, $mode);
293
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
293
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
294 294
 					$this->writeBack($tmpFile, $path);
295 295
 				});
296 296
 			case 'a':
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
 					file_put_contents($tmpFile, $source);
308 308
 				}
309 309
 				$handle = fopen($tmpFile, $mode);
310
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
310
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
311 311
 					$this->writeBack($tmpFile, $path);
312 312
 				});
313 313
 		}
@@ -316,7 +316,7 @@  discard block
 block discarded – undo
316 316
 
317 317
 	public function file_exists($path) {
318 318
 		$path = $this->normalizePath($path);
319
-		return (bool)$this->stat($path);
319
+		return (bool) $this->stat($path);
320 320
 	}
321 321
 
322 322
 	public function rename($source, $target) {
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
 			} catch (\Exception $ex) {
374 374
 				$this->logger->logException($ex, [
375 375
 					'app' => 'objectstore',
376
-					'message' => 'Could not create object for ' . $path,
376
+					'message' => 'Could not create object for '.$path,
377 377
 				]);
378 378
 				throw $ex;
379 379
 			}
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 			$this->getCache()->remove($path);
414 414
 			$this->logger->logException($ex, [
415 415
 				'app' => 'objectstore',
416
-				'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
416
+				'message' => 'Could not create object '.$this->getURN($fileId).' for '.$path,
417 417
 			]);
418 418
 			throw $ex; // make this bubble up
419 419
 		}
Please login to merge, or discard this patch.
Indentation   +402 added lines, -402 removed lines patch added patch discarded remove patch
@@ -31,406 +31,406 @@
 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
-				}
198
-				//removing from cache is ok as it does not exist in the objectstore anyway
199
-			}
200
-			$this->getCache()->remove($path);
201
-			return true;
202
-		}
203
-		return false;
204
-	}
205
-
206
-	public function stat($path) {
207
-		$path = $this->normalizePath($path);
208
-		$cacheEntry = $this->getCache()->get($path);
209
-		if ($cacheEntry instanceof CacheEntry) {
210
-			return $cacheEntry->getData();
211
-		} else {
212
-			return false;
213
-		}
214
-	}
215
-
216
-	/**
217
-	 * Override this method if you need a different unique resource identifier for your object storage implementation.
218
-	 * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
219
-	 * You may need a mapping table to store your URN if it cannot be generated from the fileid.
220
-	 *
221
-	 * @param int $fileId the fileid
222
-	 * @return null|string the unified resource name used to identify the object
223
-	 */
224
-	protected function getURN($fileId) {
225
-		if (is_numeric($fileId)) {
226
-			return $this->objectPrefix . $fileId;
227
-		}
228
-		return null;
229
-	}
230
-
231
-	public function opendir($path) {
232
-		$path = $this->normalizePath($path);
233
-
234
-		try {
235
-			$files = array();
236
-			$folderContents = $this->getCache()->getFolderContents($path);
237
-			foreach ($folderContents as $file) {
238
-				$files[] = $file['name'];
239
-			}
240
-
241
-			return IteratorDirectory::wrap($files);
242
-		} catch (\Exception $e) {
243
-			$this->logger->logException($e);
244
-			return false;
245
-		}
246
-	}
247
-
248
-	public function filetype($path) {
249
-		$path = $this->normalizePath($path);
250
-		$stat = $this->stat($path);
251
-		if ($stat) {
252
-			if ($stat['mimetype'] === 'httpd/unix-directory') {
253
-				return 'dir';
254
-			}
255
-			return 'file';
256
-		} else {
257
-			return false;
258
-		}
259
-	}
260
-
261
-	public function fopen($path, $mode) {
262
-		$path = $this->normalizePath($path);
263
-
264
-		if (strrpos($path, '.') !== false) {
265
-			$ext = substr($path, strrpos($path, '.'));
266
-		} else {
267
-			$ext = '';
268
-		}
269
-
270
-		switch ($mode) {
271
-			case 'r':
272
-			case 'rb':
273
-				$stat = $this->stat($path);
274
-				if (is_array($stat)) {
275
-					try {
276
-						return $this->objectStore->readObject($this->getURN($stat['fileid']));
277
-					} catch (\Exception $ex) {
278
-						$this->logger->logException($ex, [
279
-							'app' => 'objectstore',
280
-							'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
281
-						]);
282
-						return false;
283
-					}
284
-				} else {
285
-					return false;
286
-				}
287
-			case 'w':
288
-			case 'wb':
289
-			case 'w+':
290
-			case 'wb+':
291
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
292
-				$handle = fopen($tmpFile, $mode);
293
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
294
-					$this->writeBack($tmpFile, $path);
295
-				});
296
-			case 'a':
297
-			case 'ab':
298
-			case 'r+':
299
-			case 'a+':
300
-			case 'x':
301
-			case 'x+':
302
-			case 'c':
303
-			case 'c+':
304
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
305
-				if ($this->file_exists($path)) {
306
-					$source = $this->fopen($path, 'r');
307
-					file_put_contents($tmpFile, $source);
308
-				}
309
-				$handle = fopen($tmpFile, $mode);
310
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
311
-					$this->writeBack($tmpFile, $path);
312
-				});
313
-		}
314
-		return false;
315
-	}
316
-
317
-	public function file_exists($path) {
318
-		$path = $this->normalizePath($path);
319
-		return (bool)$this->stat($path);
320
-	}
321
-
322
-	public function rename($source, $target) {
323
-		$source = $this->normalizePath($source);
324
-		$target = $this->normalizePath($target);
325
-		$this->remove($target);
326
-		$this->getCache()->move($source, $target);
327
-		$this->touch(dirname($target));
328
-		return true;
329
-	}
330
-
331
-	public function getMimeType($path) {
332
-		$path = $this->normalizePath($path);
333
-		$stat = $this->stat($path);
334
-		if (is_array($stat)) {
335
-			return $stat['mimetype'];
336
-		} else {
337
-			return false;
338
-		}
339
-	}
340
-
341
-	public function touch($path, $mtime = null) {
342
-		if (is_null($mtime)) {
343
-			$mtime = time();
344
-		}
345
-
346
-		$path = $this->normalizePath($path);
347
-		$dirName = dirname($path);
348
-		$parentExists = $this->is_dir($dirName);
349
-		if (!$parentExists) {
350
-			return false;
351
-		}
352
-
353
-		$stat = $this->stat($path);
354
-		if (is_array($stat)) {
355
-			// update existing mtime in db
356
-			$stat['mtime'] = $mtime;
357
-			$this->getCache()->update($stat['fileid'], $stat);
358
-		} else {
359
-			try {
360
-				//create a empty file, need to have at least on char to make it
361
-				// work with all object storage implementations
362
-				$this->file_put_contents($path, ' ');
363
-				$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
364
-				$stat = array(
365
-					'etag' => $this->getETag($path),
366
-					'mimetype' => $mimeType,
367
-					'size' => 0,
368
-					'mtime' => $mtime,
369
-					'storage_mtime' => $mtime,
370
-					'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
371
-				);
372
-				$this->getCache()->put($path, $stat);
373
-			} catch (\Exception $ex) {
374
-				$this->logger->logException($ex, [
375
-					'app' => 'objectstore',
376
-					'message' => 'Could not create object for ' . $path,
377
-				]);
378
-				throw $ex;
379
-			}
380
-		}
381
-		return true;
382
-	}
383
-
384
-	public function writeBack($tmpFile, $path) {
385
-		$stat = $this->stat($path);
386
-		if (empty($stat)) {
387
-			// create new file
388
-			$stat = array(
389
-				'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
390
-			);
391
-		}
392
-		// update stat with new data
393
-		$mTime = time();
394
-		$stat['size'] = filesize($tmpFile);
395
-		$stat['mtime'] = $mTime;
396
-		$stat['storage_mtime'] = $mTime;
397
-
398
-		// run path based detection first, to use file extension because $tmpFile is only a random string
399
-		$mimetypeDetector = \OC::$server->getMimeTypeDetector();
400
-		$mimetype = $mimetypeDetector->detectPath($path);
401
-		if ($mimetype === 'application/octet-stream') {
402
-			$mimetype = $mimetypeDetector->detect($tmpFile);
403
-		}
404
-
405
-		$stat['mimetype'] = $mimetype;
406
-		$stat['etag'] = $this->getETag($path);
407
-
408
-		$fileId = $this->getCache()->put($path, $stat);
409
-		try {
410
-			//upload to object storage
411
-			$this->objectStore->writeObject($this->getURN($fileId), fopen($tmpFile, 'r'));
412
-		} catch (\Exception $ex) {
413
-			$this->getCache()->remove($path);
414
-			$this->logger->logException($ex, [
415
-				'app' => 'objectstore',
416
-				'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
417
-			]);
418
-			throw $ex; // make this bubble up
419
-		}
420
-	}
421
-
422
-	/**
423
-	 * external changes are not supported, exclusive access to the object storage is assumed
424
-	 *
425
-	 * @param string $path
426
-	 * @param int $time
427
-	 * @return false
428
-	 */
429
-	public function hasUpdated($path, $time) {
430
-		return false;
431
-	}
432
-
433
-	public function needsPartFile() {
434
-		return false;
435
-	}
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
+                }
198
+                //removing from cache is ok as it does not exist in the objectstore anyway
199
+            }
200
+            $this->getCache()->remove($path);
201
+            return true;
202
+        }
203
+        return false;
204
+    }
205
+
206
+    public function stat($path) {
207
+        $path = $this->normalizePath($path);
208
+        $cacheEntry = $this->getCache()->get($path);
209
+        if ($cacheEntry instanceof CacheEntry) {
210
+            return $cacheEntry->getData();
211
+        } else {
212
+            return false;
213
+        }
214
+    }
215
+
216
+    /**
217
+     * Override this method if you need a different unique resource identifier for your object storage implementation.
218
+     * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
219
+     * You may need a mapping table to store your URN if it cannot be generated from the fileid.
220
+     *
221
+     * @param int $fileId the fileid
222
+     * @return null|string the unified resource name used to identify the object
223
+     */
224
+    protected function getURN($fileId) {
225
+        if (is_numeric($fileId)) {
226
+            return $this->objectPrefix . $fileId;
227
+        }
228
+        return null;
229
+    }
230
+
231
+    public function opendir($path) {
232
+        $path = $this->normalizePath($path);
233
+
234
+        try {
235
+            $files = array();
236
+            $folderContents = $this->getCache()->getFolderContents($path);
237
+            foreach ($folderContents as $file) {
238
+                $files[] = $file['name'];
239
+            }
240
+
241
+            return IteratorDirectory::wrap($files);
242
+        } catch (\Exception $e) {
243
+            $this->logger->logException($e);
244
+            return false;
245
+        }
246
+    }
247
+
248
+    public function filetype($path) {
249
+        $path = $this->normalizePath($path);
250
+        $stat = $this->stat($path);
251
+        if ($stat) {
252
+            if ($stat['mimetype'] === 'httpd/unix-directory') {
253
+                return 'dir';
254
+            }
255
+            return 'file';
256
+        } else {
257
+            return false;
258
+        }
259
+    }
260
+
261
+    public function fopen($path, $mode) {
262
+        $path = $this->normalizePath($path);
263
+
264
+        if (strrpos($path, '.') !== false) {
265
+            $ext = substr($path, strrpos($path, '.'));
266
+        } else {
267
+            $ext = '';
268
+        }
269
+
270
+        switch ($mode) {
271
+            case 'r':
272
+            case 'rb':
273
+                $stat = $this->stat($path);
274
+                if (is_array($stat)) {
275
+                    try {
276
+                        return $this->objectStore->readObject($this->getURN($stat['fileid']));
277
+                    } catch (\Exception $ex) {
278
+                        $this->logger->logException($ex, [
279
+                            'app' => 'objectstore',
280
+                            'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
281
+                        ]);
282
+                        return false;
283
+                    }
284
+                } else {
285
+                    return false;
286
+                }
287
+            case 'w':
288
+            case 'wb':
289
+            case 'w+':
290
+            case 'wb+':
291
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
292
+                $handle = fopen($tmpFile, $mode);
293
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
294
+                    $this->writeBack($tmpFile, $path);
295
+                });
296
+            case 'a':
297
+            case 'ab':
298
+            case 'r+':
299
+            case 'a+':
300
+            case 'x':
301
+            case 'x+':
302
+            case 'c':
303
+            case 'c+':
304
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
305
+                if ($this->file_exists($path)) {
306
+                    $source = $this->fopen($path, 'r');
307
+                    file_put_contents($tmpFile, $source);
308
+                }
309
+                $handle = fopen($tmpFile, $mode);
310
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
311
+                    $this->writeBack($tmpFile, $path);
312
+                });
313
+        }
314
+        return false;
315
+    }
316
+
317
+    public function file_exists($path) {
318
+        $path = $this->normalizePath($path);
319
+        return (bool)$this->stat($path);
320
+    }
321
+
322
+    public function rename($source, $target) {
323
+        $source = $this->normalizePath($source);
324
+        $target = $this->normalizePath($target);
325
+        $this->remove($target);
326
+        $this->getCache()->move($source, $target);
327
+        $this->touch(dirname($target));
328
+        return true;
329
+    }
330
+
331
+    public function getMimeType($path) {
332
+        $path = $this->normalizePath($path);
333
+        $stat = $this->stat($path);
334
+        if (is_array($stat)) {
335
+            return $stat['mimetype'];
336
+        } else {
337
+            return false;
338
+        }
339
+    }
340
+
341
+    public function touch($path, $mtime = null) {
342
+        if (is_null($mtime)) {
343
+            $mtime = time();
344
+        }
345
+
346
+        $path = $this->normalizePath($path);
347
+        $dirName = dirname($path);
348
+        $parentExists = $this->is_dir($dirName);
349
+        if (!$parentExists) {
350
+            return false;
351
+        }
352
+
353
+        $stat = $this->stat($path);
354
+        if (is_array($stat)) {
355
+            // update existing mtime in db
356
+            $stat['mtime'] = $mtime;
357
+            $this->getCache()->update($stat['fileid'], $stat);
358
+        } else {
359
+            try {
360
+                //create a empty file, need to have at least on char to make it
361
+                // work with all object storage implementations
362
+                $this->file_put_contents($path, ' ');
363
+                $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
364
+                $stat = array(
365
+                    'etag' => $this->getETag($path),
366
+                    'mimetype' => $mimeType,
367
+                    'size' => 0,
368
+                    'mtime' => $mtime,
369
+                    'storage_mtime' => $mtime,
370
+                    'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
371
+                );
372
+                $this->getCache()->put($path, $stat);
373
+            } catch (\Exception $ex) {
374
+                $this->logger->logException($ex, [
375
+                    'app' => 'objectstore',
376
+                    'message' => 'Could not create object for ' . $path,
377
+                ]);
378
+                throw $ex;
379
+            }
380
+        }
381
+        return true;
382
+    }
383
+
384
+    public function writeBack($tmpFile, $path) {
385
+        $stat = $this->stat($path);
386
+        if (empty($stat)) {
387
+            // create new file
388
+            $stat = array(
389
+                'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
390
+            );
391
+        }
392
+        // update stat with new data
393
+        $mTime = time();
394
+        $stat['size'] = filesize($tmpFile);
395
+        $stat['mtime'] = $mTime;
396
+        $stat['storage_mtime'] = $mTime;
397
+
398
+        // run path based detection first, to use file extension because $tmpFile is only a random string
399
+        $mimetypeDetector = \OC::$server->getMimeTypeDetector();
400
+        $mimetype = $mimetypeDetector->detectPath($path);
401
+        if ($mimetype === 'application/octet-stream') {
402
+            $mimetype = $mimetypeDetector->detect($tmpFile);
403
+        }
404
+
405
+        $stat['mimetype'] = $mimetype;
406
+        $stat['etag'] = $this->getETag($path);
407
+
408
+        $fileId = $this->getCache()->put($path, $stat);
409
+        try {
410
+            //upload to object storage
411
+            $this->objectStore->writeObject($this->getURN($fileId), fopen($tmpFile, 'r'));
412
+        } catch (\Exception $ex) {
413
+            $this->getCache()->remove($path);
414
+            $this->logger->logException($ex, [
415
+                'app' => 'objectstore',
416
+                'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
417
+            ]);
418
+            throw $ex; // make this bubble up
419
+        }
420
+    }
421
+
422
+    /**
423
+     * external changes are not supported, exclusive access to the object storage is assumed
424
+     *
425
+     * @param string $path
426
+     * @param int $time
427
+     * @return false
428
+     */
429
+    public function hasUpdated($path, $time) {
430
+        return false;
431
+    }
432
+
433
+    public function needsPartFile() {
434
+        return false;
435
+    }
436 436
 }
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/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   +105 added lines, -105 removed lines patch added patch discarded remove patch
@@ -30,116 +30,116 @@
 block discarded – undo
30 30
 use OCP\Files\NotPermittedException;
31 31
 
32 32
 class File extends Node implements \OCP\Files\File {
33
-	/**
34
-	 * Creates a Folder that represents a non-existing path
35
-	 *
36
-	 * @param string $path path
37
-	 * @return string non-existing node class
38
-	 */
39
-	protected function createNonExistingNode($path) {
40
-		return new NonExistingFile($this->root, $this->view, $path);
41
-	}
33
+    /**
34
+     * Creates a Folder that represents a non-existing path
35
+     *
36
+     * @param string $path path
37
+     * @return string non-existing node class
38
+     */
39
+    protected function createNonExistingNode($path) {
40
+        return new NonExistingFile($this->root, $this->view, $path);
41
+    }
42 42
 
43
-	/**
44
-	 * @return string
45
-	 * @throws \OCP\Files\NotPermittedException
46
-	 */
47
-	public function getContent() {
48
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_READ)) {
49
-			/**
50
-			 * @var \OC\Files\Storage\Storage $storage;
51
-			 */
52
-			return $this->view->file_get_contents($this->path);
53
-		} else {
54
-			throw new NotPermittedException();
55
-		}
56
-	}
43
+    /**
44
+     * @return string
45
+     * @throws \OCP\Files\NotPermittedException
46
+     */
47
+    public function getContent() {
48
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_READ)) {
49
+            /**
50
+             * @var \OC\Files\Storage\Storage $storage;
51
+             */
52
+            return $this->view->file_get_contents($this->path);
53
+        } else {
54
+            throw new NotPermittedException();
55
+        }
56
+    }
57 57
 
58
-	/**
59
-	 * @param string|resource $data
60
-	 * @throws \OCP\Files\NotPermittedException
61
-	 * @throws \OCP\Files\GenericFileException
62
-	 */
63
-	public function putContent($data) {
64
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_UPDATE)) {
65
-			$this->sendHooks(array('preWrite'));
66
-			if ($this->view->file_put_contents($this->path, $data) === false) {
67
-				throw new GenericFileException('file_put_contents failed');
68
-			}
69
-			$this->fileInfo = null;
70
-			$this->sendHooks(array('postWrite'));
71
-		} else {
72
-			throw new NotPermittedException();
73
-		}
74
-	}
58
+    /**
59
+     * @param string|resource $data
60
+     * @throws \OCP\Files\NotPermittedException
61
+     * @throws \OCP\Files\GenericFileException
62
+     */
63
+    public function putContent($data) {
64
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_UPDATE)) {
65
+            $this->sendHooks(array('preWrite'));
66
+            if ($this->view->file_put_contents($this->path, $data) === false) {
67
+                throw new GenericFileException('file_put_contents failed');
68
+            }
69
+            $this->fileInfo = null;
70
+            $this->sendHooks(array('postWrite'));
71
+        } else {
72
+            throw new NotPermittedException();
73
+        }
74
+    }
75 75
 
76
-	/**
77
-	 * @param string $mode
78
-	 * @return resource
79
-	 * @throws \OCP\Files\NotPermittedException
80
-	 */
81
-	public function fopen($mode) {
82
-		$preHooks = array();
83
-		$postHooks = array();
84
-		$requiredPermissions = \OCP\Constants::PERMISSION_READ;
85
-		switch ($mode) {
86
-			case 'r+':
87
-			case 'rb+':
88
-			case 'w+':
89
-			case 'wb+':
90
-			case 'x+':
91
-			case 'xb+':
92
-			case 'a+':
93
-			case 'ab+':
94
-			case 'w':
95
-			case 'wb':
96
-			case 'x':
97
-			case 'xb':
98
-			case 'a':
99
-			case 'ab':
100
-				$preHooks[] = 'preWrite';
101
-				$postHooks[] = 'postWrite';
102
-				$requiredPermissions |= \OCP\Constants::PERMISSION_UPDATE;
103
-				break;
104
-		}
76
+    /**
77
+     * @param string $mode
78
+     * @return resource
79
+     * @throws \OCP\Files\NotPermittedException
80
+     */
81
+    public function fopen($mode) {
82
+        $preHooks = array();
83
+        $postHooks = array();
84
+        $requiredPermissions = \OCP\Constants::PERMISSION_READ;
85
+        switch ($mode) {
86
+            case 'r+':
87
+            case 'rb+':
88
+            case 'w+':
89
+            case 'wb+':
90
+            case 'x+':
91
+            case 'xb+':
92
+            case 'a+':
93
+            case 'ab+':
94
+            case 'w':
95
+            case 'wb':
96
+            case 'x':
97
+            case 'xb':
98
+            case 'a':
99
+            case 'ab':
100
+                $preHooks[] = 'preWrite';
101
+                $postHooks[] = 'postWrite';
102
+                $requiredPermissions |= \OCP\Constants::PERMISSION_UPDATE;
103
+                break;
104
+        }
105 105
 
106
-		if ($this->checkPermissions($requiredPermissions)) {
107
-			$this->sendHooks($preHooks);
108
-			$result = $this->view->fopen($this->path, $mode);
109
-			$this->sendHooks($postHooks);
110
-			return $result;
111
-		} else {
112
-			throw new NotPermittedException();
113
-		}
114
-	}
106
+        if ($this->checkPermissions($requiredPermissions)) {
107
+            $this->sendHooks($preHooks);
108
+            $result = $this->view->fopen($this->path, $mode);
109
+            $this->sendHooks($postHooks);
110
+            return $result;
111
+        } else {
112
+            throw new NotPermittedException();
113
+        }
114
+    }
115 115
 
116
-	public function delete() {
117
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
118
-			$this->sendHooks(array('preDelete'));
119
-			$fileInfo = $this->getFileInfo();
120
-			$this->view->unlink($this->path);
121
-			$nonExisting = new NonExistingFile($this->root, $this->view, $this->path, $fileInfo);
122
-			$this->root->emit('\OC\Files', 'postDelete', array($nonExisting));
123
-			$this->exists = false;
124
-			$this->fileInfo = null;
125
-		} else {
126
-			throw new NotPermittedException();
127
-		}
128
-	}
116
+    public function delete() {
117
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
118
+            $this->sendHooks(array('preDelete'));
119
+            $fileInfo = $this->getFileInfo();
120
+            $this->view->unlink($this->path);
121
+            $nonExisting = new NonExistingFile($this->root, $this->view, $this->path, $fileInfo);
122
+            $this->root->emit('\OC\Files', 'postDelete', array($nonExisting));
123
+            $this->exists = false;
124
+            $this->fileInfo = null;
125
+        } else {
126
+            throw new NotPermittedException();
127
+        }
128
+    }
129 129
 
130
-	/**
131
-	 * @param string $type
132
-	 * @param bool $raw
133
-	 * @return string
134
-	 */
135
-	public function hash($type, $raw = false) {
136
-		return $this->view->hash($type, $this->path, $raw);
137
-	}
130
+    /**
131
+     * @param string $type
132
+     * @param bool $raw
133
+     * @return string
134
+     */
135
+    public function hash($type, $raw = false) {
136
+        return $this->view->hash($type, $this->path, $raw);
137
+    }
138 138
 
139
-	/**
140
-	 * @inheritdoc
141
-	 */
142
-	public function getChecksum() {
143
-		return $this->getFileInfo()->getChecksum();
144
-	}
139
+    /**
140
+     * @inheritdoc
141
+     */
142
+    public function getChecksum() {
143
+        return $this->getFileInfo()->getChecksum();
144
+    }
145 145
 }
Please login to merge, or discard this patch.