Completed
Pull Request — master (#7112)
by Morris
81:26 queued 65:50
created
apps/user_ldap/templates/part.wizard-server.php 1 patch
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -1,16 +1,16 @@  discard block
 block discarded – undo
1 1
 <fieldset id="ldapWizard1">
2 2
 		<p>
3 3
 		<select id="ldap_serverconfig_chooser" name="ldap_serverconfig_chooser">
4
-		<?php if(count($_['serverConfigurationPrefixes']) === 0 ) {
4
+		<?php if (count($_['serverConfigurationPrefixes']) === 0) {
5 5
 			?>
6
-				<option value="" selected><?php p($l->t('1. Server'));?></option>');
6
+				<option value="" selected><?php p($l->t('1. Server')); ?></option>');
7 7
 			<?php
8 8
 		} else {
9 9
 			$i = 1;
10 10
 			$sel = ' selected';
11
-			foreach($_['serverConfigurationPrefixes'] as $prefix) {
11
+			foreach ($_['serverConfigurationPrefixes'] as $prefix) {
12 12
 				?>
13
-				<option value="<?php p($prefix); ?>"<?php p($sel); $sel = ''; ?>><?php p($l->t('%s. Server:', array($i++)));?> <?php p(' '.$_['serverConfigurationHosts'][$prefix]); ?></option>
13
+				<option value="<?php p($prefix); ?>"<?php p($sel); $sel = ''; ?>><?php p($l->t('%s. Server:', array($i++))); ?> <?php p(' '.$_['serverConfigurationHosts'][$prefix]); ?></option>
14 14
 				<?php
15 15
 			}
16 16
 		}
@@ -18,14 +18,14 @@  discard block
 block discarded – undo
18 18
 		</select>
19 19
 		<button type="button" id="ldap_action_add_configuration"
20 20
 			name="ldap_action_add_configuration" class="icon-add icon-default-style"
21
-			title="<?php p($l->t('Add a new configuration'));?>">&nbsp;</button>
21
+			title="<?php p($l->t('Add a new configuration')); ?>">&nbsp;</button>
22 22
 		<button type="button" id="ldap_action_copy_configuration"
23 23
 			name="ldap_action_copy_configuration"
24 24
 			class="ldapIconCopy icon-default-style"
25
-			title="<?php p($l->t('Copy current configuration into new directory binding'));?>">&nbsp;</button>
25
+			title="<?php p($l->t('Copy current configuration into new directory binding')); ?>">&nbsp;</button>
26 26
 		<button type="button" id="ldap_action_delete_configuration"
27 27
 			name="ldap_action_delete_configuration" class="icon-delete icon-default-style"
28
-			title="<?php p($l->t('Delete the current configuration'));?>">&nbsp;</button>
28
+			title="<?php p($l->t('Delete the current configuration')); ?>">&nbsp;</button>
29 29
 		</p>
30 30
 
31 31
 		<div class="hostPortCombinator">
@@ -34,14 +34,14 @@  discard block
 block discarded – undo
34 34
 					<div class="table">
35 35
 						<input type="text" class="host" id="ldap_host"
36 36
 							name="ldap_host"
37
-							placeholder="<?php p($l->t('Host'));?>"
38
-							title="<?php p($l->t('You can omit the protocol, unless you require SSL. If so, start with ldaps://'));?>"
37
+							placeholder="<?php p($l->t('Host')); ?>"
38
+							title="<?php p($l->t('You can omit the protocol, unless you require SSL. If so, start with ldaps://')); ?>"
39 39
 							/>
40 40
 						<span class="hostPortCombinatorSpan">
41 41
 							<input type="number" id="ldap_port" name="ldap_port"
42
-								placeholder="<?php p($l->t('Port'));?>" />
42
+								placeholder="<?php p($l->t('Port')); ?>" />
43 43
 							<button class="ldapDetectPort" name="ldapDetectPort" type="button">
44
-								<?php p($l->t('Detect Port'));?>
44
+								<?php p($l->t('Detect Port')); ?>
45 45
 							</button>
46 46
 						</span>
47 47
 					</div>
@@ -51,19 +51,19 @@  discard block
 block discarded – undo
51 51
 			<div class="tablerow">
52 52
 				<input type="text" id="ldap_dn" name="ldap_dn"
53 53
 				class="tablecell"
54
-				placeholder="<?php p($l->t('User DN'));?>" autocomplete="off"
55
-				title="<?php p($l->t('The DN of the client user with which the bind shall be done, e.g. uid=agent,dc=example,dc=com. For anonymous access, leave DN and Password empty.'));?>"
54
+				placeholder="<?php p($l->t('User DN')); ?>" autocomplete="off"
55
+				title="<?php p($l->t('The DN of the client user with which the bind shall be done, e.g. uid=agent,dc=example,dc=com. For anonymous access, leave DN and Password empty.')); ?>"
56 56
 				/>
57 57
 			</div>
58 58
 
59 59
 			<div class="tablerow">
60 60
 				<input type="password" id="ldap_agent_password"
61 61
 				class="tablecell" name="ldap_agent_password"
62
-				placeholder="<?php p($l->t('Password'));?>" autocomplete="off"
63
-				title="<?php p($l->t('For anonymous access, leave DN and Password empty.'));?>"
62
+				placeholder="<?php p($l->t('Password')); ?>" autocomplete="off"
63
+				title="<?php p($l->t('For anonymous access, leave DN and Password empty.')); ?>"
64 64
 				/>
65 65
 				<button class="ldapSaveAgentCredentials" name="ldapSaveAgentCredentials" type="button">
66
-					<?php p($l->t('Save Credentials'));?>
66
+					<?php p($l->t('Save Credentials')); ?>
67 67
 				</button>
68 68
 			</div>
69 69
 			<div class="tablerow">&nbsp;</div>
@@ -71,24 +71,24 @@  discard block
 block discarded – undo
71 71
 			<div class="tablerow">
72 72
 				<textarea id="ldap_base" name="ldap_base"
73 73
 					class="tablecell"
74
-					placeholder="<?php p($l->t('One Base DN per line'));?>"
75
-					title="<?php p($l->t('You can specify Base DN for users and groups in the Advanced tab'));?>">
74
+					placeholder="<?php p($l->t('One Base DN per line')); ?>"
75
+					title="<?php p($l->t('You can specify Base DN for users and groups in the Advanced tab')); ?>">
76 76
 				</textarea>
77 77
 				<button class="ldapDetectBase" name="ldapDetectBase" type="button">
78
-					<?php p($l->t('Detect Base DN'));?>
78
+					<?php p($l->t('Detect Base DN')); ?>
79 79
 				</button>
80 80
 				<button class="ldapTestBase" name="ldapTestBase" type="button">
81
-					<?php p($l->t('Test Base DN'));?>
81
+					<?php p($l->t('Test Base DN')); ?>
82 82
 				</button>
83 83
 			</div>
84 84
 
85 85
 			<div class="tablerow left">
86 86
 				<input type="checkbox" id="ldap_experienced_admin" value="1"
87 87
 					name="ldap_experienced_admin" class="tablecell"
88
-					title="<?php p($l->t('Avoids automatic LDAP requests. Better for bigger setups, but requires some LDAP knowledge.'));?>"
88
+					title="<?php p($l->t('Avoids automatic LDAP requests. Better for bigger setups, but requires some LDAP knowledge.')); ?>"
89 89
 					/>
90 90
 				<label for="ldap_experienced_admin" class="tablecell">
91
-					<?php p($l->t('Manually enter LDAP filters (recommended for large directories)'));?>
91
+					<?php p($l->t('Manually enter LDAP filters (recommended for large directories)')); ?>
92 92
 				</label>
93 93
 			</div>
94 94
 
Please login to merge, or discard this patch.
apps/user_ldap/lib/Configuration.php 2 patches
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
 	 */
108 108
 	public function __construct($configPrefix, $autoRead = true) {
109 109
 		$this->configPrefix = $configPrefix;
110
-		if($autoRead) {
110
+		if ($autoRead) {
111 111
 			$this->readConfiguration();
112 112
 		}
113 113
 	}
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
 	 * @return mixed|null
118 118
 	 */
119 119
 	public function __get($name) {
120
-		if(isset($this->config[$name])) {
120
+		if (isset($this->config[$name])) {
121 121
 			return $this->config[$name];
122 122
 		}
123 123
 		return null;
@@ -148,22 +148,22 @@  discard block
 block discarded – undo
148 148
 	 * @return false|null
149 149
 	 */
150 150
 	public function setConfiguration($config, &$applied = null) {
151
-		if(!is_array($config)) {
151
+		if (!is_array($config)) {
152 152
 			return false;
153 153
 		}
154 154
 
155 155
 		$cta = $this->getConfigTranslationArray();
156
-		foreach($config as $inputKey => $val) {
157
-			if(strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) {
156
+		foreach ($config as $inputKey => $val) {
157
+			if (strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) {
158 158
 				$key = $cta[$inputKey];
159
-			} elseif(array_key_exists($inputKey, $this->config)) {
159
+			} elseif (array_key_exists($inputKey, $this->config)) {
160 160
 				$key = $inputKey;
161 161
 			} else {
162 162
 				continue;
163 163
 			}
164 164
 
165 165
 			$setMethod = 'setValue';
166
-			switch($key) {
166
+			switch ($key) {
167 167
 				case 'ldapAgentPassword':
168 168
 					$setMethod = 'setRawValue';
169 169
 					break;
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 					break;
188 188
 			}
189 189
 			$this->$setMethod($key, $val);
190
-			if(is_array($applied)) {
190
+			if (is_array($applied)) {
191 191
 				$applied[] = $inputKey;
192 192
 				// storing key as index avoids duplication, and as value for simplicity
193 193
 			}
@@ -197,15 +197,15 @@  discard block
 block discarded – undo
197 197
 	}
198 198
 
199 199
 	public function readConfiguration() {
200
-		if(!$this->configRead && !is_null($this->configPrefix)) {
200
+		if (!$this->configRead && !is_null($this->configPrefix)) {
201 201
 			$cta = array_flip($this->getConfigTranslationArray());
202
-			foreach($this->config as $key => $val) {
203
-				if(!isset($cta[$key])) {
202
+			foreach ($this->config as $key => $val) {
203
+				if (!isset($cta[$key])) {
204 204
 					//some are determined
205 205
 					continue;
206 206
 				}
207 207
 				$dbKey = $cta[$key];
208
-				switch($key) {
208
+				switch ($key) {
209 209
 					case 'ldapBase':
210 210
 					case 'ldapBaseUsers':
211 211
 					case 'ldapBaseGroups':
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 	 */
249 249
 	public function saveConfiguration() {
250 250
 		$cta = array_flip($this->getConfigTranslationArray());
251
-		foreach($this->unsavedChanges as $key) {
251
+		foreach ($this->unsavedChanges as $key) {
252 252
 			$value = $this->config[$key];
253 253
 			switch ($key) {
254 254
 				case 'ldapAgentPassword':
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
 				case 'ldapGroupFilterObjectclass':
265 265
 				case 'ldapGroupFilterGroups':
266 266
 				case 'ldapLoginFilterAttributes':
267
-					if(is_array($value)) {
267
+					if (is_array($value)) {
268 268
 						$value = implode("\n", $value);
269 269
 					}
270 270
 					break;
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 				case 'ldapUuidGroupAttribute':
276 276
 					continue 2;
277 277
 			}
278
-			if(is_null($value)) {
278
+			if (is_null($value)) {
279 279
 				$value = '';
280 280
 			}
281 281
 			$this->saveValue($cta[$key], $value);
@@ -289,7 +289,7 @@  discard block
 block discarded – undo
289 289
 	 */
290 290
 	protected function getMultiLine($varName) {
291 291
 		$value = $this->getValue($varName);
292
-		if(empty($value)) {
292
+		if (empty($value)) {
293 293
 			$value = '';
294 294
 		} else {
295 295
 			$value = preg_split('/\r\n|\r|\n/', $value);
@@ -305,21 +305,21 @@  discard block
 block discarded – undo
305 305
 	 * @param array|string $value to set
306 306
 	 */
307 307
 	protected function setMultiLine($varName, $value) {
308
-		if(empty($value)) {
308
+		if (empty($value)) {
309 309
 			$value = '';
310 310
 		} else if (!is_array($value)) {
311 311
 			$value = preg_split('/\r\n|\r|\n|;/', $value);
312
-			if($value === false) {
312
+			if ($value === false) {
313 313
 				$value = '';
314 314
 			}
315 315
 		}
316 316
 
317
-		if(!is_array($value)) {
317
+		if (!is_array($value)) {
318 318
 			$finalValue = trim($value);
319 319
 		} else {
320 320
 			$finalValue = [];
321
-			foreach($value as $key => $val) {
322
-				if(is_string($val)) {
321
+			foreach ($value as $key => $val) {
322
+				if (is_string($val)) {
323 323
 					$val = trim($val);
324 324
 					if ($val !== '') {
325 325
 						//accidental line breaks are not wanted and can cause
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
 	 */
367 367
 	protected function getValue($varName) {
368 368
 		static $defaults;
369
-		if(is_null($defaults)) {
369
+		if (is_null($defaults)) {
370 370
 			$defaults = $this->getDefaults();
371 371
 		}
372 372
 		return \OCP\Config::getAppValue('user_ldap',
@@ -381,7 +381,7 @@  discard block
 block discarded – undo
381 381
 	 * @param mixed $value to set
382 382
 	 */
383 383
 	protected function setValue($varName, $value) {
384
-		if(is_string($value)) {
384
+		if (is_string($value)) {
385 385
 			$value = trim($value);
386 386
 		}
387 387
 		$this->config[$varName] = $value;
Please login to merge, or discard this patch.
Indentation   +472 added lines, -472 removed lines patch added patch discarded remove patch
@@ -35,501 +35,501 @@
 block discarded – undo
35 35
  * @property int ldapPagingSize holds an integer
36 36
  */
37 37
 class Configuration {
38
-	protected $configPrefix = null;
39
-	protected $configRead = false;
40
-	/**
41
-	 * @var string[] pre-filled with one reference key so that at least one entry is written on save request and
42
-	 *               the config ID is registered
43
-	 */
44
-	protected $unsavedChanges = ['ldapConfigurationActive' => 'ldapConfigurationActive'];
38
+    protected $configPrefix = null;
39
+    protected $configRead = false;
40
+    /**
41
+     * @var string[] pre-filled with one reference key so that at least one entry is written on save request and
42
+     *               the config ID is registered
43
+     */
44
+    protected $unsavedChanges = ['ldapConfigurationActive' => 'ldapConfigurationActive'];
45 45
 
46
-	//settings
47
-	protected $config = array(
48
-		'ldapHost' => null,
49
-		'ldapPort' => null,
50
-		'ldapBackupHost' => null,
51
-		'ldapBackupPort' => null,
52
-		'ldapBase' => null,
53
-		'ldapBaseUsers' => null,
54
-		'ldapBaseGroups' => null,
55
-		'ldapAgentName' => null,
56
-		'ldapAgentPassword' => null,
57
-		'ldapTLS' => null,
58
-		'turnOffCertCheck' => null,
59
-		'ldapIgnoreNamingRules' => null,
60
-		'ldapUserDisplayName' => null,
61
-		'ldapUserDisplayName2' => null,
62
-		'ldapGidNumber' => null,
63
-		'ldapUserFilterObjectclass' => null,
64
-		'ldapUserFilterGroups' => null,
65
-		'ldapUserFilter' => null,
66
-		'ldapUserFilterMode' => null,
67
-		'ldapGroupFilter' => null,
68
-		'ldapGroupFilterMode' => null,
69
-		'ldapGroupFilterObjectclass' => null,
70
-		'ldapGroupFilterGroups' => null,
71
-		'ldapGroupDisplayName' => null,
72
-		'ldapGroupMemberAssocAttr' => null,
73
-		'ldapLoginFilter' => null,
74
-		'ldapLoginFilterMode' => null,
75
-		'ldapLoginFilterEmail' => null,
76
-		'ldapLoginFilterUsername' => null,
77
-		'ldapLoginFilterAttributes' => null,
78
-		'ldapQuotaAttribute' => null,
79
-		'ldapQuotaDefault' => null,
80
-		'ldapEmailAttribute' => null,
81
-		'ldapCacheTTL' => null,
82
-		'ldapUuidUserAttribute' => 'auto',
83
-		'ldapUuidGroupAttribute' => 'auto',
84
-		'ldapOverrideMainServer' => false,
85
-		'ldapConfigurationActive' => false,
86
-		'ldapAttributesForUserSearch' => null,
87
-		'ldapAttributesForGroupSearch' => null,
88
-		'ldapExperiencedAdmin' => false,
89
-		'homeFolderNamingRule' => null,
90
-		'hasPagedResultSupport' => false,
91
-		'hasMemberOfFilterSupport' => false,
92
-		'useMemberOfToDetectMembership' => true,
93
-		'ldapExpertUsernameAttr' => null,
94
-		'ldapExpertUUIDUserAttr' => null,
95
-		'ldapExpertUUIDGroupAttr' => null,
96
-		'lastJpegPhotoLookup' => null,
97
-		'ldapNestedGroups' => false,
98
-		'ldapPagingSize' => null,
99
-		'turnOnPasswordChange' => false,
100
-		'ldapDynamicGroupMemberURL' => null,
101
-		'ldapDefaultPPolicyDN' => null,
102
-	);
46
+    //settings
47
+    protected $config = array(
48
+        'ldapHost' => null,
49
+        'ldapPort' => null,
50
+        'ldapBackupHost' => null,
51
+        'ldapBackupPort' => null,
52
+        'ldapBase' => null,
53
+        'ldapBaseUsers' => null,
54
+        'ldapBaseGroups' => null,
55
+        'ldapAgentName' => null,
56
+        'ldapAgentPassword' => null,
57
+        'ldapTLS' => null,
58
+        'turnOffCertCheck' => null,
59
+        'ldapIgnoreNamingRules' => null,
60
+        'ldapUserDisplayName' => null,
61
+        'ldapUserDisplayName2' => null,
62
+        'ldapGidNumber' => null,
63
+        'ldapUserFilterObjectclass' => null,
64
+        'ldapUserFilterGroups' => null,
65
+        'ldapUserFilter' => null,
66
+        'ldapUserFilterMode' => null,
67
+        'ldapGroupFilter' => null,
68
+        'ldapGroupFilterMode' => null,
69
+        'ldapGroupFilterObjectclass' => null,
70
+        'ldapGroupFilterGroups' => null,
71
+        'ldapGroupDisplayName' => null,
72
+        'ldapGroupMemberAssocAttr' => null,
73
+        'ldapLoginFilter' => null,
74
+        'ldapLoginFilterMode' => null,
75
+        'ldapLoginFilterEmail' => null,
76
+        'ldapLoginFilterUsername' => null,
77
+        'ldapLoginFilterAttributes' => null,
78
+        'ldapQuotaAttribute' => null,
79
+        'ldapQuotaDefault' => null,
80
+        'ldapEmailAttribute' => null,
81
+        'ldapCacheTTL' => null,
82
+        'ldapUuidUserAttribute' => 'auto',
83
+        'ldapUuidGroupAttribute' => 'auto',
84
+        'ldapOverrideMainServer' => false,
85
+        'ldapConfigurationActive' => false,
86
+        'ldapAttributesForUserSearch' => null,
87
+        'ldapAttributesForGroupSearch' => null,
88
+        'ldapExperiencedAdmin' => false,
89
+        'homeFolderNamingRule' => null,
90
+        'hasPagedResultSupport' => false,
91
+        'hasMemberOfFilterSupport' => false,
92
+        'useMemberOfToDetectMembership' => true,
93
+        'ldapExpertUsernameAttr' => null,
94
+        'ldapExpertUUIDUserAttr' => null,
95
+        'ldapExpertUUIDGroupAttr' => null,
96
+        'lastJpegPhotoLookup' => null,
97
+        'ldapNestedGroups' => false,
98
+        'ldapPagingSize' => null,
99
+        'turnOnPasswordChange' => false,
100
+        'ldapDynamicGroupMemberURL' => null,
101
+        'ldapDefaultPPolicyDN' => null,
102
+    );
103 103
 
104
-	/**
105
-	 * @param string $configPrefix
106
-	 * @param bool $autoRead
107
-	 */
108
-	public function __construct($configPrefix, $autoRead = true) {
109
-		$this->configPrefix = $configPrefix;
110
-		if($autoRead) {
111
-			$this->readConfiguration();
112
-		}
113
-	}
104
+    /**
105
+     * @param string $configPrefix
106
+     * @param bool $autoRead
107
+     */
108
+    public function __construct($configPrefix, $autoRead = true) {
109
+        $this->configPrefix = $configPrefix;
110
+        if($autoRead) {
111
+            $this->readConfiguration();
112
+        }
113
+    }
114 114
 
115
-	/**
116
-	 * @param string $name
117
-	 * @return mixed|null
118
-	 */
119
-	public function __get($name) {
120
-		if(isset($this->config[$name])) {
121
-			return $this->config[$name];
122
-		}
123
-		return null;
124
-	}
115
+    /**
116
+     * @param string $name
117
+     * @return mixed|null
118
+     */
119
+    public function __get($name) {
120
+        if(isset($this->config[$name])) {
121
+            return $this->config[$name];
122
+        }
123
+        return null;
124
+    }
125 125
 
126
-	/**
127
-	 * @param string $name
128
-	 * @param mixed $value
129
-	 */
130
-	public function __set($name, $value) {
131
-		$this->setConfiguration(array($name => $value));
132
-	}
126
+    /**
127
+     * @param string $name
128
+     * @param mixed $value
129
+     */
130
+    public function __set($name, $value) {
131
+        $this->setConfiguration(array($name => $value));
132
+    }
133 133
 
134
-	/**
135
-	 * @return array
136
-	 */
137
-	public function getConfiguration() {
138
-		return $this->config;
139
-	}
134
+    /**
135
+     * @return array
136
+     */
137
+    public function getConfiguration() {
138
+        return $this->config;
139
+    }
140 140
 
141
-	/**
142
-	 * set LDAP configuration with values delivered by an array, not read
143
-	 * from configuration. It does not save the configuration! To do so, you
144
-	 * must call saveConfiguration afterwards.
145
-	 * @param array $config array that holds the config parameters in an associated
146
-	 * array
147
-	 * @param array &$applied optional; array where the set fields will be given to
148
-	 * @return false|null
149
-	 */
150
-	public function setConfiguration($config, &$applied = null) {
151
-		if(!is_array($config)) {
152
-			return false;
153
-		}
141
+    /**
142
+     * set LDAP configuration with values delivered by an array, not read
143
+     * from configuration. It does not save the configuration! To do so, you
144
+     * must call saveConfiguration afterwards.
145
+     * @param array $config array that holds the config parameters in an associated
146
+     * array
147
+     * @param array &$applied optional; array where the set fields will be given to
148
+     * @return false|null
149
+     */
150
+    public function setConfiguration($config, &$applied = null) {
151
+        if(!is_array($config)) {
152
+            return false;
153
+        }
154 154
 
155
-		$cta = $this->getConfigTranslationArray();
156
-		foreach($config as $inputKey => $val) {
157
-			if(strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) {
158
-				$key = $cta[$inputKey];
159
-			} elseif(array_key_exists($inputKey, $this->config)) {
160
-				$key = $inputKey;
161
-			} else {
162
-				continue;
163
-			}
155
+        $cta = $this->getConfigTranslationArray();
156
+        foreach($config as $inputKey => $val) {
157
+            if(strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) {
158
+                $key = $cta[$inputKey];
159
+            } elseif(array_key_exists($inputKey, $this->config)) {
160
+                $key = $inputKey;
161
+            } else {
162
+                continue;
163
+            }
164 164
 
165
-			$setMethod = 'setValue';
166
-			switch($key) {
167
-				case 'ldapAgentPassword':
168
-					$setMethod = 'setRawValue';
169
-					break;
170
-				case 'homeFolderNamingRule':
171
-					$trimmedVal = trim($val);
172
-					if ($trimmedVal !== '' && strpos($val, 'attr:') === false) {
173
-						$val = 'attr:'.$trimmedVal;
174
-					}
175
-					break;
176
-				case 'ldapBase':
177
-				case 'ldapBaseUsers':
178
-				case 'ldapBaseGroups':
179
-				case 'ldapAttributesForUserSearch':
180
-				case 'ldapAttributesForGroupSearch':
181
-				case 'ldapUserFilterObjectclass':
182
-				case 'ldapUserFilterGroups':
183
-				case 'ldapGroupFilterObjectclass':
184
-				case 'ldapGroupFilterGroups':
185
-				case 'ldapLoginFilterAttributes':
186
-					$setMethod = 'setMultiLine';
187
-					break;
188
-			}
189
-			$this->$setMethod($key, $val);
190
-			if(is_array($applied)) {
191
-				$applied[] = $inputKey;
192
-				// storing key as index avoids duplication, and as value for simplicity
193
-			}
194
-			$this->unsavedChanges[$key] = $key;
195
-		}
196
-		return null;
197
-	}
165
+            $setMethod = 'setValue';
166
+            switch($key) {
167
+                case 'ldapAgentPassword':
168
+                    $setMethod = 'setRawValue';
169
+                    break;
170
+                case 'homeFolderNamingRule':
171
+                    $trimmedVal = trim($val);
172
+                    if ($trimmedVal !== '' && strpos($val, 'attr:') === false) {
173
+                        $val = 'attr:'.$trimmedVal;
174
+                    }
175
+                    break;
176
+                case 'ldapBase':
177
+                case 'ldapBaseUsers':
178
+                case 'ldapBaseGroups':
179
+                case 'ldapAttributesForUserSearch':
180
+                case 'ldapAttributesForGroupSearch':
181
+                case 'ldapUserFilterObjectclass':
182
+                case 'ldapUserFilterGroups':
183
+                case 'ldapGroupFilterObjectclass':
184
+                case 'ldapGroupFilterGroups':
185
+                case 'ldapLoginFilterAttributes':
186
+                    $setMethod = 'setMultiLine';
187
+                    break;
188
+            }
189
+            $this->$setMethod($key, $val);
190
+            if(is_array($applied)) {
191
+                $applied[] = $inputKey;
192
+                // storing key as index avoids duplication, and as value for simplicity
193
+            }
194
+            $this->unsavedChanges[$key] = $key;
195
+        }
196
+        return null;
197
+    }
198 198
 
199
-	public function readConfiguration() {
200
-		if(!$this->configRead && !is_null($this->configPrefix)) {
201
-			$cta = array_flip($this->getConfigTranslationArray());
202
-			foreach($this->config as $key => $val) {
203
-				if(!isset($cta[$key])) {
204
-					//some are determined
205
-					continue;
206
-				}
207
-				$dbKey = $cta[$key];
208
-				switch($key) {
209
-					case 'ldapBase':
210
-					case 'ldapBaseUsers':
211
-					case 'ldapBaseGroups':
212
-					case 'ldapAttributesForUserSearch':
213
-					case 'ldapAttributesForGroupSearch':
214
-					case 'ldapUserFilterObjectclass':
215
-					case 'ldapUserFilterGroups':
216
-					case 'ldapGroupFilterObjectclass':
217
-					case 'ldapGroupFilterGroups':
218
-					case 'ldapLoginFilterAttributes':
219
-						$readMethod = 'getMultiLine';
220
-						break;
221
-					case 'ldapIgnoreNamingRules':
222
-						$readMethod = 'getSystemValue';
223
-						$dbKey = $key;
224
-						break;
225
-					case 'ldapAgentPassword':
226
-						$readMethod = 'getPwd';
227
-						break;
228
-					case 'ldapUserDisplayName2':
229
-					case 'ldapGroupDisplayName':
230
-						$readMethod = 'getLcValue';
231
-						break;
232
-					case 'ldapUserDisplayName':
233
-					default:
234
-						// user display name does not lower case because
235
-						// we rely on an upper case N as indicator whether to
236
-						// auto-detect it or not. FIXME
237
-						$readMethod = 'getValue';
238
-						break;
239
-				}
240
-				$this->config[$key] = $this->$readMethod($dbKey);
241
-			}
242
-			$this->configRead = true;
243
-		}
244
-	}
199
+    public function readConfiguration() {
200
+        if(!$this->configRead && !is_null($this->configPrefix)) {
201
+            $cta = array_flip($this->getConfigTranslationArray());
202
+            foreach($this->config as $key => $val) {
203
+                if(!isset($cta[$key])) {
204
+                    //some are determined
205
+                    continue;
206
+                }
207
+                $dbKey = $cta[$key];
208
+                switch($key) {
209
+                    case 'ldapBase':
210
+                    case 'ldapBaseUsers':
211
+                    case 'ldapBaseGroups':
212
+                    case 'ldapAttributesForUserSearch':
213
+                    case 'ldapAttributesForGroupSearch':
214
+                    case 'ldapUserFilterObjectclass':
215
+                    case 'ldapUserFilterGroups':
216
+                    case 'ldapGroupFilterObjectclass':
217
+                    case 'ldapGroupFilterGroups':
218
+                    case 'ldapLoginFilterAttributes':
219
+                        $readMethod = 'getMultiLine';
220
+                        break;
221
+                    case 'ldapIgnoreNamingRules':
222
+                        $readMethod = 'getSystemValue';
223
+                        $dbKey = $key;
224
+                        break;
225
+                    case 'ldapAgentPassword':
226
+                        $readMethod = 'getPwd';
227
+                        break;
228
+                    case 'ldapUserDisplayName2':
229
+                    case 'ldapGroupDisplayName':
230
+                        $readMethod = 'getLcValue';
231
+                        break;
232
+                    case 'ldapUserDisplayName':
233
+                    default:
234
+                        // user display name does not lower case because
235
+                        // we rely on an upper case N as indicator whether to
236
+                        // auto-detect it or not. FIXME
237
+                        $readMethod = 'getValue';
238
+                        break;
239
+                }
240
+                $this->config[$key] = $this->$readMethod($dbKey);
241
+            }
242
+            $this->configRead = true;
243
+        }
244
+    }
245 245
 
246
-	/**
247
-	 * saves the current config changes in the database
248
-	 */
249
-	public function saveConfiguration() {
250
-		$cta = array_flip($this->getConfigTranslationArray());
251
-		foreach($this->unsavedChanges as $key) {
252
-			$value = $this->config[$key];
253
-			switch ($key) {
254
-				case 'ldapAgentPassword':
255
-					$value = base64_encode($value);
256
-					break;
257
-				case 'ldapBase':
258
-				case 'ldapBaseUsers':
259
-				case 'ldapBaseGroups':
260
-				case 'ldapAttributesForUserSearch':
261
-				case 'ldapAttributesForGroupSearch':
262
-				case 'ldapUserFilterObjectclass':
263
-				case 'ldapUserFilterGroups':
264
-				case 'ldapGroupFilterObjectclass':
265
-				case 'ldapGroupFilterGroups':
266
-				case 'ldapLoginFilterAttributes':
267
-					if(is_array($value)) {
268
-						$value = implode("\n", $value);
269
-					}
270
-					break;
271
-				//following options are not stored but detected, skip them
272
-				case 'ldapIgnoreNamingRules':
273
-				case 'hasPagedResultSupport':
274
-				case 'ldapUuidUserAttribute':
275
-				case 'ldapUuidGroupAttribute':
276
-					continue 2;
277
-			}
278
-			if(is_null($value)) {
279
-				$value = '';
280
-			}
281
-			$this->saveValue($cta[$key], $value);
282
-		}
283
-		$this->unsavedChanges = [];
284
-	}
246
+    /**
247
+     * saves the current config changes in the database
248
+     */
249
+    public function saveConfiguration() {
250
+        $cta = array_flip($this->getConfigTranslationArray());
251
+        foreach($this->unsavedChanges as $key) {
252
+            $value = $this->config[$key];
253
+            switch ($key) {
254
+                case 'ldapAgentPassword':
255
+                    $value = base64_encode($value);
256
+                    break;
257
+                case 'ldapBase':
258
+                case 'ldapBaseUsers':
259
+                case 'ldapBaseGroups':
260
+                case 'ldapAttributesForUserSearch':
261
+                case 'ldapAttributesForGroupSearch':
262
+                case 'ldapUserFilterObjectclass':
263
+                case 'ldapUserFilterGroups':
264
+                case 'ldapGroupFilterObjectclass':
265
+                case 'ldapGroupFilterGroups':
266
+                case 'ldapLoginFilterAttributes':
267
+                    if(is_array($value)) {
268
+                        $value = implode("\n", $value);
269
+                    }
270
+                    break;
271
+                //following options are not stored but detected, skip them
272
+                case 'ldapIgnoreNamingRules':
273
+                case 'hasPagedResultSupport':
274
+                case 'ldapUuidUserAttribute':
275
+                case 'ldapUuidGroupAttribute':
276
+                    continue 2;
277
+            }
278
+            if(is_null($value)) {
279
+                $value = '';
280
+            }
281
+            $this->saveValue($cta[$key], $value);
282
+        }
283
+        $this->unsavedChanges = [];
284
+    }
285 285
 
286
-	/**
287
-	 * @param string $varName
288
-	 * @return array|string
289
-	 */
290
-	protected function getMultiLine($varName) {
291
-		$value = $this->getValue($varName);
292
-		if(empty($value)) {
293
-			$value = '';
294
-		} else {
295
-			$value = preg_split('/\r\n|\r|\n/', $value);
296
-		}
286
+    /**
287
+     * @param string $varName
288
+     * @return array|string
289
+     */
290
+    protected function getMultiLine($varName) {
291
+        $value = $this->getValue($varName);
292
+        if(empty($value)) {
293
+            $value = '';
294
+        } else {
295
+            $value = preg_split('/\r\n|\r|\n/', $value);
296
+        }
297 297
 
298
-		return $value;
299
-	}
298
+        return $value;
299
+    }
300 300
 
301
-	/**
302
-	 * Sets multi-line values as arrays
303
-	 * 
304
-	 * @param string $varName name of config-key
305
-	 * @param array|string $value to set
306
-	 */
307
-	protected function setMultiLine($varName, $value) {
308
-		if(empty($value)) {
309
-			$value = '';
310
-		} else if (!is_array($value)) {
311
-			$value = preg_split('/\r\n|\r|\n|;/', $value);
312
-			if($value === false) {
313
-				$value = '';
314
-			}
315
-		}
301
+    /**
302
+     * Sets multi-line values as arrays
303
+     * 
304
+     * @param string $varName name of config-key
305
+     * @param array|string $value to set
306
+     */
307
+    protected function setMultiLine($varName, $value) {
308
+        if(empty($value)) {
309
+            $value = '';
310
+        } else if (!is_array($value)) {
311
+            $value = preg_split('/\r\n|\r|\n|;/', $value);
312
+            if($value === false) {
313
+                $value = '';
314
+            }
315
+        }
316 316
 
317
-		if(!is_array($value)) {
318
-			$finalValue = trim($value);
319
-		} else {
320
-			$finalValue = [];
321
-			foreach($value as $key => $val) {
322
-				if(is_string($val)) {
323
-					$val = trim($val);
324
-					if ($val !== '') {
325
-						//accidental line breaks are not wanted and can cause
326
-						// odd behaviour. Thus, away with them.
327
-						$finalValue[] = $val;
328
-					}
329
-				} else {
330
-					$finalValue[] = $val;
331
-				}
332
-			}
333
-		}
317
+        if(!is_array($value)) {
318
+            $finalValue = trim($value);
319
+        } else {
320
+            $finalValue = [];
321
+            foreach($value as $key => $val) {
322
+                if(is_string($val)) {
323
+                    $val = trim($val);
324
+                    if ($val !== '') {
325
+                        //accidental line breaks are not wanted and can cause
326
+                        // odd behaviour. Thus, away with them.
327
+                        $finalValue[] = $val;
328
+                    }
329
+                } else {
330
+                    $finalValue[] = $val;
331
+                }
332
+            }
333
+        }
334 334
 
335
-		$this->setRawValue($varName, $finalValue);
336
-	}
335
+        $this->setRawValue($varName, $finalValue);
336
+    }
337 337
 
338
-	/**
339
-	 * @param string $varName
340
-	 * @return string
341
-	 */
342
-	protected function getPwd($varName) {
343
-		return base64_decode($this->getValue($varName));
344
-	}
338
+    /**
339
+     * @param string $varName
340
+     * @return string
341
+     */
342
+    protected function getPwd($varName) {
343
+        return base64_decode($this->getValue($varName));
344
+    }
345 345
 
346
-	/**
347
-	 * @param string $varName
348
-	 * @return string
349
-	 */
350
-	protected function getLcValue($varName) {
351
-		return mb_strtolower($this->getValue($varName), 'UTF-8');
352
-	}
346
+    /**
347
+     * @param string $varName
348
+     * @return string
349
+     */
350
+    protected function getLcValue($varName) {
351
+        return mb_strtolower($this->getValue($varName), 'UTF-8');
352
+    }
353 353
 
354
-	/**
355
-	 * @param string $varName
356
-	 * @return string
357
-	 */
358
-	protected function getSystemValue($varName) {
359
-		//FIXME: if another system value is added, softcode the default value
360
-		return \OC::$server->getConfig()->getSystemValue($varName, false);
361
-	}
354
+    /**
355
+     * @param string $varName
356
+     * @return string
357
+     */
358
+    protected function getSystemValue($varName) {
359
+        //FIXME: if another system value is added, softcode the default value
360
+        return \OC::$server->getConfig()->getSystemValue($varName, false);
361
+    }
362 362
 
363
-	/**
364
-	 * @param string $varName
365
-	 * @return string
366
-	 */
367
-	protected function getValue($varName) {
368
-		static $defaults;
369
-		if(is_null($defaults)) {
370
-			$defaults = $this->getDefaults();
371
-		}
372
-		return \OCP\Config::getAppValue('user_ldap',
373
-										$this->configPrefix.$varName,
374
-										$defaults[$varName]);
375
-	}
363
+    /**
364
+     * @param string $varName
365
+     * @return string
366
+     */
367
+    protected function getValue($varName) {
368
+        static $defaults;
369
+        if(is_null($defaults)) {
370
+            $defaults = $this->getDefaults();
371
+        }
372
+        return \OCP\Config::getAppValue('user_ldap',
373
+                                        $this->configPrefix.$varName,
374
+                                        $defaults[$varName]);
375
+    }
376 376
 
377
-	/**
378
-	 * Sets a scalar value.
379
-	 * 
380
-	 * @param string $varName name of config key
381
-	 * @param mixed $value to set
382
-	 */
383
-	protected function setValue($varName, $value) {
384
-		if(is_string($value)) {
385
-			$value = trim($value);
386
-		}
387
-		$this->config[$varName] = $value;
388
-	}
377
+    /**
378
+     * Sets a scalar value.
379
+     * 
380
+     * @param string $varName name of config key
381
+     * @param mixed $value to set
382
+     */
383
+    protected function setValue($varName, $value) {
384
+        if(is_string($value)) {
385
+            $value = trim($value);
386
+        }
387
+        $this->config[$varName] = $value;
388
+    }
389 389
 
390
-	/**
391
-	 * Sets a scalar value without trimming.
392
-	 *
393
-	 * @param string $varName name of config key
394
-	 * @param mixed $value to set
395
-	 */
396
-	protected function setRawValue($varName, $value) {
397
-		$this->config[$varName] = $value;
398
-	}
390
+    /**
391
+     * Sets a scalar value without trimming.
392
+     *
393
+     * @param string $varName name of config key
394
+     * @param mixed $value to set
395
+     */
396
+    protected function setRawValue($varName, $value) {
397
+        $this->config[$varName] = $value;
398
+    }
399 399
 
400
-	/**
401
-	 * @param string $varName
402
-	 * @param string $value
403
-	 * @return bool
404
-	 */
405
-	protected function saveValue($varName, $value) {
406
-		\OC::$server->getConfig()->setAppValue(
407
-			'user_ldap',
408
-			$this->configPrefix.$varName,
409
-			$value
410
-		);
411
-		return true;
412
-	}
400
+    /**
401
+     * @param string $varName
402
+     * @param string $value
403
+     * @return bool
404
+     */
405
+    protected function saveValue($varName, $value) {
406
+        \OC::$server->getConfig()->setAppValue(
407
+            'user_ldap',
408
+            $this->configPrefix.$varName,
409
+            $value
410
+        );
411
+        return true;
412
+    }
413 413
 
414
-	/**
415
-	 * @return array an associative array with the default values. Keys are correspond
416
-	 * to config-value entries in the database table
417
-	 */
418
-	public function getDefaults() {
419
-		return array(
420
-			'ldap_host'                         => '',
421
-			'ldap_port'                         => '',
422
-			'ldap_backup_host'                  => '',
423
-			'ldap_backup_port'                  => '',
424
-			'ldap_override_main_server'         => '',
425
-			'ldap_dn'                           => '',
426
-			'ldap_agent_password'               => '',
427
-			'ldap_base'                         => '',
428
-			'ldap_base_users'                   => '',
429
-			'ldap_base_groups'                  => '',
430
-			'ldap_userlist_filter'              => '',
431
-			'ldap_user_filter_mode'             => 0,
432
-			'ldap_userfilter_objectclass'       => '',
433
-			'ldap_userfilter_groups'            => '',
434
-			'ldap_login_filter'                 => '',
435
-			'ldap_login_filter_mode'            => 0,
436
-			'ldap_loginfilter_email'            => 0,
437
-			'ldap_loginfilter_username'         => 1,
438
-			'ldap_loginfilter_attributes'       => '',
439
-			'ldap_group_filter'                 => '',
440
-			'ldap_group_filter_mode'            => 0,
441
-			'ldap_groupfilter_objectclass'      => '',
442
-			'ldap_groupfilter_groups'           => '',
443
-			'ldap_gid_number'                   => 'gidNumber',
444
-			'ldap_display_name'                 => 'displayName',
445
-			'ldap_user_display_name_2'			=> '',
446
-			'ldap_group_display_name'           => 'cn',
447
-			'ldap_tls'                          => 0,
448
-			'ldap_quota_def'                    => '',
449
-			'ldap_quota_attr'                   => '',
450
-			'ldap_email_attr'                   => '',
451
-			'ldap_group_member_assoc_attribute' => 'uniqueMember',
452
-			'ldap_cache_ttl'                    => 600,
453
-			'ldap_uuid_user_attribute'          => 'auto',
454
-			'ldap_uuid_group_attribute'         => 'auto',
455
-			'home_folder_naming_rule'           => '',
456
-			'ldap_turn_off_cert_check'          => 0,
457
-			'ldap_configuration_active'         => 0,
458
-			'ldap_attributes_for_user_search'   => '',
459
-			'ldap_attributes_for_group_search'  => '',
460
-			'ldap_expert_username_attr'         => '',
461
-			'ldap_expert_uuid_user_attr'        => '',
462
-			'ldap_expert_uuid_group_attr'       => '',
463
-			'has_memberof_filter_support'       => 0,
464
-			'use_memberof_to_detect_membership' => 1,
465
-			'last_jpegPhoto_lookup'             => 0,
466
-			'ldap_nested_groups'                => 0,
467
-			'ldap_paging_size'                  => 500,
468
-			'ldap_turn_on_pwd_change'           => 0,
469
-			'ldap_experienced_admin'            => 0,
470
-			'ldap_dynamic_group_member_url'     => '',
471
-			'ldap_default_ppolicy_dn'           => '',
472
-		);
473
-	}
414
+    /**
415
+     * @return array an associative array with the default values. Keys are correspond
416
+     * to config-value entries in the database table
417
+     */
418
+    public function getDefaults() {
419
+        return array(
420
+            'ldap_host'                         => '',
421
+            'ldap_port'                         => '',
422
+            'ldap_backup_host'                  => '',
423
+            'ldap_backup_port'                  => '',
424
+            'ldap_override_main_server'         => '',
425
+            'ldap_dn'                           => '',
426
+            'ldap_agent_password'               => '',
427
+            'ldap_base'                         => '',
428
+            'ldap_base_users'                   => '',
429
+            'ldap_base_groups'                  => '',
430
+            'ldap_userlist_filter'              => '',
431
+            'ldap_user_filter_mode'             => 0,
432
+            'ldap_userfilter_objectclass'       => '',
433
+            'ldap_userfilter_groups'            => '',
434
+            'ldap_login_filter'                 => '',
435
+            'ldap_login_filter_mode'            => 0,
436
+            'ldap_loginfilter_email'            => 0,
437
+            'ldap_loginfilter_username'         => 1,
438
+            'ldap_loginfilter_attributes'       => '',
439
+            'ldap_group_filter'                 => '',
440
+            'ldap_group_filter_mode'            => 0,
441
+            'ldap_groupfilter_objectclass'      => '',
442
+            'ldap_groupfilter_groups'           => '',
443
+            'ldap_gid_number'                   => 'gidNumber',
444
+            'ldap_display_name'                 => 'displayName',
445
+            'ldap_user_display_name_2'			=> '',
446
+            'ldap_group_display_name'           => 'cn',
447
+            'ldap_tls'                          => 0,
448
+            'ldap_quota_def'                    => '',
449
+            'ldap_quota_attr'                   => '',
450
+            'ldap_email_attr'                   => '',
451
+            'ldap_group_member_assoc_attribute' => 'uniqueMember',
452
+            'ldap_cache_ttl'                    => 600,
453
+            'ldap_uuid_user_attribute'          => 'auto',
454
+            'ldap_uuid_group_attribute'         => 'auto',
455
+            'home_folder_naming_rule'           => '',
456
+            'ldap_turn_off_cert_check'          => 0,
457
+            'ldap_configuration_active'         => 0,
458
+            'ldap_attributes_for_user_search'   => '',
459
+            'ldap_attributes_for_group_search'  => '',
460
+            'ldap_expert_username_attr'         => '',
461
+            'ldap_expert_uuid_user_attr'        => '',
462
+            'ldap_expert_uuid_group_attr'       => '',
463
+            'has_memberof_filter_support'       => 0,
464
+            'use_memberof_to_detect_membership' => 1,
465
+            'last_jpegPhoto_lookup'             => 0,
466
+            'ldap_nested_groups'                => 0,
467
+            'ldap_paging_size'                  => 500,
468
+            'ldap_turn_on_pwd_change'           => 0,
469
+            'ldap_experienced_admin'            => 0,
470
+            'ldap_dynamic_group_member_url'     => '',
471
+            'ldap_default_ppolicy_dn'           => '',
472
+        );
473
+    }
474 474
 
475
-	/**
476
-	 * @return array that maps internal variable names to database fields
477
-	 */
478
-	public function getConfigTranslationArray() {
479
-		//TODO: merge them into one representation
480
-		static $array = array(
481
-			'ldap_host'                         => 'ldapHost',
482
-			'ldap_port'                         => 'ldapPort',
483
-			'ldap_backup_host'                  => 'ldapBackupHost',
484
-			'ldap_backup_port'                  => 'ldapBackupPort',
485
-			'ldap_override_main_server'         => 'ldapOverrideMainServer',
486
-			'ldap_dn'                           => 'ldapAgentName',
487
-			'ldap_agent_password'               => 'ldapAgentPassword',
488
-			'ldap_base'                         => 'ldapBase',
489
-			'ldap_base_users'                   => 'ldapBaseUsers',
490
-			'ldap_base_groups'                  => 'ldapBaseGroups',
491
-			'ldap_userfilter_objectclass'       => 'ldapUserFilterObjectclass',
492
-			'ldap_userfilter_groups'            => 'ldapUserFilterGroups',
493
-			'ldap_userlist_filter'              => 'ldapUserFilter',
494
-			'ldap_user_filter_mode'             => 'ldapUserFilterMode',
495
-			'ldap_login_filter'                 => 'ldapLoginFilter',
496
-			'ldap_login_filter_mode'            => 'ldapLoginFilterMode',
497
-			'ldap_loginfilter_email'            => 'ldapLoginFilterEmail',
498
-			'ldap_loginfilter_username'         => 'ldapLoginFilterUsername',
499
-			'ldap_loginfilter_attributes'       => 'ldapLoginFilterAttributes',
500
-			'ldap_group_filter'                 => 'ldapGroupFilter',
501
-			'ldap_group_filter_mode'            => 'ldapGroupFilterMode',
502
-			'ldap_groupfilter_objectclass'      => 'ldapGroupFilterObjectclass',
503
-			'ldap_groupfilter_groups'           => 'ldapGroupFilterGroups',
504
-			'ldap_gid_number'                   => 'ldapGidNumber',
505
-			'ldap_display_name'                 => 'ldapUserDisplayName',
506
-			'ldap_user_display_name_2'			=> 'ldapUserDisplayName2',
507
-			'ldap_group_display_name'           => 'ldapGroupDisplayName',
508
-			'ldap_tls'                          => 'ldapTLS',
509
-			'ldap_quota_def'                    => 'ldapQuotaDefault',
510
-			'ldap_quota_attr'                   => 'ldapQuotaAttribute',
511
-			'ldap_email_attr'                   => 'ldapEmailAttribute',
512
-			'ldap_group_member_assoc_attribute' => 'ldapGroupMemberAssocAttr',
513
-			'ldap_cache_ttl'                    => 'ldapCacheTTL',
514
-			'home_folder_naming_rule'           => 'homeFolderNamingRule',
515
-			'ldap_turn_off_cert_check'          => 'turnOffCertCheck',
516
-			'ldap_configuration_active'         => 'ldapConfigurationActive',
517
-			'ldap_attributes_for_user_search'   => 'ldapAttributesForUserSearch',
518
-			'ldap_attributes_for_group_search'  => 'ldapAttributesForGroupSearch',
519
-			'ldap_expert_username_attr'         => 'ldapExpertUsernameAttr',
520
-			'ldap_expert_uuid_user_attr'        => 'ldapExpertUUIDUserAttr',
521
-			'ldap_expert_uuid_group_attr'       => 'ldapExpertUUIDGroupAttr',
522
-			'has_memberof_filter_support'       => 'hasMemberOfFilterSupport',
523
-			'use_memberof_to_detect_membership' => 'useMemberOfToDetectMembership',
524
-			'last_jpegPhoto_lookup'             => 'lastJpegPhotoLookup',
525
-			'ldap_nested_groups'                => 'ldapNestedGroups',
526
-			'ldap_paging_size'                  => 'ldapPagingSize',
527
-			'ldap_turn_on_pwd_change'           => 'turnOnPasswordChange',
528
-			'ldap_experienced_admin'            => 'ldapExperiencedAdmin',
529
-			'ldap_dynamic_group_member_url'     => 'ldapDynamicGroupMemberURL',
530
-			'ldap_default_ppolicy_dn'           => 'ldapDefaultPPolicyDN',
531
-		);
532
-		return $array;
533
-	}
475
+    /**
476
+     * @return array that maps internal variable names to database fields
477
+     */
478
+    public function getConfigTranslationArray() {
479
+        //TODO: merge them into one representation
480
+        static $array = array(
481
+            'ldap_host'                         => 'ldapHost',
482
+            'ldap_port'                         => 'ldapPort',
483
+            'ldap_backup_host'                  => 'ldapBackupHost',
484
+            'ldap_backup_port'                  => 'ldapBackupPort',
485
+            'ldap_override_main_server'         => 'ldapOverrideMainServer',
486
+            'ldap_dn'                           => 'ldapAgentName',
487
+            'ldap_agent_password'               => 'ldapAgentPassword',
488
+            'ldap_base'                         => 'ldapBase',
489
+            'ldap_base_users'                   => 'ldapBaseUsers',
490
+            'ldap_base_groups'                  => 'ldapBaseGroups',
491
+            'ldap_userfilter_objectclass'       => 'ldapUserFilterObjectclass',
492
+            'ldap_userfilter_groups'            => 'ldapUserFilterGroups',
493
+            'ldap_userlist_filter'              => 'ldapUserFilter',
494
+            'ldap_user_filter_mode'             => 'ldapUserFilterMode',
495
+            'ldap_login_filter'                 => 'ldapLoginFilter',
496
+            'ldap_login_filter_mode'            => 'ldapLoginFilterMode',
497
+            'ldap_loginfilter_email'            => 'ldapLoginFilterEmail',
498
+            'ldap_loginfilter_username'         => 'ldapLoginFilterUsername',
499
+            'ldap_loginfilter_attributes'       => 'ldapLoginFilterAttributes',
500
+            'ldap_group_filter'                 => 'ldapGroupFilter',
501
+            'ldap_group_filter_mode'            => 'ldapGroupFilterMode',
502
+            'ldap_groupfilter_objectclass'      => 'ldapGroupFilterObjectclass',
503
+            'ldap_groupfilter_groups'           => 'ldapGroupFilterGroups',
504
+            'ldap_gid_number'                   => 'ldapGidNumber',
505
+            'ldap_display_name'                 => 'ldapUserDisplayName',
506
+            'ldap_user_display_name_2'			=> 'ldapUserDisplayName2',
507
+            'ldap_group_display_name'           => 'ldapGroupDisplayName',
508
+            'ldap_tls'                          => 'ldapTLS',
509
+            'ldap_quota_def'                    => 'ldapQuotaDefault',
510
+            'ldap_quota_attr'                   => 'ldapQuotaAttribute',
511
+            'ldap_email_attr'                   => 'ldapEmailAttribute',
512
+            'ldap_group_member_assoc_attribute' => 'ldapGroupMemberAssocAttr',
513
+            'ldap_cache_ttl'                    => 'ldapCacheTTL',
514
+            'home_folder_naming_rule'           => 'homeFolderNamingRule',
515
+            'ldap_turn_off_cert_check'          => 'turnOffCertCheck',
516
+            'ldap_configuration_active'         => 'ldapConfigurationActive',
517
+            'ldap_attributes_for_user_search'   => 'ldapAttributesForUserSearch',
518
+            'ldap_attributes_for_group_search'  => 'ldapAttributesForGroupSearch',
519
+            'ldap_expert_username_attr'         => 'ldapExpertUsernameAttr',
520
+            'ldap_expert_uuid_user_attr'        => 'ldapExpertUUIDUserAttr',
521
+            'ldap_expert_uuid_group_attr'       => 'ldapExpertUUIDGroupAttr',
522
+            'has_memberof_filter_support'       => 'hasMemberOfFilterSupport',
523
+            'use_memberof_to_detect_membership' => 'useMemberOfToDetectMembership',
524
+            'last_jpegPhoto_lookup'             => 'lastJpegPhotoLookup',
525
+            'ldap_nested_groups'                => 'ldapNestedGroups',
526
+            'ldap_paging_size'                  => 'ldapPagingSize',
527
+            'ldap_turn_on_pwd_change'           => 'turnOnPasswordChange',
528
+            'ldap_experienced_admin'            => 'ldapExperiencedAdmin',
529
+            'ldap_dynamic_group_member_url'     => 'ldapDynamicGroupMemberURL',
530
+            'ldap_default_ppolicy_dn'           => 'ldapDefaultPPolicyDN',
531
+        );
532
+        return $array;
533
+    }
534 534
 
535 535
 }
Please login to merge, or discard this patch.
lib/private/Files/Config/UserMountCache.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,6 @@
 block discarded – undo
24 24
 
25 25
 namespace OC\Files\Config;
26 26
 
27
-use OC\DB\QueryBuilder\Literal;
28 27
 use OCA\Files_Sharing\SharedMount;
29 28
 use OCP\DB\QueryBuilder\IQueryBuilder;
30 29
 use OCP\Files\Config\ICachedMountFileInfo;
Please login to merge, or discard this patch.
Indentation   +346 added lines, -346 removed lines patch added patch discarded remove patch
@@ -44,350 +44,350 @@
 block discarded – undo
44 44
  * Cache mounts points per user in the cache so we can easilly look them up
45 45
  */
46 46
 class UserMountCache implements IUserMountCache {
47
-	/**
48
-	 * @var IDBConnection
49
-	 */
50
-	private $connection;
51
-
52
-	/**
53
-	 * @var IUserManager
54
-	 */
55
-	private $userManager;
56
-
57
-	/**
58
-	 * Cached mount info.
59
-	 * Map of $userId to ICachedMountInfo.
60
-	 *
61
-	 * @var ICache
62
-	 **/
63
-	private $mountsForUsers;
64
-
65
-	/**
66
-	 * @var ILogger
67
-	 */
68
-	private $logger;
69
-
70
-	/**
71
-	 * @var ICache
72
-	 */
73
-	private $cacheInfoCache;
74
-
75
-	/**
76
-	 * UserMountCache constructor.
77
-	 *
78
-	 * @param IDBConnection $connection
79
-	 * @param IUserManager $userManager
80
-	 * @param ILogger $logger
81
-	 */
82
-	public function __construct(IDBConnection $connection, IUserManager $userManager, ILogger $logger) {
83
-		$this->connection = $connection;
84
-		$this->userManager = $userManager;
85
-		$this->logger = $logger;
86
-		$this->cacheInfoCache = new CappedMemoryCache();
87
-		$this->mountsForUsers = new CappedMemoryCache();
88
-	}
89
-
90
-	public function registerMounts(IUser $user, array $mounts) {
91
-		// filter out non-proper storages coming from unit tests
92
-		$mounts = array_filter($mounts, function (IMountPoint $mount) {
93
-			return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache();
94
-		});
95
-		/** @var ICachedMountInfo[] $newMounts */
96
-		$newMounts = array_map(function (IMountPoint $mount) use ($user) {
97
-			// filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)
98
-			if ($mount->getStorageRootId() === -1) {
99
-				return null;
100
-			} else {
101
-				return new LazyStorageMountInfo($user, $mount);
102
-			}
103
-		}, $mounts);
104
-		$newMounts = array_values(array_filter($newMounts));
105
-
106
-		$cachedMounts = $this->getMountsForUser($user);
107
-		$mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
108
-			// since we are only looking for mounts for a specific user comparing on root id is enough
109
-			return $mount1->getRootId() - $mount2->getRootId();
110
-		};
111
-
112
-		/** @var ICachedMountInfo[] $addedMounts */
113
-		$addedMounts = array_udiff($newMounts, $cachedMounts, $mountDiff);
114
-		/** @var ICachedMountInfo[] $removedMounts */
115
-		$removedMounts = array_udiff($cachedMounts, $newMounts, $mountDiff);
116
-
117
-		$changedMounts = $this->findChangedMounts($newMounts, $cachedMounts);
118
-
119
-		foreach ($addedMounts as $mount) {
120
-			$this->addToCache($mount);
121
-			$this->mountsForUsers[$user->getUID()][] = $mount;
122
-		}
123
-		foreach ($removedMounts as $mount) {
124
-			$this->removeFromCache($mount);
125
-			$index = array_search($mount, $this->mountsForUsers[$user->getUID()]);
126
-			unset($this->mountsForUsers[$user->getUID()][$index]);
127
-		}
128
-		foreach ($changedMounts as $mount) {
129
-			$this->updateCachedMount($mount);
130
-		}
131
-	}
132
-
133
-	/**
134
-	 * @param ICachedMountInfo[] $newMounts
135
-	 * @param ICachedMountInfo[] $cachedMounts
136
-	 * @return ICachedMountInfo[]
137
-	 */
138
-	private function findChangedMounts(array $newMounts, array $cachedMounts) {
139
-		$changed = [];
140
-		foreach ($newMounts as $newMount) {
141
-			foreach ($cachedMounts as $cachedMount) {
142
-				if (
143
-					$newMount->getRootId() === $cachedMount->getRootId() &&
144
-					(
145
-						$newMount->getMountPoint() !== $cachedMount->getMountPoint() ||
146
-						$newMount->getStorageId() !== $cachedMount->getStorageId() ||
147
-						$newMount->getMountId() !== $cachedMount->getMountId()
148
-					)
149
-				) {
150
-					$changed[] = $newMount;
151
-				}
152
-			}
153
-		}
154
-		return $changed;
155
-	}
156
-
157
-	private function addToCache(ICachedMountInfo $mount) {
158
-		if ($mount->getStorageId() !== -1) {
159
-			$this->connection->insertIfNotExist('*PREFIX*mounts', [
160
-				'storage_id' => $mount->getStorageId(),
161
-				'root_id' => $mount->getRootId(),
162
-				'user_id' => $mount->getUser()->getUID(),
163
-				'mount_point' => $mount->getMountPoint(),
164
-				'mount_id' => $mount->getMountId()
165
-			], ['root_id', 'user_id']);
166
-		} else {
167
-			// in some cases this is legitimate, like orphaned shares
168
-			$this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
169
-		}
170
-	}
171
-
172
-	private function updateCachedMount(ICachedMountInfo $mount) {
173
-		$builder = $this->connection->getQueryBuilder();
174
-
175
-		$query = $builder->update('mounts')
176
-			->set('storage_id', $builder->createNamedParameter($mount->getStorageId()))
177
-			->set('mount_point', $builder->createNamedParameter($mount->getMountPoint()))
178
-			->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT))
179
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
180
-			->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
181
-
182
-		$query->execute();
183
-	}
184
-
185
-	private function removeFromCache(ICachedMountInfo $mount) {
186
-		$builder = $this->connection->getQueryBuilder();
187
-
188
-		$query = $builder->delete('mounts')
189
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
190
-			->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
191
-		$query->execute();
192
-	}
193
-
194
-	private function dbRowToMountInfo(array $row) {
195
-		$user = $this->userManager->get($row['user_id']);
196
-		if (is_null($user)) {
197
-			return null;
198
-		}
199
-		$mount_id = $row['mount_id'];
200
-		if (!is_null($mount_id)) {
201
-			$mount_id = (int) $mount_id;
202
-		}
203
-		return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $mount_id, isset($row['path']) ? $row['path'] : '');
204
-	}
205
-
206
-	/**
207
-	 * @param IUser $user
208
-	 * @return ICachedMountInfo[]
209
-	 */
210
-	public function getMountsForUser(IUser $user) {
211
-		if (!isset($this->mountsForUsers[$user->getUID()])) {
212
-			$builder = $this->connection->getQueryBuilder();
213
-			$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
214
-				->from('mounts', 'm')
215
-				->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
216
-				->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID())));
217
-
218
-			$rows = $query->execute()->fetchAll();
219
-
220
-			$this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
221
-		}
222
-		return $this->mountsForUsers[$user->getUID()];
223
-	}
224
-
225
-	/**
226
-	 * @param int $numericStorageId
227
-	 * @param string|null $user limit the results to a single user
228
-	 * @return CachedMountInfo[]
229
-	 */
230
-	public function getMountsForStorageId($numericStorageId, $user = null) {
231
-		$builder = $this->connection->getQueryBuilder();
232
-		$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
233
-			->from('mounts', 'm')
234
-			->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
235
-			->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT)));
236
-
237
-		if ($user) {
238
-			$query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user)));
239
-		}
240
-
241
-		$rows = $query->execute()->fetchAll();
242
-
243
-		return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
244
-	}
245
-
246
-	/**
247
-	 * @param int $rootFileId
248
-	 * @return CachedMountInfo[]
249
-	 */
250
-	public function getMountsForRootId($rootFileId) {
251
-		$builder = $this->connection->getQueryBuilder();
252
-		$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
253
-			->from('mounts', 'm')
254
-			->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
255
-			->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT)));
256
-
257
-		$rows = $query->execute()->fetchAll();
258
-
259
-		return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
260
-	}
261
-
262
-	/**
263
-	 * @param $fileId
264
-	 * @return array
265
-	 * @throws \OCP\Files\NotFoundException
266
-	 */
267
-	private function getCacheInfoFromFileId($fileId) {
268
-		if (!isset($this->cacheInfoCache[$fileId])) {
269
-			$builder = $this->connection->getQueryBuilder();
270
-			$query = $builder->select('storage', 'path', 'mimetype')
271
-				->from('filecache')
272
-				->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
273
-
274
-			$row = $query->execute()->fetch();
275
-			if (is_array($row)) {
276
-				$this->cacheInfoCache[$fileId] = [
277
-					(int)$row['storage'],
278
-					$row['path'],
279
-					(int)$row['mimetype']
280
-				];
281
-			} else {
282
-				throw new NotFoundException('File with id "' . $fileId . '" not found');
283
-			}
284
-		}
285
-		return $this->cacheInfoCache[$fileId];
286
-	}
287
-
288
-	/**
289
-	 * @param int $fileId
290
-	 * @param string|null $user optionally restrict the results to a single user
291
-	 * @return ICachedMountFileInfo[]
292
-	 * @since 9.0.0
293
-	 */
294
-	public function getMountsForFileId($fileId, $user = null) {
295
-		try {
296
-			list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId);
297
-		} catch (NotFoundException $e) {
298
-			return [];
299
-		}
300
-		$mountsForStorage = $this->getMountsForStorageId($storageId, $user);
301
-
302
-		// filter mounts that are from the same storage but a different directory
303
-		$filteredMounts = array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
304
-			if ($fileId === $mount->getRootId()) {
305
-				return true;
306
-			}
307
-			$internalMountPath = $mount->getRootInternalPath();
308
-
309
-			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
310
-		});
311
-
312
-		return array_map(function (ICachedMountInfo $mount) use ($internalPath) {
313
-			return new CachedMountFileInfo(
314
-				$mount->getUser(),
315
-				$mount->getStorageId(),
316
-				$mount->getRootId(),
317
-				$mount->getMountPoint(),
318
-				$mount->getMountId(),
319
-				$mount->getRootInternalPath(),
320
-				$internalPath
321
-			);
322
-		}, $filteredMounts);
323
-	}
324
-
325
-	/**
326
-	 * Remove all cached mounts for a user
327
-	 *
328
-	 * @param IUser $user
329
-	 */
330
-	public function removeUserMounts(IUser $user) {
331
-		$builder = $this->connection->getQueryBuilder();
332
-
333
-		$query = $builder->delete('mounts')
334
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID())));
335
-		$query->execute();
336
-	}
337
-
338
-	public function removeUserStorageMount($storageId, $userId) {
339
-		$builder = $this->connection->getQueryBuilder();
340
-
341
-		$query = $builder->delete('mounts')
342
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId)))
343
-			->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
344
-		$query->execute();
345
-	}
346
-
347
-	public function remoteStorageMounts($storageId) {
348
-		$builder = $this->connection->getQueryBuilder();
349
-
350
-		$query = $builder->delete('mounts')
351
-			->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
352
-		$query->execute();
353
-	}
354
-
355
-	/**
356
-	 * @param array $users
357
-	 * @return array
358
-	 * @suppress SqlInjectionChecker
359
-	 */
360
-	public function getUsedSpaceForUsers(array $users) {
361
-		$builder = $this->connection->getQueryBuilder();
362
-
363
-		$slash = $builder->createNamedParameter('/');
364
-
365
-		$mountPoint = $builder->func()->concat(
366
-			$builder->func()->concat($slash, 'user_id'),
367
-			$slash
368
-		);
369
-
370
-		$userIds = array_map(function (IUser $user) {
371
-			return $user->getUID();
372
-		}, $users);
373
-
374
-		$query = $builder->select('m.user_id', 'f.size')
375
-			->from('mounts', 'm')
376
-			->innerJoin('m', 'filecache', 'f',
377
-				$builder->expr()->andX(
378
-					$builder->expr()->eq('m.storage_id', 'f.storage'),
379
-					$builder->expr()->eq('f.path', $builder->createNamedParameter('files'))
380
-				))
381
-			->where($builder->expr()->eq('m.mount_point', $mountPoint))
382
-			->andWhere($builder->expr()->in('m.user_id', $builder->createNamedParameter($userIds, IQueryBuilder::PARAM_STR_ARRAY)));
383
-
384
-		$result = $query->execute();
385
-
386
-		$results = [];
387
-		while ($row = $result->fetch()) {
388
-			$results[$row['user_id']] = $row['size'];
389
-		}
390
-		$result->closeCursor();
391
-		return $results;
392
-	}
47
+    /**
48
+     * @var IDBConnection
49
+     */
50
+    private $connection;
51
+
52
+    /**
53
+     * @var IUserManager
54
+     */
55
+    private $userManager;
56
+
57
+    /**
58
+     * Cached mount info.
59
+     * Map of $userId to ICachedMountInfo.
60
+     *
61
+     * @var ICache
62
+     **/
63
+    private $mountsForUsers;
64
+
65
+    /**
66
+     * @var ILogger
67
+     */
68
+    private $logger;
69
+
70
+    /**
71
+     * @var ICache
72
+     */
73
+    private $cacheInfoCache;
74
+
75
+    /**
76
+     * UserMountCache constructor.
77
+     *
78
+     * @param IDBConnection $connection
79
+     * @param IUserManager $userManager
80
+     * @param ILogger $logger
81
+     */
82
+    public function __construct(IDBConnection $connection, IUserManager $userManager, ILogger $logger) {
83
+        $this->connection = $connection;
84
+        $this->userManager = $userManager;
85
+        $this->logger = $logger;
86
+        $this->cacheInfoCache = new CappedMemoryCache();
87
+        $this->mountsForUsers = new CappedMemoryCache();
88
+    }
89
+
90
+    public function registerMounts(IUser $user, array $mounts) {
91
+        // filter out non-proper storages coming from unit tests
92
+        $mounts = array_filter($mounts, function (IMountPoint $mount) {
93
+            return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache();
94
+        });
95
+        /** @var ICachedMountInfo[] $newMounts */
96
+        $newMounts = array_map(function (IMountPoint $mount) use ($user) {
97
+            // filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)
98
+            if ($mount->getStorageRootId() === -1) {
99
+                return null;
100
+            } else {
101
+                return new LazyStorageMountInfo($user, $mount);
102
+            }
103
+        }, $mounts);
104
+        $newMounts = array_values(array_filter($newMounts));
105
+
106
+        $cachedMounts = $this->getMountsForUser($user);
107
+        $mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
108
+            // since we are only looking for mounts for a specific user comparing on root id is enough
109
+            return $mount1->getRootId() - $mount2->getRootId();
110
+        };
111
+
112
+        /** @var ICachedMountInfo[] $addedMounts */
113
+        $addedMounts = array_udiff($newMounts, $cachedMounts, $mountDiff);
114
+        /** @var ICachedMountInfo[] $removedMounts */
115
+        $removedMounts = array_udiff($cachedMounts, $newMounts, $mountDiff);
116
+
117
+        $changedMounts = $this->findChangedMounts($newMounts, $cachedMounts);
118
+
119
+        foreach ($addedMounts as $mount) {
120
+            $this->addToCache($mount);
121
+            $this->mountsForUsers[$user->getUID()][] = $mount;
122
+        }
123
+        foreach ($removedMounts as $mount) {
124
+            $this->removeFromCache($mount);
125
+            $index = array_search($mount, $this->mountsForUsers[$user->getUID()]);
126
+            unset($this->mountsForUsers[$user->getUID()][$index]);
127
+        }
128
+        foreach ($changedMounts as $mount) {
129
+            $this->updateCachedMount($mount);
130
+        }
131
+    }
132
+
133
+    /**
134
+     * @param ICachedMountInfo[] $newMounts
135
+     * @param ICachedMountInfo[] $cachedMounts
136
+     * @return ICachedMountInfo[]
137
+     */
138
+    private function findChangedMounts(array $newMounts, array $cachedMounts) {
139
+        $changed = [];
140
+        foreach ($newMounts as $newMount) {
141
+            foreach ($cachedMounts as $cachedMount) {
142
+                if (
143
+                    $newMount->getRootId() === $cachedMount->getRootId() &&
144
+                    (
145
+                        $newMount->getMountPoint() !== $cachedMount->getMountPoint() ||
146
+                        $newMount->getStorageId() !== $cachedMount->getStorageId() ||
147
+                        $newMount->getMountId() !== $cachedMount->getMountId()
148
+                    )
149
+                ) {
150
+                    $changed[] = $newMount;
151
+                }
152
+            }
153
+        }
154
+        return $changed;
155
+    }
156
+
157
+    private function addToCache(ICachedMountInfo $mount) {
158
+        if ($mount->getStorageId() !== -1) {
159
+            $this->connection->insertIfNotExist('*PREFIX*mounts', [
160
+                'storage_id' => $mount->getStorageId(),
161
+                'root_id' => $mount->getRootId(),
162
+                'user_id' => $mount->getUser()->getUID(),
163
+                'mount_point' => $mount->getMountPoint(),
164
+                'mount_id' => $mount->getMountId()
165
+            ], ['root_id', 'user_id']);
166
+        } else {
167
+            // in some cases this is legitimate, like orphaned shares
168
+            $this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
169
+        }
170
+    }
171
+
172
+    private function updateCachedMount(ICachedMountInfo $mount) {
173
+        $builder = $this->connection->getQueryBuilder();
174
+
175
+        $query = $builder->update('mounts')
176
+            ->set('storage_id', $builder->createNamedParameter($mount->getStorageId()))
177
+            ->set('mount_point', $builder->createNamedParameter($mount->getMountPoint()))
178
+            ->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT))
179
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
180
+            ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
181
+
182
+        $query->execute();
183
+    }
184
+
185
+    private function removeFromCache(ICachedMountInfo $mount) {
186
+        $builder = $this->connection->getQueryBuilder();
187
+
188
+        $query = $builder->delete('mounts')
189
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
190
+            ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
191
+        $query->execute();
192
+    }
193
+
194
+    private function dbRowToMountInfo(array $row) {
195
+        $user = $this->userManager->get($row['user_id']);
196
+        if (is_null($user)) {
197
+            return null;
198
+        }
199
+        $mount_id = $row['mount_id'];
200
+        if (!is_null($mount_id)) {
201
+            $mount_id = (int) $mount_id;
202
+        }
203
+        return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $mount_id, isset($row['path']) ? $row['path'] : '');
204
+    }
205
+
206
+    /**
207
+     * @param IUser $user
208
+     * @return ICachedMountInfo[]
209
+     */
210
+    public function getMountsForUser(IUser $user) {
211
+        if (!isset($this->mountsForUsers[$user->getUID()])) {
212
+            $builder = $this->connection->getQueryBuilder();
213
+            $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
214
+                ->from('mounts', 'm')
215
+                ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
216
+                ->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID())));
217
+
218
+            $rows = $query->execute()->fetchAll();
219
+
220
+            $this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
221
+        }
222
+        return $this->mountsForUsers[$user->getUID()];
223
+    }
224
+
225
+    /**
226
+     * @param int $numericStorageId
227
+     * @param string|null $user limit the results to a single user
228
+     * @return CachedMountInfo[]
229
+     */
230
+    public function getMountsForStorageId($numericStorageId, $user = null) {
231
+        $builder = $this->connection->getQueryBuilder();
232
+        $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
233
+            ->from('mounts', 'm')
234
+            ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
235
+            ->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT)));
236
+
237
+        if ($user) {
238
+            $query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user)));
239
+        }
240
+
241
+        $rows = $query->execute()->fetchAll();
242
+
243
+        return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
244
+    }
245
+
246
+    /**
247
+     * @param int $rootFileId
248
+     * @return CachedMountInfo[]
249
+     */
250
+    public function getMountsForRootId($rootFileId) {
251
+        $builder = $this->connection->getQueryBuilder();
252
+        $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
253
+            ->from('mounts', 'm')
254
+            ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
255
+            ->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT)));
256
+
257
+        $rows = $query->execute()->fetchAll();
258
+
259
+        return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
260
+    }
261
+
262
+    /**
263
+     * @param $fileId
264
+     * @return array
265
+     * @throws \OCP\Files\NotFoundException
266
+     */
267
+    private function getCacheInfoFromFileId($fileId) {
268
+        if (!isset($this->cacheInfoCache[$fileId])) {
269
+            $builder = $this->connection->getQueryBuilder();
270
+            $query = $builder->select('storage', 'path', 'mimetype')
271
+                ->from('filecache')
272
+                ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
273
+
274
+            $row = $query->execute()->fetch();
275
+            if (is_array($row)) {
276
+                $this->cacheInfoCache[$fileId] = [
277
+                    (int)$row['storage'],
278
+                    $row['path'],
279
+                    (int)$row['mimetype']
280
+                ];
281
+            } else {
282
+                throw new NotFoundException('File with id "' . $fileId . '" not found');
283
+            }
284
+        }
285
+        return $this->cacheInfoCache[$fileId];
286
+    }
287
+
288
+    /**
289
+     * @param int $fileId
290
+     * @param string|null $user optionally restrict the results to a single user
291
+     * @return ICachedMountFileInfo[]
292
+     * @since 9.0.0
293
+     */
294
+    public function getMountsForFileId($fileId, $user = null) {
295
+        try {
296
+            list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId);
297
+        } catch (NotFoundException $e) {
298
+            return [];
299
+        }
300
+        $mountsForStorage = $this->getMountsForStorageId($storageId, $user);
301
+
302
+        // filter mounts that are from the same storage but a different directory
303
+        $filteredMounts = array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
304
+            if ($fileId === $mount->getRootId()) {
305
+                return true;
306
+            }
307
+            $internalMountPath = $mount->getRootInternalPath();
308
+
309
+            return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
310
+        });
311
+
312
+        return array_map(function (ICachedMountInfo $mount) use ($internalPath) {
313
+            return new CachedMountFileInfo(
314
+                $mount->getUser(),
315
+                $mount->getStorageId(),
316
+                $mount->getRootId(),
317
+                $mount->getMountPoint(),
318
+                $mount->getMountId(),
319
+                $mount->getRootInternalPath(),
320
+                $internalPath
321
+            );
322
+        }, $filteredMounts);
323
+    }
324
+
325
+    /**
326
+     * Remove all cached mounts for a user
327
+     *
328
+     * @param IUser $user
329
+     */
330
+    public function removeUserMounts(IUser $user) {
331
+        $builder = $this->connection->getQueryBuilder();
332
+
333
+        $query = $builder->delete('mounts')
334
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID())));
335
+        $query->execute();
336
+    }
337
+
338
+    public function removeUserStorageMount($storageId, $userId) {
339
+        $builder = $this->connection->getQueryBuilder();
340
+
341
+        $query = $builder->delete('mounts')
342
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId)))
343
+            ->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
344
+        $query->execute();
345
+    }
346
+
347
+    public function remoteStorageMounts($storageId) {
348
+        $builder = $this->connection->getQueryBuilder();
349
+
350
+        $query = $builder->delete('mounts')
351
+            ->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
352
+        $query->execute();
353
+    }
354
+
355
+    /**
356
+     * @param array $users
357
+     * @return array
358
+     * @suppress SqlInjectionChecker
359
+     */
360
+    public function getUsedSpaceForUsers(array $users) {
361
+        $builder = $this->connection->getQueryBuilder();
362
+
363
+        $slash = $builder->createNamedParameter('/');
364
+
365
+        $mountPoint = $builder->func()->concat(
366
+            $builder->func()->concat($slash, 'user_id'),
367
+            $slash
368
+        );
369
+
370
+        $userIds = array_map(function (IUser $user) {
371
+            return $user->getUID();
372
+        }, $users);
373
+
374
+        $query = $builder->select('m.user_id', 'f.size')
375
+            ->from('mounts', 'm')
376
+            ->innerJoin('m', 'filecache', 'f',
377
+                $builder->expr()->andX(
378
+                    $builder->expr()->eq('m.storage_id', 'f.storage'),
379
+                    $builder->expr()->eq('f.path', $builder->createNamedParameter('files'))
380
+                ))
381
+            ->where($builder->expr()->eq('m.mount_point', $mountPoint))
382
+            ->andWhere($builder->expr()->in('m.user_id', $builder->createNamedParameter($userIds, IQueryBuilder::PARAM_STR_ARRAY)));
383
+
384
+        $result = $query->execute();
385
+
386
+        $results = [];
387
+        while ($row = $result->fetch()) {
388
+            $results[$row['user_id']] = $row['size'];
389
+        }
390
+        $result->closeCursor();
391
+        return $results;
392
+    }
393 393
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -89,11 +89,11 @@  discard block
 block discarded – undo
89 89
 
90 90
 	public function registerMounts(IUser $user, array $mounts) {
91 91
 		// filter out non-proper storages coming from unit tests
92
-		$mounts = array_filter($mounts, function (IMountPoint $mount) {
92
+		$mounts = array_filter($mounts, function(IMountPoint $mount) {
93 93
 			return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache();
94 94
 		});
95 95
 		/** @var ICachedMountInfo[] $newMounts */
96
-		$newMounts = array_map(function (IMountPoint $mount) use ($user) {
96
+		$newMounts = array_map(function(IMountPoint $mount) use ($user) {
97 97
 			// filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)
98 98
 			if ($mount->getStorageRootId() === -1) {
99 99
 				return null;
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 		$newMounts = array_values(array_filter($newMounts));
105 105
 
106 106
 		$cachedMounts = $this->getMountsForUser($user);
107
-		$mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
107
+		$mountDiff = function(ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
108 108
 			// since we are only looking for mounts for a specific user comparing on root id is enough
109 109
 			return $mount1->getRootId() - $mount2->getRootId();
110 110
 		};
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 			], ['root_id', 'user_id']);
166 166
 		} else {
167 167
 			// in some cases this is legitimate, like orphaned shares
168
-			$this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
168
+			$this->logger->debug('Could not get storage info for mount at '.$mount->getMountPoint());
169 169
 		}
170 170
 	}
171 171
 
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 		if (!is_null($mount_id)) {
201 201
 			$mount_id = (int) $mount_id;
202 202
 		}
203
-		return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $mount_id, isset($row['path']) ? $row['path'] : '');
203
+		return new CachedMountInfo($user, (int) $row['storage_id'], (int) $row['root_id'], $row['mount_point'], $mount_id, isset($row['path']) ? $row['path'] : '');
204 204
 	}
205 205
 
206 206
 	/**
@@ -274,12 +274,12 @@  discard block
 block discarded – undo
274 274
 			$row = $query->execute()->fetch();
275 275
 			if (is_array($row)) {
276 276
 				$this->cacheInfoCache[$fileId] = [
277
-					(int)$row['storage'],
277
+					(int) $row['storage'],
278 278
 					$row['path'],
279
-					(int)$row['mimetype']
279
+					(int) $row['mimetype']
280 280
 				];
281 281
 			} else {
282
-				throw new NotFoundException('File with id "' . $fileId . '" not found');
282
+				throw new NotFoundException('File with id "'.$fileId.'" not found');
283 283
 			}
284 284
 		}
285 285
 		return $this->cacheInfoCache[$fileId];
@@ -300,16 +300,16 @@  discard block
 block discarded – undo
300 300
 		$mountsForStorage = $this->getMountsForStorageId($storageId, $user);
301 301
 
302 302
 		// filter mounts that are from the same storage but a different directory
303
-		$filteredMounts = array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
303
+		$filteredMounts = array_filter($mountsForStorage, function(ICachedMountInfo $mount) use ($internalPath, $fileId) {
304 304
 			if ($fileId === $mount->getRootId()) {
305 305
 				return true;
306 306
 			}
307 307
 			$internalMountPath = $mount->getRootInternalPath();
308 308
 
309
-			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
309
+			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath.'/';
310 310
 		});
311 311
 
312
-		return array_map(function (ICachedMountInfo $mount) use ($internalPath) {
312
+		return array_map(function(ICachedMountInfo $mount) use ($internalPath) {
313 313
 			return new CachedMountFileInfo(
314 314
 				$mount->getUser(),
315 315
 				$mount->getStorageId(),
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 			$slash
368 368
 		);
369 369
 
370
-		$userIds = array_map(function (IUser $user) {
370
+		$userIds = array_map(function(IUser $user) {
371 371
 			return $user->getUID();
372 372
 		}, $users);
373 373
 
Please login to merge, or discard this patch.
lib/public/Files/Config/IUserMountCache.php 1 patch
Indentation   +77 added lines, -77 removed lines patch added patch discarded remove patch
@@ -31,89 +31,89 @@
 block discarded – undo
31 31
  * @since 9.0.0
32 32
  */
33 33
 interface IUserMountCache {
34
-	/**
35
-	 * Register mounts for a user to the cache
36
-	 *
37
-	 * @param IUser $user
38
-	 * @param IMountPoint[] $mounts
39
-	 * @since 9.0.0
40
-	 */
41
-	public function registerMounts(IUser $user, array $mounts);
34
+    /**
35
+     * Register mounts for a user to the cache
36
+     *
37
+     * @param IUser $user
38
+     * @param IMountPoint[] $mounts
39
+     * @since 9.0.0
40
+     */
41
+    public function registerMounts(IUser $user, array $mounts);
42 42
 
43
-	/**
44
-	 * Get all cached mounts for a user
45
-	 *
46
-	 * @param IUser $user
47
-	 * @return ICachedMountInfo[]
48
-	 * @since 9.0.0
49
-	 */
50
-	public function getMountsForUser(IUser $user);
43
+    /**
44
+     * Get all cached mounts for a user
45
+     *
46
+     * @param IUser $user
47
+     * @return ICachedMountInfo[]
48
+     * @since 9.0.0
49
+     */
50
+    public function getMountsForUser(IUser $user);
51 51
 
52
-	/**
53
-	 * Get all cached mounts by storage
54
-	 *
55
-	 * @param int $numericStorageId
56
-	 * @param string|null $user limit the results to a single user @since 12.0.0
57
-	 * @return ICachedMountInfo[]
58
-	 * @since 9.0.0
59
-	 */
60
-	public function getMountsForStorageId($numericStorageId, $user = null);
52
+    /**
53
+     * Get all cached mounts by storage
54
+     *
55
+     * @param int $numericStorageId
56
+     * @param string|null $user limit the results to a single user @since 12.0.0
57
+     * @return ICachedMountInfo[]
58
+     * @since 9.0.0
59
+     */
60
+    public function getMountsForStorageId($numericStorageId, $user = null);
61 61
 
62
-	/**
63
-	 * Get all cached mounts by root
64
-	 *
65
-	 * @param int $rootFileId
66
-	 * @return ICachedMountInfo[]
67
-	 * @since 9.0.0
68
-	 */
69
-	public function getMountsForRootId($rootFileId);
62
+    /**
63
+     * Get all cached mounts by root
64
+     *
65
+     * @param int $rootFileId
66
+     * @return ICachedMountInfo[]
67
+     * @since 9.0.0
68
+     */
69
+    public function getMountsForRootId($rootFileId);
70 70
 
71
-	/**
72
-	 * Get all cached mounts that contain a file
73
-	 *
74
-	 * @param int $fileId
75
-	 * @param string|null $user optionally restrict the results to a single user @since 12.0.0
76
-	 * @return ICachedMountFileInfo[]
77
-	 * @since 9.0.0
78
-	 */
79
-	public function getMountsForFileId($fileId, $user = null);
71
+    /**
72
+     * Get all cached mounts that contain a file
73
+     *
74
+     * @param int $fileId
75
+     * @param string|null $user optionally restrict the results to a single user @since 12.0.0
76
+     * @return ICachedMountFileInfo[]
77
+     * @since 9.0.0
78
+     */
79
+    public function getMountsForFileId($fileId, $user = null);
80 80
 
81
-	/**
82
-	 * Remove all cached mounts for a user
83
-	 *
84
-	 * @param IUser $user
85
-	 * @since 9.0.0
86
-	 */
87
-	public function removeUserMounts(IUser $user);
81
+    /**
82
+     * Remove all cached mounts for a user
83
+     *
84
+     * @param IUser $user
85
+     * @since 9.0.0
86
+     */
87
+    public function removeUserMounts(IUser $user);
88 88
 
89
-	/**
90
-	 * Remove all mounts for a user and storage
91
-	 *
92
-	 * @param $storageId
93
-	 * @param string $userId
94
-	 * @return mixed
95
-	 * @since 9.0.0
96
-	 */
97
-	public function removeUserStorageMount($storageId, $userId);
89
+    /**
90
+     * Remove all mounts for a user and storage
91
+     *
92
+     * @param $storageId
93
+     * @param string $userId
94
+     * @return mixed
95
+     * @since 9.0.0
96
+     */
97
+    public function removeUserStorageMount($storageId, $userId);
98 98
 
99
-	/**
100
-	 * Remove all cached mounts for a storage
101
-	 *
102
-	 * @param $storageId
103
-	 * @return mixed
104
-	 * @since 9.0.0
105
-	 */
106
-	public function remoteStorageMounts($storageId);
99
+    /**
100
+     * Remove all cached mounts for a storage
101
+     *
102
+     * @param $storageId
103
+     * @return mixed
104
+     * @since 9.0.0
105
+     */
106
+    public function remoteStorageMounts($storageId);
107 107
 
108
-	/**
109
-	 * Get the used space for users
110
-	 *
111
-	 * Note that this only includes the space in their home directory,
112
-	 * not any incoming shares or external storages.
113
-	 *
114
-	 * @param IUser[] $users
115
-	 * @return int[] [$userId => $userSpace]
116
-	 * @since 13.0.0
117
-	 */
118
-	public function getUsedSpaceForUsers(array $users);
108
+    /**
109
+     * Get the used space for users
110
+     *
111
+     * Note that this only includes the space in their home directory,
112
+     * not any incoming shares or external storages.
113
+     *
114
+     * @param IUser[] $users
115
+     * @return int[] [$userId => $userSpace]
116
+     * @since 13.0.0
117
+     */
118
+    public function getUsedSpaceForUsers(array $users);
119 119
 }
Please login to merge, or discard this patch.
lib/private/Files/Config/CachedMountFileInfo.php 2 patches
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -26,23 +26,23 @@
 block discarded – undo
26 26
 use OCP\IUser;
27 27
 
28 28
 class CachedMountFileInfo extends CachedMountInfo implements ICachedMountFileInfo {
29
-	/** @var string */
30
-	private $internalPath;
29
+    /** @var string */
30
+    private $internalPath;
31 31
 
32
-	public function __construct(IUser $user, $storageId, $rootId, $mountPoint, $mountId = null, $rootInternalPath = '', $internalPath) {
33
-		parent::__construct($user, $storageId, $rootId, $mountPoint, $mountId, $rootInternalPath);
34
-		$this->internalPath = $internalPath;
35
-	}
32
+    public function __construct(IUser $user, $storageId, $rootId, $mountPoint, $mountId = null, $rootInternalPath = '', $internalPath) {
33
+        parent::__construct($user, $storageId, $rootId, $mountPoint, $mountId, $rootInternalPath);
34
+        $this->internalPath = $internalPath;
35
+    }
36 36
 
37
-	public function getInternalPath() {
38
-		if ($this->getRootInternalPath()) {
39
-			return substr($this->internalPath, strlen($this->getRootInternalPath()) + 1);
40
-		} else {
41
-			return $this->internalPath;
42
-		}
43
-	}
37
+    public function getInternalPath() {
38
+        if ($this->getRootInternalPath()) {
39
+            return substr($this->internalPath, strlen($this->getRootInternalPath()) + 1);
40
+        } else {
41
+            return $this->internalPath;
42
+        }
43
+    }
44 44
 
45
-	public function getPath() {
46
-		return $this->getMountPoint() . $this->getInternalPath();
47
-	}
45
+    public function getPath() {
46
+        return $this->getMountPoint() . $this->getInternalPath();
47
+    }
48 48
 }
49 49
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -43,6 +43,6 @@
 block discarded – undo
43 43
 	}
44 44
 
45 45
 	public function getPath() {
46
-		return $this->getMountPoint() . $this->getInternalPath();
46
+		return $this->getMountPoint().$this->getInternalPath();
47 47
 	}
48 48
 }
49 49
\ No newline at end of file
Please login to merge, or discard this patch.
lib/public/Files/Config/ICachedMountFieInfo.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -27,17 +27,17 @@
 block discarded – undo
27 27
  * @since 13.0.0
28 28
  */
29 29
 interface ICachedMountFileInfo extends ICachedMountInfo {
30
-	/**
31
-	 * Return the path for the file within the cached mount
32
-	 *
33
-	 * @return string
34
-	 * @since 13.0.0
35
-	 */
36
-	public function getInternalPath();
30
+    /**
31
+     * Return the path for the file within the cached mount
32
+     *
33
+     * @return string
34
+     * @since 13.0.0
35
+     */
36
+    public function getInternalPath();
37 37
 
38
-	/**
39
-	 * @return string
40
-	 * @since 13.0.0
41
-	 */
42
-	public function getPath();
38
+    /**
39
+     * @return string
40
+     * @since 13.0.0
41
+     */
42
+    public function getPath();
43 43
 }
Please login to merge, or discard this patch.
lib/private/Files/View.php 2 patches
Spacing   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -128,9 +128,9 @@  discard block
 block discarded – undo
128 128
 			$path = '/';
129 129
 		}
130 130
 		if ($path[0] !== '/') {
131
-			$path = '/' . $path;
131
+			$path = '/'.$path;
132 132
 		}
133
-		return $this->fakeRoot . $path;
133
+		return $this->fakeRoot.$path;
134 134
 	}
135 135
 
136 136
 	/**
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 	public function chroot($fakeRoot) {
143 143
 		if (!$fakeRoot == '') {
144 144
 			if ($fakeRoot[0] !== '/') {
145
-				$fakeRoot = '/' . $fakeRoot;
145
+				$fakeRoot = '/'.$fakeRoot;
146 146
 			}
147 147
 		}
148 148
 		$this->fakeRoot = $fakeRoot;
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
 		}
175 175
 
176 176
 		// missing slashes can cause wrong matches!
177
-		$root = rtrim($this->fakeRoot, '/') . '/';
177
+		$root = rtrim($this->fakeRoot, '/').'/';
178 178
 
179 179
 		if (strpos($path, $root) !== 0) {
180 180
 			return null;
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
 		if ($mount instanceof MoveableMount) {
281 281
 			// cut of /user/files to get the relative path to data/user/files
282 282
 			$pathParts = explode('/', $path, 4);
283
-			$relPath = '/' . $pathParts[3];
283
+			$relPath = '/'.$pathParts[3];
284 284
 			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
285 285
 			\OC_Hook::emit(
286 286
 				Filesystem::CLASSNAME, "umount",
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
 		}
683 683
 		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
684 684
 		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
685
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
685
+		$mount = Filesystem::getMountManager()->find($absolutePath.$postFix);
686 686
 		if ($mount and $mount->getInternalPath($absolutePath) === '') {
687 687
 			return $this->removeMount($mount, $absolutePath);
688 688
 		}
@@ -802,7 +802,7 @@  discard block
 block discarded – undo
802 802
 								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
803 803
 							}
804 804
 						}
805
-					} catch(\Exception $e) {
805
+					} catch (\Exception $e) {
806 806
 						throw $e;
807 807
 					} finally {
808 808
 						$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
@@ -826,7 +826,7 @@  discard block
 block discarded – undo
826 826
 						}
827 827
 					}
828 828
 				}
829
-			} catch(\Exception $e) {
829
+			} catch (\Exception $e) {
830 830
 				throw $e;
831 831
 			} finally {
832 832
 				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
@@ -959,7 +959,7 @@  discard block
 block discarded – undo
959 959
 				$hooks[] = 'write';
960 960
 				break;
961 961
 			default:
962
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
962
+				\OCP\Util::writeLog('core', 'invalid mode ('.$mode.') for '.$path, \OCP\Util::ERROR);
963 963
 		}
964 964
 
965 965
 		if ($mode !== 'r' && $mode !== 'w') {
@@ -1063,7 +1063,7 @@  discard block
 block discarded – undo
1063 1063
 					array(Filesystem::signal_param_path => $this->getHookPath($path))
1064 1064
 				);
1065 1065
 			}
1066
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1066
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1067 1067
 			if ($storage) {
1068 1068
 				$result = $storage->hash($type, $internalPath, $raw);
1069 1069
 				return $result;
@@ -1118,7 +1118,7 @@  discard block
 block discarded – undo
1118 1118
 
1119 1119
 			$run = $this->runHooks($hooks, $path);
1120 1120
 			/** @var \OC\Files\Storage\Storage $storage */
1121
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1121
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1122 1122
 			if ($run and $storage) {
1123 1123
 				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1124 1124
 					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
@@ -1157,7 +1157,7 @@  discard block
 block discarded – undo
1157 1157
 					$unlockLater = true;
1158 1158
 					// make sure our unlocking callback will still be called if connection is aborted
1159 1159
 					ignore_user_abort(true);
1160
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1160
+					$result = CallbackWrapper::wrap($result, null, null, function() use ($hooks, $path) {
1161 1161
 						if (in_array('write', $hooks)) {
1162 1162
 							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1163 1163
 						} else if (in_array('read', $hooks)) {
@@ -1218,7 +1218,7 @@  discard block
 block discarded – undo
1218 1218
 			return true;
1219 1219
 		}
1220 1220
 
1221
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1221
+		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot.'/');
1222 1222
 	}
1223 1223
 
1224 1224
 	/**
@@ -1237,7 +1237,7 @@  discard block
 block discarded – undo
1237 1237
 				if ($hook != 'read') {
1238 1238
 					\OC_Hook::emit(
1239 1239
 						Filesystem::CLASSNAME,
1240
-						$prefix . $hook,
1240
+						$prefix.$hook,
1241 1241
 						array(
1242 1242
 							Filesystem::signal_param_run => &$run,
1243 1243
 							Filesystem::signal_param_path => $path
@@ -1246,7 +1246,7 @@  discard block
 block discarded – undo
1246 1246
 				} elseif (!$post) {
1247 1247
 					\OC_Hook::emit(
1248 1248
 						Filesystem::CLASSNAME,
1249
-						$prefix . $hook,
1249
+						$prefix.$hook,
1250 1250
 						array(
1251 1251
 							Filesystem::signal_param_path => $path
1252 1252
 						)
@@ -1341,7 +1341,7 @@  discard block
 block discarded – undo
1341 1341
 			return $this->getPartFileInfo($path);
1342 1342
 		}
1343 1343
 		$relativePath = $path;
1344
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1344
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1345 1345
 
1346 1346
 		$mount = Filesystem::getMountManager()->find($path);
1347 1347
 		$storage = $mount->getStorage();
@@ -1365,7 +1365,7 @@  discard block
 block discarded – undo
1365 1365
 					//add the sizes of other mount points to the folder
1366 1366
 					$extOnly = ($includeMountPoints === 'ext');
1367 1367
 					$mounts = Filesystem::getMountManager()->findIn($path);
1368
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1368
+					$info->setSubMounts(array_filter($mounts, function(IMountPoint $mount) use ($extOnly) {
1369 1369
 						$subStorage = $mount->getStorage();
1370 1370
 						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1371 1371
 					}));
@@ -1412,12 +1412,12 @@  discard block
 block discarded – undo
1412 1412
 			/**
1413 1413
 			 * @var \OC\Files\FileInfo[] $files
1414 1414
 			 */
1415
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1415
+			$files = array_map(function(ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1416 1416
 				if ($sharingDisabled) {
1417 1417
 					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1418 1418
 				}
1419 1419
 				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1420
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1420
+				return new FileInfo($path.'/'.$content['name'], $storage, $content['path'], $content, $mount, $owner);
1421 1421
 			}, $contents);
1422 1422
 
1423 1423
 			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
@@ -1442,8 +1442,8 @@  discard block
 block discarded – undo
1442 1442
 							// sometimes when the storage is not available it can be any exception
1443 1443
 							\OCP\Util::writeLog(
1444 1444
 								'core',
1445
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1446
-								get_class($e) . ': ' . $e->getMessage(),
1445
+								'Exception while scanning storage "'.$subStorage->getId().'": '.
1446
+								get_class($e).': '.$e->getMessage(),
1447 1447
 								\OCP\Util::ERROR
1448 1448
 							);
1449 1449
 							continue;
@@ -1480,7 +1480,7 @@  discard block
 block discarded – undo
1480 1480
 									break;
1481 1481
 								}
1482 1482
 							}
1483
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1483
+							$rootEntry['path'] = substr(Filesystem::normalizePath($path.'/'.$rootEntry['name']), strlen($user) + 2); // full path without /$user/
1484 1484
 
1485 1485
 							// if sharing was disabled for the user we remove the share permissions
1486 1486
 							if (\OCP\Util::isSharingDisabledForUser()) {
@@ -1488,14 +1488,14 @@  discard block
 block discarded – undo
1488 1488
 							}
1489 1489
 
1490 1490
 							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1491
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1491
+							$files[] = new FileInfo($path.'/'.$rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1492 1492
 						}
1493 1493
 					}
1494 1494
 				}
1495 1495
 			}
1496 1496
 
1497 1497
 			if ($mimetype_filter) {
1498
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1498
+				$files = array_filter($files, function(FileInfo $file) use ($mimetype_filter) {
1499 1499
 					if (strpos($mimetype_filter, '/')) {
1500 1500
 						return $file->getMimetype() === $mimetype_filter;
1501 1501
 					} else {
@@ -1524,7 +1524,7 @@  discard block
 block discarded – undo
1524 1524
 		if ($data instanceof FileInfo) {
1525 1525
 			$data = $data->getData();
1526 1526
 		}
1527
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1527
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1528 1528
 		/**
1529 1529
 		 * @var \OC\Files\Storage\Storage $storage
1530 1530
 		 * @var string $internalPath
@@ -1551,7 +1551,7 @@  discard block
 block discarded – undo
1551 1551
 	 * @return FileInfo[]
1552 1552
 	 */
1553 1553
 	public function search($query) {
1554
-		return $this->searchCommon('search', array('%' . $query . '%'));
1554
+		return $this->searchCommon('search', array('%'.$query.'%'));
1555 1555
 	}
1556 1556
 
1557 1557
 	/**
@@ -1602,10 +1602,10 @@  discard block
 block discarded – undo
1602 1602
 
1603 1603
 			$results = call_user_func_array(array($cache, $method), $args);
1604 1604
 			foreach ($results as $result) {
1605
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1605
+				if (substr($mountPoint.$result['path'], 0, $rootLength + 1) === $this->fakeRoot.'/') {
1606 1606
 					$internalPath = $result['path'];
1607
-					$path = $mountPoint . $result['path'];
1608
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1607
+					$path = $mountPoint.$result['path'];
1608
+					$result['path'] = substr($mountPoint.$result['path'], $rootLength);
1609 1609
 					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1610 1610
 					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1611 1611
 				}
@@ -1623,8 +1623,8 @@  discard block
 block discarded – undo
1623 1623
 					if ($results) {
1624 1624
 						foreach ($results as $result) {
1625 1625
 							$internalPath = $result['path'];
1626
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1627
-							$path = rtrim($mountPoint . $internalPath, '/');
1626
+							$result['path'] = rtrim($relativeMountPoint.$result['path'], '/');
1627
+							$path = rtrim($mountPoint.$internalPath, '/');
1628 1628
 							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1629 1629
 							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1630 1630
 						}
@@ -1645,7 +1645,7 @@  discard block
 block discarded – undo
1645 1645
 	public function getOwner($path) {
1646 1646
 		$info = $this->getFileInfo($path);
1647 1647
 		if (!$info) {
1648
-			throw new NotFoundException($path . ' not found while trying to get owner');
1648
+			throw new NotFoundException($path.' not found while trying to get owner');
1649 1649
 		}
1650 1650
 		return $info->getOwner()->getUID();
1651 1651
 	}
@@ -1679,7 +1679,7 @@  discard block
 block discarded – undo
1679 1679
 	 * @return string
1680 1680
 	 */
1681 1681
 	public function getPath($id) {
1682
-		$id = (int)$id;
1682
+		$id = (int) $id;
1683 1683
 		$manager = Filesystem::getMountManager();
1684 1684
 		$mounts = $manager->findIn($this->fakeRoot);
1685 1685
 		$mounts[] = $manager->find($this->fakeRoot);
@@ -1694,7 +1694,7 @@  discard block
 block discarded – undo
1694 1694
 				$cache = $mount->getStorage()->getCache();
1695 1695
 				$internalPath = $cache->getPathById($id);
1696 1696
 				if (is_string($internalPath)) {
1697
-					$fullPath = $mount->getMountPoint() . $internalPath;
1697
+					$fullPath = $mount->getMountPoint().$internalPath;
1698 1698
 					if (!is_null($path = $this->getRelativePath($fullPath))) {
1699 1699
 						return $path;
1700 1700
 					}
@@ -1737,10 +1737,10 @@  discard block
 block discarded – undo
1737 1737
 		}
1738 1738
 
1739 1739
 		// note: cannot use the view because the target is already locked
1740
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1740
+		$fileId = (int) $targetStorage->getCache()->getId($targetInternalPath);
1741 1741
 		if ($fileId === -1) {
1742 1742
 			// target might not exist, need to check parent instead
1743
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1743
+			$fileId = (int) $targetStorage->getCache()->getId(dirname($targetInternalPath));
1744 1744
 		}
1745 1745
 
1746 1746
 		// check if any of the parents were shared by the current owner (include collections)
@@ -1840,7 +1840,7 @@  discard block
 block discarded – undo
1840 1840
 		$resultPath = '';
1841 1841
 		foreach ($parts as $part) {
1842 1842
 			if ($part) {
1843
-				$resultPath .= '/' . $part;
1843
+				$resultPath .= '/'.$part;
1844 1844
 				$result[] = $resultPath;
1845 1845
 			}
1846 1846
 		}
@@ -2103,16 +2103,16 @@  discard block
 block discarded – undo
2103 2103
 	public function getUidAndFilename($filename) {
2104 2104
 		$info = $this->getFileInfo($filename);
2105 2105
 		if (!$info instanceof \OCP\Files\FileInfo) {
2106
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2106
+			throw new NotFoundException($this->getAbsolutePath($filename).' not found');
2107 2107
 		}
2108 2108
 		$uid = $info->getOwner()->getUID();
2109 2109
 		if ($uid != \OCP\User::getUser()) {
2110 2110
 			Filesystem::initMountPoints($uid);
2111
-			$ownerView = new View('/' . $uid . '/files');
2111
+			$ownerView = new View('/'.$uid.'/files');
2112 2112
 			try {
2113 2113
 				$filename = $ownerView->getPath($info['fileid']);
2114 2114
 			} catch (NotFoundException $e) {
2115
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2115
+				throw new NotFoundException('File with id '.$info['fileid'].' not found for user '.$uid);
2116 2116
 			}
2117 2117
 		}
2118 2118
 		return [$uid, $filename];
@@ -2129,7 +2129,7 @@  discard block
 block discarded – undo
2129 2129
 		$directoryParts = array_filter($directoryParts);
2130 2130
 		foreach ($directoryParts as $key => $part) {
2131 2131
 			$currentPathElements = array_slice($directoryParts, 0, $key);
2132
-			$currentPath = '/' . implode('/', $currentPathElements);
2132
+			$currentPath = '/'.implode('/', $currentPathElements);
2133 2133
 			if ($this->is_file($currentPath)) {
2134 2134
 				return false;
2135 2135
 			}
Please login to merge, or discard this patch.
Indentation   +2078 added lines, -2078 removed lines patch added patch discarded remove patch
@@ -82,2082 +82,2082 @@
 block discarded – undo
82 82
  * \OC\Files\Storage\Storage object
83 83
  */
84 84
 class View {
85
-	/** @var string */
86
-	private $fakeRoot = '';
87
-
88
-	/**
89
-	 * @var \OCP\Lock\ILockingProvider
90
-	 */
91
-	protected $lockingProvider;
92
-
93
-	private $lockingEnabled;
94
-
95
-	private $updaterEnabled = true;
96
-
97
-	/** @var \OC\User\Manager */
98
-	private $userManager;
99
-
100
-	/** @var \OCP\ILogger */
101
-	private $logger;
102
-
103
-	/**
104
-	 * @param string $root
105
-	 * @throws \Exception If $root contains an invalid path
106
-	 */
107
-	public function __construct($root = '') {
108
-		if (is_null($root)) {
109
-			throw new \InvalidArgumentException('Root can\'t be null');
110
-		}
111
-		if (!Filesystem::isValidPath($root)) {
112
-			throw new \Exception();
113
-		}
114
-
115
-		$this->fakeRoot = $root;
116
-		$this->lockingProvider = \OC::$server->getLockingProvider();
117
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
118
-		$this->userManager = \OC::$server->getUserManager();
119
-		$this->logger = \OC::$server->getLogger();
120
-	}
121
-
122
-	public function getAbsolutePath($path = '/') {
123
-		if ($path === null) {
124
-			return null;
125
-		}
126
-		$this->assertPathLength($path);
127
-		if ($path === '') {
128
-			$path = '/';
129
-		}
130
-		if ($path[0] !== '/') {
131
-			$path = '/' . $path;
132
-		}
133
-		return $this->fakeRoot . $path;
134
-	}
135
-
136
-	/**
137
-	 * change the root to a fake root
138
-	 *
139
-	 * @param string $fakeRoot
140
-	 * @return boolean|null
141
-	 */
142
-	public function chroot($fakeRoot) {
143
-		if (!$fakeRoot == '') {
144
-			if ($fakeRoot[0] !== '/') {
145
-				$fakeRoot = '/' . $fakeRoot;
146
-			}
147
-		}
148
-		$this->fakeRoot = $fakeRoot;
149
-	}
150
-
151
-	/**
152
-	 * get the fake root
153
-	 *
154
-	 * @return string
155
-	 */
156
-	public function getRoot() {
157
-		return $this->fakeRoot;
158
-	}
159
-
160
-	/**
161
-	 * get path relative to the root of the view
162
-	 *
163
-	 * @param string $path
164
-	 * @return string
165
-	 */
166
-	public function getRelativePath($path) {
167
-		$this->assertPathLength($path);
168
-		if ($this->fakeRoot == '') {
169
-			return $path;
170
-		}
171
-
172
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
173
-			return '/';
174
-		}
175
-
176
-		// missing slashes can cause wrong matches!
177
-		$root = rtrim($this->fakeRoot, '/') . '/';
178
-
179
-		if (strpos($path, $root) !== 0) {
180
-			return null;
181
-		} else {
182
-			$path = substr($path, strlen($this->fakeRoot));
183
-			if (strlen($path) === 0) {
184
-				return '/';
185
-			} else {
186
-				return $path;
187
-			}
188
-		}
189
-	}
190
-
191
-	/**
192
-	 * get the mountpoint of the storage object for a path
193
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
194
-	 * returned mountpoint is relative to the absolute root of the filesystem
195
-	 * and does not take the chroot into account )
196
-	 *
197
-	 * @param string $path
198
-	 * @return string
199
-	 */
200
-	public function getMountPoint($path) {
201
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
202
-	}
203
-
204
-	/**
205
-	 * get the mountpoint of the storage object for a path
206
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
207
-	 * returned mountpoint is relative to the absolute root of the filesystem
208
-	 * and does not take the chroot into account )
209
-	 *
210
-	 * @param string $path
211
-	 * @return \OCP\Files\Mount\IMountPoint
212
-	 */
213
-	public function getMount($path) {
214
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
215
-	}
216
-
217
-	/**
218
-	 * resolve a path to a storage and internal path
219
-	 *
220
-	 * @param string $path
221
-	 * @return array an array consisting of the storage and the internal path
222
-	 */
223
-	public function resolvePath($path) {
224
-		$a = $this->getAbsolutePath($path);
225
-		$p = Filesystem::normalizePath($a);
226
-		return Filesystem::resolvePath($p);
227
-	}
228
-
229
-	/**
230
-	 * return the path to a local version of the file
231
-	 * we need this because we can't know if a file is stored local or not from
232
-	 * outside the filestorage and for some purposes a local file is needed
233
-	 *
234
-	 * @param string $path
235
-	 * @return string
236
-	 */
237
-	public function getLocalFile($path) {
238
-		$parent = substr($path, 0, strrpos($path, '/'));
239
-		$path = $this->getAbsolutePath($path);
240
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
241
-		if (Filesystem::isValidPath($parent) and $storage) {
242
-			return $storage->getLocalFile($internalPath);
243
-		} else {
244
-			return null;
245
-		}
246
-	}
247
-
248
-	/**
249
-	 * @param string $path
250
-	 * @return string
251
-	 */
252
-	public function getLocalFolder($path) {
253
-		$parent = substr($path, 0, strrpos($path, '/'));
254
-		$path = $this->getAbsolutePath($path);
255
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
256
-		if (Filesystem::isValidPath($parent) and $storage) {
257
-			return $storage->getLocalFolder($internalPath);
258
-		} else {
259
-			return null;
260
-		}
261
-	}
262
-
263
-	/**
264
-	 * the following functions operate with arguments and return values identical
265
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
266
-	 * for \OC\Files\Storage\Storage via basicOperation().
267
-	 */
268
-	public function mkdir($path) {
269
-		return $this->basicOperation('mkdir', $path, array('create', 'write'));
270
-	}
271
-
272
-	/**
273
-	 * remove mount point
274
-	 *
275
-	 * @param \OC\Files\Mount\MoveableMount $mount
276
-	 * @param string $path relative to data/
277
-	 * @return boolean
278
-	 */
279
-	protected function removeMount($mount, $path) {
280
-		if ($mount instanceof MoveableMount) {
281
-			// cut of /user/files to get the relative path to data/user/files
282
-			$pathParts = explode('/', $path, 4);
283
-			$relPath = '/' . $pathParts[3];
284
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
285
-			\OC_Hook::emit(
286
-				Filesystem::CLASSNAME, "umount",
287
-				array(Filesystem::signal_param_path => $relPath)
288
-			);
289
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
290
-			$result = $mount->removeMount();
291
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
292
-			if ($result) {
293
-				\OC_Hook::emit(
294
-					Filesystem::CLASSNAME, "post_umount",
295
-					array(Filesystem::signal_param_path => $relPath)
296
-				);
297
-			}
298
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
299
-			return $result;
300
-		} else {
301
-			// do not allow deleting the storage's root / the mount point
302
-			// because for some storages it might delete the whole contents
303
-			// but isn't supposed to work that way
304
-			return false;
305
-		}
306
-	}
307
-
308
-	public function disableCacheUpdate() {
309
-		$this->updaterEnabled = false;
310
-	}
311
-
312
-	public function enableCacheUpdate() {
313
-		$this->updaterEnabled = true;
314
-	}
315
-
316
-	protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
317
-		if ($this->updaterEnabled) {
318
-			if (is_null($time)) {
319
-				$time = time();
320
-			}
321
-			$storage->getUpdater()->update($internalPath, $time);
322
-		}
323
-	}
324
-
325
-	protected function removeUpdate(Storage $storage, $internalPath) {
326
-		if ($this->updaterEnabled) {
327
-			$storage->getUpdater()->remove($internalPath);
328
-		}
329
-	}
330
-
331
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
332
-		if ($this->updaterEnabled) {
333
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
334
-		}
335
-	}
336
-
337
-	/**
338
-	 * @param string $path
339
-	 * @return bool|mixed
340
-	 */
341
-	public function rmdir($path) {
342
-		$absolutePath = $this->getAbsolutePath($path);
343
-		$mount = Filesystem::getMountManager()->find($absolutePath);
344
-		if ($mount->getInternalPath($absolutePath) === '') {
345
-			return $this->removeMount($mount, $absolutePath);
346
-		}
347
-		if ($this->is_dir($path)) {
348
-			$result = $this->basicOperation('rmdir', $path, array('delete'));
349
-		} else {
350
-			$result = false;
351
-		}
352
-
353
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
354
-			$storage = $mount->getStorage();
355
-			$internalPath = $mount->getInternalPath($absolutePath);
356
-			$storage->getUpdater()->remove($internalPath);
357
-		}
358
-		return $result;
359
-	}
360
-
361
-	/**
362
-	 * @param string $path
363
-	 * @return resource
364
-	 */
365
-	public function opendir($path) {
366
-		return $this->basicOperation('opendir', $path, array('read'));
367
-	}
368
-
369
-	/**
370
-	 * @param string $path
371
-	 * @return bool|mixed
372
-	 */
373
-	public function is_dir($path) {
374
-		if ($path == '/') {
375
-			return true;
376
-		}
377
-		return $this->basicOperation('is_dir', $path);
378
-	}
379
-
380
-	/**
381
-	 * @param string $path
382
-	 * @return bool|mixed
383
-	 */
384
-	public function is_file($path) {
385
-		if ($path == '/') {
386
-			return false;
387
-		}
388
-		return $this->basicOperation('is_file', $path);
389
-	}
390
-
391
-	/**
392
-	 * @param string $path
393
-	 * @return mixed
394
-	 */
395
-	public function stat($path) {
396
-		return $this->basicOperation('stat', $path);
397
-	}
398
-
399
-	/**
400
-	 * @param string $path
401
-	 * @return mixed
402
-	 */
403
-	public function filetype($path) {
404
-		return $this->basicOperation('filetype', $path);
405
-	}
406
-
407
-	/**
408
-	 * @param string $path
409
-	 * @return mixed
410
-	 */
411
-	public function filesize($path) {
412
-		return $this->basicOperation('filesize', $path);
413
-	}
414
-
415
-	/**
416
-	 * @param string $path
417
-	 * @return bool|mixed
418
-	 * @throws \OCP\Files\InvalidPathException
419
-	 */
420
-	public function readfile($path) {
421
-		$this->assertPathLength($path);
422
-		@ob_end_clean();
423
-		$handle = $this->fopen($path, 'rb');
424
-		if ($handle) {
425
-			$chunkSize = 8192; // 8 kB chunks
426
-			while (!feof($handle)) {
427
-				echo fread($handle, $chunkSize);
428
-				flush();
429
-			}
430
-			fclose($handle);
431
-			$size = $this->filesize($path);
432
-			return $size;
433
-		}
434
-		return false;
435
-	}
436
-
437
-	/**
438
-	 * @param string $path
439
-	 * @param int $from
440
-	 * @param int $to
441
-	 * @return bool|mixed
442
-	 * @throws \OCP\Files\InvalidPathException
443
-	 * @throws \OCP\Files\UnseekableException
444
-	 */
445
-	public function readfilePart($path, $from, $to) {
446
-		$this->assertPathLength($path);
447
-		@ob_end_clean();
448
-		$handle = $this->fopen($path, 'rb');
449
-		if ($handle) {
450
-			$chunkSize = 8192; // 8 kB chunks
451
-			$startReading = true;
452
-
453
-			if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
454
-				// forward file handle via chunked fread because fseek seem to have failed
455
-
456
-				$end = $from + 1;
457
-				while (!feof($handle) && ftell($handle) < $end) {
458
-					$len = $from - ftell($handle);
459
-					if ($len > $chunkSize) {
460
-						$len = $chunkSize;
461
-					}
462
-					$result = fread($handle, $len);
463
-
464
-					if ($result === false) {
465
-						$startReading = false;
466
-						break;
467
-					}
468
-				}
469
-			}
470
-
471
-			if ($startReading) {
472
-				$end = $to + 1;
473
-				while (!feof($handle) && ftell($handle) < $end) {
474
-					$len = $end - ftell($handle);
475
-					if ($len > $chunkSize) {
476
-						$len = $chunkSize;
477
-					}
478
-					echo fread($handle, $len);
479
-					flush();
480
-				}
481
-				$size = ftell($handle) - $from;
482
-				return $size;
483
-			}
484
-
485
-			throw new \OCP\Files\UnseekableException('fseek error');
486
-		}
487
-		return false;
488
-	}
489
-
490
-	/**
491
-	 * @param string $path
492
-	 * @return mixed
493
-	 */
494
-	public function isCreatable($path) {
495
-		return $this->basicOperation('isCreatable', $path);
496
-	}
497
-
498
-	/**
499
-	 * @param string $path
500
-	 * @return mixed
501
-	 */
502
-	public function isReadable($path) {
503
-		return $this->basicOperation('isReadable', $path);
504
-	}
505
-
506
-	/**
507
-	 * @param string $path
508
-	 * @return mixed
509
-	 */
510
-	public function isUpdatable($path) {
511
-		return $this->basicOperation('isUpdatable', $path);
512
-	}
513
-
514
-	/**
515
-	 * @param string $path
516
-	 * @return bool|mixed
517
-	 */
518
-	public function isDeletable($path) {
519
-		$absolutePath = $this->getAbsolutePath($path);
520
-		$mount = Filesystem::getMountManager()->find($absolutePath);
521
-		if ($mount->getInternalPath($absolutePath) === '') {
522
-			return $mount instanceof MoveableMount;
523
-		}
524
-		return $this->basicOperation('isDeletable', $path);
525
-	}
526
-
527
-	/**
528
-	 * @param string $path
529
-	 * @return mixed
530
-	 */
531
-	public function isSharable($path) {
532
-		return $this->basicOperation('isSharable', $path);
533
-	}
534
-
535
-	/**
536
-	 * @param string $path
537
-	 * @return bool|mixed
538
-	 */
539
-	public function file_exists($path) {
540
-		if ($path == '/') {
541
-			return true;
542
-		}
543
-		return $this->basicOperation('file_exists', $path);
544
-	}
545
-
546
-	/**
547
-	 * @param string $path
548
-	 * @return mixed
549
-	 */
550
-	public function filemtime($path) {
551
-		return $this->basicOperation('filemtime', $path);
552
-	}
553
-
554
-	/**
555
-	 * @param string $path
556
-	 * @param int|string $mtime
557
-	 * @return bool
558
-	 */
559
-	public function touch($path, $mtime = null) {
560
-		if (!is_null($mtime) and !is_numeric($mtime)) {
561
-			$mtime = strtotime($mtime);
562
-		}
563
-
564
-		$hooks = array('touch');
565
-
566
-		if (!$this->file_exists($path)) {
567
-			$hooks[] = 'create';
568
-			$hooks[] = 'write';
569
-		}
570
-		$result = $this->basicOperation('touch', $path, $hooks, $mtime);
571
-		if (!$result) {
572
-			// If create file fails because of permissions on external storage like SMB folders,
573
-			// check file exists and return false if not.
574
-			if (!$this->file_exists($path)) {
575
-				return false;
576
-			}
577
-			if (is_null($mtime)) {
578
-				$mtime = time();
579
-			}
580
-			//if native touch fails, we emulate it by changing the mtime in the cache
581
-			$this->putFileInfo($path, array('mtime' => floor($mtime)));
582
-		}
583
-		return true;
584
-	}
585
-
586
-	/**
587
-	 * @param string $path
588
-	 * @return mixed
589
-	 */
590
-	public function file_get_contents($path) {
591
-		return $this->basicOperation('file_get_contents', $path, array('read'));
592
-	}
593
-
594
-	/**
595
-	 * @param bool $exists
596
-	 * @param string $path
597
-	 * @param bool $run
598
-	 */
599
-	protected function emit_file_hooks_pre($exists, $path, &$run) {
600
-		if (!$exists) {
601
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
602
-				Filesystem::signal_param_path => $this->getHookPath($path),
603
-				Filesystem::signal_param_run => &$run,
604
-			));
605
-		} else {
606
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
607
-				Filesystem::signal_param_path => $this->getHookPath($path),
608
-				Filesystem::signal_param_run => &$run,
609
-			));
610
-		}
611
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
612
-			Filesystem::signal_param_path => $this->getHookPath($path),
613
-			Filesystem::signal_param_run => &$run,
614
-		));
615
-	}
616
-
617
-	/**
618
-	 * @param bool $exists
619
-	 * @param string $path
620
-	 */
621
-	protected function emit_file_hooks_post($exists, $path) {
622
-		if (!$exists) {
623
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
624
-				Filesystem::signal_param_path => $this->getHookPath($path),
625
-			));
626
-		} else {
627
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
628
-				Filesystem::signal_param_path => $this->getHookPath($path),
629
-			));
630
-		}
631
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
632
-			Filesystem::signal_param_path => $this->getHookPath($path),
633
-		));
634
-	}
635
-
636
-	/**
637
-	 * @param string $path
638
-	 * @param mixed $data
639
-	 * @return bool|mixed
640
-	 * @throws \Exception
641
-	 */
642
-	public function file_put_contents($path, $data) {
643
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
644
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
645
-			if (Filesystem::isValidPath($path)
646
-				and !Filesystem::isFileBlacklisted($path)
647
-			) {
648
-				$path = $this->getRelativePath($absolutePath);
649
-
650
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
651
-
652
-				$exists = $this->file_exists($path);
653
-				$run = true;
654
-				if ($this->shouldEmitHooks($path)) {
655
-					$this->emit_file_hooks_pre($exists, $path, $run);
656
-				}
657
-				if (!$run) {
658
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
659
-					return false;
660
-				}
661
-
662
-				$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
663
-
664
-				/** @var \OC\Files\Storage\Storage $storage */
665
-				list($storage, $internalPath) = $this->resolvePath($path);
666
-				$target = $storage->fopen($internalPath, 'w');
667
-				if ($target) {
668
-					list (, $result) = \OC_Helper::streamCopy($data, $target);
669
-					fclose($target);
670
-					fclose($data);
671
-
672
-					$this->writeUpdate($storage, $internalPath);
673
-
674
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
675
-
676
-					if ($this->shouldEmitHooks($path) && $result !== false) {
677
-						$this->emit_file_hooks_post($exists, $path);
678
-					}
679
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
680
-					return $result;
681
-				} else {
682
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
683
-					return false;
684
-				}
685
-			} else {
686
-				return false;
687
-			}
688
-		} else {
689
-			$hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
690
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
691
-		}
692
-	}
693
-
694
-	/**
695
-	 * @param string $path
696
-	 * @return bool|mixed
697
-	 */
698
-	public function unlink($path) {
699
-		if ($path === '' || $path === '/') {
700
-			// do not allow deleting the root
701
-			return false;
702
-		}
703
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
704
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
705
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
706
-		if ($mount and $mount->getInternalPath($absolutePath) === '') {
707
-			return $this->removeMount($mount, $absolutePath);
708
-		}
709
-		if ($this->is_dir($path)) {
710
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
711
-		} else {
712
-			$result = $this->basicOperation('unlink', $path, ['delete']);
713
-		}
714
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
715
-			$storage = $mount->getStorage();
716
-			$internalPath = $mount->getInternalPath($absolutePath);
717
-			$storage->getUpdater()->remove($internalPath);
718
-			return true;
719
-		} else {
720
-			return $result;
721
-		}
722
-	}
723
-
724
-	/**
725
-	 * @param string $directory
726
-	 * @return bool|mixed
727
-	 */
728
-	public function deleteAll($directory) {
729
-		return $this->rmdir($directory);
730
-	}
731
-
732
-	/**
733
-	 * Rename/move a file or folder from the source path to target path.
734
-	 *
735
-	 * @param string $path1 source path
736
-	 * @param string $path2 target path
737
-	 *
738
-	 * @return bool|mixed
739
-	 */
740
-	public function rename($path1, $path2) {
741
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
742
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
743
-		$result = false;
744
-		if (
745
-			Filesystem::isValidPath($path2)
746
-			and Filesystem::isValidPath($path1)
747
-			and !Filesystem::isFileBlacklisted($path2)
748
-		) {
749
-			$path1 = $this->getRelativePath($absolutePath1);
750
-			$path2 = $this->getRelativePath($absolutePath2);
751
-			$exists = $this->file_exists($path2);
752
-
753
-			if ($path1 == null or $path2 == null) {
754
-				return false;
755
-			}
756
-
757
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
758
-			try {
759
-				$this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
760
-
761
-				$run = true;
762
-				if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
763
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
764
-					$this->emit_file_hooks_pre($exists, $path2, $run);
765
-				} elseif ($this->shouldEmitHooks($path1)) {
766
-					\OC_Hook::emit(
767
-						Filesystem::CLASSNAME, Filesystem::signal_rename,
768
-						array(
769
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
770
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
771
-							Filesystem::signal_param_run => &$run
772
-						)
773
-					);
774
-				}
775
-				if ($run) {
776
-					$this->verifyPath(dirname($path2), basename($path2));
777
-
778
-					$manager = Filesystem::getMountManager();
779
-					$mount1 = $this->getMount($path1);
780
-					$mount2 = $this->getMount($path2);
781
-					$storage1 = $mount1->getStorage();
782
-					$storage2 = $mount2->getStorage();
783
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
784
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
785
-
786
-					$this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
787
-					try {
788
-						$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
789
-
790
-						if ($internalPath1 === '') {
791
-							if ($mount1 instanceof MoveableMount) {
792
-								if ($this->isTargetAllowed($absolutePath2)) {
793
-									/**
794
-									 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
795
-									 */
796
-									$sourceMountPoint = $mount1->getMountPoint();
797
-									$result = $mount1->moveMount($absolutePath2);
798
-									$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
799
-								} else {
800
-									$result = false;
801
-								}
802
-							} else {
803
-								$result = false;
804
-							}
805
-							// moving a file/folder within the same mount point
806
-						} elseif ($storage1 === $storage2) {
807
-							if ($storage1) {
808
-								$result = $storage1->rename($internalPath1, $internalPath2);
809
-							} else {
810
-								$result = false;
811
-							}
812
-							// moving a file/folder between storages (from $storage1 to $storage2)
813
-						} else {
814
-							$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
815
-						}
816
-
817
-						if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
818
-							// if it was a rename from a part file to a regular file it was a write and not a rename operation
819
-							$this->writeUpdate($storage2, $internalPath2);
820
-						} else if ($result) {
821
-							if ($internalPath1 !== '') { // don't do a cache update for moved mounts
822
-								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
823
-							}
824
-						}
825
-					} catch(\Exception $e) {
826
-						throw $e;
827
-					} finally {
828
-						$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
829
-						$this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
830
-					}
831
-
832
-					if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
833
-						if ($this->shouldEmitHooks()) {
834
-							$this->emit_file_hooks_post($exists, $path2);
835
-						}
836
-					} elseif ($result) {
837
-						if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
838
-							\OC_Hook::emit(
839
-								Filesystem::CLASSNAME,
840
-								Filesystem::signal_post_rename,
841
-								array(
842
-									Filesystem::signal_param_oldpath => $this->getHookPath($path1),
843
-									Filesystem::signal_param_newpath => $this->getHookPath($path2)
844
-								)
845
-							);
846
-						}
847
-					}
848
-				}
849
-			} catch(\Exception $e) {
850
-				throw $e;
851
-			} finally {
852
-				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
853
-				$this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
854
-			}
855
-		}
856
-		return $result;
857
-	}
858
-
859
-	/**
860
-	 * Copy a file/folder from the source path to target path
861
-	 *
862
-	 * @param string $path1 source path
863
-	 * @param string $path2 target path
864
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
865
-	 *
866
-	 * @return bool|mixed
867
-	 */
868
-	public function copy($path1, $path2, $preserveMtime = false) {
869
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
870
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
871
-		$result = false;
872
-		if (
873
-			Filesystem::isValidPath($path2)
874
-			and Filesystem::isValidPath($path1)
875
-			and !Filesystem::isFileBlacklisted($path2)
876
-		) {
877
-			$path1 = $this->getRelativePath($absolutePath1);
878
-			$path2 = $this->getRelativePath($absolutePath2);
879
-
880
-			if ($path1 == null or $path2 == null) {
881
-				return false;
882
-			}
883
-			$run = true;
884
-
885
-			$this->lockFile($path2, ILockingProvider::LOCK_SHARED);
886
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED);
887
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
888
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
889
-
890
-			try {
891
-
892
-				$exists = $this->file_exists($path2);
893
-				if ($this->shouldEmitHooks()) {
894
-					\OC_Hook::emit(
895
-						Filesystem::CLASSNAME,
896
-						Filesystem::signal_copy,
897
-						array(
898
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
899
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
900
-							Filesystem::signal_param_run => &$run
901
-						)
902
-					);
903
-					$this->emit_file_hooks_pre($exists, $path2, $run);
904
-				}
905
-				if ($run) {
906
-					$mount1 = $this->getMount($path1);
907
-					$mount2 = $this->getMount($path2);
908
-					$storage1 = $mount1->getStorage();
909
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
910
-					$storage2 = $mount2->getStorage();
911
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
912
-
913
-					$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
914
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
915
-
916
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
917
-						if ($storage1) {
918
-							$result = $storage1->copy($internalPath1, $internalPath2);
919
-						} else {
920
-							$result = false;
921
-						}
922
-					} else {
923
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
924
-					}
925
-
926
-					$this->writeUpdate($storage2, $internalPath2);
927
-
928
-					$this->changeLock($path2, ILockingProvider::LOCK_SHARED);
929
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
930
-
931
-					if ($this->shouldEmitHooks() && $result !== false) {
932
-						\OC_Hook::emit(
933
-							Filesystem::CLASSNAME,
934
-							Filesystem::signal_post_copy,
935
-							array(
936
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
937
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
938
-							)
939
-						);
940
-						$this->emit_file_hooks_post($exists, $path2);
941
-					}
942
-
943
-				}
944
-			} catch (\Exception $e) {
945
-				$this->unlockFile($path2, $lockTypePath2);
946
-				$this->unlockFile($path1, $lockTypePath1);
947
-				throw $e;
948
-			}
949
-
950
-			$this->unlockFile($path2, $lockTypePath2);
951
-			$this->unlockFile($path1, $lockTypePath1);
952
-
953
-		}
954
-		return $result;
955
-	}
956
-
957
-	/**
958
-	 * @param string $path
959
-	 * @param string $mode 'r' or 'w'
960
-	 * @return resource
961
-	 */
962
-	public function fopen($path, $mode) {
963
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
964
-		$hooks = array();
965
-		switch ($mode) {
966
-			case 'r':
967
-				$hooks[] = 'read';
968
-				break;
969
-			case 'r+':
970
-			case 'w+':
971
-			case 'x+':
972
-			case 'a+':
973
-				$hooks[] = 'read';
974
-				$hooks[] = 'write';
975
-				break;
976
-			case 'w':
977
-			case 'x':
978
-			case 'a':
979
-				$hooks[] = 'write';
980
-				break;
981
-			default:
982
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
983
-		}
984
-
985
-		if ($mode !== 'r' && $mode !== 'w') {
986
-			\OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
987
-		}
988
-
989
-		return $this->basicOperation('fopen', $path, $hooks, $mode);
990
-	}
991
-
992
-	/**
993
-	 * @param string $path
994
-	 * @return bool|string
995
-	 * @throws \OCP\Files\InvalidPathException
996
-	 */
997
-	public function toTmpFile($path) {
998
-		$this->assertPathLength($path);
999
-		if (Filesystem::isValidPath($path)) {
1000
-			$source = $this->fopen($path, 'r');
1001
-			if ($source) {
1002
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
1003
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1004
-				file_put_contents($tmpFile, $source);
1005
-				return $tmpFile;
1006
-			} else {
1007
-				return false;
1008
-			}
1009
-		} else {
1010
-			return false;
1011
-		}
1012
-	}
1013
-
1014
-	/**
1015
-	 * @param string $tmpFile
1016
-	 * @param string $path
1017
-	 * @return bool|mixed
1018
-	 * @throws \OCP\Files\InvalidPathException
1019
-	 */
1020
-	public function fromTmpFile($tmpFile, $path) {
1021
-		$this->assertPathLength($path);
1022
-		if (Filesystem::isValidPath($path)) {
1023
-
1024
-			// Get directory that the file is going into
1025
-			$filePath = dirname($path);
1026
-
1027
-			// Create the directories if any
1028
-			if (!$this->file_exists($filePath)) {
1029
-				$result = $this->createParentDirectories($filePath);
1030
-				if ($result === false) {
1031
-					return false;
1032
-				}
1033
-			}
1034
-
1035
-			$source = fopen($tmpFile, 'r');
1036
-			if ($source) {
1037
-				$result = $this->file_put_contents($path, $source);
1038
-				// $this->file_put_contents() might have already closed
1039
-				// the resource, so we check it, before trying to close it
1040
-				// to avoid messages in the error log.
1041
-				if (is_resource($source)) {
1042
-					fclose($source);
1043
-				}
1044
-				unlink($tmpFile);
1045
-				return $result;
1046
-			} else {
1047
-				return false;
1048
-			}
1049
-		} else {
1050
-			return false;
1051
-		}
1052
-	}
1053
-
1054
-
1055
-	/**
1056
-	 * @param string $path
1057
-	 * @return mixed
1058
-	 * @throws \OCP\Files\InvalidPathException
1059
-	 */
1060
-	public function getMimeType($path) {
1061
-		$this->assertPathLength($path);
1062
-		return $this->basicOperation('getMimeType', $path);
1063
-	}
1064
-
1065
-	/**
1066
-	 * @param string $type
1067
-	 * @param string $path
1068
-	 * @param bool $raw
1069
-	 * @return bool|null|string
1070
-	 */
1071
-	public function hash($type, $path, $raw = false) {
1072
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1073
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1074
-		if (Filesystem::isValidPath($path)) {
1075
-			$path = $this->getRelativePath($absolutePath);
1076
-			if ($path == null) {
1077
-				return false;
1078
-			}
1079
-			if ($this->shouldEmitHooks($path)) {
1080
-				\OC_Hook::emit(
1081
-					Filesystem::CLASSNAME,
1082
-					Filesystem::signal_read,
1083
-					array(Filesystem::signal_param_path => $this->getHookPath($path))
1084
-				);
1085
-			}
1086
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1087
-			if ($storage) {
1088
-				$result = $storage->hash($type, $internalPath, $raw);
1089
-				return $result;
1090
-			}
1091
-		}
1092
-		return null;
1093
-	}
1094
-
1095
-	/**
1096
-	 * @param string $path
1097
-	 * @return mixed
1098
-	 * @throws \OCP\Files\InvalidPathException
1099
-	 */
1100
-	public function free_space($path = '/') {
1101
-		$this->assertPathLength($path);
1102
-		$result = $this->basicOperation('free_space', $path);
1103
-		if ($result === null) {
1104
-			throw new InvalidPathException();
1105
-		}
1106
-		return $result;
1107
-	}
1108
-
1109
-	/**
1110
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1111
-	 *
1112
-	 * @param string $operation
1113
-	 * @param string $path
1114
-	 * @param array $hooks (optional)
1115
-	 * @param mixed $extraParam (optional)
1116
-	 * @return mixed
1117
-	 * @throws \Exception
1118
-	 *
1119
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1120
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1121
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1122
-	 */
1123
-	private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1124
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1125
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1126
-		if (Filesystem::isValidPath($path)
1127
-			and !Filesystem::isFileBlacklisted($path)
1128
-		) {
1129
-			$path = $this->getRelativePath($absolutePath);
1130
-			if ($path == null) {
1131
-				return false;
1132
-			}
1133
-
1134
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1135
-				// always a shared lock during pre-hooks so the hook can read the file
1136
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1137
-			}
1138
-
1139
-			$run = $this->runHooks($hooks, $path);
1140
-			/** @var \OC\Files\Storage\Storage $storage */
1141
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1142
-			if ($run and $storage) {
1143
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1144
-					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1145
-				}
1146
-				try {
1147
-					if (!is_null($extraParam)) {
1148
-						$result = $storage->$operation($internalPath, $extraParam);
1149
-					} else {
1150
-						$result = $storage->$operation($internalPath);
1151
-					}
1152
-				} catch (\Exception $e) {
1153
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1154
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1155
-					} else if (in_array('read', $hooks)) {
1156
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1157
-					}
1158
-					throw $e;
1159
-				}
1160
-
1161
-				if ($result && in_array('delete', $hooks) and $result) {
1162
-					$this->removeUpdate($storage, $internalPath);
1163
-				}
1164
-				if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1165
-					$this->writeUpdate($storage, $internalPath);
1166
-				}
1167
-				if ($result && in_array('touch', $hooks)) {
1168
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1169
-				}
1170
-
1171
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1172
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1173
-				}
1174
-
1175
-				$unlockLater = false;
1176
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1177
-					$unlockLater = true;
1178
-					// make sure our unlocking callback will still be called if connection is aborted
1179
-					ignore_user_abort(true);
1180
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1181
-						if (in_array('write', $hooks)) {
1182
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1183
-						} else if (in_array('read', $hooks)) {
1184
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1185
-						}
1186
-					});
1187
-				}
1188
-
1189
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1190
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1191
-						$this->runHooks($hooks, $path, true);
1192
-					}
1193
-				}
1194
-
1195
-				if (!$unlockLater
1196
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1197
-				) {
1198
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1199
-				}
1200
-				return $result;
1201
-			} else {
1202
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1203
-			}
1204
-		}
1205
-		return null;
1206
-	}
1207
-
1208
-	/**
1209
-	 * get the path relative to the default root for hook usage
1210
-	 *
1211
-	 * @param string $path
1212
-	 * @return string
1213
-	 */
1214
-	private function getHookPath($path) {
1215
-		if (!Filesystem::getView()) {
1216
-			return $path;
1217
-		}
1218
-		return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1219
-	}
1220
-
1221
-	private function shouldEmitHooks($path = '') {
1222
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1223
-			return false;
1224
-		}
1225
-		if (!Filesystem::$loaded) {
1226
-			return false;
1227
-		}
1228
-		$defaultRoot = Filesystem::getRoot();
1229
-		if ($defaultRoot === null) {
1230
-			return false;
1231
-		}
1232
-		if ($this->fakeRoot === $defaultRoot) {
1233
-			return true;
1234
-		}
1235
-		$fullPath = $this->getAbsolutePath($path);
1236
-
1237
-		if ($fullPath === $defaultRoot) {
1238
-			return true;
1239
-		}
1240
-
1241
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1242
-	}
1243
-
1244
-	/**
1245
-	 * @param string[] $hooks
1246
-	 * @param string $path
1247
-	 * @param bool $post
1248
-	 * @return bool
1249
-	 */
1250
-	private function runHooks($hooks, $path, $post = false) {
1251
-		$relativePath = $path;
1252
-		$path = $this->getHookPath($path);
1253
-		$prefix = ($post) ? 'post_' : '';
1254
-		$run = true;
1255
-		if ($this->shouldEmitHooks($relativePath)) {
1256
-			foreach ($hooks as $hook) {
1257
-				if ($hook != 'read') {
1258
-					\OC_Hook::emit(
1259
-						Filesystem::CLASSNAME,
1260
-						$prefix . $hook,
1261
-						array(
1262
-							Filesystem::signal_param_run => &$run,
1263
-							Filesystem::signal_param_path => $path
1264
-						)
1265
-					);
1266
-				} elseif (!$post) {
1267
-					\OC_Hook::emit(
1268
-						Filesystem::CLASSNAME,
1269
-						$prefix . $hook,
1270
-						array(
1271
-							Filesystem::signal_param_path => $path
1272
-						)
1273
-					);
1274
-				}
1275
-			}
1276
-		}
1277
-		return $run;
1278
-	}
1279
-
1280
-	/**
1281
-	 * check if a file or folder has been updated since $time
1282
-	 *
1283
-	 * @param string $path
1284
-	 * @param int $time
1285
-	 * @return bool
1286
-	 */
1287
-	public function hasUpdated($path, $time) {
1288
-		return $this->basicOperation('hasUpdated', $path, array(), $time);
1289
-	}
1290
-
1291
-	/**
1292
-	 * @param string $ownerId
1293
-	 * @return \OC\User\User
1294
-	 */
1295
-	private function getUserObjectForOwner($ownerId) {
1296
-		$owner = $this->userManager->get($ownerId);
1297
-		if ($owner instanceof IUser) {
1298
-			return $owner;
1299
-		} else {
1300
-			return new User($ownerId, null);
1301
-		}
1302
-	}
1303
-
1304
-	/**
1305
-	 * Get file info from cache
1306
-	 *
1307
-	 * If the file is not in cached it will be scanned
1308
-	 * If the file has changed on storage the cache will be updated
1309
-	 *
1310
-	 * @param \OC\Files\Storage\Storage $storage
1311
-	 * @param string $internalPath
1312
-	 * @param string $relativePath
1313
-	 * @return ICacheEntry|bool
1314
-	 */
1315
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1316
-		$cache = $storage->getCache($internalPath);
1317
-		$data = $cache->get($internalPath);
1318
-		$watcher = $storage->getWatcher($internalPath);
1319
-
1320
-		try {
1321
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1322
-			if (!$data || $data['size'] === -1) {
1323
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1324
-				if (!$storage->file_exists($internalPath)) {
1325
-					$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1326
-					return false;
1327
-				}
1328
-				$scanner = $storage->getScanner($internalPath);
1329
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1330
-				$data = $cache->get($internalPath);
1331
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1332
-			} else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1333
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1334
-				$watcher->update($internalPath, $data);
1335
-				$storage->getPropagator()->propagateChange($internalPath, time());
1336
-				$data = $cache->get($internalPath);
1337
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1338
-			}
1339
-		} catch (LockedException $e) {
1340
-			// if the file is locked we just use the old cache info
1341
-		}
1342
-
1343
-		return $data;
1344
-	}
1345
-
1346
-	/**
1347
-	 * get the filesystem info
1348
-	 *
1349
-	 * @param string $path
1350
-	 * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1351
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1352
-	 * defaults to true
1353
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1354
-	 */
1355
-	public function getFileInfo($path, $includeMountPoints = true) {
1356
-		$this->assertPathLength($path);
1357
-		if (!Filesystem::isValidPath($path)) {
1358
-			return false;
1359
-		}
1360
-		if (Cache\Scanner::isPartialFile($path)) {
1361
-			return $this->getPartFileInfo($path);
1362
-		}
1363
-		$relativePath = $path;
1364
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1365
-
1366
-		$mount = Filesystem::getMountManager()->find($path);
1367
-		$storage = $mount->getStorage();
1368
-		$internalPath = $mount->getInternalPath($path);
1369
-		if ($storage) {
1370
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1371
-
1372
-			if (!$data instanceof ICacheEntry) {
1373
-				return false;
1374
-			}
1375
-
1376
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1377
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1378
-			}
1379
-
1380
-			$owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1381
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1382
-
1383
-			if ($data and isset($data['fileid'])) {
1384
-				if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1385
-					//add the sizes of other mount points to the folder
1386
-					$extOnly = ($includeMountPoints === 'ext');
1387
-					$mounts = Filesystem::getMountManager()->findIn($path);
1388
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1389
-						$subStorage = $mount->getStorage();
1390
-						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1391
-					}));
1392
-				}
1393
-			}
1394
-
1395
-			return $info;
1396
-		}
1397
-
1398
-		return false;
1399
-	}
1400
-
1401
-	/**
1402
-	 * get the content of a directory
1403
-	 *
1404
-	 * @param string $directory path under datadirectory
1405
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1406
-	 * @return FileInfo[]
1407
-	 */
1408
-	public function getDirectoryContent($directory, $mimetype_filter = '') {
1409
-		$this->assertPathLength($directory);
1410
-		if (!Filesystem::isValidPath($directory)) {
1411
-			return [];
1412
-		}
1413
-		$path = $this->getAbsolutePath($directory);
1414
-		$path = Filesystem::normalizePath($path);
1415
-		$mount = $this->getMount($directory);
1416
-		$storage = $mount->getStorage();
1417
-		$internalPath = $mount->getInternalPath($path);
1418
-		if ($storage) {
1419
-			$cache = $storage->getCache($internalPath);
1420
-			$user = \OC_User::getUser();
1421
-
1422
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1423
-
1424
-			if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1425
-				return [];
1426
-			}
1427
-
1428
-			$folderId = $data['fileid'];
1429
-			$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1430
-
1431
-			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1432
-			/**
1433
-			 * @var \OC\Files\FileInfo[] $files
1434
-			 */
1435
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1436
-				if ($sharingDisabled) {
1437
-					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1438
-				}
1439
-				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1440
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1441
-			}, $contents);
1442
-
1443
-			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1444
-			$mounts = Filesystem::getMountManager()->findIn($path);
1445
-			$dirLength = strlen($path);
1446
-			foreach ($mounts as $mount) {
1447
-				$mountPoint = $mount->getMountPoint();
1448
-				$subStorage = $mount->getStorage();
1449
-				if ($subStorage) {
1450
-					$subCache = $subStorage->getCache('');
1451
-
1452
-					$rootEntry = $subCache->get('');
1453
-					if (!$rootEntry) {
1454
-						$subScanner = $subStorage->getScanner('');
1455
-						try {
1456
-							$subScanner->scanFile('');
1457
-						} catch (\OCP\Files\StorageNotAvailableException $e) {
1458
-							continue;
1459
-						} catch (\OCP\Files\StorageInvalidException $e) {
1460
-							continue;
1461
-						} catch (\Exception $e) {
1462
-							// sometimes when the storage is not available it can be any exception
1463
-							\OCP\Util::writeLog(
1464
-								'core',
1465
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1466
-								get_class($e) . ': ' . $e->getMessage(),
1467
-								\OCP\Util::ERROR
1468
-							);
1469
-							continue;
1470
-						}
1471
-						$rootEntry = $subCache->get('');
1472
-					}
1473
-
1474
-					if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1475
-						$relativePath = trim(substr($mountPoint, $dirLength), '/');
1476
-						if ($pos = strpos($relativePath, '/')) {
1477
-							//mountpoint inside subfolder add size to the correct folder
1478
-							$entryName = substr($relativePath, 0, $pos);
1479
-							foreach ($files as &$entry) {
1480
-								if ($entry->getName() === $entryName) {
1481
-									$entry->addSubEntry($rootEntry, $mountPoint);
1482
-								}
1483
-							}
1484
-						} else { //mountpoint in this folder, add an entry for it
1485
-							$rootEntry['name'] = $relativePath;
1486
-							$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1487
-							$permissions = $rootEntry['permissions'];
1488
-							// do not allow renaming/deleting the mount point if they are not shared files/folders
1489
-							// for shared files/folders we use the permissions given by the owner
1490
-							if ($mount instanceof MoveableMount) {
1491
-								$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1492
-							} else {
1493
-								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1494
-							}
1495
-
1496
-							//remove any existing entry with the same name
1497
-							foreach ($files as $i => $file) {
1498
-								if ($file['name'] === $rootEntry['name']) {
1499
-									unset($files[$i]);
1500
-									break;
1501
-								}
1502
-							}
1503
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1504
-
1505
-							// if sharing was disabled for the user we remove the share permissions
1506
-							if (\OCP\Util::isSharingDisabledForUser()) {
1507
-								$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1508
-							}
1509
-
1510
-							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1511
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1512
-						}
1513
-					}
1514
-				}
1515
-			}
1516
-
1517
-			if ($mimetype_filter) {
1518
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1519
-					if (strpos($mimetype_filter, '/')) {
1520
-						return $file->getMimetype() === $mimetype_filter;
1521
-					} else {
1522
-						return $file->getMimePart() === $mimetype_filter;
1523
-					}
1524
-				});
1525
-			}
1526
-
1527
-			return $files;
1528
-		} else {
1529
-			return [];
1530
-		}
1531
-	}
1532
-
1533
-	/**
1534
-	 * change file metadata
1535
-	 *
1536
-	 * @param string $path
1537
-	 * @param array|\OCP\Files\FileInfo $data
1538
-	 * @return int
1539
-	 *
1540
-	 * returns the fileid of the updated file
1541
-	 */
1542
-	public function putFileInfo($path, $data) {
1543
-		$this->assertPathLength($path);
1544
-		if ($data instanceof FileInfo) {
1545
-			$data = $data->getData();
1546
-		}
1547
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1548
-		/**
1549
-		 * @var \OC\Files\Storage\Storage $storage
1550
-		 * @var string $internalPath
1551
-		 */
1552
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
1553
-		if ($storage) {
1554
-			$cache = $storage->getCache($path);
1555
-
1556
-			if (!$cache->inCache($internalPath)) {
1557
-				$scanner = $storage->getScanner($internalPath);
1558
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1559
-			}
1560
-
1561
-			return $cache->put($internalPath, $data);
1562
-		} else {
1563
-			return -1;
1564
-		}
1565
-	}
1566
-
1567
-	/**
1568
-	 * search for files with the name matching $query
1569
-	 *
1570
-	 * @param string $query
1571
-	 * @return FileInfo[]
1572
-	 */
1573
-	public function search($query) {
1574
-		return $this->searchCommon('search', array('%' . $query . '%'));
1575
-	}
1576
-
1577
-	/**
1578
-	 * search for files with the name matching $query
1579
-	 *
1580
-	 * @param string $query
1581
-	 * @return FileInfo[]
1582
-	 */
1583
-	public function searchRaw($query) {
1584
-		return $this->searchCommon('search', array($query));
1585
-	}
1586
-
1587
-	/**
1588
-	 * search for files by mimetype
1589
-	 *
1590
-	 * @param string $mimetype
1591
-	 * @return FileInfo[]
1592
-	 */
1593
-	public function searchByMime($mimetype) {
1594
-		return $this->searchCommon('searchByMime', array($mimetype));
1595
-	}
1596
-
1597
-	/**
1598
-	 * search for files by tag
1599
-	 *
1600
-	 * @param string|int $tag name or tag id
1601
-	 * @param string $userId owner of the tags
1602
-	 * @return FileInfo[]
1603
-	 */
1604
-	public function searchByTag($tag, $userId) {
1605
-		return $this->searchCommon('searchByTag', array($tag, $userId));
1606
-	}
1607
-
1608
-	/**
1609
-	 * @param string $method cache method
1610
-	 * @param array $args
1611
-	 * @return FileInfo[]
1612
-	 */
1613
-	private function searchCommon($method, $args) {
1614
-		$files = array();
1615
-		$rootLength = strlen($this->fakeRoot);
1616
-
1617
-		$mount = $this->getMount('');
1618
-		$mountPoint = $mount->getMountPoint();
1619
-		$storage = $mount->getStorage();
1620
-		if ($storage) {
1621
-			$cache = $storage->getCache('');
1622
-
1623
-			$results = call_user_func_array(array($cache, $method), $args);
1624
-			foreach ($results as $result) {
1625
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1626
-					$internalPath = $result['path'];
1627
-					$path = $mountPoint . $result['path'];
1628
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1629
-					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1630
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1631
-				}
1632
-			}
1633
-
1634
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1635
-			foreach ($mounts as $mount) {
1636
-				$mountPoint = $mount->getMountPoint();
1637
-				$storage = $mount->getStorage();
1638
-				if ($storage) {
1639
-					$cache = $storage->getCache('');
1640
-
1641
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1642
-					$results = call_user_func_array(array($cache, $method), $args);
1643
-					if ($results) {
1644
-						foreach ($results as $result) {
1645
-							$internalPath = $result['path'];
1646
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1647
-							$path = rtrim($mountPoint . $internalPath, '/');
1648
-							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1649
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1650
-						}
1651
-					}
1652
-				}
1653
-			}
1654
-		}
1655
-		return $files;
1656
-	}
1657
-
1658
-	/**
1659
-	 * Get the owner for a file or folder
1660
-	 *
1661
-	 * @param string $path
1662
-	 * @return string the user id of the owner
1663
-	 * @throws NotFoundException
1664
-	 */
1665
-	public function getOwner($path) {
1666
-		$info = $this->getFileInfo($path);
1667
-		if (!$info) {
1668
-			throw new NotFoundException($path . ' not found while trying to get owner');
1669
-		}
1670
-		return $info->getOwner()->getUID();
1671
-	}
1672
-
1673
-	/**
1674
-	 * get the ETag for a file or folder
1675
-	 *
1676
-	 * @param string $path
1677
-	 * @return string
1678
-	 */
1679
-	public function getETag($path) {
1680
-		/**
1681
-		 * @var Storage\Storage $storage
1682
-		 * @var string $internalPath
1683
-		 */
1684
-		list($storage, $internalPath) = $this->resolvePath($path);
1685
-		if ($storage) {
1686
-			return $storage->getETag($internalPath);
1687
-		} else {
1688
-			return null;
1689
-		}
1690
-	}
1691
-
1692
-	/**
1693
-	 * Get the path of a file by id, relative to the view
1694
-	 *
1695
-	 * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1696
-	 *
1697
-	 * @param int $id
1698
-	 * @throws NotFoundException
1699
-	 * @return string
1700
-	 */
1701
-	public function getPath($id) {
1702
-		$id = (int)$id;
1703
-		$manager = Filesystem::getMountManager();
1704
-		$mounts = $manager->findIn($this->fakeRoot);
1705
-		$mounts[] = $manager->find($this->fakeRoot);
1706
-		// reverse the array so we start with the storage this view is in
1707
-		// which is the most likely to contain the file we're looking for
1708
-		$mounts = array_reverse($mounts);
1709
-		foreach ($mounts as $mount) {
1710
-			/**
1711
-			 * @var \OC\Files\Mount\MountPoint $mount
1712
-			 */
1713
-			if ($mount->getStorage()) {
1714
-				$cache = $mount->getStorage()->getCache();
1715
-				$internalPath = $cache->getPathById($id);
1716
-				if (is_string($internalPath)) {
1717
-					$fullPath = $mount->getMountPoint() . $internalPath;
1718
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1719
-						return $path;
1720
-					}
1721
-				}
1722
-			}
1723
-		}
1724
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1725
-	}
1726
-
1727
-	/**
1728
-	 * @param string $path
1729
-	 * @throws InvalidPathException
1730
-	 */
1731
-	private function assertPathLength($path) {
1732
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1733
-		// Check for the string length - performed using isset() instead of strlen()
1734
-		// because isset() is about 5x-40x faster.
1735
-		if (isset($path[$maxLen])) {
1736
-			$pathLen = strlen($path);
1737
-			throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1738
-		}
1739
-	}
1740
-
1741
-	/**
1742
-	 * check if it is allowed to move a mount point to a given target.
1743
-	 * It is not allowed to move a mount point into a different mount point or
1744
-	 * into an already shared folder
1745
-	 *
1746
-	 * @param string $target path
1747
-	 * @return boolean
1748
-	 */
1749
-	private function isTargetAllowed($target) {
1750
-
1751
-		list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1752
-		if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1753
-			\OCP\Util::writeLog('files',
1754
-				'It is not allowed to move one mount point into another one',
1755
-				\OCP\Util::DEBUG);
1756
-			return false;
1757
-		}
1758
-
1759
-		// note: cannot use the view because the target is already locked
1760
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1761
-		if ($fileId === -1) {
1762
-			// target might not exist, need to check parent instead
1763
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1764
-		}
1765
-
1766
-		// check if any of the parents were shared by the current owner (include collections)
1767
-		$shares = \OCP\Share::getItemShared(
1768
-			'folder',
1769
-			$fileId,
1770
-			\OCP\Share::FORMAT_NONE,
1771
-			null,
1772
-			true
1773
-		);
1774
-
1775
-		if (count($shares) > 0) {
1776
-			\OCP\Util::writeLog('files',
1777
-				'It is not allowed to move one mount point into a shared folder',
1778
-				\OCP\Util::DEBUG);
1779
-			return false;
1780
-		}
1781
-
1782
-		return true;
1783
-	}
1784
-
1785
-	/**
1786
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1787
-	 *
1788
-	 * @param string $path
1789
-	 * @return \OCP\Files\FileInfo
1790
-	 */
1791
-	private function getPartFileInfo($path) {
1792
-		$mount = $this->getMount($path);
1793
-		$storage = $mount->getStorage();
1794
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1795
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1796
-		return new FileInfo(
1797
-			$this->getAbsolutePath($path),
1798
-			$storage,
1799
-			$internalPath,
1800
-			[
1801
-				'fileid' => null,
1802
-				'mimetype' => $storage->getMimeType($internalPath),
1803
-				'name' => basename($path),
1804
-				'etag' => null,
1805
-				'size' => $storage->filesize($internalPath),
1806
-				'mtime' => $storage->filemtime($internalPath),
1807
-				'encrypted' => false,
1808
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1809
-			],
1810
-			$mount,
1811
-			$owner
1812
-		);
1813
-	}
1814
-
1815
-	/**
1816
-	 * @param string $path
1817
-	 * @param string $fileName
1818
-	 * @throws InvalidPathException
1819
-	 */
1820
-	public function verifyPath($path, $fileName) {
1821
-		try {
1822
-			/** @type \OCP\Files\Storage $storage */
1823
-			list($storage, $internalPath) = $this->resolvePath($path);
1824
-			$storage->verifyPath($internalPath, $fileName);
1825
-		} catch (ReservedWordException $ex) {
1826
-			$l = \OC::$server->getL10N('lib');
1827
-			throw new InvalidPathException($l->t('File name is a reserved word'));
1828
-		} catch (InvalidCharacterInPathException $ex) {
1829
-			$l = \OC::$server->getL10N('lib');
1830
-			throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1831
-		} catch (FileNameTooLongException $ex) {
1832
-			$l = \OC::$server->getL10N('lib');
1833
-			throw new InvalidPathException($l->t('File name is too long'));
1834
-		} catch (InvalidDirectoryException $ex) {
1835
-			$l = \OC::$server->getL10N('lib');
1836
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1837
-		} catch (EmptyFileNameException $ex) {
1838
-			$l = \OC::$server->getL10N('lib');
1839
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1840
-		}
1841
-	}
1842
-
1843
-	/**
1844
-	 * get all parent folders of $path
1845
-	 *
1846
-	 * @param string $path
1847
-	 * @return string[]
1848
-	 */
1849
-	private function getParents($path) {
1850
-		$path = trim($path, '/');
1851
-		if (!$path) {
1852
-			return [];
1853
-		}
1854
-
1855
-		$parts = explode('/', $path);
1856
-
1857
-		// remove the single file
1858
-		array_pop($parts);
1859
-		$result = array('/');
1860
-		$resultPath = '';
1861
-		foreach ($parts as $part) {
1862
-			if ($part) {
1863
-				$resultPath .= '/' . $part;
1864
-				$result[] = $resultPath;
1865
-			}
1866
-		}
1867
-		return $result;
1868
-	}
1869
-
1870
-	/**
1871
-	 * Returns the mount point for which to lock
1872
-	 *
1873
-	 * @param string $absolutePath absolute path
1874
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1875
-	 * is mounted directly on the given path, false otherwise
1876
-	 * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1877
-	 */
1878
-	private function getMountForLock($absolutePath, $useParentMount = false) {
1879
-		$results = [];
1880
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1881
-		if (!$mount) {
1882
-			return $results;
1883
-		}
1884
-
1885
-		if ($useParentMount) {
1886
-			// find out if something is mounted directly on the path
1887
-			$internalPath = $mount->getInternalPath($absolutePath);
1888
-			if ($internalPath === '') {
1889
-				// resolve the parent mount instead
1890
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1891
-			}
1892
-		}
1893
-
1894
-		return $mount;
1895
-	}
1896
-
1897
-	/**
1898
-	 * Lock the given path
1899
-	 *
1900
-	 * @param string $path the path of the file to lock, relative to the view
1901
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1902
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1903
-	 *
1904
-	 * @return bool False if the path is excluded from locking, true otherwise
1905
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1906
-	 */
1907
-	private function lockPath($path, $type, $lockMountPoint = false) {
1908
-		$absolutePath = $this->getAbsolutePath($path);
1909
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1910
-		if (!$this->shouldLockFile($absolutePath)) {
1911
-			return false;
1912
-		}
1913
-
1914
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1915
-		if ($mount) {
1916
-			try {
1917
-				$storage = $mount->getStorage();
1918
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1919
-					$storage->acquireLock(
1920
-						$mount->getInternalPath($absolutePath),
1921
-						$type,
1922
-						$this->lockingProvider
1923
-					);
1924
-				}
1925
-			} catch (\OCP\Lock\LockedException $e) {
1926
-				// rethrow with the a human-readable path
1927
-				throw new \OCP\Lock\LockedException(
1928
-					$this->getPathRelativeToFiles($absolutePath),
1929
-					$e
1930
-				);
1931
-			}
1932
-		}
1933
-
1934
-		return true;
1935
-	}
1936
-
1937
-	/**
1938
-	 * Change the lock type
1939
-	 *
1940
-	 * @param string $path the path of the file to lock, relative to the view
1941
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1942
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1943
-	 *
1944
-	 * @return bool False if the path is excluded from locking, true otherwise
1945
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1946
-	 */
1947
-	public function changeLock($path, $type, $lockMountPoint = false) {
1948
-		$path = Filesystem::normalizePath($path);
1949
-		$absolutePath = $this->getAbsolutePath($path);
1950
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1951
-		if (!$this->shouldLockFile($absolutePath)) {
1952
-			return false;
1953
-		}
1954
-
1955
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1956
-		if ($mount) {
1957
-			try {
1958
-				$storage = $mount->getStorage();
1959
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1960
-					$storage->changeLock(
1961
-						$mount->getInternalPath($absolutePath),
1962
-						$type,
1963
-						$this->lockingProvider
1964
-					);
1965
-				}
1966
-			} catch (\OCP\Lock\LockedException $e) {
1967
-				try {
1968
-					// rethrow with the a human-readable path
1969
-					throw new \OCP\Lock\LockedException(
1970
-						$this->getPathRelativeToFiles($absolutePath),
1971
-						$e
1972
-					);
1973
-				} catch (\InvalidArgumentException $e) {
1974
-					throw new \OCP\Lock\LockedException(
1975
-						$absolutePath,
1976
-						$e
1977
-					);
1978
-				}
1979
-			}
1980
-		}
1981
-
1982
-		return true;
1983
-	}
1984
-
1985
-	/**
1986
-	 * Unlock the given path
1987
-	 *
1988
-	 * @param string $path the path of the file to unlock, relative to the view
1989
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1990
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1991
-	 *
1992
-	 * @return bool False if the path is excluded from locking, true otherwise
1993
-	 */
1994
-	private function unlockPath($path, $type, $lockMountPoint = false) {
1995
-		$absolutePath = $this->getAbsolutePath($path);
1996
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1997
-		if (!$this->shouldLockFile($absolutePath)) {
1998
-			return false;
1999
-		}
2000
-
2001
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2002
-		if ($mount) {
2003
-			$storage = $mount->getStorage();
2004
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2005
-				$storage->releaseLock(
2006
-					$mount->getInternalPath($absolutePath),
2007
-					$type,
2008
-					$this->lockingProvider
2009
-				);
2010
-			}
2011
-		}
2012
-
2013
-		return true;
2014
-	}
2015
-
2016
-	/**
2017
-	 * Lock a path and all its parents up to the root of the view
2018
-	 *
2019
-	 * @param string $path the path of the file to lock relative to the view
2020
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2021
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2022
-	 *
2023
-	 * @return bool False if the path is excluded from locking, true otherwise
2024
-	 */
2025
-	public function lockFile($path, $type, $lockMountPoint = false) {
2026
-		$absolutePath = $this->getAbsolutePath($path);
2027
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2028
-		if (!$this->shouldLockFile($absolutePath)) {
2029
-			return false;
2030
-		}
2031
-
2032
-		$this->lockPath($path, $type, $lockMountPoint);
2033
-
2034
-		$parents = $this->getParents($path);
2035
-		foreach ($parents as $parent) {
2036
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2037
-		}
2038
-
2039
-		return true;
2040
-	}
2041
-
2042
-	/**
2043
-	 * Unlock a path and all its parents up to the root of the view
2044
-	 *
2045
-	 * @param string $path the path of the file to lock relative to the view
2046
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2047
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2048
-	 *
2049
-	 * @return bool False if the path is excluded from locking, true otherwise
2050
-	 */
2051
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2052
-		$absolutePath = $this->getAbsolutePath($path);
2053
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2054
-		if (!$this->shouldLockFile($absolutePath)) {
2055
-			return false;
2056
-		}
2057
-
2058
-		$this->unlockPath($path, $type, $lockMountPoint);
2059
-
2060
-		$parents = $this->getParents($path);
2061
-		foreach ($parents as $parent) {
2062
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2063
-		}
2064
-
2065
-		return true;
2066
-	}
2067
-
2068
-	/**
2069
-	 * Only lock files in data/user/files/
2070
-	 *
2071
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2072
-	 * @return bool
2073
-	 */
2074
-	protected function shouldLockFile($path) {
2075
-		$path = Filesystem::normalizePath($path);
2076
-
2077
-		$pathSegments = explode('/', $path);
2078
-		if (isset($pathSegments[2])) {
2079
-			// E.g.: /username/files/path-to-file
2080
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2081
-		}
2082
-
2083
-		return strpos($path, '/appdata_') !== 0;
2084
-	}
2085
-
2086
-	/**
2087
-	 * Shortens the given absolute path to be relative to
2088
-	 * "$user/files".
2089
-	 *
2090
-	 * @param string $absolutePath absolute path which is under "files"
2091
-	 *
2092
-	 * @return string path relative to "files" with trimmed slashes or null
2093
-	 * if the path was NOT relative to files
2094
-	 *
2095
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2096
-	 * @since 8.1.0
2097
-	 */
2098
-	public function getPathRelativeToFiles($absolutePath) {
2099
-		$path = Filesystem::normalizePath($absolutePath);
2100
-		$parts = explode('/', trim($path, '/'), 3);
2101
-		// "$user", "files", "path/to/dir"
2102
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2103
-			$this->logger->error(
2104
-				'$absolutePath must be relative to "files", value is "%s"',
2105
-				[
2106
-					$absolutePath
2107
-				]
2108
-			);
2109
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2110
-		}
2111
-		if (isset($parts[2])) {
2112
-			return $parts[2];
2113
-		}
2114
-		return '';
2115
-	}
2116
-
2117
-	/**
2118
-	 * @param string $filename
2119
-	 * @return array
2120
-	 * @throws \OC\User\NoUserException
2121
-	 * @throws NotFoundException
2122
-	 */
2123
-	public function getUidAndFilename($filename) {
2124
-		$info = $this->getFileInfo($filename);
2125
-		if (!$info instanceof \OCP\Files\FileInfo) {
2126
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2127
-		}
2128
-		$uid = $info->getOwner()->getUID();
2129
-		if ($uid != \OCP\User::getUser()) {
2130
-			Filesystem::initMountPoints($uid);
2131
-			$ownerView = new View('/' . $uid . '/files');
2132
-			try {
2133
-				$filename = $ownerView->getPath($info['fileid']);
2134
-			} catch (NotFoundException $e) {
2135
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2136
-			}
2137
-		}
2138
-		return [$uid, $filename];
2139
-	}
2140
-
2141
-	/**
2142
-	 * Creates parent non-existing folders
2143
-	 *
2144
-	 * @param string $filePath
2145
-	 * @return bool
2146
-	 */
2147
-	private function createParentDirectories($filePath) {
2148
-		$directoryParts = explode('/', $filePath);
2149
-		$directoryParts = array_filter($directoryParts);
2150
-		foreach ($directoryParts as $key => $part) {
2151
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2152
-			$currentPath = '/' . implode('/', $currentPathElements);
2153
-			if ($this->is_file($currentPath)) {
2154
-				return false;
2155
-			}
2156
-			if (!$this->file_exists($currentPath)) {
2157
-				$this->mkdir($currentPath);
2158
-			}
2159
-		}
2160
-
2161
-		return true;
2162
-	}
85
+    /** @var string */
86
+    private $fakeRoot = '';
87
+
88
+    /**
89
+     * @var \OCP\Lock\ILockingProvider
90
+     */
91
+    protected $lockingProvider;
92
+
93
+    private $lockingEnabled;
94
+
95
+    private $updaterEnabled = true;
96
+
97
+    /** @var \OC\User\Manager */
98
+    private $userManager;
99
+
100
+    /** @var \OCP\ILogger */
101
+    private $logger;
102
+
103
+    /**
104
+     * @param string $root
105
+     * @throws \Exception If $root contains an invalid path
106
+     */
107
+    public function __construct($root = '') {
108
+        if (is_null($root)) {
109
+            throw new \InvalidArgumentException('Root can\'t be null');
110
+        }
111
+        if (!Filesystem::isValidPath($root)) {
112
+            throw new \Exception();
113
+        }
114
+
115
+        $this->fakeRoot = $root;
116
+        $this->lockingProvider = \OC::$server->getLockingProvider();
117
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
118
+        $this->userManager = \OC::$server->getUserManager();
119
+        $this->logger = \OC::$server->getLogger();
120
+    }
121
+
122
+    public function getAbsolutePath($path = '/') {
123
+        if ($path === null) {
124
+            return null;
125
+        }
126
+        $this->assertPathLength($path);
127
+        if ($path === '') {
128
+            $path = '/';
129
+        }
130
+        if ($path[0] !== '/') {
131
+            $path = '/' . $path;
132
+        }
133
+        return $this->fakeRoot . $path;
134
+    }
135
+
136
+    /**
137
+     * change the root to a fake root
138
+     *
139
+     * @param string $fakeRoot
140
+     * @return boolean|null
141
+     */
142
+    public function chroot($fakeRoot) {
143
+        if (!$fakeRoot == '') {
144
+            if ($fakeRoot[0] !== '/') {
145
+                $fakeRoot = '/' . $fakeRoot;
146
+            }
147
+        }
148
+        $this->fakeRoot = $fakeRoot;
149
+    }
150
+
151
+    /**
152
+     * get the fake root
153
+     *
154
+     * @return string
155
+     */
156
+    public function getRoot() {
157
+        return $this->fakeRoot;
158
+    }
159
+
160
+    /**
161
+     * get path relative to the root of the view
162
+     *
163
+     * @param string $path
164
+     * @return string
165
+     */
166
+    public function getRelativePath($path) {
167
+        $this->assertPathLength($path);
168
+        if ($this->fakeRoot == '') {
169
+            return $path;
170
+        }
171
+
172
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
173
+            return '/';
174
+        }
175
+
176
+        // missing slashes can cause wrong matches!
177
+        $root = rtrim($this->fakeRoot, '/') . '/';
178
+
179
+        if (strpos($path, $root) !== 0) {
180
+            return null;
181
+        } else {
182
+            $path = substr($path, strlen($this->fakeRoot));
183
+            if (strlen($path) === 0) {
184
+                return '/';
185
+            } else {
186
+                return $path;
187
+            }
188
+        }
189
+    }
190
+
191
+    /**
192
+     * get the mountpoint of the storage object for a path
193
+     * ( note: because a storage is not always mounted inside the fakeroot, the
194
+     * returned mountpoint is relative to the absolute root of the filesystem
195
+     * and does not take the chroot into account )
196
+     *
197
+     * @param string $path
198
+     * @return string
199
+     */
200
+    public function getMountPoint($path) {
201
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
202
+    }
203
+
204
+    /**
205
+     * get the mountpoint of the storage object for a path
206
+     * ( note: because a storage is not always mounted inside the fakeroot, the
207
+     * returned mountpoint is relative to the absolute root of the filesystem
208
+     * and does not take the chroot into account )
209
+     *
210
+     * @param string $path
211
+     * @return \OCP\Files\Mount\IMountPoint
212
+     */
213
+    public function getMount($path) {
214
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
215
+    }
216
+
217
+    /**
218
+     * resolve a path to a storage and internal path
219
+     *
220
+     * @param string $path
221
+     * @return array an array consisting of the storage and the internal path
222
+     */
223
+    public function resolvePath($path) {
224
+        $a = $this->getAbsolutePath($path);
225
+        $p = Filesystem::normalizePath($a);
226
+        return Filesystem::resolvePath($p);
227
+    }
228
+
229
+    /**
230
+     * return the path to a local version of the file
231
+     * we need this because we can't know if a file is stored local or not from
232
+     * outside the filestorage and for some purposes a local file is needed
233
+     *
234
+     * @param string $path
235
+     * @return string
236
+     */
237
+    public function getLocalFile($path) {
238
+        $parent = substr($path, 0, strrpos($path, '/'));
239
+        $path = $this->getAbsolutePath($path);
240
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
241
+        if (Filesystem::isValidPath($parent) and $storage) {
242
+            return $storage->getLocalFile($internalPath);
243
+        } else {
244
+            return null;
245
+        }
246
+    }
247
+
248
+    /**
249
+     * @param string $path
250
+     * @return string
251
+     */
252
+    public function getLocalFolder($path) {
253
+        $parent = substr($path, 0, strrpos($path, '/'));
254
+        $path = $this->getAbsolutePath($path);
255
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
256
+        if (Filesystem::isValidPath($parent) and $storage) {
257
+            return $storage->getLocalFolder($internalPath);
258
+        } else {
259
+            return null;
260
+        }
261
+    }
262
+
263
+    /**
264
+     * the following functions operate with arguments and return values identical
265
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
266
+     * for \OC\Files\Storage\Storage via basicOperation().
267
+     */
268
+    public function mkdir($path) {
269
+        return $this->basicOperation('mkdir', $path, array('create', 'write'));
270
+    }
271
+
272
+    /**
273
+     * remove mount point
274
+     *
275
+     * @param \OC\Files\Mount\MoveableMount $mount
276
+     * @param string $path relative to data/
277
+     * @return boolean
278
+     */
279
+    protected function removeMount($mount, $path) {
280
+        if ($mount instanceof MoveableMount) {
281
+            // cut of /user/files to get the relative path to data/user/files
282
+            $pathParts = explode('/', $path, 4);
283
+            $relPath = '/' . $pathParts[3];
284
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
285
+            \OC_Hook::emit(
286
+                Filesystem::CLASSNAME, "umount",
287
+                array(Filesystem::signal_param_path => $relPath)
288
+            );
289
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
290
+            $result = $mount->removeMount();
291
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
292
+            if ($result) {
293
+                \OC_Hook::emit(
294
+                    Filesystem::CLASSNAME, "post_umount",
295
+                    array(Filesystem::signal_param_path => $relPath)
296
+                );
297
+            }
298
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
299
+            return $result;
300
+        } else {
301
+            // do not allow deleting the storage's root / the mount point
302
+            // because for some storages it might delete the whole contents
303
+            // but isn't supposed to work that way
304
+            return false;
305
+        }
306
+    }
307
+
308
+    public function disableCacheUpdate() {
309
+        $this->updaterEnabled = false;
310
+    }
311
+
312
+    public function enableCacheUpdate() {
313
+        $this->updaterEnabled = true;
314
+    }
315
+
316
+    protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
317
+        if ($this->updaterEnabled) {
318
+            if (is_null($time)) {
319
+                $time = time();
320
+            }
321
+            $storage->getUpdater()->update($internalPath, $time);
322
+        }
323
+    }
324
+
325
+    protected function removeUpdate(Storage $storage, $internalPath) {
326
+        if ($this->updaterEnabled) {
327
+            $storage->getUpdater()->remove($internalPath);
328
+        }
329
+    }
330
+
331
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
332
+        if ($this->updaterEnabled) {
333
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
334
+        }
335
+    }
336
+
337
+    /**
338
+     * @param string $path
339
+     * @return bool|mixed
340
+     */
341
+    public function rmdir($path) {
342
+        $absolutePath = $this->getAbsolutePath($path);
343
+        $mount = Filesystem::getMountManager()->find($absolutePath);
344
+        if ($mount->getInternalPath($absolutePath) === '') {
345
+            return $this->removeMount($mount, $absolutePath);
346
+        }
347
+        if ($this->is_dir($path)) {
348
+            $result = $this->basicOperation('rmdir', $path, array('delete'));
349
+        } else {
350
+            $result = false;
351
+        }
352
+
353
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
354
+            $storage = $mount->getStorage();
355
+            $internalPath = $mount->getInternalPath($absolutePath);
356
+            $storage->getUpdater()->remove($internalPath);
357
+        }
358
+        return $result;
359
+    }
360
+
361
+    /**
362
+     * @param string $path
363
+     * @return resource
364
+     */
365
+    public function opendir($path) {
366
+        return $this->basicOperation('opendir', $path, array('read'));
367
+    }
368
+
369
+    /**
370
+     * @param string $path
371
+     * @return bool|mixed
372
+     */
373
+    public function is_dir($path) {
374
+        if ($path == '/') {
375
+            return true;
376
+        }
377
+        return $this->basicOperation('is_dir', $path);
378
+    }
379
+
380
+    /**
381
+     * @param string $path
382
+     * @return bool|mixed
383
+     */
384
+    public function is_file($path) {
385
+        if ($path == '/') {
386
+            return false;
387
+        }
388
+        return $this->basicOperation('is_file', $path);
389
+    }
390
+
391
+    /**
392
+     * @param string $path
393
+     * @return mixed
394
+     */
395
+    public function stat($path) {
396
+        return $this->basicOperation('stat', $path);
397
+    }
398
+
399
+    /**
400
+     * @param string $path
401
+     * @return mixed
402
+     */
403
+    public function filetype($path) {
404
+        return $this->basicOperation('filetype', $path);
405
+    }
406
+
407
+    /**
408
+     * @param string $path
409
+     * @return mixed
410
+     */
411
+    public function filesize($path) {
412
+        return $this->basicOperation('filesize', $path);
413
+    }
414
+
415
+    /**
416
+     * @param string $path
417
+     * @return bool|mixed
418
+     * @throws \OCP\Files\InvalidPathException
419
+     */
420
+    public function readfile($path) {
421
+        $this->assertPathLength($path);
422
+        @ob_end_clean();
423
+        $handle = $this->fopen($path, 'rb');
424
+        if ($handle) {
425
+            $chunkSize = 8192; // 8 kB chunks
426
+            while (!feof($handle)) {
427
+                echo fread($handle, $chunkSize);
428
+                flush();
429
+            }
430
+            fclose($handle);
431
+            $size = $this->filesize($path);
432
+            return $size;
433
+        }
434
+        return false;
435
+    }
436
+
437
+    /**
438
+     * @param string $path
439
+     * @param int $from
440
+     * @param int $to
441
+     * @return bool|mixed
442
+     * @throws \OCP\Files\InvalidPathException
443
+     * @throws \OCP\Files\UnseekableException
444
+     */
445
+    public function readfilePart($path, $from, $to) {
446
+        $this->assertPathLength($path);
447
+        @ob_end_clean();
448
+        $handle = $this->fopen($path, 'rb');
449
+        if ($handle) {
450
+            $chunkSize = 8192; // 8 kB chunks
451
+            $startReading = true;
452
+
453
+            if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
454
+                // forward file handle via chunked fread because fseek seem to have failed
455
+
456
+                $end = $from + 1;
457
+                while (!feof($handle) && ftell($handle) < $end) {
458
+                    $len = $from - ftell($handle);
459
+                    if ($len > $chunkSize) {
460
+                        $len = $chunkSize;
461
+                    }
462
+                    $result = fread($handle, $len);
463
+
464
+                    if ($result === false) {
465
+                        $startReading = false;
466
+                        break;
467
+                    }
468
+                }
469
+            }
470
+
471
+            if ($startReading) {
472
+                $end = $to + 1;
473
+                while (!feof($handle) && ftell($handle) < $end) {
474
+                    $len = $end - ftell($handle);
475
+                    if ($len > $chunkSize) {
476
+                        $len = $chunkSize;
477
+                    }
478
+                    echo fread($handle, $len);
479
+                    flush();
480
+                }
481
+                $size = ftell($handle) - $from;
482
+                return $size;
483
+            }
484
+
485
+            throw new \OCP\Files\UnseekableException('fseek error');
486
+        }
487
+        return false;
488
+    }
489
+
490
+    /**
491
+     * @param string $path
492
+     * @return mixed
493
+     */
494
+    public function isCreatable($path) {
495
+        return $this->basicOperation('isCreatable', $path);
496
+    }
497
+
498
+    /**
499
+     * @param string $path
500
+     * @return mixed
501
+     */
502
+    public function isReadable($path) {
503
+        return $this->basicOperation('isReadable', $path);
504
+    }
505
+
506
+    /**
507
+     * @param string $path
508
+     * @return mixed
509
+     */
510
+    public function isUpdatable($path) {
511
+        return $this->basicOperation('isUpdatable', $path);
512
+    }
513
+
514
+    /**
515
+     * @param string $path
516
+     * @return bool|mixed
517
+     */
518
+    public function isDeletable($path) {
519
+        $absolutePath = $this->getAbsolutePath($path);
520
+        $mount = Filesystem::getMountManager()->find($absolutePath);
521
+        if ($mount->getInternalPath($absolutePath) === '') {
522
+            return $mount instanceof MoveableMount;
523
+        }
524
+        return $this->basicOperation('isDeletable', $path);
525
+    }
526
+
527
+    /**
528
+     * @param string $path
529
+     * @return mixed
530
+     */
531
+    public function isSharable($path) {
532
+        return $this->basicOperation('isSharable', $path);
533
+    }
534
+
535
+    /**
536
+     * @param string $path
537
+     * @return bool|mixed
538
+     */
539
+    public function file_exists($path) {
540
+        if ($path == '/') {
541
+            return true;
542
+        }
543
+        return $this->basicOperation('file_exists', $path);
544
+    }
545
+
546
+    /**
547
+     * @param string $path
548
+     * @return mixed
549
+     */
550
+    public function filemtime($path) {
551
+        return $this->basicOperation('filemtime', $path);
552
+    }
553
+
554
+    /**
555
+     * @param string $path
556
+     * @param int|string $mtime
557
+     * @return bool
558
+     */
559
+    public function touch($path, $mtime = null) {
560
+        if (!is_null($mtime) and !is_numeric($mtime)) {
561
+            $mtime = strtotime($mtime);
562
+        }
563
+
564
+        $hooks = array('touch');
565
+
566
+        if (!$this->file_exists($path)) {
567
+            $hooks[] = 'create';
568
+            $hooks[] = 'write';
569
+        }
570
+        $result = $this->basicOperation('touch', $path, $hooks, $mtime);
571
+        if (!$result) {
572
+            // If create file fails because of permissions on external storage like SMB folders,
573
+            // check file exists and return false if not.
574
+            if (!$this->file_exists($path)) {
575
+                return false;
576
+            }
577
+            if (is_null($mtime)) {
578
+                $mtime = time();
579
+            }
580
+            //if native touch fails, we emulate it by changing the mtime in the cache
581
+            $this->putFileInfo($path, array('mtime' => floor($mtime)));
582
+        }
583
+        return true;
584
+    }
585
+
586
+    /**
587
+     * @param string $path
588
+     * @return mixed
589
+     */
590
+    public function file_get_contents($path) {
591
+        return $this->basicOperation('file_get_contents', $path, array('read'));
592
+    }
593
+
594
+    /**
595
+     * @param bool $exists
596
+     * @param string $path
597
+     * @param bool $run
598
+     */
599
+    protected function emit_file_hooks_pre($exists, $path, &$run) {
600
+        if (!$exists) {
601
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
602
+                Filesystem::signal_param_path => $this->getHookPath($path),
603
+                Filesystem::signal_param_run => &$run,
604
+            ));
605
+        } else {
606
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
607
+                Filesystem::signal_param_path => $this->getHookPath($path),
608
+                Filesystem::signal_param_run => &$run,
609
+            ));
610
+        }
611
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
612
+            Filesystem::signal_param_path => $this->getHookPath($path),
613
+            Filesystem::signal_param_run => &$run,
614
+        ));
615
+    }
616
+
617
+    /**
618
+     * @param bool $exists
619
+     * @param string $path
620
+     */
621
+    protected function emit_file_hooks_post($exists, $path) {
622
+        if (!$exists) {
623
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
624
+                Filesystem::signal_param_path => $this->getHookPath($path),
625
+            ));
626
+        } else {
627
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
628
+                Filesystem::signal_param_path => $this->getHookPath($path),
629
+            ));
630
+        }
631
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
632
+            Filesystem::signal_param_path => $this->getHookPath($path),
633
+        ));
634
+    }
635
+
636
+    /**
637
+     * @param string $path
638
+     * @param mixed $data
639
+     * @return bool|mixed
640
+     * @throws \Exception
641
+     */
642
+    public function file_put_contents($path, $data) {
643
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
644
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
645
+            if (Filesystem::isValidPath($path)
646
+                and !Filesystem::isFileBlacklisted($path)
647
+            ) {
648
+                $path = $this->getRelativePath($absolutePath);
649
+
650
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
651
+
652
+                $exists = $this->file_exists($path);
653
+                $run = true;
654
+                if ($this->shouldEmitHooks($path)) {
655
+                    $this->emit_file_hooks_pre($exists, $path, $run);
656
+                }
657
+                if (!$run) {
658
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
659
+                    return false;
660
+                }
661
+
662
+                $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
663
+
664
+                /** @var \OC\Files\Storage\Storage $storage */
665
+                list($storage, $internalPath) = $this->resolvePath($path);
666
+                $target = $storage->fopen($internalPath, 'w');
667
+                if ($target) {
668
+                    list (, $result) = \OC_Helper::streamCopy($data, $target);
669
+                    fclose($target);
670
+                    fclose($data);
671
+
672
+                    $this->writeUpdate($storage, $internalPath);
673
+
674
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
675
+
676
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
677
+                        $this->emit_file_hooks_post($exists, $path);
678
+                    }
679
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
680
+                    return $result;
681
+                } else {
682
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
683
+                    return false;
684
+                }
685
+            } else {
686
+                return false;
687
+            }
688
+        } else {
689
+            $hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
690
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
691
+        }
692
+    }
693
+
694
+    /**
695
+     * @param string $path
696
+     * @return bool|mixed
697
+     */
698
+    public function unlink($path) {
699
+        if ($path === '' || $path === '/') {
700
+            // do not allow deleting the root
701
+            return false;
702
+        }
703
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
704
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
705
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
706
+        if ($mount and $mount->getInternalPath($absolutePath) === '') {
707
+            return $this->removeMount($mount, $absolutePath);
708
+        }
709
+        if ($this->is_dir($path)) {
710
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
711
+        } else {
712
+            $result = $this->basicOperation('unlink', $path, ['delete']);
713
+        }
714
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
715
+            $storage = $mount->getStorage();
716
+            $internalPath = $mount->getInternalPath($absolutePath);
717
+            $storage->getUpdater()->remove($internalPath);
718
+            return true;
719
+        } else {
720
+            return $result;
721
+        }
722
+    }
723
+
724
+    /**
725
+     * @param string $directory
726
+     * @return bool|mixed
727
+     */
728
+    public function deleteAll($directory) {
729
+        return $this->rmdir($directory);
730
+    }
731
+
732
+    /**
733
+     * Rename/move a file or folder from the source path to target path.
734
+     *
735
+     * @param string $path1 source path
736
+     * @param string $path2 target path
737
+     *
738
+     * @return bool|mixed
739
+     */
740
+    public function rename($path1, $path2) {
741
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
742
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
743
+        $result = false;
744
+        if (
745
+            Filesystem::isValidPath($path2)
746
+            and Filesystem::isValidPath($path1)
747
+            and !Filesystem::isFileBlacklisted($path2)
748
+        ) {
749
+            $path1 = $this->getRelativePath($absolutePath1);
750
+            $path2 = $this->getRelativePath($absolutePath2);
751
+            $exists = $this->file_exists($path2);
752
+
753
+            if ($path1 == null or $path2 == null) {
754
+                return false;
755
+            }
756
+
757
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
758
+            try {
759
+                $this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
760
+
761
+                $run = true;
762
+                if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
763
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
764
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
765
+                } elseif ($this->shouldEmitHooks($path1)) {
766
+                    \OC_Hook::emit(
767
+                        Filesystem::CLASSNAME, Filesystem::signal_rename,
768
+                        array(
769
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
770
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
771
+                            Filesystem::signal_param_run => &$run
772
+                        )
773
+                    );
774
+                }
775
+                if ($run) {
776
+                    $this->verifyPath(dirname($path2), basename($path2));
777
+
778
+                    $manager = Filesystem::getMountManager();
779
+                    $mount1 = $this->getMount($path1);
780
+                    $mount2 = $this->getMount($path2);
781
+                    $storage1 = $mount1->getStorage();
782
+                    $storage2 = $mount2->getStorage();
783
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
784
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
785
+
786
+                    $this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
787
+                    try {
788
+                        $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
789
+
790
+                        if ($internalPath1 === '') {
791
+                            if ($mount1 instanceof MoveableMount) {
792
+                                if ($this->isTargetAllowed($absolutePath2)) {
793
+                                    /**
794
+                                     * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
795
+                                     */
796
+                                    $sourceMountPoint = $mount1->getMountPoint();
797
+                                    $result = $mount1->moveMount($absolutePath2);
798
+                                    $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
799
+                                } else {
800
+                                    $result = false;
801
+                                }
802
+                            } else {
803
+                                $result = false;
804
+                            }
805
+                            // moving a file/folder within the same mount point
806
+                        } elseif ($storage1 === $storage2) {
807
+                            if ($storage1) {
808
+                                $result = $storage1->rename($internalPath1, $internalPath2);
809
+                            } else {
810
+                                $result = false;
811
+                            }
812
+                            // moving a file/folder between storages (from $storage1 to $storage2)
813
+                        } else {
814
+                            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
815
+                        }
816
+
817
+                        if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
818
+                            // if it was a rename from a part file to a regular file it was a write and not a rename operation
819
+                            $this->writeUpdate($storage2, $internalPath2);
820
+                        } else if ($result) {
821
+                            if ($internalPath1 !== '') { // don't do a cache update for moved mounts
822
+                                $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
823
+                            }
824
+                        }
825
+                    } catch(\Exception $e) {
826
+                        throw $e;
827
+                    } finally {
828
+                        $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
829
+                        $this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
830
+                    }
831
+
832
+                    if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
833
+                        if ($this->shouldEmitHooks()) {
834
+                            $this->emit_file_hooks_post($exists, $path2);
835
+                        }
836
+                    } elseif ($result) {
837
+                        if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
838
+                            \OC_Hook::emit(
839
+                                Filesystem::CLASSNAME,
840
+                                Filesystem::signal_post_rename,
841
+                                array(
842
+                                    Filesystem::signal_param_oldpath => $this->getHookPath($path1),
843
+                                    Filesystem::signal_param_newpath => $this->getHookPath($path2)
844
+                                )
845
+                            );
846
+                        }
847
+                    }
848
+                }
849
+            } catch(\Exception $e) {
850
+                throw $e;
851
+            } finally {
852
+                $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
853
+                $this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
854
+            }
855
+        }
856
+        return $result;
857
+    }
858
+
859
+    /**
860
+     * Copy a file/folder from the source path to target path
861
+     *
862
+     * @param string $path1 source path
863
+     * @param string $path2 target path
864
+     * @param bool $preserveMtime whether to preserve mtime on the copy
865
+     *
866
+     * @return bool|mixed
867
+     */
868
+    public function copy($path1, $path2, $preserveMtime = false) {
869
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
870
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
871
+        $result = false;
872
+        if (
873
+            Filesystem::isValidPath($path2)
874
+            and Filesystem::isValidPath($path1)
875
+            and !Filesystem::isFileBlacklisted($path2)
876
+        ) {
877
+            $path1 = $this->getRelativePath($absolutePath1);
878
+            $path2 = $this->getRelativePath($absolutePath2);
879
+
880
+            if ($path1 == null or $path2 == null) {
881
+                return false;
882
+            }
883
+            $run = true;
884
+
885
+            $this->lockFile($path2, ILockingProvider::LOCK_SHARED);
886
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED);
887
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
888
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
889
+
890
+            try {
891
+
892
+                $exists = $this->file_exists($path2);
893
+                if ($this->shouldEmitHooks()) {
894
+                    \OC_Hook::emit(
895
+                        Filesystem::CLASSNAME,
896
+                        Filesystem::signal_copy,
897
+                        array(
898
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
899
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
900
+                            Filesystem::signal_param_run => &$run
901
+                        )
902
+                    );
903
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
904
+                }
905
+                if ($run) {
906
+                    $mount1 = $this->getMount($path1);
907
+                    $mount2 = $this->getMount($path2);
908
+                    $storage1 = $mount1->getStorage();
909
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
910
+                    $storage2 = $mount2->getStorage();
911
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
912
+
913
+                    $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
914
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
915
+
916
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
917
+                        if ($storage1) {
918
+                            $result = $storage1->copy($internalPath1, $internalPath2);
919
+                        } else {
920
+                            $result = false;
921
+                        }
922
+                    } else {
923
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
924
+                    }
925
+
926
+                    $this->writeUpdate($storage2, $internalPath2);
927
+
928
+                    $this->changeLock($path2, ILockingProvider::LOCK_SHARED);
929
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
930
+
931
+                    if ($this->shouldEmitHooks() && $result !== false) {
932
+                        \OC_Hook::emit(
933
+                            Filesystem::CLASSNAME,
934
+                            Filesystem::signal_post_copy,
935
+                            array(
936
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
937
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
938
+                            )
939
+                        );
940
+                        $this->emit_file_hooks_post($exists, $path2);
941
+                    }
942
+
943
+                }
944
+            } catch (\Exception $e) {
945
+                $this->unlockFile($path2, $lockTypePath2);
946
+                $this->unlockFile($path1, $lockTypePath1);
947
+                throw $e;
948
+            }
949
+
950
+            $this->unlockFile($path2, $lockTypePath2);
951
+            $this->unlockFile($path1, $lockTypePath1);
952
+
953
+        }
954
+        return $result;
955
+    }
956
+
957
+    /**
958
+     * @param string $path
959
+     * @param string $mode 'r' or 'w'
960
+     * @return resource
961
+     */
962
+    public function fopen($path, $mode) {
963
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
964
+        $hooks = array();
965
+        switch ($mode) {
966
+            case 'r':
967
+                $hooks[] = 'read';
968
+                break;
969
+            case 'r+':
970
+            case 'w+':
971
+            case 'x+':
972
+            case 'a+':
973
+                $hooks[] = 'read';
974
+                $hooks[] = 'write';
975
+                break;
976
+            case 'w':
977
+            case 'x':
978
+            case 'a':
979
+                $hooks[] = 'write';
980
+                break;
981
+            default:
982
+                \OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
983
+        }
984
+
985
+        if ($mode !== 'r' && $mode !== 'w') {
986
+            \OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
987
+        }
988
+
989
+        return $this->basicOperation('fopen', $path, $hooks, $mode);
990
+    }
991
+
992
+    /**
993
+     * @param string $path
994
+     * @return bool|string
995
+     * @throws \OCP\Files\InvalidPathException
996
+     */
997
+    public function toTmpFile($path) {
998
+        $this->assertPathLength($path);
999
+        if (Filesystem::isValidPath($path)) {
1000
+            $source = $this->fopen($path, 'r');
1001
+            if ($source) {
1002
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
1003
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1004
+                file_put_contents($tmpFile, $source);
1005
+                return $tmpFile;
1006
+            } else {
1007
+                return false;
1008
+            }
1009
+        } else {
1010
+            return false;
1011
+        }
1012
+    }
1013
+
1014
+    /**
1015
+     * @param string $tmpFile
1016
+     * @param string $path
1017
+     * @return bool|mixed
1018
+     * @throws \OCP\Files\InvalidPathException
1019
+     */
1020
+    public function fromTmpFile($tmpFile, $path) {
1021
+        $this->assertPathLength($path);
1022
+        if (Filesystem::isValidPath($path)) {
1023
+
1024
+            // Get directory that the file is going into
1025
+            $filePath = dirname($path);
1026
+
1027
+            // Create the directories if any
1028
+            if (!$this->file_exists($filePath)) {
1029
+                $result = $this->createParentDirectories($filePath);
1030
+                if ($result === false) {
1031
+                    return false;
1032
+                }
1033
+            }
1034
+
1035
+            $source = fopen($tmpFile, 'r');
1036
+            if ($source) {
1037
+                $result = $this->file_put_contents($path, $source);
1038
+                // $this->file_put_contents() might have already closed
1039
+                // the resource, so we check it, before trying to close it
1040
+                // to avoid messages in the error log.
1041
+                if (is_resource($source)) {
1042
+                    fclose($source);
1043
+                }
1044
+                unlink($tmpFile);
1045
+                return $result;
1046
+            } else {
1047
+                return false;
1048
+            }
1049
+        } else {
1050
+            return false;
1051
+        }
1052
+    }
1053
+
1054
+
1055
+    /**
1056
+     * @param string $path
1057
+     * @return mixed
1058
+     * @throws \OCP\Files\InvalidPathException
1059
+     */
1060
+    public function getMimeType($path) {
1061
+        $this->assertPathLength($path);
1062
+        return $this->basicOperation('getMimeType', $path);
1063
+    }
1064
+
1065
+    /**
1066
+     * @param string $type
1067
+     * @param string $path
1068
+     * @param bool $raw
1069
+     * @return bool|null|string
1070
+     */
1071
+    public function hash($type, $path, $raw = false) {
1072
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1073
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1074
+        if (Filesystem::isValidPath($path)) {
1075
+            $path = $this->getRelativePath($absolutePath);
1076
+            if ($path == null) {
1077
+                return false;
1078
+            }
1079
+            if ($this->shouldEmitHooks($path)) {
1080
+                \OC_Hook::emit(
1081
+                    Filesystem::CLASSNAME,
1082
+                    Filesystem::signal_read,
1083
+                    array(Filesystem::signal_param_path => $this->getHookPath($path))
1084
+                );
1085
+            }
1086
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1087
+            if ($storage) {
1088
+                $result = $storage->hash($type, $internalPath, $raw);
1089
+                return $result;
1090
+            }
1091
+        }
1092
+        return null;
1093
+    }
1094
+
1095
+    /**
1096
+     * @param string $path
1097
+     * @return mixed
1098
+     * @throws \OCP\Files\InvalidPathException
1099
+     */
1100
+    public function free_space($path = '/') {
1101
+        $this->assertPathLength($path);
1102
+        $result = $this->basicOperation('free_space', $path);
1103
+        if ($result === null) {
1104
+            throw new InvalidPathException();
1105
+        }
1106
+        return $result;
1107
+    }
1108
+
1109
+    /**
1110
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1111
+     *
1112
+     * @param string $operation
1113
+     * @param string $path
1114
+     * @param array $hooks (optional)
1115
+     * @param mixed $extraParam (optional)
1116
+     * @return mixed
1117
+     * @throws \Exception
1118
+     *
1119
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1120
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1121
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1122
+     */
1123
+    private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1124
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1125
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1126
+        if (Filesystem::isValidPath($path)
1127
+            and !Filesystem::isFileBlacklisted($path)
1128
+        ) {
1129
+            $path = $this->getRelativePath($absolutePath);
1130
+            if ($path == null) {
1131
+                return false;
1132
+            }
1133
+
1134
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1135
+                // always a shared lock during pre-hooks so the hook can read the file
1136
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1137
+            }
1138
+
1139
+            $run = $this->runHooks($hooks, $path);
1140
+            /** @var \OC\Files\Storage\Storage $storage */
1141
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1142
+            if ($run and $storage) {
1143
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1144
+                    $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1145
+                }
1146
+                try {
1147
+                    if (!is_null($extraParam)) {
1148
+                        $result = $storage->$operation($internalPath, $extraParam);
1149
+                    } else {
1150
+                        $result = $storage->$operation($internalPath);
1151
+                    }
1152
+                } catch (\Exception $e) {
1153
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1154
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1155
+                    } else if (in_array('read', $hooks)) {
1156
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1157
+                    }
1158
+                    throw $e;
1159
+                }
1160
+
1161
+                if ($result && in_array('delete', $hooks) and $result) {
1162
+                    $this->removeUpdate($storage, $internalPath);
1163
+                }
1164
+                if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1165
+                    $this->writeUpdate($storage, $internalPath);
1166
+                }
1167
+                if ($result && in_array('touch', $hooks)) {
1168
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1169
+                }
1170
+
1171
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1172
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1173
+                }
1174
+
1175
+                $unlockLater = false;
1176
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1177
+                    $unlockLater = true;
1178
+                    // make sure our unlocking callback will still be called if connection is aborted
1179
+                    ignore_user_abort(true);
1180
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1181
+                        if (in_array('write', $hooks)) {
1182
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1183
+                        } else if (in_array('read', $hooks)) {
1184
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1185
+                        }
1186
+                    });
1187
+                }
1188
+
1189
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1190
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1191
+                        $this->runHooks($hooks, $path, true);
1192
+                    }
1193
+                }
1194
+
1195
+                if (!$unlockLater
1196
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1197
+                ) {
1198
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1199
+                }
1200
+                return $result;
1201
+            } else {
1202
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1203
+            }
1204
+        }
1205
+        return null;
1206
+    }
1207
+
1208
+    /**
1209
+     * get the path relative to the default root for hook usage
1210
+     *
1211
+     * @param string $path
1212
+     * @return string
1213
+     */
1214
+    private function getHookPath($path) {
1215
+        if (!Filesystem::getView()) {
1216
+            return $path;
1217
+        }
1218
+        return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1219
+    }
1220
+
1221
+    private function shouldEmitHooks($path = '') {
1222
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1223
+            return false;
1224
+        }
1225
+        if (!Filesystem::$loaded) {
1226
+            return false;
1227
+        }
1228
+        $defaultRoot = Filesystem::getRoot();
1229
+        if ($defaultRoot === null) {
1230
+            return false;
1231
+        }
1232
+        if ($this->fakeRoot === $defaultRoot) {
1233
+            return true;
1234
+        }
1235
+        $fullPath = $this->getAbsolutePath($path);
1236
+
1237
+        if ($fullPath === $defaultRoot) {
1238
+            return true;
1239
+        }
1240
+
1241
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1242
+    }
1243
+
1244
+    /**
1245
+     * @param string[] $hooks
1246
+     * @param string $path
1247
+     * @param bool $post
1248
+     * @return bool
1249
+     */
1250
+    private function runHooks($hooks, $path, $post = false) {
1251
+        $relativePath = $path;
1252
+        $path = $this->getHookPath($path);
1253
+        $prefix = ($post) ? 'post_' : '';
1254
+        $run = true;
1255
+        if ($this->shouldEmitHooks($relativePath)) {
1256
+            foreach ($hooks as $hook) {
1257
+                if ($hook != 'read') {
1258
+                    \OC_Hook::emit(
1259
+                        Filesystem::CLASSNAME,
1260
+                        $prefix . $hook,
1261
+                        array(
1262
+                            Filesystem::signal_param_run => &$run,
1263
+                            Filesystem::signal_param_path => $path
1264
+                        )
1265
+                    );
1266
+                } elseif (!$post) {
1267
+                    \OC_Hook::emit(
1268
+                        Filesystem::CLASSNAME,
1269
+                        $prefix . $hook,
1270
+                        array(
1271
+                            Filesystem::signal_param_path => $path
1272
+                        )
1273
+                    );
1274
+                }
1275
+            }
1276
+        }
1277
+        return $run;
1278
+    }
1279
+
1280
+    /**
1281
+     * check if a file or folder has been updated since $time
1282
+     *
1283
+     * @param string $path
1284
+     * @param int $time
1285
+     * @return bool
1286
+     */
1287
+    public function hasUpdated($path, $time) {
1288
+        return $this->basicOperation('hasUpdated', $path, array(), $time);
1289
+    }
1290
+
1291
+    /**
1292
+     * @param string $ownerId
1293
+     * @return \OC\User\User
1294
+     */
1295
+    private function getUserObjectForOwner($ownerId) {
1296
+        $owner = $this->userManager->get($ownerId);
1297
+        if ($owner instanceof IUser) {
1298
+            return $owner;
1299
+        } else {
1300
+            return new User($ownerId, null);
1301
+        }
1302
+    }
1303
+
1304
+    /**
1305
+     * Get file info from cache
1306
+     *
1307
+     * If the file is not in cached it will be scanned
1308
+     * If the file has changed on storage the cache will be updated
1309
+     *
1310
+     * @param \OC\Files\Storage\Storage $storage
1311
+     * @param string $internalPath
1312
+     * @param string $relativePath
1313
+     * @return ICacheEntry|bool
1314
+     */
1315
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1316
+        $cache = $storage->getCache($internalPath);
1317
+        $data = $cache->get($internalPath);
1318
+        $watcher = $storage->getWatcher($internalPath);
1319
+
1320
+        try {
1321
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1322
+            if (!$data || $data['size'] === -1) {
1323
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1324
+                if (!$storage->file_exists($internalPath)) {
1325
+                    $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1326
+                    return false;
1327
+                }
1328
+                $scanner = $storage->getScanner($internalPath);
1329
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1330
+                $data = $cache->get($internalPath);
1331
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1332
+            } else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1333
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1334
+                $watcher->update($internalPath, $data);
1335
+                $storage->getPropagator()->propagateChange($internalPath, time());
1336
+                $data = $cache->get($internalPath);
1337
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1338
+            }
1339
+        } catch (LockedException $e) {
1340
+            // if the file is locked we just use the old cache info
1341
+        }
1342
+
1343
+        return $data;
1344
+    }
1345
+
1346
+    /**
1347
+     * get the filesystem info
1348
+     *
1349
+     * @param string $path
1350
+     * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1351
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1352
+     * defaults to true
1353
+     * @return \OC\Files\FileInfo|false False if file does not exist
1354
+     */
1355
+    public function getFileInfo($path, $includeMountPoints = true) {
1356
+        $this->assertPathLength($path);
1357
+        if (!Filesystem::isValidPath($path)) {
1358
+            return false;
1359
+        }
1360
+        if (Cache\Scanner::isPartialFile($path)) {
1361
+            return $this->getPartFileInfo($path);
1362
+        }
1363
+        $relativePath = $path;
1364
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1365
+
1366
+        $mount = Filesystem::getMountManager()->find($path);
1367
+        $storage = $mount->getStorage();
1368
+        $internalPath = $mount->getInternalPath($path);
1369
+        if ($storage) {
1370
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1371
+
1372
+            if (!$data instanceof ICacheEntry) {
1373
+                return false;
1374
+            }
1375
+
1376
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1377
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1378
+            }
1379
+
1380
+            $owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1381
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1382
+
1383
+            if ($data and isset($data['fileid'])) {
1384
+                if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1385
+                    //add the sizes of other mount points to the folder
1386
+                    $extOnly = ($includeMountPoints === 'ext');
1387
+                    $mounts = Filesystem::getMountManager()->findIn($path);
1388
+                    $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1389
+                        $subStorage = $mount->getStorage();
1390
+                        return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1391
+                    }));
1392
+                }
1393
+            }
1394
+
1395
+            return $info;
1396
+        }
1397
+
1398
+        return false;
1399
+    }
1400
+
1401
+    /**
1402
+     * get the content of a directory
1403
+     *
1404
+     * @param string $directory path under datadirectory
1405
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1406
+     * @return FileInfo[]
1407
+     */
1408
+    public function getDirectoryContent($directory, $mimetype_filter = '') {
1409
+        $this->assertPathLength($directory);
1410
+        if (!Filesystem::isValidPath($directory)) {
1411
+            return [];
1412
+        }
1413
+        $path = $this->getAbsolutePath($directory);
1414
+        $path = Filesystem::normalizePath($path);
1415
+        $mount = $this->getMount($directory);
1416
+        $storage = $mount->getStorage();
1417
+        $internalPath = $mount->getInternalPath($path);
1418
+        if ($storage) {
1419
+            $cache = $storage->getCache($internalPath);
1420
+            $user = \OC_User::getUser();
1421
+
1422
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1423
+
1424
+            if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1425
+                return [];
1426
+            }
1427
+
1428
+            $folderId = $data['fileid'];
1429
+            $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1430
+
1431
+            $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1432
+            /**
1433
+             * @var \OC\Files\FileInfo[] $files
1434
+             */
1435
+            $files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1436
+                if ($sharingDisabled) {
1437
+                    $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1438
+                }
1439
+                $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1440
+                return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1441
+            }, $contents);
1442
+
1443
+            //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1444
+            $mounts = Filesystem::getMountManager()->findIn($path);
1445
+            $dirLength = strlen($path);
1446
+            foreach ($mounts as $mount) {
1447
+                $mountPoint = $mount->getMountPoint();
1448
+                $subStorage = $mount->getStorage();
1449
+                if ($subStorage) {
1450
+                    $subCache = $subStorage->getCache('');
1451
+
1452
+                    $rootEntry = $subCache->get('');
1453
+                    if (!$rootEntry) {
1454
+                        $subScanner = $subStorage->getScanner('');
1455
+                        try {
1456
+                            $subScanner->scanFile('');
1457
+                        } catch (\OCP\Files\StorageNotAvailableException $e) {
1458
+                            continue;
1459
+                        } catch (\OCP\Files\StorageInvalidException $e) {
1460
+                            continue;
1461
+                        } catch (\Exception $e) {
1462
+                            // sometimes when the storage is not available it can be any exception
1463
+                            \OCP\Util::writeLog(
1464
+                                'core',
1465
+                                'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1466
+                                get_class($e) . ': ' . $e->getMessage(),
1467
+                                \OCP\Util::ERROR
1468
+                            );
1469
+                            continue;
1470
+                        }
1471
+                        $rootEntry = $subCache->get('');
1472
+                    }
1473
+
1474
+                    if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1475
+                        $relativePath = trim(substr($mountPoint, $dirLength), '/');
1476
+                        if ($pos = strpos($relativePath, '/')) {
1477
+                            //mountpoint inside subfolder add size to the correct folder
1478
+                            $entryName = substr($relativePath, 0, $pos);
1479
+                            foreach ($files as &$entry) {
1480
+                                if ($entry->getName() === $entryName) {
1481
+                                    $entry->addSubEntry($rootEntry, $mountPoint);
1482
+                                }
1483
+                            }
1484
+                        } else { //mountpoint in this folder, add an entry for it
1485
+                            $rootEntry['name'] = $relativePath;
1486
+                            $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1487
+                            $permissions = $rootEntry['permissions'];
1488
+                            // do not allow renaming/deleting the mount point if they are not shared files/folders
1489
+                            // for shared files/folders we use the permissions given by the owner
1490
+                            if ($mount instanceof MoveableMount) {
1491
+                                $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1492
+                            } else {
1493
+                                $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1494
+                            }
1495
+
1496
+                            //remove any existing entry with the same name
1497
+                            foreach ($files as $i => $file) {
1498
+                                if ($file['name'] === $rootEntry['name']) {
1499
+                                    unset($files[$i]);
1500
+                                    break;
1501
+                                }
1502
+                            }
1503
+                            $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1504
+
1505
+                            // if sharing was disabled for the user we remove the share permissions
1506
+                            if (\OCP\Util::isSharingDisabledForUser()) {
1507
+                                $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1508
+                            }
1509
+
1510
+                            $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1511
+                            $files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1512
+                        }
1513
+                    }
1514
+                }
1515
+            }
1516
+
1517
+            if ($mimetype_filter) {
1518
+                $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1519
+                    if (strpos($mimetype_filter, '/')) {
1520
+                        return $file->getMimetype() === $mimetype_filter;
1521
+                    } else {
1522
+                        return $file->getMimePart() === $mimetype_filter;
1523
+                    }
1524
+                });
1525
+            }
1526
+
1527
+            return $files;
1528
+        } else {
1529
+            return [];
1530
+        }
1531
+    }
1532
+
1533
+    /**
1534
+     * change file metadata
1535
+     *
1536
+     * @param string $path
1537
+     * @param array|\OCP\Files\FileInfo $data
1538
+     * @return int
1539
+     *
1540
+     * returns the fileid of the updated file
1541
+     */
1542
+    public function putFileInfo($path, $data) {
1543
+        $this->assertPathLength($path);
1544
+        if ($data instanceof FileInfo) {
1545
+            $data = $data->getData();
1546
+        }
1547
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1548
+        /**
1549
+         * @var \OC\Files\Storage\Storage $storage
1550
+         * @var string $internalPath
1551
+         */
1552
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
1553
+        if ($storage) {
1554
+            $cache = $storage->getCache($path);
1555
+
1556
+            if (!$cache->inCache($internalPath)) {
1557
+                $scanner = $storage->getScanner($internalPath);
1558
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1559
+            }
1560
+
1561
+            return $cache->put($internalPath, $data);
1562
+        } else {
1563
+            return -1;
1564
+        }
1565
+    }
1566
+
1567
+    /**
1568
+     * search for files with the name matching $query
1569
+     *
1570
+     * @param string $query
1571
+     * @return FileInfo[]
1572
+     */
1573
+    public function search($query) {
1574
+        return $this->searchCommon('search', array('%' . $query . '%'));
1575
+    }
1576
+
1577
+    /**
1578
+     * search for files with the name matching $query
1579
+     *
1580
+     * @param string $query
1581
+     * @return FileInfo[]
1582
+     */
1583
+    public function searchRaw($query) {
1584
+        return $this->searchCommon('search', array($query));
1585
+    }
1586
+
1587
+    /**
1588
+     * search for files by mimetype
1589
+     *
1590
+     * @param string $mimetype
1591
+     * @return FileInfo[]
1592
+     */
1593
+    public function searchByMime($mimetype) {
1594
+        return $this->searchCommon('searchByMime', array($mimetype));
1595
+    }
1596
+
1597
+    /**
1598
+     * search for files by tag
1599
+     *
1600
+     * @param string|int $tag name or tag id
1601
+     * @param string $userId owner of the tags
1602
+     * @return FileInfo[]
1603
+     */
1604
+    public function searchByTag($tag, $userId) {
1605
+        return $this->searchCommon('searchByTag', array($tag, $userId));
1606
+    }
1607
+
1608
+    /**
1609
+     * @param string $method cache method
1610
+     * @param array $args
1611
+     * @return FileInfo[]
1612
+     */
1613
+    private function searchCommon($method, $args) {
1614
+        $files = array();
1615
+        $rootLength = strlen($this->fakeRoot);
1616
+
1617
+        $mount = $this->getMount('');
1618
+        $mountPoint = $mount->getMountPoint();
1619
+        $storage = $mount->getStorage();
1620
+        if ($storage) {
1621
+            $cache = $storage->getCache('');
1622
+
1623
+            $results = call_user_func_array(array($cache, $method), $args);
1624
+            foreach ($results as $result) {
1625
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1626
+                    $internalPath = $result['path'];
1627
+                    $path = $mountPoint . $result['path'];
1628
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1629
+                    $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1630
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1631
+                }
1632
+            }
1633
+
1634
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1635
+            foreach ($mounts as $mount) {
1636
+                $mountPoint = $mount->getMountPoint();
1637
+                $storage = $mount->getStorage();
1638
+                if ($storage) {
1639
+                    $cache = $storage->getCache('');
1640
+
1641
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1642
+                    $results = call_user_func_array(array($cache, $method), $args);
1643
+                    if ($results) {
1644
+                        foreach ($results as $result) {
1645
+                            $internalPath = $result['path'];
1646
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1647
+                            $path = rtrim($mountPoint . $internalPath, '/');
1648
+                            $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1649
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1650
+                        }
1651
+                    }
1652
+                }
1653
+            }
1654
+        }
1655
+        return $files;
1656
+    }
1657
+
1658
+    /**
1659
+     * Get the owner for a file or folder
1660
+     *
1661
+     * @param string $path
1662
+     * @return string the user id of the owner
1663
+     * @throws NotFoundException
1664
+     */
1665
+    public function getOwner($path) {
1666
+        $info = $this->getFileInfo($path);
1667
+        if (!$info) {
1668
+            throw new NotFoundException($path . ' not found while trying to get owner');
1669
+        }
1670
+        return $info->getOwner()->getUID();
1671
+    }
1672
+
1673
+    /**
1674
+     * get the ETag for a file or folder
1675
+     *
1676
+     * @param string $path
1677
+     * @return string
1678
+     */
1679
+    public function getETag($path) {
1680
+        /**
1681
+         * @var Storage\Storage $storage
1682
+         * @var string $internalPath
1683
+         */
1684
+        list($storage, $internalPath) = $this->resolvePath($path);
1685
+        if ($storage) {
1686
+            return $storage->getETag($internalPath);
1687
+        } else {
1688
+            return null;
1689
+        }
1690
+    }
1691
+
1692
+    /**
1693
+     * Get the path of a file by id, relative to the view
1694
+     *
1695
+     * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1696
+     *
1697
+     * @param int $id
1698
+     * @throws NotFoundException
1699
+     * @return string
1700
+     */
1701
+    public function getPath($id) {
1702
+        $id = (int)$id;
1703
+        $manager = Filesystem::getMountManager();
1704
+        $mounts = $manager->findIn($this->fakeRoot);
1705
+        $mounts[] = $manager->find($this->fakeRoot);
1706
+        // reverse the array so we start with the storage this view is in
1707
+        // which is the most likely to contain the file we're looking for
1708
+        $mounts = array_reverse($mounts);
1709
+        foreach ($mounts as $mount) {
1710
+            /**
1711
+             * @var \OC\Files\Mount\MountPoint $mount
1712
+             */
1713
+            if ($mount->getStorage()) {
1714
+                $cache = $mount->getStorage()->getCache();
1715
+                $internalPath = $cache->getPathById($id);
1716
+                if (is_string($internalPath)) {
1717
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1718
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1719
+                        return $path;
1720
+                    }
1721
+                }
1722
+            }
1723
+        }
1724
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1725
+    }
1726
+
1727
+    /**
1728
+     * @param string $path
1729
+     * @throws InvalidPathException
1730
+     */
1731
+    private function assertPathLength($path) {
1732
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1733
+        // Check for the string length - performed using isset() instead of strlen()
1734
+        // because isset() is about 5x-40x faster.
1735
+        if (isset($path[$maxLen])) {
1736
+            $pathLen = strlen($path);
1737
+            throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1738
+        }
1739
+    }
1740
+
1741
+    /**
1742
+     * check if it is allowed to move a mount point to a given target.
1743
+     * It is not allowed to move a mount point into a different mount point or
1744
+     * into an already shared folder
1745
+     *
1746
+     * @param string $target path
1747
+     * @return boolean
1748
+     */
1749
+    private function isTargetAllowed($target) {
1750
+
1751
+        list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1752
+        if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1753
+            \OCP\Util::writeLog('files',
1754
+                'It is not allowed to move one mount point into another one',
1755
+                \OCP\Util::DEBUG);
1756
+            return false;
1757
+        }
1758
+
1759
+        // note: cannot use the view because the target is already locked
1760
+        $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1761
+        if ($fileId === -1) {
1762
+            // target might not exist, need to check parent instead
1763
+            $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1764
+        }
1765
+
1766
+        // check if any of the parents were shared by the current owner (include collections)
1767
+        $shares = \OCP\Share::getItemShared(
1768
+            'folder',
1769
+            $fileId,
1770
+            \OCP\Share::FORMAT_NONE,
1771
+            null,
1772
+            true
1773
+        );
1774
+
1775
+        if (count($shares) > 0) {
1776
+            \OCP\Util::writeLog('files',
1777
+                'It is not allowed to move one mount point into a shared folder',
1778
+                \OCP\Util::DEBUG);
1779
+            return false;
1780
+        }
1781
+
1782
+        return true;
1783
+    }
1784
+
1785
+    /**
1786
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1787
+     *
1788
+     * @param string $path
1789
+     * @return \OCP\Files\FileInfo
1790
+     */
1791
+    private function getPartFileInfo($path) {
1792
+        $mount = $this->getMount($path);
1793
+        $storage = $mount->getStorage();
1794
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1795
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1796
+        return new FileInfo(
1797
+            $this->getAbsolutePath($path),
1798
+            $storage,
1799
+            $internalPath,
1800
+            [
1801
+                'fileid' => null,
1802
+                'mimetype' => $storage->getMimeType($internalPath),
1803
+                'name' => basename($path),
1804
+                'etag' => null,
1805
+                'size' => $storage->filesize($internalPath),
1806
+                'mtime' => $storage->filemtime($internalPath),
1807
+                'encrypted' => false,
1808
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1809
+            ],
1810
+            $mount,
1811
+            $owner
1812
+        );
1813
+    }
1814
+
1815
+    /**
1816
+     * @param string $path
1817
+     * @param string $fileName
1818
+     * @throws InvalidPathException
1819
+     */
1820
+    public function verifyPath($path, $fileName) {
1821
+        try {
1822
+            /** @type \OCP\Files\Storage $storage */
1823
+            list($storage, $internalPath) = $this->resolvePath($path);
1824
+            $storage->verifyPath($internalPath, $fileName);
1825
+        } catch (ReservedWordException $ex) {
1826
+            $l = \OC::$server->getL10N('lib');
1827
+            throw new InvalidPathException($l->t('File name is a reserved word'));
1828
+        } catch (InvalidCharacterInPathException $ex) {
1829
+            $l = \OC::$server->getL10N('lib');
1830
+            throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1831
+        } catch (FileNameTooLongException $ex) {
1832
+            $l = \OC::$server->getL10N('lib');
1833
+            throw new InvalidPathException($l->t('File name is too long'));
1834
+        } catch (InvalidDirectoryException $ex) {
1835
+            $l = \OC::$server->getL10N('lib');
1836
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1837
+        } catch (EmptyFileNameException $ex) {
1838
+            $l = \OC::$server->getL10N('lib');
1839
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1840
+        }
1841
+    }
1842
+
1843
+    /**
1844
+     * get all parent folders of $path
1845
+     *
1846
+     * @param string $path
1847
+     * @return string[]
1848
+     */
1849
+    private function getParents($path) {
1850
+        $path = trim($path, '/');
1851
+        if (!$path) {
1852
+            return [];
1853
+        }
1854
+
1855
+        $parts = explode('/', $path);
1856
+
1857
+        // remove the single file
1858
+        array_pop($parts);
1859
+        $result = array('/');
1860
+        $resultPath = '';
1861
+        foreach ($parts as $part) {
1862
+            if ($part) {
1863
+                $resultPath .= '/' . $part;
1864
+                $result[] = $resultPath;
1865
+            }
1866
+        }
1867
+        return $result;
1868
+    }
1869
+
1870
+    /**
1871
+     * Returns the mount point for which to lock
1872
+     *
1873
+     * @param string $absolutePath absolute path
1874
+     * @param bool $useParentMount true to return parent mount instead of whatever
1875
+     * is mounted directly on the given path, false otherwise
1876
+     * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1877
+     */
1878
+    private function getMountForLock($absolutePath, $useParentMount = false) {
1879
+        $results = [];
1880
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1881
+        if (!$mount) {
1882
+            return $results;
1883
+        }
1884
+
1885
+        if ($useParentMount) {
1886
+            // find out if something is mounted directly on the path
1887
+            $internalPath = $mount->getInternalPath($absolutePath);
1888
+            if ($internalPath === '') {
1889
+                // resolve the parent mount instead
1890
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1891
+            }
1892
+        }
1893
+
1894
+        return $mount;
1895
+    }
1896
+
1897
+    /**
1898
+     * Lock the given path
1899
+     *
1900
+     * @param string $path the path of the file to lock, relative to the view
1901
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1902
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1903
+     *
1904
+     * @return bool False if the path is excluded from locking, true otherwise
1905
+     * @throws \OCP\Lock\LockedException if the path is already locked
1906
+     */
1907
+    private function lockPath($path, $type, $lockMountPoint = false) {
1908
+        $absolutePath = $this->getAbsolutePath($path);
1909
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1910
+        if (!$this->shouldLockFile($absolutePath)) {
1911
+            return false;
1912
+        }
1913
+
1914
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1915
+        if ($mount) {
1916
+            try {
1917
+                $storage = $mount->getStorage();
1918
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1919
+                    $storage->acquireLock(
1920
+                        $mount->getInternalPath($absolutePath),
1921
+                        $type,
1922
+                        $this->lockingProvider
1923
+                    );
1924
+                }
1925
+            } catch (\OCP\Lock\LockedException $e) {
1926
+                // rethrow with the a human-readable path
1927
+                throw new \OCP\Lock\LockedException(
1928
+                    $this->getPathRelativeToFiles($absolutePath),
1929
+                    $e
1930
+                );
1931
+            }
1932
+        }
1933
+
1934
+        return true;
1935
+    }
1936
+
1937
+    /**
1938
+     * Change the lock type
1939
+     *
1940
+     * @param string $path the path of the file to lock, relative to the view
1941
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1942
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1943
+     *
1944
+     * @return bool False if the path is excluded from locking, true otherwise
1945
+     * @throws \OCP\Lock\LockedException if the path is already locked
1946
+     */
1947
+    public function changeLock($path, $type, $lockMountPoint = false) {
1948
+        $path = Filesystem::normalizePath($path);
1949
+        $absolutePath = $this->getAbsolutePath($path);
1950
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1951
+        if (!$this->shouldLockFile($absolutePath)) {
1952
+            return false;
1953
+        }
1954
+
1955
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1956
+        if ($mount) {
1957
+            try {
1958
+                $storage = $mount->getStorage();
1959
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1960
+                    $storage->changeLock(
1961
+                        $mount->getInternalPath($absolutePath),
1962
+                        $type,
1963
+                        $this->lockingProvider
1964
+                    );
1965
+                }
1966
+            } catch (\OCP\Lock\LockedException $e) {
1967
+                try {
1968
+                    // rethrow with the a human-readable path
1969
+                    throw new \OCP\Lock\LockedException(
1970
+                        $this->getPathRelativeToFiles($absolutePath),
1971
+                        $e
1972
+                    );
1973
+                } catch (\InvalidArgumentException $e) {
1974
+                    throw new \OCP\Lock\LockedException(
1975
+                        $absolutePath,
1976
+                        $e
1977
+                    );
1978
+                }
1979
+            }
1980
+        }
1981
+
1982
+        return true;
1983
+    }
1984
+
1985
+    /**
1986
+     * Unlock the given path
1987
+     *
1988
+     * @param string $path the path of the file to unlock, relative to the view
1989
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1990
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1991
+     *
1992
+     * @return bool False if the path is excluded from locking, true otherwise
1993
+     */
1994
+    private function unlockPath($path, $type, $lockMountPoint = false) {
1995
+        $absolutePath = $this->getAbsolutePath($path);
1996
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1997
+        if (!$this->shouldLockFile($absolutePath)) {
1998
+            return false;
1999
+        }
2000
+
2001
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2002
+        if ($mount) {
2003
+            $storage = $mount->getStorage();
2004
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2005
+                $storage->releaseLock(
2006
+                    $mount->getInternalPath($absolutePath),
2007
+                    $type,
2008
+                    $this->lockingProvider
2009
+                );
2010
+            }
2011
+        }
2012
+
2013
+        return true;
2014
+    }
2015
+
2016
+    /**
2017
+     * Lock a path and all its parents up to the root of the view
2018
+     *
2019
+     * @param string $path the path of the file to lock relative to the view
2020
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2021
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2022
+     *
2023
+     * @return bool False if the path is excluded from locking, true otherwise
2024
+     */
2025
+    public function lockFile($path, $type, $lockMountPoint = false) {
2026
+        $absolutePath = $this->getAbsolutePath($path);
2027
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2028
+        if (!$this->shouldLockFile($absolutePath)) {
2029
+            return false;
2030
+        }
2031
+
2032
+        $this->lockPath($path, $type, $lockMountPoint);
2033
+
2034
+        $parents = $this->getParents($path);
2035
+        foreach ($parents as $parent) {
2036
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2037
+        }
2038
+
2039
+        return true;
2040
+    }
2041
+
2042
+    /**
2043
+     * Unlock a path and all its parents up to the root of the view
2044
+     *
2045
+     * @param string $path the path of the file to lock relative to the view
2046
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2047
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2048
+     *
2049
+     * @return bool False if the path is excluded from locking, true otherwise
2050
+     */
2051
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2052
+        $absolutePath = $this->getAbsolutePath($path);
2053
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2054
+        if (!$this->shouldLockFile($absolutePath)) {
2055
+            return false;
2056
+        }
2057
+
2058
+        $this->unlockPath($path, $type, $lockMountPoint);
2059
+
2060
+        $parents = $this->getParents($path);
2061
+        foreach ($parents as $parent) {
2062
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2063
+        }
2064
+
2065
+        return true;
2066
+    }
2067
+
2068
+    /**
2069
+     * Only lock files in data/user/files/
2070
+     *
2071
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2072
+     * @return bool
2073
+     */
2074
+    protected function shouldLockFile($path) {
2075
+        $path = Filesystem::normalizePath($path);
2076
+
2077
+        $pathSegments = explode('/', $path);
2078
+        if (isset($pathSegments[2])) {
2079
+            // E.g.: /username/files/path-to-file
2080
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2081
+        }
2082
+
2083
+        return strpos($path, '/appdata_') !== 0;
2084
+    }
2085
+
2086
+    /**
2087
+     * Shortens the given absolute path to be relative to
2088
+     * "$user/files".
2089
+     *
2090
+     * @param string $absolutePath absolute path which is under "files"
2091
+     *
2092
+     * @return string path relative to "files" with trimmed slashes or null
2093
+     * if the path was NOT relative to files
2094
+     *
2095
+     * @throws \InvalidArgumentException if the given path was not under "files"
2096
+     * @since 8.1.0
2097
+     */
2098
+    public function getPathRelativeToFiles($absolutePath) {
2099
+        $path = Filesystem::normalizePath($absolutePath);
2100
+        $parts = explode('/', trim($path, '/'), 3);
2101
+        // "$user", "files", "path/to/dir"
2102
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2103
+            $this->logger->error(
2104
+                '$absolutePath must be relative to "files", value is "%s"',
2105
+                [
2106
+                    $absolutePath
2107
+                ]
2108
+            );
2109
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2110
+        }
2111
+        if (isset($parts[2])) {
2112
+            return $parts[2];
2113
+        }
2114
+        return '';
2115
+    }
2116
+
2117
+    /**
2118
+     * @param string $filename
2119
+     * @return array
2120
+     * @throws \OC\User\NoUserException
2121
+     * @throws NotFoundException
2122
+     */
2123
+    public function getUidAndFilename($filename) {
2124
+        $info = $this->getFileInfo($filename);
2125
+        if (!$info instanceof \OCP\Files\FileInfo) {
2126
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2127
+        }
2128
+        $uid = $info->getOwner()->getUID();
2129
+        if ($uid != \OCP\User::getUser()) {
2130
+            Filesystem::initMountPoints($uid);
2131
+            $ownerView = new View('/' . $uid . '/files');
2132
+            try {
2133
+                $filename = $ownerView->getPath($info['fileid']);
2134
+            } catch (NotFoundException $e) {
2135
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2136
+            }
2137
+        }
2138
+        return [$uid, $filename];
2139
+    }
2140
+
2141
+    /**
2142
+     * Creates parent non-existing folders
2143
+     *
2144
+     * @param string $filePath
2145
+     * @return bool
2146
+     */
2147
+    private function createParentDirectories($filePath) {
2148
+        $directoryParts = explode('/', $filePath);
2149
+        $directoryParts = array_filter($directoryParts);
2150
+        foreach ($directoryParts as $key => $part) {
2151
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2152
+            $currentPath = '/' . implode('/', $currentPathElements);
2153
+            if ($this->is_file($currentPath)) {
2154
+                return false;
2155
+            }
2156
+            if (!$this->file_exists($currentPath)) {
2157
+                $this->mkdir($currentPath);
2158
+            }
2159
+        }
2160
+
2161
+        return true;
2162
+    }
2163 2163
 }
Please login to merge, or discard this patch.
lib/private/Repair/RepairMimeTypes.php 2 patches
Indentation   +140 added lines, -140 removed lines patch added patch discarded remove patch
@@ -34,162 +34,162 @@
 block discarded – undo
34 34
 use OCP\Migration\IRepairStep;
35 35
 
36 36
 class RepairMimeTypes implements IRepairStep {
37
-	/**
38
-	 * @var \OCP\IConfig
39
-	 */
40
-	protected $config;
41
-
42
-	/**
43
-	 * @var int
44
-	 */
45
-	protected $folderMimeTypeId;
46
-
47
-	/**
48
-	 * @param \OCP\IConfig $config
49
-	 */
50
-	public function __construct($config) {
51
-		$this->config = $config;
52
-	}
53
-
54
-	public function getName() {
55
-		return 'Repair mime types';
56
-	}
57
-
58
-	private static function existsStmt() {
59
-		return \OC_DB::prepare('
37
+    /**
38
+     * @var \OCP\IConfig
39
+     */
40
+    protected $config;
41
+
42
+    /**
43
+     * @var int
44
+     */
45
+    protected $folderMimeTypeId;
46
+
47
+    /**
48
+     * @param \OCP\IConfig $config
49
+     */
50
+    public function __construct($config) {
51
+        $this->config = $config;
52
+    }
53
+
54
+    public function getName() {
55
+        return 'Repair mime types';
56
+    }
57
+
58
+    private static function existsStmt() {
59
+        return \OC_DB::prepare('
60 60
 			SELECT count(`mimetype`)
61 61
 			FROM   `*PREFIX*mimetypes`
62 62
 			WHERE  `mimetype` = ?
63 63
 		');
64
-	}
64
+    }
65 65
 
66
-	private static function getIdStmt() {
67
-		return \OC_DB::prepare('
66
+    private static function getIdStmt() {
67
+        return \OC_DB::prepare('
68 68
 			SELECT `id`
69 69
 			FROM   `*PREFIX*mimetypes`
70 70
 			WHERE  `mimetype` = ?
71 71
 		');
72
-	}
72
+    }
73 73
 
74
-	private static function insertStmt() {
75
-		return \OC_DB::prepare('
74
+    private static function insertStmt() {
75
+        return \OC_DB::prepare('
76 76
 			INSERT INTO `*PREFIX*mimetypes` ( `mimetype` )
77 77
 			VALUES ( ? )
78 78
 		');
79
-	}
79
+    }
80 80
 
81
-	private static function updateByNameStmt() {
82
-		return \OC_DB::prepare('
81
+    private static function updateByNameStmt() {
82
+        return \OC_DB::prepare('
83 83
 			UPDATE `*PREFIX*filecache`
84 84
 			SET `mimetype` = ?
85 85
 			WHERE `mimetype` <> ? AND `mimetype` <> ? AND `name` ILIKE ?
86 86
 		');
87
-	}
88
-
89
-	private function updateMimetypes($updatedMimetypes) {
90
-		if (empty($this->folderMimeTypeId)) {
91
-			$result = \OC_DB::executeAudited(self::getIdStmt(), array('httpd/unix-directory'));
92
-			$this->folderMimeTypeId = (int)$result->fetchOne();
93
-		}
94
-
95
-		$count = 0;
96
-		foreach ($updatedMimetypes as $extension => $mimetype) {
97
-			$result = \OC_DB::executeAudited(self::existsStmt(), array($mimetype));
98
-			$exists = $result->fetchOne();
99
-
100
-			if (!$exists) {
101
-				// insert mimetype
102
-				\OC_DB::executeAudited(self::insertStmt(), array($mimetype));
103
-			}
104
-
105
-			// get target mimetype id
106
-			$result = \OC_DB::executeAudited(self::getIdStmt(), array($mimetype));
107
-			$mimetypeId = $result->fetchOne();
108
-
109
-			// change mimetype for files with x extension
110
-			$count += \OC_DB::executeAudited(self::updateByNameStmt(), array($mimetypeId, $this->folderMimeTypeId, $mimetypeId, '%.' . $extension));
111
-		}
112
-
113
-		return $count;
114
-	}
115
-
116
-	private function introduceImageTypes() {
117
-		$updatedMimetypes = array(
118
-			'jp2' => 'image/jp2',
119
-			'webp' => 'image/webp',
120
-		);
121
-
122
-		return $this->updateMimetypes($updatedMimetypes);
123
-	}
124
-
125
-	private function introduceWindowsProgramTypes() {
126
-		$updatedMimetypes = array(
127
-			'htaccess' => 'text/plain',
128
-			'bat' => 'application/x-msdos-program',
129
-			'cmd' => 'application/cmd',
130
-		);
131
-
132
-		return $this->updateMimetypes($updatedMimetypes);
133
-	}
134
-
135
-	private function introduceLocationTypes() {
136
-		$updatedMimetypes = [
137
-			'gpx' => 'application/gpx+xml',
138
-			'kml' => 'application/vnd.google-earth.kml+xml',
139
-			'kmz' => 'application/vnd.google-earth.kmz',
140
-			'tcx' => 'application/vnd.garmin.tcx+xml',
141
-		];
142
-
143
-		return $this->updateMimetypes($updatedMimetypes);
144
-	}
145
-
146
-	private function introduceInternetShortcutTypes() {
147
-		$updatedMimetypes = [
148
-			'url' => 'application/internet-shortcut',
149
-			'webloc' => 'application/internet-shortcut'
150
-		];
151
-
152
-		return $this->updateMimetypes($updatedMimetypes);
153
-	}
154
-
155
-	private function introduceStreamingTypes() {
156
-		$updatedMimetypes = [
157
-			'm3u' => 'audio/mpegurl',
158
-			'm3u8' => 'audio/mpegurl',
159
-			'pls' => 'audio/x-scpls'
160
-		];
161
-
162
-		return $this->updateMimetypes($updatedMimetypes);
163
-	}
164
-
165
-	/**
166
-	 * Fix mime types
167
-	 */
168
-	public function run(IOutput $out) {
169
-
170
-		$ocVersionFromBeforeUpdate = $this->config->getSystemValue('version', '0.0.0');
171
-
172
-		// NOTE TO DEVELOPERS: when adding new mime types, please make sure to
173
-		// add a version comparison to avoid doing it every time
174
-
175
-		if (version_compare($ocVersionFromBeforeUpdate, '12.0.0.14', '<') && $this->introduceImageTypes()) {
176
-			$out->info('Fixed image mime types');
177
-		}
178
-
179
-		if (version_compare($ocVersionFromBeforeUpdate, '12.0.0.13', '<') && $this->introduceWindowsProgramTypes()) {
180
-			$out->info('Fixed windows program mime types');
181
-		}
182
-
183
-		if (version_compare($ocVersionFromBeforeUpdate, '13.0.0.0', '<') && $this->introduceLocationTypes()) {
184
-			$out->info('Fixed geospatial mime types');
185
-		}
186
-
187
-		if (version_compare($ocVersionFromBeforeUpdate, '13.0.0.3', '<') && $this->introduceInternetShortcutTypes()) {
188
-			$out->info('Fixed internet-shortcut mime types');
189
-		}
190
-
191
-		if (version_compare($ocVersionFromBeforeUpdate, '13.0.0.6', '<') && $this->introduceStreamingTypes()) {
192
-			$out->info('Fixed streaming mime types');
193
-		}
194
-	}
87
+    }
88
+
89
+    private function updateMimetypes($updatedMimetypes) {
90
+        if (empty($this->folderMimeTypeId)) {
91
+            $result = \OC_DB::executeAudited(self::getIdStmt(), array('httpd/unix-directory'));
92
+            $this->folderMimeTypeId = (int)$result->fetchOne();
93
+        }
94
+
95
+        $count = 0;
96
+        foreach ($updatedMimetypes as $extension => $mimetype) {
97
+            $result = \OC_DB::executeAudited(self::existsStmt(), array($mimetype));
98
+            $exists = $result->fetchOne();
99
+
100
+            if (!$exists) {
101
+                // insert mimetype
102
+                \OC_DB::executeAudited(self::insertStmt(), array($mimetype));
103
+            }
104
+
105
+            // get target mimetype id
106
+            $result = \OC_DB::executeAudited(self::getIdStmt(), array($mimetype));
107
+            $mimetypeId = $result->fetchOne();
108
+
109
+            // change mimetype for files with x extension
110
+            $count += \OC_DB::executeAudited(self::updateByNameStmt(), array($mimetypeId, $this->folderMimeTypeId, $mimetypeId, '%.' . $extension));
111
+        }
112
+
113
+        return $count;
114
+    }
115
+
116
+    private function introduceImageTypes() {
117
+        $updatedMimetypes = array(
118
+            'jp2' => 'image/jp2',
119
+            'webp' => 'image/webp',
120
+        );
121
+
122
+        return $this->updateMimetypes($updatedMimetypes);
123
+    }
124
+
125
+    private function introduceWindowsProgramTypes() {
126
+        $updatedMimetypes = array(
127
+            'htaccess' => 'text/plain',
128
+            'bat' => 'application/x-msdos-program',
129
+            'cmd' => 'application/cmd',
130
+        );
131
+
132
+        return $this->updateMimetypes($updatedMimetypes);
133
+    }
134
+
135
+    private function introduceLocationTypes() {
136
+        $updatedMimetypes = [
137
+            'gpx' => 'application/gpx+xml',
138
+            'kml' => 'application/vnd.google-earth.kml+xml',
139
+            'kmz' => 'application/vnd.google-earth.kmz',
140
+            'tcx' => 'application/vnd.garmin.tcx+xml',
141
+        ];
142
+
143
+        return $this->updateMimetypes($updatedMimetypes);
144
+    }
145
+
146
+    private function introduceInternetShortcutTypes() {
147
+        $updatedMimetypes = [
148
+            'url' => 'application/internet-shortcut',
149
+            'webloc' => 'application/internet-shortcut'
150
+        ];
151
+
152
+        return $this->updateMimetypes($updatedMimetypes);
153
+    }
154
+
155
+    private function introduceStreamingTypes() {
156
+        $updatedMimetypes = [
157
+            'm3u' => 'audio/mpegurl',
158
+            'm3u8' => 'audio/mpegurl',
159
+            'pls' => 'audio/x-scpls'
160
+        ];
161
+
162
+        return $this->updateMimetypes($updatedMimetypes);
163
+    }
164
+
165
+    /**
166
+     * Fix mime types
167
+     */
168
+    public function run(IOutput $out) {
169
+
170
+        $ocVersionFromBeforeUpdate = $this->config->getSystemValue('version', '0.0.0');
171
+
172
+        // NOTE TO DEVELOPERS: when adding new mime types, please make sure to
173
+        // add a version comparison to avoid doing it every time
174
+
175
+        if (version_compare($ocVersionFromBeforeUpdate, '12.0.0.14', '<') && $this->introduceImageTypes()) {
176
+            $out->info('Fixed image mime types');
177
+        }
178
+
179
+        if (version_compare($ocVersionFromBeforeUpdate, '12.0.0.13', '<') && $this->introduceWindowsProgramTypes()) {
180
+            $out->info('Fixed windows program mime types');
181
+        }
182
+
183
+        if (version_compare($ocVersionFromBeforeUpdate, '13.0.0.0', '<') && $this->introduceLocationTypes()) {
184
+            $out->info('Fixed geospatial mime types');
185
+        }
186
+
187
+        if (version_compare($ocVersionFromBeforeUpdate, '13.0.0.3', '<') && $this->introduceInternetShortcutTypes()) {
188
+            $out->info('Fixed internet-shortcut mime types');
189
+        }
190
+
191
+        if (version_compare($ocVersionFromBeforeUpdate, '13.0.0.6', '<') && $this->introduceStreamingTypes()) {
192
+            $out->info('Fixed streaming mime types');
193
+        }
194
+    }
195 195
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	private function updateMimetypes($updatedMimetypes) {
90 90
 		if (empty($this->folderMimeTypeId)) {
91 91
 			$result = \OC_DB::executeAudited(self::getIdStmt(), array('httpd/unix-directory'));
92
-			$this->folderMimeTypeId = (int)$result->fetchOne();
92
+			$this->folderMimeTypeId = (int) $result->fetchOne();
93 93
 		}
94 94
 
95 95
 		$count = 0;
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
 			$mimetypeId = $result->fetchOne();
108 108
 
109 109
 			// change mimetype for files with x extension
110
-			$count += \OC_DB::executeAudited(self::updateByNameStmt(), array($mimetypeId, $this->folderMimeTypeId, $mimetypeId, '%.' . $extension));
110
+			$count += \OC_DB::executeAudited(self::updateByNameStmt(), array($mimetypeId, $this->folderMimeTypeId, $mimetypeId, '%.'.$extension));
111 111
 		}
112 112
 
113 113
 		return $count;
Please login to merge, or discard this patch.
lib/private/Template/JSCombiner.php 1 patch
Indentation   +192 added lines, -192 removed lines patch added patch discarded remove patch
@@ -35,196 +35,196 @@
 block discarded – undo
35 35
 
36 36
 class JSCombiner {
37 37
 
38
-	/** @var IAppData */
39
-	protected $appData;
40
-
41
-	/** @var IURLGenerator */
42
-	protected $urlGenerator;
43
-
44
-	/** @var ICache */
45
-	protected $depsCache;
46
-
47
-	/** @var SystemConfig */
48
-	protected $config;
49
-
50
-	/** @var ILogger */
51
-	protected $logger;
52
-
53
-	/**
54
-	 * @param IAppData $appData
55
-	 * @param IURLGenerator $urlGenerator
56
-	 * @param ICache $depsCache
57
-	 * @param SystemConfig $config
58
-	 * @param ILogger $logger
59
-	 */
60
-	public function __construct(IAppData $appData,
61
-								IURLGenerator $urlGenerator,
62
-								ICache $depsCache,
63
-								SystemConfig $config,
64
-								ILogger $logger) {
65
-		$this->appData = $appData;
66
-		$this->urlGenerator = $urlGenerator;
67
-		$this->depsCache = $depsCache;
68
-		$this->config = $config;
69
-		$this->logger = $logger;
70
-	}
71
-
72
-	/**
73
-	 * @param string $root
74
-	 * @param string $file
75
-	 * @param string $app
76
-	 * @return bool
77
-	 */
78
-	public function process($root, $file, $app) {
79
-		if ($this->config->getValue('debug') || !$this->config->getValue('installed')) {
80
-			return false;
81
-		}
82
-
83
-		$path = explode('/', $root . '/' . $file);
84
-
85
-		$fileName = array_pop($path);
86
-		$path = implode('/', $path);
87
-
88
-		try {
89
-			$folder = $this->appData->getFolder($app);
90
-		} catch(NotFoundException $e) {
91
-			// creating css appdata folder
92
-			$folder = $this->appData->newFolder($app);
93
-		}
94
-
95
-		if($this->isCached($fileName, $folder)) {
96
-			return true;
97
-		}
98
-		return $this->cache($path, $fileName, $folder);
99
-	}
100
-
101
-	/**
102
-	 * @param string $fileName
103
-	 * @param ISimpleFolder $folder
104
-	 * @return bool
105
-	 */
106
-	protected function isCached($fileName, ISimpleFolder $folder) {
107
-		$fileName = str_replace('.json', '.js', $fileName) . '.deps';
108
-		try {
109
-			$deps = $this->depsCache->get($folder->getName() . '-' . $fileName);
110
-			if ($deps === null || $deps === '') {
111
-				$depFile = $folder->getFile($fileName);
112
-				$deps = $depFile->getContent();
113
-			}
114
-			// check again
115
-			if ($deps === null || $deps === '') {
116
-				$this->logger->info('JSCombiner: deps file empty: ' . $fileName);
117
-				return false;
118
-			}
119
-
120
-			$deps = json_decode($deps, true);
121
-
122
-			if ($deps === NULL) {
123
-				return false;
124
-			}
125
-
126
-			foreach ($deps as $file=>$mtime) {
127
-				if (!file_exists($file) || filemtime($file) > $mtime) {
128
-					return false;
129
-				}
130
-			}
131
-
132
-			return true;
133
-		} catch(NotFoundException $e) {
134
-			return false;
135
-		}
136
-	}
137
-
138
-	/**
139
-	 * @param string $path
140
-	 * @param string $fileName
141
-	 * @param ISimpleFolder $folder
142
-	 * @return bool
143
-	 */
144
-	protected function cache($path, $fileName, ISimpleFolder $folder) {
145
-		$deps = [];
146
-		$fullPath = $path . '/' . $fileName;
147
-		$data = json_decode(file_get_contents($fullPath));
148
-		$deps[$fullPath] = filemtime($fullPath);
149
-
150
-		$res = '';
151
-		foreach ($data as $file) {
152
-			$filePath = $path . '/' . $file;
153
-
154
-			if (is_file($filePath)) {
155
-				$res .= file_get_contents($filePath);
156
-				$res .= PHP_EOL . PHP_EOL;
157
-				$deps[$filePath] = filemtime($filePath);
158
-			}
159
-		}
160
-
161
-		$fileName = str_replace('.json', '.js', $fileName);
162
-		try {
163
-			$cachedfile = $folder->getFile($fileName);
164
-		} catch(NotFoundException $e) {
165
-			$cachedfile = $folder->newFile($fileName);
166
-		}
167
-
168
-		$depFileName = $fileName . '.deps';
169
-		try {
170
-			$depFile = $folder->getFile($depFileName);
171
-		} catch (NotFoundException $e) {
172
-			$depFile = $folder->newFile($depFileName);
173
-		}
174
-
175
-		try {
176
-			$gzipFile = $folder->getFile($fileName . '.gzip'); # Safari doesn't like .gz
177
-		} catch (NotFoundException $e) {
178
-			$gzipFile = $folder->newFile($fileName . '.gzip'); # Safari doesn't like .gz
179
-		}
180
-
181
-		try {
182
-			$cachedfile->putContent($res);
183
-			$deps = json_encode($deps);
184
-			$depFile->putContent($deps);
185
-			$this->depsCache->set($folder->getName() . '-' . $depFileName, $deps);
186
-			$gzipFile->putContent(gzencode($res, 9));
187
-
188
-			return true;
189
-		} catch (NotPermittedException $e) {
190
-			return false;
191
-		}
192
-	}
193
-
194
-	/**
195
-	 * @param string $appName
196
-	 * @param string $fileName
197
-	 * @return string
198
-	 */
199
-	public function getCachedJS($appName, $fileName) {
200
-		$tmpfileLoc = explode('/', $fileName);
201
-		$fileName = array_pop($tmpfileLoc);
202
-		$fileName = str_replace('.json', '.js', $fileName);
203
-
204
-		return substr($this->urlGenerator->linkToRoute('core.Js.getJs', array('fileName' => $fileName, 'appName' => $appName)), strlen(\OC::$WEBROOT) + 1);
205
-	}
206
-
207
-	/**
208
-	 * @param string $root
209
-	 * @param string $file
210
-	 * @return string[]
211
-	 */
212
-	public function getContent($root, $file) {
213
-		/** @var array $data */
214
-		$data = json_decode(file_get_contents($root . '/' . $file));
215
-		if(!is_array($data)) {
216
-			return [];
217
-		}
218
-
219
-		$path = explode('/', $file);
220
-		array_pop($path);
221
-		$path = implode('/', $path);
222
-
223
-		$result = [];
224
-		foreach ($data as $f) {
225
-			$result[] = $path . '/' . $f;
226
-		}
227
-
228
-		return $result;
229
-	}
38
+    /** @var IAppData */
39
+    protected $appData;
40
+
41
+    /** @var IURLGenerator */
42
+    protected $urlGenerator;
43
+
44
+    /** @var ICache */
45
+    protected $depsCache;
46
+
47
+    /** @var SystemConfig */
48
+    protected $config;
49
+
50
+    /** @var ILogger */
51
+    protected $logger;
52
+
53
+    /**
54
+     * @param IAppData $appData
55
+     * @param IURLGenerator $urlGenerator
56
+     * @param ICache $depsCache
57
+     * @param SystemConfig $config
58
+     * @param ILogger $logger
59
+     */
60
+    public function __construct(IAppData $appData,
61
+                                IURLGenerator $urlGenerator,
62
+                                ICache $depsCache,
63
+                                SystemConfig $config,
64
+                                ILogger $logger) {
65
+        $this->appData = $appData;
66
+        $this->urlGenerator = $urlGenerator;
67
+        $this->depsCache = $depsCache;
68
+        $this->config = $config;
69
+        $this->logger = $logger;
70
+    }
71
+
72
+    /**
73
+     * @param string $root
74
+     * @param string $file
75
+     * @param string $app
76
+     * @return bool
77
+     */
78
+    public function process($root, $file, $app) {
79
+        if ($this->config->getValue('debug') || !$this->config->getValue('installed')) {
80
+            return false;
81
+        }
82
+
83
+        $path = explode('/', $root . '/' . $file);
84
+
85
+        $fileName = array_pop($path);
86
+        $path = implode('/', $path);
87
+
88
+        try {
89
+            $folder = $this->appData->getFolder($app);
90
+        } catch(NotFoundException $e) {
91
+            // creating css appdata folder
92
+            $folder = $this->appData->newFolder($app);
93
+        }
94
+
95
+        if($this->isCached($fileName, $folder)) {
96
+            return true;
97
+        }
98
+        return $this->cache($path, $fileName, $folder);
99
+    }
100
+
101
+    /**
102
+     * @param string $fileName
103
+     * @param ISimpleFolder $folder
104
+     * @return bool
105
+     */
106
+    protected function isCached($fileName, ISimpleFolder $folder) {
107
+        $fileName = str_replace('.json', '.js', $fileName) . '.deps';
108
+        try {
109
+            $deps = $this->depsCache->get($folder->getName() . '-' . $fileName);
110
+            if ($deps === null || $deps === '') {
111
+                $depFile = $folder->getFile($fileName);
112
+                $deps = $depFile->getContent();
113
+            }
114
+            // check again
115
+            if ($deps === null || $deps === '') {
116
+                $this->logger->info('JSCombiner: deps file empty: ' . $fileName);
117
+                return false;
118
+            }
119
+
120
+            $deps = json_decode($deps, true);
121
+
122
+            if ($deps === NULL) {
123
+                return false;
124
+            }
125
+
126
+            foreach ($deps as $file=>$mtime) {
127
+                if (!file_exists($file) || filemtime($file) > $mtime) {
128
+                    return false;
129
+                }
130
+            }
131
+
132
+            return true;
133
+        } catch(NotFoundException $e) {
134
+            return false;
135
+        }
136
+    }
137
+
138
+    /**
139
+     * @param string $path
140
+     * @param string $fileName
141
+     * @param ISimpleFolder $folder
142
+     * @return bool
143
+     */
144
+    protected function cache($path, $fileName, ISimpleFolder $folder) {
145
+        $deps = [];
146
+        $fullPath = $path . '/' . $fileName;
147
+        $data = json_decode(file_get_contents($fullPath));
148
+        $deps[$fullPath] = filemtime($fullPath);
149
+
150
+        $res = '';
151
+        foreach ($data as $file) {
152
+            $filePath = $path . '/' . $file;
153
+
154
+            if (is_file($filePath)) {
155
+                $res .= file_get_contents($filePath);
156
+                $res .= PHP_EOL . PHP_EOL;
157
+                $deps[$filePath] = filemtime($filePath);
158
+            }
159
+        }
160
+
161
+        $fileName = str_replace('.json', '.js', $fileName);
162
+        try {
163
+            $cachedfile = $folder->getFile($fileName);
164
+        } catch(NotFoundException $e) {
165
+            $cachedfile = $folder->newFile($fileName);
166
+        }
167
+
168
+        $depFileName = $fileName . '.deps';
169
+        try {
170
+            $depFile = $folder->getFile($depFileName);
171
+        } catch (NotFoundException $e) {
172
+            $depFile = $folder->newFile($depFileName);
173
+        }
174
+
175
+        try {
176
+            $gzipFile = $folder->getFile($fileName . '.gzip'); # Safari doesn't like .gz
177
+        } catch (NotFoundException $e) {
178
+            $gzipFile = $folder->newFile($fileName . '.gzip'); # Safari doesn't like .gz
179
+        }
180
+
181
+        try {
182
+            $cachedfile->putContent($res);
183
+            $deps = json_encode($deps);
184
+            $depFile->putContent($deps);
185
+            $this->depsCache->set($folder->getName() . '-' . $depFileName, $deps);
186
+            $gzipFile->putContent(gzencode($res, 9));
187
+
188
+            return true;
189
+        } catch (NotPermittedException $e) {
190
+            return false;
191
+        }
192
+    }
193
+
194
+    /**
195
+     * @param string $appName
196
+     * @param string $fileName
197
+     * @return string
198
+     */
199
+    public function getCachedJS($appName, $fileName) {
200
+        $tmpfileLoc = explode('/', $fileName);
201
+        $fileName = array_pop($tmpfileLoc);
202
+        $fileName = str_replace('.json', '.js', $fileName);
203
+
204
+        return substr($this->urlGenerator->linkToRoute('core.Js.getJs', array('fileName' => $fileName, 'appName' => $appName)), strlen(\OC::$WEBROOT) + 1);
205
+    }
206
+
207
+    /**
208
+     * @param string $root
209
+     * @param string $file
210
+     * @return string[]
211
+     */
212
+    public function getContent($root, $file) {
213
+        /** @var array $data */
214
+        $data = json_decode(file_get_contents($root . '/' . $file));
215
+        if(!is_array($data)) {
216
+            return [];
217
+        }
218
+
219
+        $path = explode('/', $file);
220
+        array_pop($path);
221
+        $path = implode('/', $path);
222
+
223
+        $result = [];
224
+        foreach ($data as $f) {
225
+            $result[] = $path . '/' . $f;
226
+        }
227
+
228
+        return $result;
229
+    }
230 230
 }
Please login to merge, or discard this patch.