Passed
Push — master ( 0f0dfc...2f5810 )
by Roeland
23:19 queued 13:50
created
lib/private/Share20/Manager.php 1 patch
Indentation   +1553 added lines, -1553 removed lines patch added patch discarded remove patch
@@ -72,1581 +72,1581 @@
 block discarded – undo
72 72
  */
73 73
 class Manager implements IManager {
74 74
 
75
-	/** @var IProviderFactory */
76
-	private $factory;
77
-	/** @var ILogger */
78
-	private $logger;
79
-	/** @var IConfig */
80
-	private $config;
81
-	/** @var ISecureRandom */
82
-	private $secureRandom;
83
-	/** @var IHasher */
84
-	private $hasher;
85
-	/** @var IMountManager */
86
-	private $mountManager;
87
-	/** @var IGroupManager */
88
-	private $groupManager;
89
-	/** @var IL10N */
90
-	private $l;
91
-	/** @var IFactory */
92
-	private $l10nFactory;
93
-	/** @var IUserManager */
94
-	private $userManager;
95
-	/** @var IRootFolder */
96
-	private $rootFolder;
97
-	/** @var CappedMemoryCache */
98
-	private $sharingDisabledForUsersCache;
99
-	/** @var EventDispatcherInterface */
100
-	private $eventDispatcher;
101
-	/** @var LegacyHooks */
102
-	private $legacyHooks;
103
-	/** @var IMailer */
104
-	private $mailer;
105
-	/** @var IURLGenerator */
106
-	private $urlGenerator;
107
-	/** @var \OC_Defaults */
108
-	private $defaults;
109
-
110
-
111
-	/**
112
-	 * Manager constructor.
113
-	 *
114
-	 * @param ILogger $logger
115
-	 * @param IConfig $config
116
-	 * @param ISecureRandom $secureRandom
117
-	 * @param IHasher $hasher
118
-	 * @param IMountManager $mountManager
119
-	 * @param IGroupManager $groupManager
120
-	 * @param IL10N $l
121
-	 * @param IFactory $l10nFactory
122
-	 * @param IProviderFactory $factory
123
-	 * @param IUserManager $userManager
124
-	 * @param IRootFolder $rootFolder
125
-	 * @param EventDispatcherInterface $eventDispatcher
126
-	 * @param IMailer $mailer
127
-	 * @param IURLGenerator $urlGenerator
128
-	 * @param \OC_Defaults $defaults
129
-	 */
130
-	public function __construct(
131
-			ILogger $logger,
132
-			IConfig $config,
133
-			ISecureRandom $secureRandom,
134
-			IHasher $hasher,
135
-			IMountManager $mountManager,
136
-			IGroupManager $groupManager,
137
-			IL10N $l,
138
-			IFactory $l10nFactory,
139
-			IProviderFactory $factory,
140
-			IUserManager $userManager,
141
-			IRootFolder $rootFolder,
142
-			EventDispatcherInterface $eventDispatcher,
143
-			IMailer $mailer,
144
-			IURLGenerator $urlGenerator,
145
-			\OC_Defaults $defaults
146
-	) {
147
-		$this->logger = $logger;
148
-		$this->config = $config;
149
-		$this->secureRandom = $secureRandom;
150
-		$this->hasher = $hasher;
151
-		$this->mountManager = $mountManager;
152
-		$this->groupManager = $groupManager;
153
-		$this->l = $l;
154
-		$this->l10nFactory = $l10nFactory;
155
-		$this->factory = $factory;
156
-		$this->userManager = $userManager;
157
-		$this->rootFolder = $rootFolder;
158
-		$this->eventDispatcher = $eventDispatcher;
159
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
160
-		$this->legacyHooks = new LegacyHooks($this->eventDispatcher);
161
-		$this->mailer = $mailer;
162
-		$this->urlGenerator = $urlGenerator;
163
-		$this->defaults = $defaults;
164
-	}
165
-
166
-	/**
167
-	 * Convert from a full share id to a tuple (providerId, shareId)
168
-	 *
169
-	 * @param string $id
170
-	 * @return string[]
171
-	 */
172
-	private function splitFullId($id) {
173
-		return explode(':', $id, 2);
174
-	}
175
-
176
-	/**
177
-	 * Verify if a password meets all requirements
178
-	 *
179
-	 * @param string $password
180
-	 * @throws \Exception
181
-	 */
182
-	protected function verifyPassword($password) {
183
-		if ($password === null) {
184
-			// No password is set, check if this is allowed.
185
-			if ($this->shareApiLinkEnforcePassword()) {
186
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
187
-			}
188
-
189
-			return;
190
-		}
191
-
192
-		// Let others verify the password
193
-		try {
194
-			$event = new GenericEvent($password);
195
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
196
-		} catch (HintException $e) {
197
-			throw new \Exception($e->getHint());
198
-		}
199
-	}
200
-
201
-	/**
202
-	 * Check for generic requirements before creating a share
203
-	 *
204
-	 * @param \OCP\Share\IShare $share
205
-	 * @throws \InvalidArgumentException
206
-	 * @throws GenericShareException
207
-	 *
208
-	 * @suppress PhanUndeclaredClassMethod
209
-	 */
210
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
211
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
212
-			// We expect a valid user as sharedWith for user shares
213
-			if (!$this->userManager->userExists($share->getSharedWith())) {
214
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
215
-			}
216
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
217
-			// We expect a valid group as sharedWith for group shares
218
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
219
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
220
-			}
221
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
222
-			if ($share->getSharedWith() !== null) {
223
-				throw new \InvalidArgumentException('SharedWith should be empty');
224
-			}
225
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
226
-			if ($share->getSharedWith() === null) {
227
-				throw new \InvalidArgumentException('SharedWith should not be empty');
228
-			}
229
-		}  else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
230
-			if ($share->getSharedWith() === null) {
231
-				throw new \InvalidArgumentException('SharedWith should not be empty');
232
-			}
233
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
234
-			if ($share->getSharedWith() === null) {
235
-				throw new \InvalidArgumentException('SharedWith should not be empty');
236
-			}
237
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
238
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
239
-			if ($circle === null) {
240
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
241
-			}
242
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_ROOM) {
243
-		} else {
244
-			// We can't handle other types yet
245
-			throw new \InvalidArgumentException('unknown share type');
246
-		}
247
-
248
-		// Verify the initiator of the share is set
249
-		if ($share->getSharedBy() === null) {
250
-			throw new \InvalidArgumentException('SharedBy should be set');
251
-		}
252
-
253
-		// Cannot share with yourself
254
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
255
-			$share->getSharedWith() === $share->getSharedBy()) {
256
-			throw new \InvalidArgumentException('Can’t share with yourself');
257
-		}
258
-
259
-		// The path should be set
260
-		if ($share->getNode() === null) {
261
-			throw new \InvalidArgumentException('Path should be set');
262
-		}
263
-
264
-		// And it should be a file or a folder
265
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
266
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
267
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
268
-		}
269
-
270
-		// And you can't share your rootfolder
271
-		if ($this->userManager->userExists($share->getSharedBy())) {
272
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
273
-		} else {
274
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
275
-		}
276
-		if ($sharedPath === $share->getNode()->getPath()) {
277
-			throw new \InvalidArgumentException('You can’t share your root folder');
278
-		}
279
-
280
-		// Check if we actually have share permissions
281
-		if (!$share->getNode()->isShareable()) {
282
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
283
-			throw new GenericShareException($message_t, $message_t, 404);
284
-		}
285
-
286
-		// Permissions should be set
287
-		if ($share->getPermissions() === null) {
288
-			throw new \InvalidArgumentException('A share requires permissions');
289
-		}
290
-
291
-		/*
75
+    /** @var IProviderFactory */
76
+    private $factory;
77
+    /** @var ILogger */
78
+    private $logger;
79
+    /** @var IConfig */
80
+    private $config;
81
+    /** @var ISecureRandom */
82
+    private $secureRandom;
83
+    /** @var IHasher */
84
+    private $hasher;
85
+    /** @var IMountManager */
86
+    private $mountManager;
87
+    /** @var IGroupManager */
88
+    private $groupManager;
89
+    /** @var IL10N */
90
+    private $l;
91
+    /** @var IFactory */
92
+    private $l10nFactory;
93
+    /** @var IUserManager */
94
+    private $userManager;
95
+    /** @var IRootFolder */
96
+    private $rootFolder;
97
+    /** @var CappedMemoryCache */
98
+    private $sharingDisabledForUsersCache;
99
+    /** @var EventDispatcherInterface */
100
+    private $eventDispatcher;
101
+    /** @var LegacyHooks */
102
+    private $legacyHooks;
103
+    /** @var IMailer */
104
+    private $mailer;
105
+    /** @var IURLGenerator */
106
+    private $urlGenerator;
107
+    /** @var \OC_Defaults */
108
+    private $defaults;
109
+
110
+
111
+    /**
112
+     * Manager constructor.
113
+     *
114
+     * @param ILogger $logger
115
+     * @param IConfig $config
116
+     * @param ISecureRandom $secureRandom
117
+     * @param IHasher $hasher
118
+     * @param IMountManager $mountManager
119
+     * @param IGroupManager $groupManager
120
+     * @param IL10N $l
121
+     * @param IFactory $l10nFactory
122
+     * @param IProviderFactory $factory
123
+     * @param IUserManager $userManager
124
+     * @param IRootFolder $rootFolder
125
+     * @param EventDispatcherInterface $eventDispatcher
126
+     * @param IMailer $mailer
127
+     * @param IURLGenerator $urlGenerator
128
+     * @param \OC_Defaults $defaults
129
+     */
130
+    public function __construct(
131
+            ILogger $logger,
132
+            IConfig $config,
133
+            ISecureRandom $secureRandom,
134
+            IHasher $hasher,
135
+            IMountManager $mountManager,
136
+            IGroupManager $groupManager,
137
+            IL10N $l,
138
+            IFactory $l10nFactory,
139
+            IProviderFactory $factory,
140
+            IUserManager $userManager,
141
+            IRootFolder $rootFolder,
142
+            EventDispatcherInterface $eventDispatcher,
143
+            IMailer $mailer,
144
+            IURLGenerator $urlGenerator,
145
+            \OC_Defaults $defaults
146
+    ) {
147
+        $this->logger = $logger;
148
+        $this->config = $config;
149
+        $this->secureRandom = $secureRandom;
150
+        $this->hasher = $hasher;
151
+        $this->mountManager = $mountManager;
152
+        $this->groupManager = $groupManager;
153
+        $this->l = $l;
154
+        $this->l10nFactory = $l10nFactory;
155
+        $this->factory = $factory;
156
+        $this->userManager = $userManager;
157
+        $this->rootFolder = $rootFolder;
158
+        $this->eventDispatcher = $eventDispatcher;
159
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
160
+        $this->legacyHooks = new LegacyHooks($this->eventDispatcher);
161
+        $this->mailer = $mailer;
162
+        $this->urlGenerator = $urlGenerator;
163
+        $this->defaults = $defaults;
164
+    }
165
+
166
+    /**
167
+     * Convert from a full share id to a tuple (providerId, shareId)
168
+     *
169
+     * @param string $id
170
+     * @return string[]
171
+     */
172
+    private function splitFullId($id) {
173
+        return explode(':', $id, 2);
174
+    }
175
+
176
+    /**
177
+     * Verify if a password meets all requirements
178
+     *
179
+     * @param string $password
180
+     * @throws \Exception
181
+     */
182
+    protected function verifyPassword($password) {
183
+        if ($password === null) {
184
+            // No password is set, check if this is allowed.
185
+            if ($this->shareApiLinkEnforcePassword()) {
186
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
187
+            }
188
+
189
+            return;
190
+        }
191
+
192
+        // Let others verify the password
193
+        try {
194
+            $event = new GenericEvent($password);
195
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
196
+        } catch (HintException $e) {
197
+            throw new \Exception($e->getHint());
198
+        }
199
+    }
200
+
201
+    /**
202
+     * Check for generic requirements before creating a share
203
+     *
204
+     * @param \OCP\Share\IShare $share
205
+     * @throws \InvalidArgumentException
206
+     * @throws GenericShareException
207
+     *
208
+     * @suppress PhanUndeclaredClassMethod
209
+     */
210
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
211
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
212
+            // We expect a valid user as sharedWith for user shares
213
+            if (!$this->userManager->userExists($share->getSharedWith())) {
214
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
215
+            }
216
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
217
+            // We expect a valid group as sharedWith for group shares
218
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
219
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
220
+            }
221
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
222
+            if ($share->getSharedWith() !== null) {
223
+                throw new \InvalidArgumentException('SharedWith should be empty');
224
+            }
225
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
226
+            if ($share->getSharedWith() === null) {
227
+                throw new \InvalidArgumentException('SharedWith should not be empty');
228
+            }
229
+        }  else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
230
+            if ($share->getSharedWith() === null) {
231
+                throw new \InvalidArgumentException('SharedWith should not be empty');
232
+            }
233
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
234
+            if ($share->getSharedWith() === null) {
235
+                throw new \InvalidArgumentException('SharedWith should not be empty');
236
+            }
237
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
238
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
239
+            if ($circle === null) {
240
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
241
+            }
242
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_ROOM) {
243
+        } else {
244
+            // We can't handle other types yet
245
+            throw new \InvalidArgumentException('unknown share type');
246
+        }
247
+
248
+        // Verify the initiator of the share is set
249
+        if ($share->getSharedBy() === null) {
250
+            throw new \InvalidArgumentException('SharedBy should be set');
251
+        }
252
+
253
+        // Cannot share with yourself
254
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
255
+            $share->getSharedWith() === $share->getSharedBy()) {
256
+            throw new \InvalidArgumentException('Can’t share with yourself');
257
+        }
258
+
259
+        // The path should be set
260
+        if ($share->getNode() === null) {
261
+            throw new \InvalidArgumentException('Path should be set');
262
+        }
263
+
264
+        // And it should be a file or a folder
265
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
266
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
267
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
268
+        }
269
+
270
+        // And you can't share your rootfolder
271
+        if ($this->userManager->userExists($share->getSharedBy())) {
272
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
273
+        } else {
274
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
275
+        }
276
+        if ($sharedPath === $share->getNode()->getPath()) {
277
+            throw new \InvalidArgumentException('You can’t share your root folder');
278
+        }
279
+
280
+        // Check if we actually have share permissions
281
+        if (!$share->getNode()->isShareable()) {
282
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
283
+            throw new GenericShareException($message_t, $message_t, 404);
284
+        }
285
+
286
+        // Permissions should be set
287
+        if ($share->getPermissions() === null) {
288
+            throw new \InvalidArgumentException('A share requires permissions');
289
+        }
290
+
291
+        /*
292 292
 		 * Quick fix for #23536
293 293
 		 * Non moveable mount points do not have update and delete permissions
294 294
 		 * while we 'most likely' do have that on the storage.
295 295
 		 */
296
-		$permissions = $share->getNode()->getPermissions();
297
-		$mount = $share->getNode()->getMountPoint();
298
-		if (!($mount instanceof MoveableMount)) {
299
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
300
-		}
301
-
302
-		// Check that we do not share with more permissions than we have
303
-		if ($share->getPermissions() & ~$permissions) {
304
-			$message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
305
-			throw new GenericShareException($message_t, $message_t, 404);
306
-		}
307
-
308
-
309
-		// Check that read permissions are always set
310
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
311
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
312
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
313
-		if (!$noReadPermissionRequired &&
314
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
315
-			throw new \InvalidArgumentException('Shares need at least read permissions');
316
-		}
317
-
318
-		if ($share->getNode() instanceof \OCP\Files\File) {
319
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
320
-				$message_t = $this->l->t('Files can’t be shared with delete permissions');
321
-				throw new GenericShareException($message_t);
322
-			}
323
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
324
-				$message_t = $this->l->t('Files can’t be shared with create permissions');
325
-				throw new GenericShareException($message_t);
326
-			}
327
-		}
328
-	}
329
-
330
-	/**
331
-	 * Validate if the expiration date fits the system settings
332
-	 *
333
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
334
-	 * @return \OCP\Share\IShare The modified share object
335
-	 * @throws GenericShareException
336
-	 * @throws \InvalidArgumentException
337
-	 * @throws \Exception
338
-	 */
339
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
340
-
341
-		$expirationDate = $share->getExpirationDate();
342
-
343
-		if ($expirationDate !== null) {
344
-			//Make sure the expiration date is a date
345
-			$expirationDate->setTime(0, 0, 0);
346
-
347
-			$date = new \DateTime();
348
-			$date->setTime(0, 0, 0);
349
-			if ($date >= $expirationDate) {
350
-				$message = $this->l->t('Expiration date is in the past');
351
-				throw new GenericShareException($message, $message, 404);
352
-			}
353
-		}
354
-
355
-		// If expiredate is empty set a default one if there is a default
356
-		$fullId = null;
357
-		try {
358
-			$fullId = $share->getFullId();
359
-		} catch (\UnexpectedValueException $e) {
360
-			// This is a new share
361
-		}
362
-
363
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
364
-			$expirationDate = new \DateTime();
365
-			$expirationDate->setTime(0,0,0);
366
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
367
-		}
368
-
369
-		// If we enforce the expiration date check that is does not exceed
370
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
371
-			if ($expirationDate === null) {
372
-				throw new \InvalidArgumentException('Expiration date is enforced');
373
-			}
374
-
375
-			$date = new \DateTime();
376
-			$date->setTime(0, 0, 0);
377
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
378
-			if ($date < $expirationDate) {
379
-				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
380
-				throw new GenericShareException($message, $message, 404);
381
-			}
382
-		}
383
-
384
-		$accepted = true;
385
-		$message = '';
386
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
387
-			'expirationDate' => &$expirationDate,
388
-			'accepted' => &$accepted,
389
-			'message' => &$message,
390
-			'passwordSet' => $share->getPassword() !== null,
391
-		]);
392
-
393
-		if (!$accepted) {
394
-			throw new \Exception($message);
395
-		}
396
-
397
-		$share->setExpirationDate($expirationDate);
398
-
399
-		return $share;
400
-	}
401
-
402
-	/**
403
-	 * Check for pre share requirements for user shares
404
-	 *
405
-	 * @param \OCP\Share\IShare $share
406
-	 * @throws \Exception
407
-	 */
408
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
409
-		// Check if we can share with group members only
410
-		if ($this->shareWithGroupMembersOnly()) {
411
-			$sharedBy = $this->userManager->get($share->getSharedBy());
412
-			$sharedWith = $this->userManager->get($share->getSharedWith());
413
-			// Verify we can share with this user
414
-			$groups = array_intersect(
415
-					$this->groupManager->getUserGroupIds($sharedBy),
416
-					$this->groupManager->getUserGroupIds($sharedWith)
417
-			);
418
-			if (empty($groups)) {
419
-				throw new \Exception('Sharing is only allowed with group members');
420
-			}
421
-		}
422
-
423
-		/*
296
+        $permissions = $share->getNode()->getPermissions();
297
+        $mount = $share->getNode()->getMountPoint();
298
+        if (!($mount instanceof MoveableMount)) {
299
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
300
+        }
301
+
302
+        // Check that we do not share with more permissions than we have
303
+        if ($share->getPermissions() & ~$permissions) {
304
+            $message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
305
+            throw new GenericShareException($message_t, $message_t, 404);
306
+        }
307
+
308
+
309
+        // Check that read permissions are always set
310
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
311
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
312
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
313
+        if (!$noReadPermissionRequired &&
314
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
315
+            throw new \InvalidArgumentException('Shares need at least read permissions');
316
+        }
317
+
318
+        if ($share->getNode() instanceof \OCP\Files\File) {
319
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
320
+                $message_t = $this->l->t('Files can’t be shared with delete permissions');
321
+                throw new GenericShareException($message_t);
322
+            }
323
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
324
+                $message_t = $this->l->t('Files can’t be shared with create permissions');
325
+                throw new GenericShareException($message_t);
326
+            }
327
+        }
328
+    }
329
+
330
+    /**
331
+     * Validate if the expiration date fits the system settings
332
+     *
333
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
334
+     * @return \OCP\Share\IShare The modified share object
335
+     * @throws GenericShareException
336
+     * @throws \InvalidArgumentException
337
+     * @throws \Exception
338
+     */
339
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
340
+
341
+        $expirationDate = $share->getExpirationDate();
342
+
343
+        if ($expirationDate !== null) {
344
+            //Make sure the expiration date is a date
345
+            $expirationDate->setTime(0, 0, 0);
346
+
347
+            $date = new \DateTime();
348
+            $date->setTime(0, 0, 0);
349
+            if ($date >= $expirationDate) {
350
+                $message = $this->l->t('Expiration date is in the past');
351
+                throw new GenericShareException($message, $message, 404);
352
+            }
353
+        }
354
+
355
+        // If expiredate is empty set a default one if there is a default
356
+        $fullId = null;
357
+        try {
358
+            $fullId = $share->getFullId();
359
+        } catch (\UnexpectedValueException $e) {
360
+            // This is a new share
361
+        }
362
+
363
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
364
+            $expirationDate = new \DateTime();
365
+            $expirationDate->setTime(0,0,0);
366
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
367
+        }
368
+
369
+        // If we enforce the expiration date check that is does not exceed
370
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
371
+            if ($expirationDate === null) {
372
+                throw new \InvalidArgumentException('Expiration date is enforced');
373
+            }
374
+
375
+            $date = new \DateTime();
376
+            $date->setTime(0, 0, 0);
377
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
378
+            if ($date < $expirationDate) {
379
+                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
380
+                throw new GenericShareException($message, $message, 404);
381
+            }
382
+        }
383
+
384
+        $accepted = true;
385
+        $message = '';
386
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
387
+            'expirationDate' => &$expirationDate,
388
+            'accepted' => &$accepted,
389
+            'message' => &$message,
390
+            'passwordSet' => $share->getPassword() !== null,
391
+        ]);
392
+
393
+        if (!$accepted) {
394
+            throw new \Exception($message);
395
+        }
396
+
397
+        $share->setExpirationDate($expirationDate);
398
+
399
+        return $share;
400
+    }
401
+
402
+    /**
403
+     * Check for pre share requirements for user shares
404
+     *
405
+     * @param \OCP\Share\IShare $share
406
+     * @throws \Exception
407
+     */
408
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
409
+        // Check if we can share with group members only
410
+        if ($this->shareWithGroupMembersOnly()) {
411
+            $sharedBy = $this->userManager->get($share->getSharedBy());
412
+            $sharedWith = $this->userManager->get($share->getSharedWith());
413
+            // Verify we can share with this user
414
+            $groups = array_intersect(
415
+                    $this->groupManager->getUserGroupIds($sharedBy),
416
+                    $this->groupManager->getUserGroupIds($sharedWith)
417
+            );
418
+            if (empty($groups)) {
419
+                throw new \Exception('Sharing is only allowed with group members');
420
+            }
421
+        }
422
+
423
+        /*
424 424
 		 * TODO: Could be costly, fix
425 425
 		 *
426 426
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
427 427
 		 */
428
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
429
-		$existingShares = $provider->getSharesByPath($share->getNode());
430
-		foreach($existingShares as $existingShare) {
431
-			// Ignore if it is the same share
432
-			try {
433
-				if ($existingShare->getFullId() === $share->getFullId()) {
434
-					continue;
435
-				}
436
-			} catch (\UnexpectedValueException $e) {
437
-				//Shares are not identical
438
-			}
439
-
440
-			// Identical share already existst
441
-			if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
442
-				throw new \Exception('Path is already shared with this user');
443
-			}
444
-
445
-			// The share is already shared with this user via a group share
446
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
447
-				$group = $this->groupManager->get($existingShare->getSharedWith());
448
-				if (!is_null($group)) {
449
-					$user = $this->userManager->get($share->getSharedWith());
450
-
451
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
452
-						throw new \Exception('Path is already shared with this user');
453
-					}
454
-				}
455
-			}
456
-		}
457
-	}
458
-
459
-	/**
460
-	 * Check for pre share requirements for group shares
461
-	 *
462
-	 * @param \OCP\Share\IShare $share
463
-	 * @throws \Exception
464
-	 */
465
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
466
-		// Verify group shares are allowed
467
-		if (!$this->allowGroupSharing()) {
468
-			throw new \Exception('Group sharing is now allowed');
469
-		}
470
-
471
-		// Verify if the user can share with this group
472
-		if ($this->shareWithGroupMembersOnly()) {
473
-			$sharedBy = $this->userManager->get($share->getSharedBy());
474
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
475
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
476
-				throw new \Exception('Sharing is only allowed within your own groups');
477
-			}
478
-		}
479
-
480
-		/*
428
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
429
+        $existingShares = $provider->getSharesByPath($share->getNode());
430
+        foreach($existingShares as $existingShare) {
431
+            // Ignore if it is the same share
432
+            try {
433
+                if ($existingShare->getFullId() === $share->getFullId()) {
434
+                    continue;
435
+                }
436
+            } catch (\UnexpectedValueException $e) {
437
+                //Shares are not identical
438
+            }
439
+
440
+            // Identical share already existst
441
+            if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
442
+                throw new \Exception('Path is already shared with this user');
443
+            }
444
+
445
+            // The share is already shared with this user via a group share
446
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
447
+                $group = $this->groupManager->get($existingShare->getSharedWith());
448
+                if (!is_null($group)) {
449
+                    $user = $this->userManager->get($share->getSharedWith());
450
+
451
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
452
+                        throw new \Exception('Path is already shared with this user');
453
+                    }
454
+                }
455
+            }
456
+        }
457
+    }
458
+
459
+    /**
460
+     * Check for pre share requirements for group shares
461
+     *
462
+     * @param \OCP\Share\IShare $share
463
+     * @throws \Exception
464
+     */
465
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
466
+        // Verify group shares are allowed
467
+        if (!$this->allowGroupSharing()) {
468
+            throw new \Exception('Group sharing is now allowed');
469
+        }
470
+
471
+        // Verify if the user can share with this group
472
+        if ($this->shareWithGroupMembersOnly()) {
473
+            $sharedBy = $this->userManager->get($share->getSharedBy());
474
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
475
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
476
+                throw new \Exception('Sharing is only allowed within your own groups');
477
+            }
478
+        }
479
+
480
+        /*
481 481
 		 * TODO: Could be costly, fix
482 482
 		 *
483 483
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
484 484
 		 */
485
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
486
-		$existingShares = $provider->getSharesByPath($share->getNode());
487
-		foreach($existingShares as $existingShare) {
488
-			try {
489
-				if ($existingShare->getFullId() === $share->getFullId()) {
490
-					continue;
491
-				}
492
-			} catch (\UnexpectedValueException $e) {
493
-				//It is a new share so just continue
494
-			}
495
-
496
-			if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
497
-				throw new \Exception('Path is already shared with this group');
498
-			}
499
-		}
500
-	}
501
-
502
-	/**
503
-	 * Check for pre share requirements for link shares
504
-	 *
505
-	 * @param \OCP\Share\IShare $share
506
-	 * @throws \Exception
507
-	 */
508
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
509
-		// Are link shares allowed?
510
-		if (!$this->shareApiAllowLinks()) {
511
-			throw new \Exception('Link sharing is not allowed');
512
-		}
513
-
514
-		// Link shares by definition can't have share permissions
515
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
516
-			throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
517
-		}
518
-
519
-		// Check if public upload is allowed
520
-		if (!$this->shareApiLinkAllowPublicUpload() &&
521
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
522
-			throw new \InvalidArgumentException('Public upload is not allowed');
523
-		}
524
-	}
525
-
526
-	/**
527
-	 * To make sure we don't get invisible link shares we set the parent
528
-	 * of a link if it is a reshare. This is a quick word around
529
-	 * until we can properly display multiple link shares in the UI
530
-	 *
531
-	 * See: https://github.com/owncloud/core/issues/22295
532
-	 *
533
-	 * FIXME: Remove once multiple link shares can be properly displayed
534
-	 *
535
-	 * @param \OCP\Share\IShare $share
536
-	 */
537
-	protected function setLinkParent(\OCP\Share\IShare $share) {
538
-
539
-		// No sense in checking if the method is not there.
540
-		if (method_exists($share, 'setParent')) {
541
-			$storage = $share->getNode()->getStorage();
542
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
543
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
544
-				$share->setParent($storage->getShareId());
545
-			}
546
-		}
547
-	}
548
-
549
-	/**
550
-	 * @param File|Folder $path
551
-	 */
552
-	protected function pathCreateChecks($path) {
553
-		// Make sure that we do not share a path that contains a shared mountpoint
554
-		if ($path instanceof \OCP\Files\Folder) {
555
-			$mounts = $this->mountManager->findIn($path->getPath());
556
-			foreach($mounts as $mount) {
557
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
558
-					throw new \InvalidArgumentException('Path contains files shared with you');
559
-				}
560
-			}
561
-		}
562
-	}
563
-
564
-	/**
565
-	 * Check if the user that is sharing can actually share
566
-	 *
567
-	 * @param \OCP\Share\IShare $share
568
-	 * @throws \Exception
569
-	 */
570
-	protected function canShare(\OCP\Share\IShare $share) {
571
-		if (!$this->shareApiEnabled()) {
572
-			throw new \Exception('Sharing is disabled');
573
-		}
574
-
575
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
576
-			throw new \Exception('Sharing is disabled for you');
577
-		}
578
-	}
579
-
580
-	/**
581
-	 * Share a path
582
-	 *
583
-	 * @param \OCP\Share\IShare $share
584
-	 * @return Share The share object
585
-	 * @throws \Exception
586
-	 *
587
-	 * TODO: handle link share permissions or check them
588
-	 */
589
-	public function createShare(\OCP\Share\IShare $share) {
590
-		$this->canShare($share);
591
-
592
-		$this->generalCreateChecks($share);
593
-
594
-		// Verify if there are any issues with the path
595
-		$this->pathCreateChecks($share->getNode());
596
-
597
-		/*
485
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
486
+        $existingShares = $provider->getSharesByPath($share->getNode());
487
+        foreach($existingShares as $existingShare) {
488
+            try {
489
+                if ($existingShare->getFullId() === $share->getFullId()) {
490
+                    continue;
491
+                }
492
+            } catch (\UnexpectedValueException $e) {
493
+                //It is a new share so just continue
494
+            }
495
+
496
+            if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
497
+                throw new \Exception('Path is already shared with this group');
498
+            }
499
+        }
500
+    }
501
+
502
+    /**
503
+     * Check for pre share requirements for link shares
504
+     *
505
+     * @param \OCP\Share\IShare $share
506
+     * @throws \Exception
507
+     */
508
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
509
+        // Are link shares allowed?
510
+        if (!$this->shareApiAllowLinks()) {
511
+            throw new \Exception('Link sharing is not allowed');
512
+        }
513
+
514
+        // Link shares by definition can't have share permissions
515
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
516
+            throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
517
+        }
518
+
519
+        // Check if public upload is allowed
520
+        if (!$this->shareApiLinkAllowPublicUpload() &&
521
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
522
+            throw new \InvalidArgumentException('Public upload is not allowed');
523
+        }
524
+    }
525
+
526
+    /**
527
+     * To make sure we don't get invisible link shares we set the parent
528
+     * of a link if it is a reshare. This is a quick word around
529
+     * until we can properly display multiple link shares in the UI
530
+     *
531
+     * See: https://github.com/owncloud/core/issues/22295
532
+     *
533
+     * FIXME: Remove once multiple link shares can be properly displayed
534
+     *
535
+     * @param \OCP\Share\IShare $share
536
+     */
537
+    protected function setLinkParent(\OCP\Share\IShare $share) {
538
+
539
+        // No sense in checking if the method is not there.
540
+        if (method_exists($share, 'setParent')) {
541
+            $storage = $share->getNode()->getStorage();
542
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
543
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
544
+                $share->setParent($storage->getShareId());
545
+            }
546
+        }
547
+    }
548
+
549
+    /**
550
+     * @param File|Folder $path
551
+     */
552
+    protected function pathCreateChecks($path) {
553
+        // Make sure that we do not share a path that contains a shared mountpoint
554
+        if ($path instanceof \OCP\Files\Folder) {
555
+            $mounts = $this->mountManager->findIn($path->getPath());
556
+            foreach($mounts as $mount) {
557
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
558
+                    throw new \InvalidArgumentException('Path contains files shared with you');
559
+                }
560
+            }
561
+        }
562
+    }
563
+
564
+    /**
565
+     * Check if the user that is sharing can actually share
566
+     *
567
+     * @param \OCP\Share\IShare $share
568
+     * @throws \Exception
569
+     */
570
+    protected function canShare(\OCP\Share\IShare $share) {
571
+        if (!$this->shareApiEnabled()) {
572
+            throw new \Exception('Sharing is disabled');
573
+        }
574
+
575
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
576
+            throw new \Exception('Sharing is disabled for you');
577
+        }
578
+    }
579
+
580
+    /**
581
+     * Share a path
582
+     *
583
+     * @param \OCP\Share\IShare $share
584
+     * @return Share The share object
585
+     * @throws \Exception
586
+     *
587
+     * TODO: handle link share permissions or check them
588
+     */
589
+    public function createShare(\OCP\Share\IShare $share) {
590
+        $this->canShare($share);
591
+
592
+        $this->generalCreateChecks($share);
593
+
594
+        // Verify if there are any issues with the path
595
+        $this->pathCreateChecks($share->getNode());
596
+
597
+        /*
598 598
 		 * On creation of a share the owner is always the owner of the path
599 599
 		 * Except for mounted federated shares.
600 600
 		 */
601
-		$storage = $share->getNode()->getStorage();
602
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
603
-			$parent = $share->getNode()->getParent();
604
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
605
-				$parent = $parent->getParent();
606
-			}
607
-			$share->setShareOwner($parent->getOwner()->getUID());
608
-		} else {
609
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
610
-		}
611
-
612
-		//Verify share type
613
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
614
-			$this->userCreateChecks($share);
615
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
616
-			$this->groupCreateChecks($share);
617
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
618
-			$this->linkCreateChecks($share);
619
-			$this->setLinkParent($share);
620
-
621
-			/*
601
+        $storage = $share->getNode()->getStorage();
602
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
603
+            $parent = $share->getNode()->getParent();
604
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
605
+                $parent = $parent->getParent();
606
+            }
607
+            $share->setShareOwner($parent->getOwner()->getUID());
608
+        } else {
609
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
610
+        }
611
+
612
+        //Verify share type
613
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
614
+            $this->userCreateChecks($share);
615
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
616
+            $this->groupCreateChecks($share);
617
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
618
+            $this->linkCreateChecks($share);
619
+            $this->setLinkParent($share);
620
+
621
+            /*
622 622
 			 * For now ignore a set token.
623 623
 			 */
624
-			$share->setToken(
625
-				$this->secureRandom->generate(
626
-					\OC\Share\Constants::TOKEN_LENGTH,
627
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
628
-				)
629
-			);
630
-
631
-			//Verify the expiration date
632
-			$this->validateExpirationDate($share);
633
-
634
-			//Verify the password
635
-			$this->verifyPassword($share->getPassword());
636
-
637
-			// If a password is set. Hash it!
638
-			if ($share->getPassword() !== null) {
639
-				$share->setPassword($this->hasher->hash($share->getPassword()));
640
-			}
641
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
642
-			$share->setToken(
643
-				$this->secureRandom->generate(
644
-					\OC\Share\Constants::TOKEN_LENGTH,
645
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
646
-				)
647
-			);
648
-		}
649
-
650
-		// Cannot share with the owner
651
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
652
-			$share->getSharedWith() === $share->getShareOwner()) {
653
-			throw new \InvalidArgumentException('Can’t share with the share owner');
654
-		}
655
-
656
-		// Generate the target
657
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
658
-		$target = \OC\Files\Filesystem::normalizePath($target);
659
-		$share->setTarget($target);
660
-
661
-		// Pre share event
662
-		$event = new GenericEvent($share);
663
-		$this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
664
-		if ($event->isPropagationStopped() && $event->hasArgument('error')) {
665
-			throw new \Exception($event->getArgument('error'));
666
-		}
667
-
668
-		$oldShare = $share;
669
-		$provider = $this->factory->getProviderForType($share->getShareType());
670
-		$share = $provider->create($share);
671
-		//reuse the node we already have
672
-		$share->setNode($oldShare->getNode());
673
-
674
-		// Post share event
675
-		$event = new GenericEvent($share);
676
-		$this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
677
-
678
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
679
-			$mailSend = $share->getMailSend();
680
-			if($mailSend === true) {
681
-				$user = $this->userManager->get($share->getSharedWith());
682
-				if ($user !== null) {
683
-					$emailAddress = $user->getEMailAddress();
684
-					if ($emailAddress !== null && $emailAddress !== '') {
685
-						$userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
686
-						$l = $this->l10nFactory->get('lib', $userLang);
687
-						$this->sendMailNotification(
688
-							$l,
689
-							$share->getNode()->getName(),
690
-							$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]),
691
-							$share->getSharedBy(),
692
-							$emailAddress,
693
-							$share->getExpirationDate()
694
-						);
695
-						$this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
696
-					} else {
697
-						$this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
698
-					}
699
-				} else {
700
-					$this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
701
-				}
702
-			} else {
703
-				$this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']);
704
-			}
705
-		}
706
-
707
-		return $share;
708
-	}
709
-
710
-	/**
711
-	 * Send mail notifications
712
-	 *
713
-	 * This method will catch and log mail transmission errors
714
-	 *
715
-	 * @param IL10N $l Language of the recipient
716
-	 * @param string $filename file/folder name
717
-	 * @param string $link link to the file/folder
718
-	 * @param string $initiator user ID of share sender
719
-	 * @param string $shareWith email address of share receiver
720
-	 * @param \DateTime|null $expiration
721
-	 */
722
-	protected function sendMailNotification(IL10N $l,
723
-											$filename,
724
-											$link,
725
-											$initiator,
726
-											$shareWith,
727
-											\DateTime $expiration = null) {
728
-		$initiatorUser = $this->userManager->get($initiator);
729
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
730
-
731
-		$message = $this->mailer->createMessage();
732
-
733
-		$emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
734
-			'filename' => $filename,
735
-			'link' => $link,
736
-			'initiator' => $initiatorDisplayName,
737
-			'expiration' => $expiration,
738
-			'shareWith' => $shareWith,
739
-		]);
740
-
741
-		$emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', array($initiatorDisplayName, $filename)));
742
-		$emailTemplate->addHeader();
743
-		$emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
744
-		$text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
745
-
746
-		$emailTemplate->addBodyText(
747
-			htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
748
-			$text
749
-		);
750
-		$emailTemplate->addBodyButton(
751
-			$l->t('Open »%s«', [$filename]),
752
-			$link
753
-		);
754
-
755
-		$message->setTo([$shareWith]);
756
-
757
-		// The "From" contains the sharers name
758
-		$instanceName = $this->defaults->getName();
759
-		$senderName = $l->t(
760
-			'%1$s via %2$s',
761
-			[
762
-				$initiatorDisplayName,
763
-				$instanceName
764
-			]
765
-		);
766
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
767
-
768
-		// The "Reply-To" is set to the sharer if an mail address is configured
769
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
770
-		$initiatorEmail = $initiatorUser->getEMailAddress();
771
-		if($initiatorEmail !== null) {
772
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
773
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
774
-		} else {
775
-			$emailTemplate->addFooter();
776
-		}
777
-
778
-		$message->useTemplate($emailTemplate);
779
-		try {
780
-			$failedRecipients = $this->mailer->send($message);
781
-			if(!empty($failedRecipients)) {
782
-				$this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
783
-				return;
784
-			}
785
-		} catch (\Exception $e) {
786
-			$this->logger->logException($e, ['message' => 'Share notification mail could not be sent']);
787
-		}
788
-	}
789
-
790
-	/**
791
-	 * Update a share
792
-	 *
793
-	 * @param \OCP\Share\IShare $share
794
-	 * @return \OCP\Share\IShare The share object
795
-	 * @throws \InvalidArgumentException
796
-	 */
797
-	public function updateShare(\OCP\Share\IShare $share) {
798
-		$expirationDateUpdated = false;
799
-
800
-		$this->canShare($share);
801
-
802
-		try {
803
-			$originalShare = $this->getShareById($share->getFullId());
804
-		} catch (\UnexpectedValueException $e) {
805
-			throw new \InvalidArgumentException('Share does not have a full id');
806
-		}
807
-
808
-		// We can't change the share type!
809
-		if ($share->getShareType() !== $originalShare->getShareType()) {
810
-			throw new \InvalidArgumentException('Can’t change share type');
811
-		}
812
-
813
-		// We can only change the recipient on user shares
814
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
815
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
816
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
817
-		}
818
-
819
-		// Cannot share with the owner
820
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
821
-			$share->getSharedWith() === $share->getShareOwner()) {
822
-			throw new \InvalidArgumentException('Can’t share with the share owner');
823
-		}
824
-
825
-		$this->generalCreateChecks($share);
826
-
827
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
828
-			$this->userCreateChecks($share);
829
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
830
-			$this->groupCreateChecks($share);
831
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
832
-			$this->linkCreateChecks($share);
833
-
834
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
835
-
836
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
837
-				//Verify the expiration date
838
-				$this->validateExpirationDate($share);
839
-				$expirationDateUpdated = true;
840
-			}
841
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
842
-			// The new password is not set again if it is the same as the old
843
-			// one, unless when switching from sending by Talk to sending by
844
-			// mail.
845
-			$plainTextPassword = $share->getPassword();
846
-			if (!empty($plainTextPassword) && !$this->updateSharePasswordIfNeeded($share, $originalShare) &&
847
-					!($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk())) {
848
-				$plainTextPassword = null;
849
-			}
850
-			if (empty($plainTextPassword) && !$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) {
851
-				// If the same password was already sent by mail the recipient
852
-				// would already have access to the share without having to call
853
-				// the sharer to verify her identity
854
-				throw new \InvalidArgumentException('Can’t enable sending the password by Talk without setting a new password');
855
-			}
856
-		}
857
-
858
-		$this->pathCreateChecks($share->getNode());
859
-
860
-		// Now update the share!
861
-		$provider = $this->factory->getProviderForType($share->getShareType());
862
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
863
-			$share = $provider->update($share, $plainTextPassword);
864
-		} else {
865
-			$share = $provider->update($share);
866
-		}
867
-
868
-		if ($expirationDateUpdated === true) {
869
-			\OC_Hook::emit(Share::class, 'post_set_expiration_date', [
870
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
871
-				'itemSource' => $share->getNode()->getId(),
872
-				'date' => $share->getExpirationDate(),
873
-				'uidOwner' => $share->getSharedBy(),
874
-			]);
875
-		}
876
-
877
-		if ($share->getPassword() !== $originalShare->getPassword()) {
878
-			\OC_Hook::emit(Share::class, 'post_update_password', [
879
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
880
-				'itemSource' => $share->getNode()->getId(),
881
-				'uidOwner' => $share->getSharedBy(),
882
-				'token' => $share->getToken(),
883
-				'disabled' => is_null($share->getPassword()),
884
-			]);
885
-		}
886
-
887
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
888
-			if ($this->userManager->userExists($share->getShareOwner())) {
889
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
890
-			} else {
891
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
892
-			}
893
-			\OC_Hook::emit(Share::class, 'post_update_permissions', array(
894
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
895
-				'itemSource' => $share->getNode()->getId(),
896
-				'shareType' => $share->getShareType(),
897
-				'shareWith' => $share->getSharedWith(),
898
-				'uidOwner' => $share->getSharedBy(),
899
-				'permissions' => $share->getPermissions(),
900
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
901
-			));
902
-		}
903
-
904
-		return $share;
905
-	}
906
-
907
-	/**
908
-	 * Updates the password of the given share if it is not the same as the
909
-	 * password of the original share.
910
-	 *
911
-	 * @param \OCP\Share\IShare $share the share to update its password.
912
-	 * @param \OCP\Share\IShare $originalShare the original share to compare its
913
-	 *        password with.
914
-	 * @return boolean whether the password was updated or not.
915
-	 */
916
-	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
917
-		// Password updated.
918
-		if ($share->getPassword() !== $originalShare->getPassword()) {
919
-			//Verify the password
920
-			$this->verifyPassword($share->getPassword());
921
-
922
-			// If a password is set. Hash it!
923
-			if ($share->getPassword() !== null) {
924
-				$share->setPassword($this->hasher->hash($share->getPassword()));
925
-
926
-				return true;
927
-			}
928
-		}
929
-
930
-		return false;
931
-	}
932
-
933
-	/**
934
-	 * Delete all the children of this share
935
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
936
-	 *
937
-	 * @param \OCP\Share\IShare $share
938
-	 * @return \OCP\Share\IShare[] List of deleted shares
939
-	 */
940
-	protected function deleteChildren(\OCP\Share\IShare $share) {
941
-		$deletedShares = [];
942
-
943
-		$provider = $this->factory->getProviderForType($share->getShareType());
944
-
945
-		foreach ($provider->getChildren($share) as $child) {
946
-			$deletedChildren = $this->deleteChildren($child);
947
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
948
-
949
-			$provider->delete($child);
950
-			$deletedShares[] = $child;
951
-		}
952
-
953
-		return $deletedShares;
954
-	}
955
-
956
-	/**
957
-	 * Delete a share
958
-	 *
959
-	 * @param \OCP\Share\IShare $share
960
-	 * @throws ShareNotFound
961
-	 * @throws \InvalidArgumentException
962
-	 */
963
-	public function deleteShare(\OCP\Share\IShare $share) {
964
-
965
-		try {
966
-			$share->getFullId();
967
-		} catch (\UnexpectedValueException $e) {
968
-			throw new \InvalidArgumentException('Share does not have a full id');
969
-		}
970
-
971
-		$event = new GenericEvent($share);
972
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
973
-
974
-		// Get all children and delete them as well
975
-		$deletedShares = $this->deleteChildren($share);
976
-
977
-		// Do the actual delete
978
-		$provider = $this->factory->getProviderForType($share->getShareType());
979
-		$provider->delete($share);
980
-
981
-		// All the deleted shares caused by this delete
982
-		$deletedShares[] = $share;
983
-
984
-		// Emit post hook
985
-		$event->setArgument('deletedShares', $deletedShares);
986
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
987
-	}
988
-
989
-
990
-	/**
991
-	 * Unshare a file as the recipient.
992
-	 * This can be different from a regular delete for example when one of
993
-	 * the users in a groups deletes that share. But the provider should
994
-	 * handle this.
995
-	 *
996
-	 * @param \OCP\Share\IShare $share
997
-	 * @param string $recipientId
998
-	 */
999
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
1000
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1001
-		$provider = $this->factory->getProvider($providerId);
1002
-
1003
-		$provider->deleteFromSelf($share, $recipientId);
1004
-		$event = new GenericEvent($share);
1005
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
1006
-	}
1007
-
1008
-	public function restoreShare(IShare $share, string $recipientId): IShare {
1009
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1010
-		$provider = $this->factory->getProvider($providerId);
1011
-
1012
-		return $provider->restore($share, $recipientId);
1013
-	}
1014
-
1015
-	/**
1016
-	 * @inheritdoc
1017
-	 */
1018
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
1019
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
1020
-			throw new \InvalidArgumentException('Can’t change target of link share');
1021
-		}
1022
-
1023
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
1024
-			throw new \InvalidArgumentException('Invalid recipient');
1025
-		}
1026
-
1027
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1028
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
1029
-			if (is_null($sharedWith)) {
1030
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1031
-			}
1032
-			$recipient = $this->userManager->get($recipientId);
1033
-			if (!$sharedWith->inGroup($recipient)) {
1034
-				throw new \InvalidArgumentException('Invalid recipient');
1035
-			}
1036
-		}
1037
-
1038
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1039
-		$provider = $this->factory->getProvider($providerId);
1040
-
1041
-		$provider->move($share, $recipientId);
1042
-	}
1043
-
1044
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1045
-		$providers = $this->factory->getAllProviders();
1046
-
1047
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1048
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1049
-			foreach ($newShares as $fid => $data) {
1050
-				if (!isset($shares[$fid])) {
1051
-					$shares[$fid] = [];
1052
-				}
1053
-
1054
-				$shares[$fid] = array_merge($shares[$fid], $data);
1055
-			}
1056
-			return $shares;
1057
-		}, []);
1058
-	}
1059
-
1060
-	/**
1061
-	 * @inheritdoc
1062
-	 */
1063
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1064
-		if ($path !== null &&
1065
-				!($path instanceof \OCP\Files\File) &&
1066
-				!($path instanceof \OCP\Files\Folder)) {
1067
-			throw new \InvalidArgumentException('invalid path');
1068
-		}
1069
-
1070
-		try {
1071
-			$provider = $this->factory->getProviderForType($shareType);
1072
-		} catch (ProviderException $e) {
1073
-			return [];
1074
-		}
1075
-
1076
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1077
-
1078
-		/*
624
+            $share->setToken(
625
+                $this->secureRandom->generate(
626
+                    \OC\Share\Constants::TOKEN_LENGTH,
627
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
628
+                )
629
+            );
630
+
631
+            //Verify the expiration date
632
+            $this->validateExpirationDate($share);
633
+
634
+            //Verify the password
635
+            $this->verifyPassword($share->getPassword());
636
+
637
+            // If a password is set. Hash it!
638
+            if ($share->getPassword() !== null) {
639
+                $share->setPassword($this->hasher->hash($share->getPassword()));
640
+            }
641
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
642
+            $share->setToken(
643
+                $this->secureRandom->generate(
644
+                    \OC\Share\Constants::TOKEN_LENGTH,
645
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
646
+                )
647
+            );
648
+        }
649
+
650
+        // Cannot share with the owner
651
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
652
+            $share->getSharedWith() === $share->getShareOwner()) {
653
+            throw new \InvalidArgumentException('Can’t share with the share owner');
654
+        }
655
+
656
+        // Generate the target
657
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
658
+        $target = \OC\Files\Filesystem::normalizePath($target);
659
+        $share->setTarget($target);
660
+
661
+        // Pre share event
662
+        $event = new GenericEvent($share);
663
+        $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
664
+        if ($event->isPropagationStopped() && $event->hasArgument('error')) {
665
+            throw new \Exception($event->getArgument('error'));
666
+        }
667
+
668
+        $oldShare = $share;
669
+        $provider = $this->factory->getProviderForType($share->getShareType());
670
+        $share = $provider->create($share);
671
+        //reuse the node we already have
672
+        $share->setNode($oldShare->getNode());
673
+
674
+        // Post share event
675
+        $event = new GenericEvent($share);
676
+        $this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
677
+
678
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
679
+            $mailSend = $share->getMailSend();
680
+            if($mailSend === true) {
681
+                $user = $this->userManager->get($share->getSharedWith());
682
+                if ($user !== null) {
683
+                    $emailAddress = $user->getEMailAddress();
684
+                    if ($emailAddress !== null && $emailAddress !== '') {
685
+                        $userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
686
+                        $l = $this->l10nFactory->get('lib', $userLang);
687
+                        $this->sendMailNotification(
688
+                            $l,
689
+                            $share->getNode()->getName(),
690
+                            $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]),
691
+                            $share->getSharedBy(),
692
+                            $emailAddress,
693
+                            $share->getExpirationDate()
694
+                        );
695
+                        $this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
696
+                    } else {
697
+                        $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
698
+                    }
699
+                } else {
700
+                    $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
701
+                }
702
+            } else {
703
+                $this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']);
704
+            }
705
+        }
706
+
707
+        return $share;
708
+    }
709
+
710
+    /**
711
+     * Send mail notifications
712
+     *
713
+     * This method will catch and log mail transmission errors
714
+     *
715
+     * @param IL10N $l Language of the recipient
716
+     * @param string $filename file/folder name
717
+     * @param string $link link to the file/folder
718
+     * @param string $initiator user ID of share sender
719
+     * @param string $shareWith email address of share receiver
720
+     * @param \DateTime|null $expiration
721
+     */
722
+    protected function sendMailNotification(IL10N $l,
723
+                                            $filename,
724
+                                            $link,
725
+                                            $initiator,
726
+                                            $shareWith,
727
+                                            \DateTime $expiration = null) {
728
+        $initiatorUser = $this->userManager->get($initiator);
729
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
730
+
731
+        $message = $this->mailer->createMessage();
732
+
733
+        $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
734
+            'filename' => $filename,
735
+            'link' => $link,
736
+            'initiator' => $initiatorDisplayName,
737
+            'expiration' => $expiration,
738
+            'shareWith' => $shareWith,
739
+        ]);
740
+
741
+        $emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', array($initiatorDisplayName, $filename)));
742
+        $emailTemplate->addHeader();
743
+        $emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
744
+        $text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
745
+
746
+        $emailTemplate->addBodyText(
747
+            htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
748
+            $text
749
+        );
750
+        $emailTemplate->addBodyButton(
751
+            $l->t('Open »%s«', [$filename]),
752
+            $link
753
+        );
754
+
755
+        $message->setTo([$shareWith]);
756
+
757
+        // The "From" contains the sharers name
758
+        $instanceName = $this->defaults->getName();
759
+        $senderName = $l->t(
760
+            '%1$s via %2$s',
761
+            [
762
+                $initiatorDisplayName,
763
+                $instanceName
764
+            ]
765
+        );
766
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
767
+
768
+        // The "Reply-To" is set to the sharer if an mail address is configured
769
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
770
+        $initiatorEmail = $initiatorUser->getEMailAddress();
771
+        if($initiatorEmail !== null) {
772
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
773
+            $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
774
+        } else {
775
+            $emailTemplate->addFooter();
776
+        }
777
+
778
+        $message->useTemplate($emailTemplate);
779
+        try {
780
+            $failedRecipients = $this->mailer->send($message);
781
+            if(!empty($failedRecipients)) {
782
+                $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
783
+                return;
784
+            }
785
+        } catch (\Exception $e) {
786
+            $this->logger->logException($e, ['message' => 'Share notification mail could not be sent']);
787
+        }
788
+    }
789
+
790
+    /**
791
+     * Update a share
792
+     *
793
+     * @param \OCP\Share\IShare $share
794
+     * @return \OCP\Share\IShare The share object
795
+     * @throws \InvalidArgumentException
796
+     */
797
+    public function updateShare(\OCP\Share\IShare $share) {
798
+        $expirationDateUpdated = false;
799
+
800
+        $this->canShare($share);
801
+
802
+        try {
803
+            $originalShare = $this->getShareById($share->getFullId());
804
+        } catch (\UnexpectedValueException $e) {
805
+            throw new \InvalidArgumentException('Share does not have a full id');
806
+        }
807
+
808
+        // We can't change the share type!
809
+        if ($share->getShareType() !== $originalShare->getShareType()) {
810
+            throw new \InvalidArgumentException('Can’t change share type');
811
+        }
812
+
813
+        // We can only change the recipient on user shares
814
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
815
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
816
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
817
+        }
818
+
819
+        // Cannot share with the owner
820
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
821
+            $share->getSharedWith() === $share->getShareOwner()) {
822
+            throw new \InvalidArgumentException('Can’t share with the share owner');
823
+        }
824
+
825
+        $this->generalCreateChecks($share);
826
+
827
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
828
+            $this->userCreateChecks($share);
829
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
830
+            $this->groupCreateChecks($share);
831
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
832
+            $this->linkCreateChecks($share);
833
+
834
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
835
+
836
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
837
+                //Verify the expiration date
838
+                $this->validateExpirationDate($share);
839
+                $expirationDateUpdated = true;
840
+            }
841
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
842
+            // The new password is not set again if it is the same as the old
843
+            // one, unless when switching from sending by Talk to sending by
844
+            // mail.
845
+            $plainTextPassword = $share->getPassword();
846
+            if (!empty($plainTextPassword) && !$this->updateSharePasswordIfNeeded($share, $originalShare) &&
847
+                    !($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk())) {
848
+                $plainTextPassword = null;
849
+            }
850
+            if (empty($plainTextPassword) && !$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) {
851
+                // If the same password was already sent by mail the recipient
852
+                // would already have access to the share without having to call
853
+                // the sharer to verify her identity
854
+                throw new \InvalidArgumentException('Can’t enable sending the password by Talk without setting a new password');
855
+            }
856
+        }
857
+
858
+        $this->pathCreateChecks($share->getNode());
859
+
860
+        // Now update the share!
861
+        $provider = $this->factory->getProviderForType($share->getShareType());
862
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
863
+            $share = $provider->update($share, $plainTextPassword);
864
+        } else {
865
+            $share = $provider->update($share);
866
+        }
867
+
868
+        if ($expirationDateUpdated === true) {
869
+            \OC_Hook::emit(Share::class, 'post_set_expiration_date', [
870
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
871
+                'itemSource' => $share->getNode()->getId(),
872
+                'date' => $share->getExpirationDate(),
873
+                'uidOwner' => $share->getSharedBy(),
874
+            ]);
875
+        }
876
+
877
+        if ($share->getPassword() !== $originalShare->getPassword()) {
878
+            \OC_Hook::emit(Share::class, 'post_update_password', [
879
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
880
+                'itemSource' => $share->getNode()->getId(),
881
+                'uidOwner' => $share->getSharedBy(),
882
+                'token' => $share->getToken(),
883
+                'disabled' => is_null($share->getPassword()),
884
+            ]);
885
+        }
886
+
887
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
888
+            if ($this->userManager->userExists($share->getShareOwner())) {
889
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
890
+            } else {
891
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
892
+            }
893
+            \OC_Hook::emit(Share::class, 'post_update_permissions', array(
894
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
895
+                'itemSource' => $share->getNode()->getId(),
896
+                'shareType' => $share->getShareType(),
897
+                'shareWith' => $share->getSharedWith(),
898
+                'uidOwner' => $share->getSharedBy(),
899
+                'permissions' => $share->getPermissions(),
900
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
901
+            ));
902
+        }
903
+
904
+        return $share;
905
+    }
906
+
907
+    /**
908
+     * Updates the password of the given share if it is not the same as the
909
+     * password of the original share.
910
+     *
911
+     * @param \OCP\Share\IShare $share the share to update its password.
912
+     * @param \OCP\Share\IShare $originalShare the original share to compare its
913
+     *        password with.
914
+     * @return boolean whether the password was updated or not.
915
+     */
916
+    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
917
+        // Password updated.
918
+        if ($share->getPassword() !== $originalShare->getPassword()) {
919
+            //Verify the password
920
+            $this->verifyPassword($share->getPassword());
921
+
922
+            // If a password is set. Hash it!
923
+            if ($share->getPassword() !== null) {
924
+                $share->setPassword($this->hasher->hash($share->getPassword()));
925
+
926
+                return true;
927
+            }
928
+        }
929
+
930
+        return false;
931
+    }
932
+
933
+    /**
934
+     * Delete all the children of this share
935
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
936
+     *
937
+     * @param \OCP\Share\IShare $share
938
+     * @return \OCP\Share\IShare[] List of deleted shares
939
+     */
940
+    protected function deleteChildren(\OCP\Share\IShare $share) {
941
+        $deletedShares = [];
942
+
943
+        $provider = $this->factory->getProviderForType($share->getShareType());
944
+
945
+        foreach ($provider->getChildren($share) as $child) {
946
+            $deletedChildren = $this->deleteChildren($child);
947
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
948
+
949
+            $provider->delete($child);
950
+            $deletedShares[] = $child;
951
+        }
952
+
953
+        return $deletedShares;
954
+    }
955
+
956
+    /**
957
+     * Delete a share
958
+     *
959
+     * @param \OCP\Share\IShare $share
960
+     * @throws ShareNotFound
961
+     * @throws \InvalidArgumentException
962
+     */
963
+    public function deleteShare(\OCP\Share\IShare $share) {
964
+
965
+        try {
966
+            $share->getFullId();
967
+        } catch (\UnexpectedValueException $e) {
968
+            throw new \InvalidArgumentException('Share does not have a full id');
969
+        }
970
+
971
+        $event = new GenericEvent($share);
972
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
973
+
974
+        // Get all children and delete them as well
975
+        $deletedShares = $this->deleteChildren($share);
976
+
977
+        // Do the actual delete
978
+        $provider = $this->factory->getProviderForType($share->getShareType());
979
+        $provider->delete($share);
980
+
981
+        // All the deleted shares caused by this delete
982
+        $deletedShares[] = $share;
983
+
984
+        // Emit post hook
985
+        $event->setArgument('deletedShares', $deletedShares);
986
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
987
+    }
988
+
989
+
990
+    /**
991
+     * Unshare a file as the recipient.
992
+     * This can be different from a regular delete for example when one of
993
+     * the users in a groups deletes that share. But the provider should
994
+     * handle this.
995
+     *
996
+     * @param \OCP\Share\IShare $share
997
+     * @param string $recipientId
998
+     */
999
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
1000
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1001
+        $provider = $this->factory->getProvider($providerId);
1002
+
1003
+        $provider->deleteFromSelf($share, $recipientId);
1004
+        $event = new GenericEvent($share);
1005
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
1006
+    }
1007
+
1008
+    public function restoreShare(IShare $share, string $recipientId): IShare {
1009
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1010
+        $provider = $this->factory->getProvider($providerId);
1011
+
1012
+        return $provider->restore($share, $recipientId);
1013
+    }
1014
+
1015
+    /**
1016
+     * @inheritdoc
1017
+     */
1018
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
1019
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
1020
+            throw new \InvalidArgumentException('Can’t change target of link share');
1021
+        }
1022
+
1023
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
1024
+            throw new \InvalidArgumentException('Invalid recipient');
1025
+        }
1026
+
1027
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1028
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
1029
+            if (is_null($sharedWith)) {
1030
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1031
+            }
1032
+            $recipient = $this->userManager->get($recipientId);
1033
+            if (!$sharedWith->inGroup($recipient)) {
1034
+                throw new \InvalidArgumentException('Invalid recipient');
1035
+            }
1036
+        }
1037
+
1038
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1039
+        $provider = $this->factory->getProvider($providerId);
1040
+
1041
+        $provider->move($share, $recipientId);
1042
+    }
1043
+
1044
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1045
+        $providers = $this->factory->getAllProviders();
1046
+
1047
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1048
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1049
+            foreach ($newShares as $fid => $data) {
1050
+                if (!isset($shares[$fid])) {
1051
+                    $shares[$fid] = [];
1052
+                }
1053
+
1054
+                $shares[$fid] = array_merge($shares[$fid], $data);
1055
+            }
1056
+            return $shares;
1057
+        }, []);
1058
+    }
1059
+
1060
+    /**
1061
+     * @inheritdoc
1062
+     */
1063
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1064
+        if ($path !== null &&
1065
+                !($path instanceof \OCP\Files\File) &&
1066
+                !($path instanceof \OCP\Files\Folder)) {
1067
+            throw new \InvalidArgumentException('invalid path');
1068
+        }
1069
+
1070
+        try {
1071
+            $provider = $this->factory->getProviderForType($shareType);
1072
+        } catch (ProviderException $e) {
1073
+            return [];
1074
+        }
1075
+
1076
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1077
+
1078
+        /*
1079 1079
 		 * Work around so we don't return expired shares but still follow
1080 1080
 		 * proper pagination.
1081 1081
 		 */
1082 1082
 
1083
-		$shares2 = [];
1084
-
1085
-		while(true) {
1086
-			$added = 0;
1087
-			foreach ($shares as $share) {
1088
-
1089
-				try {
1090
-					$this->checkExpireDate($share);
1091
-				} catch (ShareNotFound $e) {
1092
-					//Ignore since this basically means the share is deleted
1093
-					continue;
1094
-				}
1095
-
1096
-				$added++;
1097
-				$shares2[] = $share;
1098
-
1099
-				if (count($shares2) === $limit) {
1100
-					break;
1101
-				}
1102
-			}
1103
-
1104
-			// If we did not fetch more shares than the limit then there are no more shares
1105
-			if (count($shares) < $limit) {
1106
-				break;
1107
-			}
1108
-
1109
-			if (count($shares2) === $limit) {
1110
-				break;
1111
-			}
1112
-
1113
-			// If there was no limit on the select we are done
1114
-			if ($limit === -1) {
1115
-				break;
1116
-			}
1117
-
1118
-			$offset += $added;
1119
-
1120
-			// Fetch again $limit shares
1121
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1122
-
1123
-			// No more shares means we are done
1124
-			if (empty($shares)) {
1125
-				break;
1126
-			}
1127
-		}
1128
-
1129
-		$shares = $shares2;
1130
-
1131
-		return $shares;
1132
-	}
1133
-
1134
-	/**
1135
-	 * @inheritdoc
1136
-	 */
1137
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1138
-		try {
1139
-			$provider = $this->factory->getProviderForType($shareType);
1140
-		} catch (ProviderException $e) {
1141
-			return [];
1142
-		}
1143
-
1144
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1145
-
1146
-		// remove all shares which are already expired
1147
-		foreach ($shares as $key => $share) {
1148
-			try {
1149
-				$this->checkExpireDate($share);
1150
-			} catch (ShareNotFound $e) {
1151
-				unset($shares[$key]);
1152
-			}
1153
-		}
1154
-
1155
-		return $shares;
1156
-	}
1157
-
1158
-	/**
1159
-	 * @inheritdoc
1160
-	 */
1161
-	public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1162
-		$shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
1163
-
1164
-		// Only get deleted shares
1165
-		$shares = array_filter($shares, function(IShare $share) {
1166
-			return $share->getPermissions() === 0;
1167
-		});
1168
-
1169
-		// Only get shares where the owner still exists
1170
-		$shares = array_filter($shares, function (IShare $share) {
1171
-			return $this->userManager->userExists($share->getShareOwner());
1172
-		});
1173
-
1174
-		return $shares;
1175
-	}
1176
-
1177
-	/**
1178
-	 * @inheritdoc
1179
-	 */
1180
-	public function getShareById($id, $recipient = null) {
1181
-		if ($id === null) {
1182
-			throw new ShareNotFound();
1183
-		}
1184
-
1185
-		list($providerId, $id) = $this->splitFullId($id);
1186
-
1187
-		try {
1188
-			$provider = $this->factory->getProvider($providerId);
1189
-		} catch (ProviderException $e) {
1190
-			throw new ShareNotFound();
1191
-		}
1192
-
1193
-		$share = $provider->getShareById($id, $recipient);
1194
-
1195
-		$this->checkExpireDate($share);
1196
-
1197
-		return $share;
1198
-	}
1199
-
1200
-	/**
1201
-	 * Get all the shares for a given path
1202
-	 *
1203
-	 * @param \OCP\Files\Node $path
1204
-	 * @param int $page
1205
-	 * @param int $perPage
1206
-	 *
1207
-	 * @return Share[]
1208
-	 */
1209
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1210
-		return [];
1211
-	}
1212
-
1213
-	/**
1214
-	 * Get the share by token possible with password
1215
-	 *
1216
-	 * @param string $token
1217
-	 * @return Share
1218
-	 *
1219
-	 * @throws ShareNotFound
1220
-	 */
1221
-	public function getShareByToken($token) {
1222
-		// tokens can't be valid local user names
1223
-		if ($this->userManager->userExists($token)) {
1224
-			throw new ShareNotFound();
1225
-		}
1226
-		$share = null;
1227
-		try {
1228
-			if($this->shareApiAllowLinks()) {
1229
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1230
-				$share = $provider->getShareByToken($token);
1231
-			}
1232
-		} catch (ProviderException $e) {
1233
-		} catch (ShareNotFound $e) {
1234
-		}
1235
-
1236
-
1237
-		// If it is not a link share try to fetch a federated share by token
1238
-		if ($share === null) {
1239
-			try {
1240
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1241
-				$share = $provider->getShareByToken($token);
1242
-			} catch (ProviderException $e) {
1243
-			} catch (ShareNotFound $e) {
1244
-			}
1245
-		}
1246
-
1247
-		// If it is not a link share try to fetch a mail share by token
1248
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1249
-			try {
1250
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1251
-				$share = $provider->getShareByToken($token);
1252
-			} catch (ProviderException $e) {
1253
-			} catch (ShareNotFound $e) {
1254
-			}
1255
-		}
1256
-
1257
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1258
-			try {
1259
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1260
-				$share = $provider->getShareByToken($token);
1261
-			} catch (ProviderException $e) {
1262
-			} catch (ShareNotFound $e) {
1263
-			}
1264
-		}
1265
-
1266
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_ROOM)) {
1267
-			try {
1268
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_ROOM);
1269
-				$share = $provider->getShareByToken($token);
1270
-			} catch (ProviderException $e) {
1271
-			} catch (ShareNotFound $e) {
1272
-			}
1273
-		}
1274
-
1275
-		if ($share === null) {
1276
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1277
-		}
1278
-
1279
-		$this->checkExpireDate($share);
1280
-
1281
-		/*
1083
+        $shares2 = [];
1084
+
1085
+        while(true) {
1086
+            $added = 0;
1087
+            foreach ($shares as $share) {
1088
+
1089
+                try {
1090
+                    $this->checkExpireDate($share);
1091
+                } catch (ShareNotFound $e) {
1092
+                    //Ignore since this basically means the share is deleted
1093
+                    continue;
1094
+                }
1095
+
1096
+                $added++;
1097
+                $shares2[] = $share;
1098
+
1099
+                if (count($shares2) === $limit) {
1100
+                    break;
1101
+                }
1102
+            }
1103
+
1104
+            // If we did not fetch more shares than the limit then there are no more shares
1105
+            if (count($shares) < $limit) {
1106
+                break;
1107
+            }
1108
+
1109
+            if (count($shares2) === $limit) {
1110
+                break;
1111
+            }
1112
+
1113
+            // If there was no limit on the select we are done
1114
+            if ($limit === -1) {
1115
+                break;
1116
+            }
1117
+
1118
+            $offset += $added;
1119
+
1120
+            // Fetch again $limit shares
1121
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1122
+
1123
+            // No more shares means we are done
1124
+            if (empty($shares)) {
1125
+                break;
1126
+            }
1127
+        }
1128
+
1129
+        $shares = $shares2;
1130
+
1131
+        return $shares;
1132
+    }
1133
+
1134
+    /**
1135
+     * @inheritdoc
1136
+     */
1137
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1138
+        try {
1139
+            $provider = $this->factory->getProviderForType($shareType);
1140
+        } catch (ProviderException $e) {
1141
+            return [];
1142
+        }
1143
+
1144
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1145
+
1146
+        // remove all shares which are already expired
1147
+        foreach ($shares as $key => $share) {
1148
+            try {
1149
+                $this->checkExpireDate($share);
1150
+            } catch (ShareNotFound $e) {
1151
+                unset($shares[$key]);
1152
+            }
1153
+        }
1154
+
1155
+        return $shares;
1156
+    }
1157
+
1158
+    /**
1159
+     * @inheritdoc
1160
+     */
1161
+    public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1162
+        $shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
1163
+
1164
+        // Only get deleted shares
1165
+        $shares = array_filter($shares, function(IShare $share) {
1166
+            return $share->getPermissions() === 0;
1167
+        });
1168
+
1169
+        // Only get shares where the owner still exists
1170
+        $shares = array_filter($shares, function (IShare $share) {
1171
+            return $this->userManager->userExists($share->getShareOwner());
1172
+        });
1173
+
1174
+        return $shares;
1175
+    }
1176
+
1177
+    /**
1178
+     * @inheritdoc
1179
+     */
1180
+    public function getShareById($id, $recipient = null) {
1181
+        if ($id === null) {
1182
+            throw new ShareNotFound();
1183
+        }
1184
+
1185
+        list($providerId, $id) = $this->splitFullId($id);
1186
+
1187
+        try {
1188
+            $provider = $this->factory->getProvider($providerId);
1189
+        } catch (ProviderException $e) {
1190
+            throw new ShareNotFound();
1191
+        }
1192
+
1193
+        $share = $provider->getShareById($id, $recipient);
1194
+
1195
+        $this->checkExpireDate($share);
1196
+
1197
+        return $share;
1198
+    }
1199
+
1200
+    /**
1201
+     * Get all the shares for a given path
1202
+     *
1203
+     * @param \OCP\Files\Node $path
1204
+     * @param int $page
1205
+     * @param int $perPage
1206
+     *
1207
+     * @return Share[]
1208
+     */
1209
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1210
+        return [];
1211
+    }
1212
+
1213
+    /**
1214
+     * Get the share by token possible with password
1215
+     *
1216
+     * @param string $token
1217
+     * @return Share
1218
+     *
1219
+     * @throws ShareNotFound
1220
+     */
1221
+    public function getShareByToken($token) {
1222
+        // tokens can't be valid local user names
1223
+        if ($this->userManager->userExists($token)) {
1224
+            throw new ShareNotFound();
1225
+        }
1226
+        $share = null;
1227
+        try {
1228
+            if($this->shareApiAllowLinks()) {
1229
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1230
+                $share = $provider->getShareByToken($token);
1231
+            }
1232
+        } catch (ProviderException $e) {
1233
+        } catch (ShareNotFound $e) {
1234
+        }
1235
+
1236
+
1237
+        // If it is not a link share try to fetch a federated share by token
1238
+        if ($share === null) {
1239
+            try {
1240
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1241
+                $share = $provider->getShareByToken($token);
1242
+            } catch (ProviderException $e) {
1243
+            } catch (ShareNotFound $e) {
1244
+            }
1245
+        }
1246
+
1247
+        // If it is not a link share try to fetch a mail share by token
1248
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1249
+            try {
1250
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1251
+                $share = $provider->getShareByToken($token);
1252
+            } catch (ProviderException $e) {
1253
+            } catch (ShareNotFound $e) {
1254
+            }
1255
+        }
1256
+
1257
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1258
+            try {
1259
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1260
+                $share = $provider->getShareByToken($token);
1261
+            } catch (ProviderException $e) {
1262
+            } catch (ShareNotFound $e) {
1263
+            }
1264
+        }
1265
+
1266
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_ROOM)) {
1267
+            try {
1268
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_ROOM);
1269
+                $share = $provider->getShareByToken($token);
1270
+            } catch (ProviderException $e) {
1271
+            } catch (ShareNotFound $e) {
1272
+            }
1273
+        }
1274
+
1275
+        if ($share === null) {
1276
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1277
+        }
1278
+
1279
+        $this->checkExpireDate($share);
1280
+
1281
+        /*
1282 1282
 		 * Reduce the permissions for link shares if public upload is not enabled
1283 1283
 		 */
1284
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1285
-			!$this->shareApiLinkAllowPublicUpload()) {
1286
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1287
-		}
1288
-
1289
-		return $share;
1290
-	}
1291
-
1292
-	protected function checkExpireDate($share) {
1293
-		if ($share->getExpirationDate() !== null &&
1294
-			$share->getExpirationDate() <= new \DateTime()) {
1295
-			$this->deleteShare($share);
1296
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1297
-		}
1298
-
1299
-	}
1300
-
1301
-	/**
1302
-	 * Verify the password of a public share
1303
-	 *
1304
-	 * @param \OCP\Share\IShare $share
1305
-	 * @param string $password
1306
-	 * @return bool
1307
-	 */
1308
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1309
-		$passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1310
-			|| $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1311
-		if (!$passwordProtected) {
1312
-			//TODO maybe exception?
1313
-			return false;
1314
-		}
1315
-
1316
-		if ($password === null || $share->getPassword() === null) {
1317
-			return false;
1318
-		}
1319
-
1320
-		$newHash = '';
1321
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1322
-			return false;
1323
-		}
1324
-
1325
-		if (!empty($newHash)) {
1326
-			$share->setPassword($newHash);
1327
-			$provider = $this->factory->getProviderForType($share->getShareType());
1328
-			$provider->update($share);
1329
-		}
1330
-
1331
-		return true;
1332
-	}
1333
-
1334
-	/**
1335
-	 * @inheritdoc
1336
-	 */
1337
-	public function userDeleted($uid) {
1338
-		$types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1339
-
1340
-		foreach ($types as $type) {
1341
-			try {
1342
-				$provider = $this->factory->getProviderForType($type);
1343
-			} catch (ProviderException $e) {
1344
-				continue;
1345
-			}
1346
-			$provider->userDeleted($uid, $type);
1347
-		}
1348
-	}
1349
-
1350
-	/**
1351
-	 * @inheritdoc
1352
-	 */
1353
-	public function groupDeleted($gid) {
1354
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1355
-		$provider->groupDeleted($gid);
1356
-	}
1357
-
1358
-	/**
1359
-	 * @inheritdoc
1360
-	 */
1361
-	public function userDeletedFromGroup($uid, $gid) {
1362
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1363
-		$provider->userDeletedFromGroup($uid, $gid);
1364
-	}
1365
-
1366
-	/**
1367
-	 * Get access list to a path. This means
1368
-	 * all the users that can access a given path.
1369
-	 *
1370
-	 * Consider:
1371
-	 * -root
1372
-	 * |-folder1 (23)
1373
-	 *  |-folder2 (32)
1374
-	 *   |-fileA (42)
1375
-	 *
1376
-	 * fileA is shared with user1 and user1@server1
1377
-	 * folder2 is shared with group2 (user4 is a member of group2)
1378
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1379
-	 *
1380
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1381
-	 * [
1382
-	 *  users  => [
1383
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1384
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1385
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1386
-	 *  ],
1387
-	 *  remote => [
1388
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1389
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1390
-	 *  ],
1391
-	 *  public => bool
1392
-	 *  mail => bool
1393
-	 * ]
1394
-	 *
1395
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1396
-	 * [
1397
-	 *  users  => ['user1', 'user2', 'user4'],
1398
-	 *  remote => bool,
1399
-	 *  public => bool
1400
-	 *  mail => bool
1401
-	 * ]
1402
-	 *
1403
-	 * This is required for encryption/activity
1404
-	 *
1405
-	 * @param \OCP\Files\Node $path
1406
-	 * @param bool $recursive Should we check all parent folders as well
1407
-	 * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1408
-	 * @return array
1409
-	 */
1410
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1411
-		$owner = $path->getOwner();
1412
-
1413
-		if ($owner === null) {
1414
-			return [];
1415
-		}
1416
-
1417
-		$owner = $owner->getUID();
1418
-
1419
-		if ($currentAccess) {
1420
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1421
-		} else {
1422
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1423
-		}
1424
-		if (!$this->userManager->userExists($owner)) {
1425
-			return $al;
1426
-		}
1427
-
1428
-		//Get node for the owner and correct the owner in case of external storages
1429
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1430
-		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1431
-			$nodes = $userFolder->getById($path->getId());
1432
-			$path = array_shift($nodes);
1433
-			if ($path->getOwner() === null) {
1434
-				return [];
1435
-			}
1436
-			$owner = $path->getOwner()->getUID();
1437
-		}
1438
-
1439
-		$providers = $this->factory->getAllProviders();
1440
-
1441
-		/** @var Node[] $nodes */
1442
-		$nodes = [];
1443
-
1444
-
1445
-		if ($currentAccess) {
1446
-			$ownerPath = $path->getPath();
1447
-			$ownerPath = explode('/', $ownerPath, 4);
1448
-			if (count($ownerPath) < 4) {
1449
-				$ownerPath = '';
1450
-			} else {
1451
-				$ownerPath = $ownerPath[3];
1452
-			}
1453
-			$al['users'][$owner] = [
1454
-				'node_id' => $path->getId(),
1455
-				'node_path' => '/' . $ownerPath,
1456
-			];
1457
-		} else {
1458
-			$al['users'][] = $owner;
1459
-		}
1460
-
1461
-		// Collect all the shares
1462
-		while ($path->getPath() !== $userFolder->getPath()) {
1463
-			$nodes[] = $path;
1464
-			if (!$recursive) {
1465
-				break;
1466
-			}
1467
-			$path = $path->getParent();
1468
-		}
1469
-
1470
-		foreach ($providers as $provider) {
1471
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1472
-
1473
-			foreach ($tmp as $k => $v) {
1474
-				if (isset($al[$k])) {
1475
-					if (is_array($al[$k])) {
1476
-						if ($currentAccess) {
1477
-							$al[$k] += $v;
1478
-						} else {
1479
-							$al[$k] = array_merge($al[$k], $v);
1480
-							$al[$k] = array_unique($al[$k]);
1481
-							$al[$k] = array_values($al[$k]);
1482
-						}
1483
-					} else {
1484
-						$al[$k] = $al[$k] || $v;
1485
-					}
1486
-				} else {
1487
-					$al[$k] = $v;
1488
-				}
1489
-			}
1490
-		}
1491
-
1492
-		return $al;
1493
-	}
1494
-
1495
-	/**
1496
-	 * Create a new share
1497
-	 * @return \OCP\Share\IShare
1498
-	 */
1499
-	public function newShare() {
1500
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1501
-	}
1502
-
1503
-	/**
1504
-	 * Is the share API enabled
1505
-	 *
1506
-	 * @return bool
1507
-	 */
1508
-	public function shareApiEnabled() {
1509
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1510
-	}
1511
-
1512
-	/**
1513
-	 * Is public link sharing enabled
1514
-	 *
1515
-	 * @return bool
1516
-	 */
1517
-	public function shareApiAllowLinks() {
1518
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1519
-	}
1520
-
1521
-	/**
1522
-	 * Is password on public link requires
1523
-	 *
1524
-	 * @return bool
1525
-	 */
1526
-	public function shareApiLinkEnforcePassword() {
1527
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1528
-	}
1529
-
1530
-	/**
1531
-	 * Is default expire date enabled
1532
-	 *
1533
-	 * @return bool
1534
-	 */
1535
-	public function shareApiLinkDefaultExpireDate() {
1536
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1537
-	}
1538
-
1539
-	/**
1540
-	 * Is default expire date enforced
1541
-	 *`
1542
-	 * @return bool
1543
-	 */
1544
-	public function shareApiLinkDefaultExpireDateEnforced() {
1545
-		return $this->shareApiLinkDefaultExpireDate() &&
1546
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1547
-	}
1548
-
1549
-	/**
1550
-	 * Number of default expire days
1551
-	 *shareApiLinkAllowPublicUpload
1552
-	 * @return int
1553
-	 */
1554
-	public function shareApiLinkDefaultExpireDays() {
1555
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1556
-	}
1557
-
1558
-	/**
1559
-	 * Allow public upload on link shares
1560
-	 *
1561
-	 * @return bool
1562
-	 */
1563
-	public function shareApiLinkAllowPublicUpload() {
1564
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1565
-	}
1566
-
1567
-	/**
1568
-	 * check if user can only share with group members
1569
-	 * @return bool
1570
-	 */
1571
-	public function shareWithGroupMembersOnly() {
1572
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1573
-	}
1574
-
1575
-	/**
1576
-	 * Check if users can share with groups
1577
-	 * @return bool
1578
-	 */
1579
-	public function allowGroupSharing() {
1580
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1581
-	}
1582
-
1583
-	/**
1584
-	 * Copied from \OC_Util::isSharingDisabledForUser
1585
-	 *
1586
-	 * TODO: Deprecate fuction from OC_Util
1587
-	 *
1588
-	 * @param string $userId
1589
-	 * @return bool
1590
-	 */
1591
-	public function sharingDisabledForUser($userId) {
1592
-		if ($userId === null) {
1593
-			return false;
1594
-		}
1595
-
1596
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1597
-			return $this->sharingDisabledForUsersCache[$userId];
1598
-		}
1599
-
1600
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1601
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1602
-			$excludedGroups = json_decode($groupsList);
1603
-			if (is_null($excludedGroups)) {
1604
-				$excludedGroups = explode(',', $groupsList);
1605
-				$newValue = json_encode($excludedGroups);
1606
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1607
-			}
1608
-			$user = $this->userManager->get($userId);
1609
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1610
-			if (!empty($usersGroups)) {
1611
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1612
-				// if the user is only in groups which are disabled for sharing then
1613
-				// sharing is also disabled for the user
1614
-				if (empty($remainingGroups)) {
1615
-					$this->sharingDisabledForUsersCache[$userId] = true;
1616
-					return true;
1617
-				}
1618
-			}
1619
-		}
1620
-
1621
-		$this->sharingDisabledForUsersCache[$userId] = false;
1622
-		return false;
1623
-	}
1624
-
1625
-	/**
1626
-	 * @inheritdoc
1627
-	 */
1628
-	public function outgoingServer2ServerSharesAllowed() {
1629
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1630
-	}
1631
-
1632
-	/**
1633
-	 * @inheritdoc
1634
-	 */
1635
-	public function outgoingServer2ServerGroupSharesAllowed() {
1636
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
1637
-	}
1638
-
1639
-	/**
1640
-	 * @inheritdoc
1641
-	 */
1642
-	public function shareProviderExists($shareType) {
1643
-		try {
1644
-			$this->factory->getProviderForType($shareType);
1645
-		} catch (ProviderException $e) {
1646
-			return false;
1647
-		}
1648
-
1649
-		return true;
1650
-	}
1284
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1285
+            !$this->shareApiLinkAllowPublicUpload()) {
1286
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1287
+        }
1288
+
1289
+        return $share;
1290
+    }
1291
+
1292
+    protected function checkExpireDate($share) {
1293
+        if ($share->getExpirationDate() !== null &&
1294
+            $share->getExpirationDate() <= new \DateTime()) {
1295
+            $this->deleteShare($share);
1296
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1297
+        }
1298
+
1299
+    }
1300
+
1301
+    /**
1302
+     * Verify the password of a public share
1303
+     *
1304
+     * @param \OCP\Share\IShare $share
1305
+     * @param string $password
1306
+     * @return bool
1307
+     */
1308
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1309
+        $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1310
+            || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1311
+        if (!$passwordProtected) {
1312
+            //TODO maybe exception?
1313
+            return false;
1314
+        }
1315
+
1316
+        if ($password === null || $share->getPassword() === null) {
1317
+            return false;
1318
+        }
1319
+
1320
+        $newHash = '';
1321
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1322
+            return false;
1323
+        }
1324
+
1325
+        if (!empty($newHash)) {
1326
+            $share->setPassword($newHash);
1327
+            $provider = $this->factory->getProviderForType($share->getShareType());
1328
+            $provider->update($share);
1329
+        }
1330
+
1331
+        return true;
1332
+    }
1333
+
1334
+    /**
1335
+     * @inheritdoc
1336
+     */
1337
+    public function userDeleted($uid) {
1338
+        $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1339
+
1340
+        foreach ($types as $type) {
1341
+            try {
1342
+                $provider = $this->factory->getProviderForType($type);
1343
+            } catch (ProviderException $e) {
1344
+                continue;
1345
+            }
1346
+            $provider->userDeleted($uid, $type);
1347
+        }
1348
+    }
1349
+
1350
+    /**
1351
+     * @inheritdoc
1352
+     */
1353
+    public function groupDeleted($gid) {
1354
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1355
+        $provider->groupDeleted($gid);
1356
+    }
1357
+
1358
+    /**
1359
+     * @inheritdoc
1360
+     */
1361
+    public function userDeletedFromGroup($uid, $gid) {
1362
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1363
+        $provider->userDeletedFromGroup($uid, $gid);
1364
+    }
1365
+
1366
+    /**
1367
+     * Get access list to a path. This means
1368
+     * all the users that can access a given path.
1369
+     *
1370
+     * Consider:
1371
+     * -root
1372
+     * |-folder1 (23)
1373
+     *  |-folder2 (32)
1374
+     *   |-fileA (42)
1375
+     *
1376
+     * fileA is shared with user1 and user1@server1
1377
+     * folder2 is shared with group2 (user4 is a member of group2)
1378
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1379
+     *
1380
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1381
+     * [
1382
+     *  users  => [
1383
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1384
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1385
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1386
+     *  ],
1387
+     *  remote => [
1388
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1389
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1390
+     *  ],
1391
+     *  public => bool
1392
+     *  mail => bool
1393
+     * ]
1394
+     *
1395
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1396
+     * [
1397
+     *  users  => ['user1', 'user2', 'user4'],
1398
+     *  remote => bool,
1399
+     *  public => bool
1400
+     *  mail => bool
1401
+     * ]
1402
+     *
1403
+     * This is required for encryption/activity
1404
+     *
1405
+     * @param \OCP\Files\Node $path
1406
+     * @param bool $recursive Should we check all parent folders as well
1407
+     * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1408
+     * @return array
1409
+     */
1410
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1411
+        $owner = $path->getOwner();
1412
+
1413
+        if ($owner === null) {
1414
+            return [];
1415
+        }
1416
+
1417
+        $owner = $owner->getUID();
1418
+
1419
+        if ($currentAccess) {
1420
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1421
+        } else {
1422
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1423
+        }
1424
+        if (!$this->userManager->userExists($owner)) {
1425
+            return $al;
1426
+        }
1427
+
1428
+        //Get node for the owner and correct the owner in case of external storages
1429
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1430
+        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1431
+            $nodes = $userFolder->getById($path->getId());
1432
+            $path = array_shift($nodes);
1433
+            if ($path->getOwner() === null) {
1434
+                return [];
1435
+            }
1436
+            $owner = $path->getOwner()->getUID();
1437
+        }
1438
+
1439
+        $providers = $this->factory->getAllProviders();
1440
+
1441
+        /** @var Node[] $nodes */
1442
+        $nodes = [];
1443
+
1444
+
1445
+        if ($currentAccess) {
1446
+            $ownerPath = $path->getPath();
1447
+            $ownerPath = explode('/', $ownerPath, 4);
1448
+            if (count($ownerPath) < 4) {
1449
+                $ownerPath = '';
1450
+            } else {
1451
+                $ownerPath = $ownerPath[3];
1452
+            }
1453
+            $al['users'][$owner] = [
1454
+                'node_id' => $path->getId(),
1455
+                'node_path' => '/' . $ownerPath,
1456
+            ];
1457
+        } else {
1458
+            $al['users'][] = $owner;
1459
+        }
1460
+
1461
+        // Collect all the shares
1462
+        while ($path->getPath() !== $userFolder->getPath()) {
1463
+            $nodes[] = $path;
1464
+            if (!$recursive) {
1465
+                break;
1466
+            }
1467
+            $path = $path->getParent();
1468
+        }
1469
+
1470
+        foreach ($providers as $provider) {
1471
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1472
+
1473
+            foreach ($tmp as $k => $v) {
1474
+                if (isset($al[$k])) {
1475
+                    if (is_array($al[$k])) {
1476
+                        if ($currentAccess) {
1477
+                            $al[$k] += $v;
1478
+                        } else {
1479
+                            $al[$k] = array_merge($al[$k], $v);
1480
+                            $al[$k] = array_unique($al[$k]);
1481
+                            $al[$k] = array_values($al[$k]);
1482
+                        }
1483
+                    } else {
1484
+                        $al[$k] = $al[$k] || $v;
1485
+                    }
1486
+                } else {
1487
+                    $al[$k] = $v;
1488
+                }
1489
+            }
1490
+        }
1491
+
1492
+        return $al;
1493
+    }
1494
+
1495
+    /**
1496
+     * Create a new share
1497
+     * @return \OCP\Share\IShare
1498
+     */
1499
+    public function newShare() {
1500
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1501
+    }
1502
+
1503
+    /**
1504
+     * Is the share API enabled
1505
+     *
1506
+     * @return bool
1507
+     */
1508
+    public function shareApiEnabled() {
1509
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1510
+    }
1511
+
1512
+    /**
1513
+     * Is public link sharing enabled
1514
+     *
1515
+     * @return bool
1516
+     */
1517
+    public function shareApiAllowLinks() {
1518
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1519
+    }
1520
+
1521
+    /**
1522
+     * Is password on public link requires
1523
+     *
1524
+     * @return bool
1525
+     */
1526
+    public function shareApiLinkEnforcePassword() {
1527
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1528
+    }
1529
+
1530
+    /**
1531
+     * Is default expire date enabled
1532
+     *
1533
+     * @return bool
1534
+     */
1535
+    public function shareApiLinkDefaultExpireDate() {
1536
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1537
+    }
1538
+
1539
+    /**
1540
+     * Is default expire date enforced
1541
+     *`
1542
+     * @return bool
1543
+     */
1544
+    public function shareApiLinkDefaultExpireDateEnforced() {
1545
+        return $this->shareApiLinkDefaultExpireDate() &&
1546
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1547
+    }
1548
+
1549
+    /**
1550
+     * Number of default expire days
1551
+     *shareApiLinkAllowPublicUpload
1552
+     * @return int
1553
+     */
1554
+    public function shareApiLinkDefaultExpireDays() {
1555
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1556
+    }
1557
+
1558
+    /**
1559
+     * Allow public upload on link shares
1560
+     *
1561
+     * @return bool
1562
+     */
1563
+    public function shareApiLinkAllowPublicUpload() {
1564
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1565
+    }
1566
+
1567
+    /**
1568
+     * check if user can only share with group members
1569
+     * @return bool
1570
+     */
1571
+    public function shareWithGroupMembersOnly() {
1572
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1573
+    }
1574
+
1575
+    /**
1576
+     * Check if users can share with groups
1577
+     * @return bool
1578
+     */
1579
+    public function allowGroupSharing() {
1580
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1581
+    }
1582
+
1583
+    /**
1584
+     * Copied from \OC_Util::isSharingDisabledForUser
1585
+     *
1586
+     * TODO: Deprecate fuction from OC_Util
1587
+     *
1588
+     * @param string $userId
1589
+     * @return bool
1590
+     */
1591
+    public function sharingDisabledForUser($userId) {
1592
+        if ($userId === null) {
1593
+            return false;
1594
+        }
1595
+
1596
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1597
+            return $this->sharingDisabledForUsersCache[$userId];
1598
+        }
1599
+
1600
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1601
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1602
+            $excludedGroups = json_decode($groupsList);
1603
+            if (is_null($excludedGroups)) {
1604
+                $excludedGroups = explode(',', $groupsList);
1605
+                $newValue = json_encode($excludedGroups);
1606
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1607
+            }
1608
+            $user = $this->userManager->get($userId);
1609
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1610
+            if (!empty($usersGroups)) {
1611
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1612
+                // if the user is only in groups which are disabled for sharing then
1613
+                // sharing is also disabled for the user
1614
+                if (empty($remainingGroups)) {
1615
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1616
+                    return true;
1617
+                }
1618
+            }
1619
+        }
1620
+
1621
+        $this->sharingDisabledForUsersCache[$userId] = false;
1622
+        return false;
1623
+    }
1624
+
1625
+    /**
1626
+     * @inheritdoc
1627
+     */
1628
+    public function outgoingServer2ServerSharesAllowed() {
1629
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1630
+    }
1631
+
1632
+    /**
1633
+     * @inheritdoc
1634
+     */
1635
+    public function outgoingServer2ServerGroupSharesAllowed() {
1636
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
1637
+    }
1638
+
1639
+    /**
1640
+     * @inheritdoc
1641
+     */
1642
+    public function shareProviderExists($shareType) {
1643
+        try {
1644
+            $this->factory->getProviderForType($shareType);
1645
+        } catch (ProviderException $e) {
1646
+            return false;
1647
+        }
1648
+
1649
+        return true;
1650
+    }
1651 1651
 
1652 1652
 }
Please login to merge, or discard this patch.
lib/private/Files/View.php 1 patch
Indentation   +2095 added lines, -2095 removed lines patch added patch discarded remove patch
@@ -83,2099 +83,2099 @@
 block discarded – undo
83 83
  * \OC\Files\Storage\Storage object
84 84
  */
85 85
 class View {
86
-	/** @var string */
87
-	private $fakeRoot = '';
88
-
89
-	/**
90
-	 * @var \OCP\Lock\ILockingProvider
91
-	 */
92
-	protected $lockingProvider;
93
-
94
-	private $lockingEnabled;
95
-
96
-	private $updaterEnabled = true;
97
-
98
-	/** @var \OC\User\Manager */
99
-	private $userManager;
100
-
101
-	/** @var \OCP\ILogger */
102
-	private $logger;
103
-
104
-	/**
105
-	 * @param string $root
106
-	 * @throws \Exception If $root contains an invalid path
107
-	 */
108
-	public function __construct($root = '') {
109
-		if (is_null($root)) {
110
-			throw new \InvalidArgumentException('Root can\'t be null');
111
-		}
112
-		if (!Filesystem::isValidPath($root)) {
113
-			throw new \Exception();
114
-		}
115
-
116
-		$this->fakeRoot = $root;
117
-		$this->lockingProvider = \OC::$server->getLockingProvider();
118
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
119
-		$this->userManager = \OC::$server->getUserManager();
120
-		$this->logger = \OC::$server->getLogger();
121
-	}
122
-
123
-	public function getAbsolutePath($path = '/') {
124
-		if ($path === null) {
125
-			return null;
126
-		}
127
-		$this->assertPathLength($path);
128
-		if ($path === '') {
129
-			$path = '/';
130
-		}
131
-		if ($path[0] !== '/') {
132
-			$path = '/' . $path;
133
-		}
134
-		return $this->fakeRoot . $path;
135
-	}
136
-
137
-	/**
138
-	 * change the root to a fake root
139
-	 *
140
-	 * @param string $fakeRoot
141
-	 * @return boolean|null
142
-	 */
143
-	public function chroot($fakeRoot) {
144
-		if (!$fakeRoot == '') {
145
-			if ($fakeRoot[0] !== '/') {
146
-				$fakeRoot = '/' . $fakeRoot;
147
-			}
148
-		}
149
-		$this->fakeRoot = $fakeRoot;
150
-	}
151
-
152
-	/**
153
-	 * get the fake root
154
-	 *
155
-	 * @return string
156
-	 */
157
-	public function getRoot() {
158
-		return $this->fakeRoot;
159
-	}
160
-
161
-	/**
162
-	 * get path relative to the root of the view
163
-	 *
164
-	 * @param string $path
165
-	 * @return string
166
-	 */
167
-	public function getRelativePath($path) {
168
-		$this->assertPathLength($path);
169
-		if ($this->fakeRoot == '') {
170
-			return $path;
171
-		}
172
-
173
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
174
-			return '/';
175
-		}
176
-
177
-		// missing slashes can cause wrong matches!
178
-		$root = rtrim($this->fakeRoot, '/') . '/';
179
-
180
-		if (strpos($path, $root) !== 0) {
181
-			return null;
182
-		} else {
183
-			$path = substr($path, strlen($this->fakeRoot));
184
-			if (strlen($path) === 0) {
185
-				return '/';
186
-			} else {
187
-				return $path;
188
-			}
189
-		}
190
-	}
191
-
192
-	/**
193
-	 * get the mountpoint of the storage object for a path
194
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
195
-	 * returned mountpoint is relative to the absolute root of the filesystem
196
-	 * and does not take the chroot into account )
197
-	 *
198
-	 * @param string $path
199
-	 * @return string
200
-	 */
201
-	public function getMountPoint($path) {
202
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
203
-	}
204
-
205
-	/**
206
-	 * get the mountpoint of the storage object for a path
207
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
208
-	 * returned mountpoint is relative to the absolute root of the filesystem
209
-	 * and does not take the chroot into account )
210
-	 *
211
-	 * @param string $path
212
-	 * @return \OCP\Files\Mount\IMountPoint
213
-	 */
214
-	public function getMount($path) {
215
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
216
-	}
217
-
218
-	/**
219
-	 * resolve a path to a storage and internal path
220
-	 *
221
-	 * @param string $path
222
-	 * @return array an array consisting of the storage and the internal path
223
-	 */
224
-	public function resolvePath($path) {
225
-		$a = $this->getAbsolutePath($path);
226
-		$p = Filesystem::normalizePath($a);
227
-		return Filesystem::resolvePath($p);
228
-	}
229
-
230
-	/**
231
-	 * return the path to a local version of the file
232
-	 * we need this because we can't know if a file is stored local or not from
233
-	 * outside the filestorage and for some purposes a local file is needed
234
-	 *
235
-	 * @param string $path
236
-	 * @return string
237
-	 */
238
-	public function getLocalFile($path) {
239
-		$parent = substr($path, 0, strrpos($path, '/'));
240
-		$path = $this->getAbsolutePath($path);
241
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
242
-		if (Filesystem::isValidPath($parent) and $storage) {
243
-			return $storage->getLocalFile($internalPath);
244
-		} else {
245
-			return null;
246
-		}
247
-	}
248
-
249
-	/**
250
-	 * @param string $path
251
-	 * @return string
252
-	 */
253
-	public function getLocalFolder($path) {
254
-		$parent = substr($path, 0, strrpos($path, '/'));
255
-		$path = $this->getAbsolutePath($path);
256
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
257
-		if (Filesystem::isValidPath($parent) and $storage) {
258
-			return $storage->getLocalFolder($internalPath);
259
-		} else {
260
-			return null;
261
-		}
262
-	}
263
-
264
-	/**
265
-	 * the following functions operate with arguments and return values identical
266
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
267
-	 * for \OC\Files\Storage\Storage via basicOperation().
268
-	 */
269
-	public function mkdir($path) {
270
-		return $this->basicOperation('mkdir', $path, array('create', 'write'));
271
-	}
272
-
273
-	/**
274
-	 * remove mount point
275
-	 *
276
-	 * @param \OC\Files\Mount\MoveableMount $mount
277
-	 * @param string $path relative to data/
278
-	 * @return boolean
279
-	 */
280
-	protected function removeMount($mount, $path) {
281
-		if ($mount instanceof MoveableMount) {
282
-			// cut of /user/files to get the relative path to data/user/files
283
-			$pathParts = explode('/', $path, 4);
284
-			$relPath = '/' . $pathParts[3];
285
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
286
-			\OC_Hook::emit(
287
-				Filesystem::CLASSNAME, "umount",
288
-				array(Filesystem::signal_param_path => $relPath)
289
-			);
290
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
291
-			$result = $mount->removeMount();
292
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
293
-			if ($result) {
294
-				\OC_Hook::emit(
295
-					Filesystem::CLASSNAME, "post_umount",
296
-					array(Filesystem::signal_param_path => $relPath)
297
-				);
298
-			}
299
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
300
-			return $result;
301
-		} else {
302
-			// do not allow deleting the storage's root / the mount point
303
-			// because for some storages it might delete the whole contents
304
-			// but isn't supposed to work that way
305
-			return false;
306
-		}
307
-	}
308
-
309
-	public function disableCacheUpdate() {
310
-		$this->updaterEnabled = false;
311
-	}
312
-
313
-	public function enableCacheUpdate() {
314
-		$this->updaterEnabled = true;
315
-	}
316
-
317
-	protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
318
-		if ($this->updaterEnabled) {
319
-			if (is_null($time)) {
320
-				$time = time();
321
-			}
322
-			$storage->getUpdater()->update($internalPath, $time);
323
-		}
324
-	}
325
-
326
-	protected function removeUpdate(Storage $storage, $internalPath) {
327
-		if ($this->updaterEnabled) {
328
-			$storage->getUpdater()->remove($internalPath);
329
-		}
330
-	}
331
-
332
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
333
-		if ($this->updaterEnabled) {
334
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
335
-		}
336
-	}
337
-
338
-	/**
339
-	 * @param string $path
340
-	 * @return bool|mixed
341
-	 */
342
-	public function rmdir($path) {
343
-		$absolutePath = $this->getAbsolutePath($path);
344
-		$mount = Filesystem::getMountManager()->find($absolutePath);
345
-		if ($mount->getInternalPath($absolutePath) === '') {
346
-			return $this->removeMount($mount, $absolutePath);
347
-		}
348
-		if ($this->is_dir($path)) {
349
-			$result = $this->basicOperation('rmdir', $path, array('delete'));
350
-		} else {
351
-			$result = false;
352
-		}
353
-
354
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
355
-			$storage = $mount->getStorage();
356
-			$internalPath = $mount->getInternalPath($absolutePath);
357
-			$storage->getUpdater()->remove($internalPath);
358
-		}
359
-		return $result;
360
-	}
361
-
362
-	/**
363
-	 * @param string $path
364
-	 * @return resource
365
-	 */
366
-	public function opendir($path) {
367
-		return $this->basicOperation('opendir', $path, array('read'));
368
-	}
369
-
370
-	/**
371
-	 * @param string $path
372
-	 * @return bool|mixed
373
-	 */
374
-	public function is_dir($path) {
375
-		if ($path == '/') {
376
-			return true;
377
-		}
378
-		return $this->basicOperation('is_dir', $path);
379
-	}
380
-
381
-	/**
382
-	 * @param string $path
383
-	 * @return bool|mixed
384
-	 */
385
-	public function is_file($path) {
386
-		if ($path == '/') {
387
-			return false;
388
-		}
389
-		return $this->basicOperation('is_file', $path);
390
-	}
391
-
392
-	/**
393
-	 * @param string $path
394
-	 * @return mixed
395
-	 */
396
-	public function stat($path) {
397
-		return $this->basicOperation('stat', $path);
398
-	}
399
-
400
-	/**
401
-	 * @param string $path
402
-	 * @return mixed
403
-	 */
404
-	public function filetype($path) {
405
-		return $this->basicOperation('filetype', $path);
406
-	}
407
-
408
-	/**
409
-	 * @param string $path
410
-	 * @return mixed
411
-	 */
412
-	public function filesize($path) {
413
-		return $this->basicOperation('filesize', $path);
414
-	}
415
-
416
-	/**
417
-	 * @param string $path
418
-	 * @return bool|mixed
419
-	 * @throws \OCP\Files\InvalidPathException
420
-	 */
421
-	public function readfile($path) {
422
-		$this->assertPathLength($path);
423
-		@ob_end_clean();
424
-		$handle = $this->fopen($path, 'rb');
425
-		if ($handle) {
426
-			$chunkSize = 8192; // 8 kB chunks
427
-			while (!feof($handle)) {
428
-				echo fread($handle, $chunkSize);
429
-				flush();
430
-			}
431
-			fclose($handle);
432
-			return $this->filesize($path);
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
-				return ftell($handle) - $from;
482
-			}
483
-
484
-			throw new \OCP\Files\UnseekableException('fseek error');
485
-		}
486
-		return false;
487
-	}
488
-
489
-	/**
490
-	 * @param string $path
491
-	 * @return mixed
492
-	 */
493
-	public function isCreatable($path) {
494
-		return $this->basicOperation('isCreatable', $path);
495
-	}
496
-
497
-	/**
498
-	 * @param string $path
499
-	 * @return mixed
500
-	 */
501
-	public function isReadable($path) {
502
-		return $this->basicOperation('isReadable', $path);
503
-	}
504
-
505
-	/**
506
-	 * @param string $path
507
-	 * @return mixed
508
-	 */
509
-	public function isUpdatable($path) {
510
-		return $this->basicOperation('isUpdatable', $path);
511
-	}
512
-
513
-	/**
514
-	 * @param string $path
515
-	 * @return bool|mixed
516
-	 */
517
-	public function isDeletable($path) {
518
-		$absolutePath = $this->getAbsolutePath($path);
519
-		$mount = Filesystem::getMountManager()->find($absolutePath);
520
-		if ($mount->getInternalPath($absolutePath) === '') {
521
-			return $mount instanceof MoveableMount;
522
-		}
523
-		return $this->basicOperation('isDeletable', $path);
524
-	}
525
-
526
-	/**
527
-	 * @param string $path
528
-	 * @return mixed
529
-	 */
530
-	public function isSharable($path) {
531
-		return $this->basicOperation('isSharable', $path);
532
-	}
533
-
534
-	/**
535
-	 * @param string $path
536
-	 * @return bool|mixed
537
-	 */
538
-	public function file_exists($path) {
539
-		if ($path == '/') {
540
-			return true;
541
-		}
542
-		return $this->basicOperation('file_exists', $path);
543
-	}
544
-
545
-	/**
546
-	 * @param string $path
547
-	 * @return mixed
548
-	 */
549
-	public function filemtime($path) {
550
-		return $this->basicOperation('filemtime', $path);
551
-	}
552
-
553
-	/**
554
-	 * @param string $path
555
-	 * @param int|string $mtime
556
-	 * @return bool
557
-	 */
558
-	public function touch($path, $mtime = null) {
559
-		if (!is_null($mtime) and !is_numeric($mtime)) {
560
-			$mtime = strtotime($mtime);
561
-		}
562
-
563
-		$hooks = array('touch');
564
-
565
-		if (!$this->file_exists($path)) {
566
-			$hooks[] = 'create';
567
-			$hooks[] = 'write';
568
-		}
569
-		try {
570
-			$result = $this->basicOperation('touch', $path, $hooks, $mtime);
571
-		} catch (\Exception $e) {
572
-			$this->logger->logException($e, ['level' => ILogger::INFO, 'message' => 'Error while setting modified time']);
573
-			$result = false;
574
-		}
575
-		if (!$result) {
576
-			// If create file fails because of permissions on external storage like SMB folders,
577
-			// check file exists and return false if not.
578
-			if (!$this->file_exists($path)) {
579
-				return false;
580
-			}
581
-			if (is_null($mtime)) {
582
-				$mtime = time();
583
-			}
584
-			//if native touch fails, we emulate it by changing the mtime in the cache
585
-			$this->putFileInfo($path, array('mtime' => floor($mtime)));
586
-		}
587
-		return true;
588
-	}
589
-
590
-	/**
591
-	 * @param string $path
592
-	 * @return mixed
593
-	 */
594
-	public function file_get_contents($path) {
595
-		return $this->basicOperation('file_get_contents', $path, array('read'));
596
-	}
597
-
598
-	/**
599
-	 * @param bool $exists
600
-	 * @param string $path
601
-	 * @param bool $run
602
-	 */
603
-	protected function emit_file_hooks_pre($exists, $path, &$run) {
604
-		if (!$exists) {
605
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
606
-				Filesystem::signal_param_path => $this->getHookPath($path),
607
-				Filesystem::signal_param_run => &$run,
608
-			));
609
-		} else {
610
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
611
-				Filesystem::signal_param_path => $this->getHookPath($path),
612
-				Filesystem::signal_param_run => &$run,
613
-			));
614
-		}
615
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
616
-			Filesystem::signal_param_path => $this->getHookPath($path),
617
-			Filesystem::signal_param_run => &$run,
618
-		));
619
-	}
620
-
621
-	/**
622
-	 * @param bool $exists
623
-	 * @param string $path
624
-	 */
625
-	protected function emit_file_hooks_post($exists, $path) {
626
-		if (!$exists) {
627
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
628
-				Filesystem::signal_param_path => $this->getHookPath($path),
629
-			));
630
-		} else {
631
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
632
-				Filesystem::signal_param_path => $this->getHookPath($path),
633
-			));
634
-		}
635
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
636
-			Filesystem::signal_param_path => $this->getHookPath($path),
637
-		));
638
-	}
639
-
640
-	/**
641
-	 * @param string $path
642
-	 * @param string|resource $data
643
-	 * @return bool|mixed
644
-	 * @throws \Exception
645
-	 */
646
-	public function file_put_contents($path, $data) {
647
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
648
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
649
-			if (Filesystem::isValidPath($path)
650
-				and !Filesystem::isFileBlacklisted($path)
651
-			) {
652
-				$path = $this->getRelativePath($absolutePath);
653
-
654
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
655
-
656
-				$exists = $this->file_exists($path);
657
-				$run = true;
658
-				if ($this->shouldEmitHooks($path)) {
659
-					$this->emit_file_hooks_pre($exists, $path, $run);
660
-				}
661
-				if (!$run) {
662
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
663
-					return false;
664
-				}
665
-
666
-				$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
667
-
668
-				/** @var \OC\Files\Storage\Storage $storage */
669
-				list($storage, $internalPath) = $this->resolvePath($path);
670
-				$target = $storage->fopen($internalPath, 'w');
671
-				if ($target) {
672
-					list (, $result) = \OC_Helper::streamCopy($data, $target);
673
-					fclose($target);
674
-					fclose($data);
675
-
676
-					$this->writeUpdate($storage, $internalPath);
677
-
678
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
679
-
680
-					if ($this->shouldEmitHooks($path) && $result !== false) {
681
-						$this->emit_file_hooks_post($exists, $path);
682
-					}
683
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
684
-					return $result;
685
-				} else {
686
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
687
-					return false;
688
-				}
689
-			} else {
690
-				return false;
691
-			}
692
-		} else {
693
-			$hooks = $this->file_exists($path) ? array('update', 'write') : array('create', 'write');
694
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
695
-		}
696
-	}
697
-
698
-	/**
699
-	 * @param string $path
700
-	 * @return bool|mixed
701
-	 */
702
-	public function unlink($path) {
703
-		if ($path === '' || $path === '/') {
704
-			// do not allow deleting the root
705
-			return false;
706
-		}
707
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
708
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
709
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
710
-		if ($mount and $mount->getInternalPath($absolutePath) === '') {
711
-			return $this->removeMount($mount, $absolutePath);
712
-		}
713
-		if ($this->is_dir($path)) {
714
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
715
-		} else {
716
-			$result = $this->basicOperation('unlink', $path, ['delete']);
717
-		}
718
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
719
-			$storage = $mount->getStorage();
720
-			$internalPath = $mount->getInternalPath($absolutePath);
721
-			$storage->getUpdater()->remove($internalPath);
722
-			return true;
723
-		} else {
724
-			return $result;
725
-		}
726
-	}
727
-
728
-	/**
729
-	 * @param string $directory
730
-	 * @return bool|mixed
731
-	 */
732
-	public function deleteAll($directory) {
733
-		return $this->rmdir($directory);
734
-	}
735
-
736
-	/**
737
-	 * Rename/move a file or folder from the source path to target path.
738
-	 *
739
-	 * @param string $path1 source path
740
-	 * @param string $path2 target path
741
-	 *
742
-	 * @return bool|mixed
743
-	 */
744
-	public function rename($path1, $path2) {
745
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
746
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
747
-		$result = false;
748
-		if (
749
-			Filesystem::isValidPath($path2)
750
-			and Filesystem::isValidPath($path1)
751
-			and !Filesystem::isFileBlacklisted($path2)
752
-		) {
753
-			$path1 = $this->getRelativePath($absolutePath1);
754
-			$path2 = $this->getRelativePath($absolutePath2);
755
-			$exists = $this->file_exists($path2);
756
-
757
-			if ($path1 == null or $path2 == null) {
758
-				return false;
759
-			}
760
-
761
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
762
-			try {
763
-				$this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
764
-
765
-				$run = true;
766
-				if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
767
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
768
-					$this->emit_file_hooks_pre($exists, $path2, $run);
769
-				} elseif ($this->shouldEmitHooks($path1)) {
770
-					\OC_Hook::emit(
771
-						Filesystem::CLASSNAME, Filesystem::signal_rename,
772
-						array(
773
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
774
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
775
-							Filesystem::signal_param_run => &$run
776
-						)
777
-					);
778
-				}
779
-				if ($run) {
780
-					$this->verifyPath(dirname($path2), basename($path2));
781
-
782
-					$manager = Filesystem::getMountManager();
783
-					$mount1 = $this->getMount($path1);
784
-					$mount2 = $this->getMount($path2);
785
-					$storage1 = $mount1->getStorage();
786
-					$storage2 = $mount2->getStorage();
787
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
788
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
789
-
790
-					$this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
791
-					try {
792
-						$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
793
-
794
-						if ($internalPath1 === '') {
795
-							if ($mount1 instanceof MoveableMount) {
796
-								$sourceParentMount = $this->getMount(dirname($path1));
797
-								if ($sourceParentMount === $mount2 && $this->targetIsNotShared($storage2, $internalPath2)) {
798
-									/**
799
-									 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
800
-									 */
801
-									$sourceMountPoint = $mount1->getMountPoint();
802
-									$result = $mount1->moveMount($absolutePath2);
803
-									$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
804
-								} else {
805
-									$result = false;
806
-								}
807
-							} else {
808
-								$result = false;
809
-							}
810
-							// moving a file/folder within the same mount point
811
-						} elseif ($storage1 === $storage2) {
812
-							if ($storage1) {
813
-								$result = $storage1->rename($internalPath1, $internalPath2);
814
-							} else {
815
-								$result = false;
816
-							}
817
-							// moving a file/folder between storages (from $storage1 to $storage2)
818
-						} else {
819
-							$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
820
-						}
821
-
822
-						if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
823
-							// if it was a rename from a part file to a regular file it was a write and not a rename operation
824
-							$this->writeUpdate($storage2, $internalPath2);
825
-						} else if ($result) {
826
-							if ($internalPath1 !== '') { // don't do a cache update for moved mounts
827
-								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
828
-							}
829
-						}
830
-					} catch(\Exception $e) {
831
-						throw $e;
832
-					} finally {
833
-						$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
834
-						$this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
835
-					}
836
-
837
-					if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
838
-						if ($this->shouldEmitHooks()) {
839
-							$this->emit_file_hooks_post($exists, $path2);
840
-						}
841
-					} elseif ($result) {
842
-						if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
843
-							\OC_Hook::emit(
844
-								Filesystem::CLASSNAME,
845
-								Filesystem::signal_post_rename,
846
-								array(
847
-									Filesystem::signal_param_oldpath => $this->getHookPath($path1),
848
-									Filesystem::signal_param_newpath => $this->getHookPath($path2)
849
-								)
850
-							);
851
-						}
852
-					}
853
-				}
854
-			} catch(\Exception $e) {
855
-				throw $e;
856
-			} finally {
857
-				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
858
-				$this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
859
-			}
860
-		}
861
-		return $result;
862
-	}
863
-
864
-	/**
865
-	 * Copy a file/folder from the source path to target path
866
-	 *
867
-	 * @param string $path1 source path
868
-	 * @param string $path2 target path
869
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
870
-	 *
871
-	 * @return bool|mixed
872
-	 */
873
-	public function copy($path1, $path2, $preserveMtime = false) {
874
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
875
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
876
-		$result = false;
877
-		if (
878
-			Filesystem::isValidPath($path2)
879
-			and Filesystem::isValidPath($path1)
880
-			and !Filesystem::isFileBlacklisted($path2)
881
-		) {
882
-			$path1 = $this->getRelativePath($absolutePath1);
883
-			$path2 = $this->getRelativePath($absolutePath2);
884
-
885
-			if ($path1 == null or $path2 == null) {
886
-				return false;
887
-			}
888
-			$run = true;
889
-
890
-			$this->lockFile($path2, ILockingProvider::LOCK_SHARED);
891
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED);
892
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
893
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
894
-
895
-			try {
896
-
897
-				$exists = $this->file_exists($path2);
898
-				if ($this->shouldEmitHooks()) {
899
-					\OC_Hook::emit(
900
-						Filesystem::CLASSNAME,
901
-						Filesystem::signal_copy,
902
-						array(
903
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
904
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
905
-							Filesystem::signal_param_run => &$run
906
-						)
907
-					);
908
-					$this->emit_file_hooks_pre($exists, $path2, $run);
909
-				}
910
-				if ($run) {
911
-					$mount1 = $this->getMount($path1);
912
-					$mount2 = $this->getMount($path2);
913
-					$storage1 = $mount1->getStorage();
914
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
915
-					$storage2 = $mount2->getStorage();
916
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
917
-
918
-					$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
919
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
920
-
921
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
922
-						if ($storage1) {
923
-							$result = $storage1->copy($internalPath1, $internalPath2);
924
-						} else {
925
-							$result = false;
926
-						}
927
-					} else {
928
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
929
-					}
930
-
931
-					$this->writeUpdate($storage2, $internalPath2);
932
-
933
-					$this->changeLock($path2, ILockingProvider::LOCK_SHARED);
934
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
935
-
936
-					if ($this->shouldEmitHooks() && $result !== false) {
937
-						\OC_Hook::emit(
938
-							Filesystem::CLASSNAME,
939
-							Filesystem::signal_post_copy,
940
-							array(
941
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
942
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
943
-							)
944
-						);
945
-						$this->emit_file_hooks_post($exists, $path2);
946
-					}
947
-
948
-				}
949
-			} catch (\Exception $e) {
950
-				$this->unlockFile($path2, $lockTypePath2);
951
-				$this->unlockFile($path1, $lockTypePath1);
952
-				throw $e;
953
-			}
954
-
955
-			$this->unlockFile($path2, $lockTypePath2);
956
-			$this->unlockFile($path1, $lockTypePath1);
957
-
958
-		}
959
-		return $result;
960
-	}
961
-
962
-	/**
963
-	 * @param string $path
964
-	 * @param string $mode 'r' or 'w'
965
-	 * @return resource
966
-	 */
967
-	public function fopen($path, $mode) {
968
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
969
-		$hooks = array();
970
-		switch ($mode) {
971
-			case 'r':
972
-				$hooks[] = 'read';
973
-				break;
974
-			case 'r+':
975
-			case 'w+':
976
-			case 'x+':
977
-			case 'a+':
978
-				$hooks[] = 'read';
979
-				$hooks[] = 'write';
980
-				break;
981
-			case 'w':
982
-			case 'x':
983
-			case 'a':
984
-				$hooks[] = 'write';
985
-				break;
986
-			default:
987
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, ILogger::ERROR);
988
-		}
989
-
990
-		if ($mode !== 'r' && $mode !== 'w') {
991
-			\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');
992
-		}
993
-
994
-		return $this->basicOperation('fopen', $path, $hooks, $mode);
995
-	}
996
-
997
-	/**
998
-	 * @param string $path
999
-	 * @return bool|string
1000
-	 * @throws \OCP\Files\InvalidPathException
1001
-	 */
1002
-	public function toTmpFile($path) {
1003
-		$this->assertPathLength($path);
1004
-		if (Filesystem::isValidPath($path)) {
1005
-			$source = $this->fopen($path, 'r');
1006
-			if ($source) {
1007
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
1008
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1009
-				file_put_contents($tmpFile, $source);
1010
-				return $tmpFile;
1011
-			} else {
1012
-				return false;
1013
-			}
1014
-		} else {
1015
-			return false;
1016
-		}
1017
-	}
1018
-
1019
-	/**
1020
-	 * @param string $tmpFile
1021
-	 * @param string $path
1022
-	 * @return bool|mixed
1023
-	 * @throws \OCP\Files\InvalidPathException
1024
-	 */
1025
-	public function fromTmpFile($tmpFile, $path) {
1026
-		$this->assertPathLength($path);
1027
-		if (Filesystem::isValidPath($path)) {
1028
-
1029
-			// Get directory that the file is going into
1030
-			$filePath = dirname($path);
1031
-
1032
-			// Create the directories if any
1033
-			if (!$this->file_exists($filePath)) {
1034
-				$result = $this->createParentDirectories($filePath);
1035
-				if ($result === false) {
1036
-					return false;
1037
-				}
1038
-			}
1039
-
1040
-			$source = fopen($tmpFile, 'r');
1041
-			if ($source) {
1042
-				$result = $this->file_put_contents($path, $source);
1043
-				// $this->file_put_contents() might have already closed
1044
-				// the resource, so we check it, before trying to close it
1045
-				// to avoid messages in the error log.
1046
-				if (is_resource($source)) {
1047
-					fclose($source);
1048
-				}
1049
-				unlink($tmpFile);
1050
-				return $result;
1051
-			} else {
1052
-				return false;
1053
-			}
1054
-		} else {
1055
-			return false;
1056
-		}
1057
-	}
1058
-
1059
-
1060
-	/**
1061
-	 * @param string $path
1062
-	 * @return mixed
1063
-	 * @throws \OCP\Files\InvalidPathException
1064
-	 */
1065
-	public function getMimeType($path) {
1066
-		$this->assertPathLength($path);
1067
-		return $this->basicOperation('getMimeType', $path);
1068
-	}
1069
-
1070
-	/**
1071
-	 * @param string $type
1072
-	 * @param string $path
1073
-	 * @param bool $raw
1074
-	 * @return bool|null|string
1075
-	 */
1076
-	public function hash($type, $path, $raw = false) {
1077
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1078
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1079
-		if (Filesystem::isValidPath($path)) {
1080
-			$path = $this->getRelativePath($absolutePath);
1081
-			if ($path == null) {
1082
-				return false;
1083
-			}
1084
-			if ($this->shouldEmitHooks($path)) {
1085
-				\OC_Hook::emit(
1086
-					Filesystem::CLASSNAME,
1087
-					Filesystem::signal_read,
1088
-					array(Filesystem::signal_param_path => $this->getHookPath($path))
1089
-				);
1090
-			}
1091
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1092
-			if ($storage) {
1093
-				return $storage->hash($type, $internalPath, $raw);
1094
-			}
1095
-		}
1096
-		return null;
1097
-	}
1098
-
1099
-	/**
1100
-	 * @param string $path
1101
-	 * @return mixed
1102
-	 * @throws \OCP\Files\InvalidPathException
1103
-	 */
1104
-	public function free_space($path = '/') {
1105
-		$this->assertPathLength($path);
1106
-		$result = $this->basicOperation('free_space', $path);
1107
-		if ($result === null) {
1108
-			throw new InvalidPathException();
1109
-		}
1110
-		return $result;
1111
-	}
1112
-
1113
-	/**
1114
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1115
-	 *
1116
-	 * @param string $operation
1117
-	 * @param string $path
1118
-	 * @param array $hooks (optional)
1119
-	 * @param mixed $extraParam (optional)
1120
-	 * @return mixed
1121
-	 * @throws \Exception
1122
-	 *
1123
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1124
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1125
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1126
-	 */
1127
-	private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1128
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1129
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1130
-		if (Filesystem::isValidPath($path)
1131
-			and !Filesystem::isFileBlacklisted($path)
1132
-		) {
1133
-			$path = $this->getRelativePath($absolutePath);
1134
-			if ($path == null) {
1135
-				return false;
1136
-			}
1137
-
1138
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1139
-				// always a shared lock during pre-hooks so the hook can read the file
1140
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1141
-			}
1142
-
1143
-			$run = $this->runHooks($hooks, $path);
1144
-			/** @var \OC\Files\Storage\Storage $storage */
1145
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1146
-			if ($run and $storage) {
1147
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1148
-					try {
1149
-						$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1150
-					} catch (LockedException $e) {
1151
-						// release the shared lock we acquired before quiting
1152
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1153
-						throw $e;
1154
-					}
1155
-				}
1156
-				try {
1157
-					if (!is_null($extraParam)) {
1158
-						$result = $storage->$operation($internalPath, $extraParam);
1159
-					} else {
1160
-						$result = $storage->$operation($internalPath);
1161
-					}
1162
-				} catch (\Exception $e) {
1163
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1164
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1165
-					} else if (in_array('read', $hooks)) {
1166
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1167
-					}
1168
-					throw $e;
1169
-				}
1170
-
1171
-				if ($result && in_array('delete', $hooks) and $result) {
1172
-					$this->removeUpdate($storage, $internalPath);
1173
-				}
1174
-				if ($result && in_array('write', $hooks,  true) && $operation !== 'fopen' && $operation !== 'touch') {
1175
-					$this->writeUpdate($storage, $internalPath);
1176
-				}
1177
-				if ($result && in_array('touch', $hooks)) {
1178
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1179
-				}
1180
-
1181
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1182
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1183
-				}
1184
-
1185
-				$unlockLater = false;
1186
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1187
-					$unlockLater = true;
1188
-					// make sure our unlocking callback will still be called if connection is aborted
1189
-					ignore_user_abort(true);
1190
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1191
-						if (in_array('write', $hooks)) {
1192
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1193
-						} else if (in_array('read', $hooks)) {
1194
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1195
-						}
1196
-					});
1197
-				}
1198
-
1199
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1200
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1201
-						$this->runHooks($hooks, $path, true);
1202
-					}
1203
-				}
1204
-
1205
-				if (!$unlockLater
1206
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1207
-				) {
1208
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1209
-				}
1210
-				return $result;
1211
-			} else {
1212
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1213
-			}
1214
-		}
1215
-		return null;
1216
-	}
1217
-
1218
-	/**
1219
-	 * get the path relative to the default root for hook usage
1220
-	 *
1221
-	 * @param string $path
1222
-	 * @return string
1223
-	 */
1224
-	private function getHookPath($path) {
1225
-		if (!Filesystem::getView()) {
1226
-			return $path;
1227
-		}
1228
-		return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1229
-	}
1230
-
1231
-	private function shouldEmitHooks($path = '') {
1232
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1233
-			return false;
1234
-		}
1235
-		if (!Filesystem::$loaded) {
1236
-			return false;
1237
-		}
1238
-		$defaultRoot = Filesystem::getRoot();
1239
-		if ($defaultRoot === null) {
1240
-			return false;
1241
-		}
1242
-		if ($this->fakeRoot === $defaultRoot) {
1243
-			return true;
1244
-		}
1245
-		$fullPath = $this->getAbsolutePath($path);
1246
-
1247
-		if ($fullPath === $defaultRoot) {
1248
-			return true;
1249
-		}
1250
-
1251
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1252
-	}
1253
-
1254
-	/**
1255
-	 * @param string[] $hooks
1256
-	 * @param string $path
1257
-	 * @param bool $post
1258
-	 * @return bool
1259
-	 */
1260
-	private function runHooks($hooks, $path, $post = false) {
1261
-		$relativePath = $path;
1262
-		$path = $this->getHookPath($path);
1263
-		$prefix = $post ? 'post_' : '';
1264
-		$run = true;
1265
-		if ($this->shouldEmitHooks($relativePath)) {
1266
-			foreach ($hooks as $hook) {
1267
-				if ($hook != 'read') {
1268
-					\OC_Hook::emit(
1269
-						Filesystem::CLASSNAME,
1270
-						$prefix . $hook,
1271
-						array(
1272
-							Filesystem::signal_param_run => &$run,
1273
-							Filesystem::signal_param_path => $path
1274
-						)
1275
-					);
1276
-				} elseif (!$post) {
1277
-					\OC_Hook::emit(
1278
-						Filesystem::CLASSNAME,
1279
-						$prefix . $hook,
1280
-						array(
1281
-							Filesystem::signal_param_path => $path
1282
-						)
1283
-					);
1284
-				}
1285
-			}
1286
-		}
1287
-		return $run;
1288
-	}
1289
-
1290
-	/**
1291
-	 * check if a file or folder has been updated since $time
1292
-	 *
1293
-	 * @param string $path
1294
-	 * @param int $time
1295
-	 * @return bool
1296
-	 */
1297
-	public function hasUpdated($path, $time) {
1298
-		return $this->basicOperation('hasUpdated', $path, array(), $time);
1299
-	}
1300
-
1301
-	/**
1302
-	 * @param string $ownerId
1303
-	 * @return \OC\User\User
1304
-	 */
1305
-	private function getUserObjectForOwner($ownerId) {
1306
-		$owner = $this->userManager->get($ownerId);
1307
-		if ($owner instanceof IUser) {
1308
-			return $owner;
1309
-		} else {
1310
-			return new User($ownerId, null, \OC::$server->getEventDispatcher());
1311
-		}
1312
-	}
1313
-
1314
-	/**
1315
-	 * Get file info from cache
1316
-	 *
1317
-	 * If the file is not in cached it will be scanned
1318
-	 * If the file has changed on storage the cache will be updated
1319
-	 *
1320
-	 * @param \OC\Files\Storage\Storage $storage
1321
-	 * @param string $internalPath
1322
-	 * @param string $relativePath
1323
-	 * @return ICacheEntry|bool
1324
-	 */
1325
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1326
-		$cache = $storage->getCache($internalPath);
1327
-		$data = $cache->get($internalPath);
1328
-		$watcher = $storage->getWatcher($internalPath);
1329
-
1330
-		try {
1331
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1332
-			if (!$data || $data['size'] === -1) {
1333
-				if (!$storage->file_exists($internalPath)) {
1334
-					return false;
1335
-				}
1336
-				// don't need to get a lock here since the scanner does it's own locking
1337
-				$scanner = $storage->getScanner($internalPath);
1338
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1339
-				$data = $cache->get($internalPath);
1340
-			} else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1341
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1342
-				$watcher->update($internalPath, $data);
1343
-				$storage->getPropagator()->propagateChange($internalPath, time());
1344
-				$data = $cache->get($internalPath);
1345
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1346
-			}
1347
-		} catch (LockedException $e) {
1348
-			// if the file is locked we just use the old cache info
1349
-		}
1350
-
1351
-		return $data;
1352
-	}
1353
-
1354
-	/**
1355
-	 * get the filesystem info
1356
-	 *
1357
-	 * @param string $path
1358
-	 * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1359
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1360
-	 * defaults to true
1361
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1362
-	 */
1363
-	public function getFileInfo($path, $includeMountPoints = true) {
1364
-		$this->assertPathLength($path);
1365
-		if (!Filesystem::isValidPath($path)) {
1366
-			return false;
1367
-		}
1368
-		if (Cache\Scanner::isPartialFile($path)) {
1369
-			return $this->getPartFileInfo($path);
1370
-		}
1371
-		$relativePath = $path;
1372
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1373
-
1374
-		$mount = Filesystem::getMountManager()->find($path);
1375
-		if (!$mount) {
1376
-			\OC::$server->getLogger()->warning('Mountpoint not found for path: ' . $path);
1377
-			return false;
1378
-		}
1379
-		$storage = $mount->getStorage();
1380
-		$internalPath = $mount->getInternalPath($path);
1381
-		if ($storage) {
1382
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1383
-
1384
-			if (!$data instanceof ICacheEntry) {
1385
-				return false;
1386
-			}
1387
-
1388
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1389
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1390
-			}
1391
-			$ownerId = $storage->getOwner($internalPath);
1392
-			$owner = null;
1393
-			if ($ownerId !== null) {
1394
-				// ownerId might be null if files are accessed with an access token without file system access
1395
-				$owner = $this->getUserObjectForOwner($ownerId);
1396
-			}
1397
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1398
-
1399
-			if ($data and isset($data['fileid'])) {
1400
-				if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1401
-					//add the sizes of other mount points to the folder
1402
-					$extOnly = ($includeMountPoints === 'ext');
1403
-					$mounts = Filesystem::getMountManager()->findIn($path);
1404
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1405
-						$subStorage = $mount->getStorage();
1406
-						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1407
-					}));
1408
-				}
1409
-			}
1410
-
1411
-			return $info;
1412
-		} else {
1413
-			\OC::$server->getLogger()->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint());
1414
-		}
1415
-
1416
-		return false;
1417
-	}
1418
-
1419
-	/**
1420
-	 * get the content of a directory
1421
-	 *
1422
-	 * @param string $directory path under datadirectory
1423
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1424
-	 * @return FileInfo[]
1425
-	 */
1426
-	public function getDirectoryContent($directory, $mimetype_filter = '') {
1427
-		$this->assertPathLength($directory);
1428
-		if (!Filesystem::isValidPath($directory)) {
1429
-			return [];
1430
-		}
1431
-		$path = $this->getAbsolutePath($directory);
1432
-		$path = Filesystem::normalizePath($path);
1433
-		$mount = $this->getMount($directory);
1434
-		if (!$mount) {
1435
-			return [];
1436
-		}
1437
-		$storage = $mount->getStorage();
1438
-		$internalPath = $mount->getInternalPath($path);
1439
-		if ($storage) {
1440
-			$cache = $storage->getCache($internalPath);
1441
-			$user = \OC_User::getUser();
1442
-
1443
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1444
-
1445
-			if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1446
-				return [];
1447
-			}
1448
-
1449
-			$folderId = $data['fileid'];
1450
-			$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1451
-
1452
-			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1453
-
1454
-			$fileNames = array_map(function(ICacheEntry $content) {
1455
-				return $content->getName();
1456
-			}, $contents);
1457
-			/**
1458
-			 * @var \OC\Files\FileInfo[] $fileInfos
1459
-			 */
1460
-			$fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1461
-				if ($sharingDisabled) {
1462
-					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1463
-				}
1464
-				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1465
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1466
-			}, $contents);
1467
-			$files = array_combine($fileNames, $fileInfos);
1468
-
1469
-			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1470
-			$mounts = Filesystem::getMountManager()->findIn($path);
1471
-			$dirLength = strlen($path);
1472
-			foreach ($mounts as $mount) {
1473
-				$mountPoint = $mount->getMountPoint();
1474
-				$subStorage = $mount->getStorage();
1475
-				if ($subStorage) {
1476
-					$subCache = $subStorage->getCache('');
1477
-
1478
-					$rootEntry = $subCache->get('');
1479
-					if (!$rootEntry) {
1480
-						$subScanner = $subStorage->getScanner('');
1481
-						try {
1482
-							$subScanner->scanFile('');
1483
-						} catch (\OCP\Files\StorageNotAvailableException $e) {
1484
-							continue;
1485
-						} catch (\OCP\Files\StorageInvalidException $e) {
1486
-							continue;
1487
-						} catch (\Exception $e) {
1488
-							// sometimes when the storage is not available it can be any exception
1489
-							\OC::$server->getLogger()->logException($e, [
1490
-								'message' => 'Exception while scanning storage "' . $subStorage->getId() . '"',
1491
-								'level' => ILogger::ERROR,
1492
-								'app' => 'lib',
1493
-							]);
1494
-							continue;
1495
-						}
1496
-						$rootEntry = $subCache->get('');
1497
-					}
1498
-
1499
-					if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1500
-						$relativePath = trim(substr($mountPoint, $dirLength), '/');
1501
-						if ($pos = strpos($relativePath, '/')) {
1502
-							//mountpoint inside subfolder add size to the correct folder
1503
-							$entryName = substr($relativePath, 0, $pos);
1504
-							foreach ($files as &$entry) {
1505
-								if ($entry->getName() === $entryName) {
1506
-									$entry->addSubEntry($rootEntry, $mountPoint);
1507
-								}
1508
-							}
1509
-						} else { //mountpoint in this folder, add an entry for it
1510
-							$rootEntry['name'] = $relativePath;
1511
-							$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1512
-							$permissions = $rootEntry['permissions'];
1513
-							// do not allow renaming/deleting the mount point if they are not shared files/folders
1514
-							// for shared files/folders we use the permissions given by the owner
1515
-							if ($mount instanceof MoveableMount) {
1516
-								$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1517
-							} else {
1518
-								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1519
-							}
1520
-
1521
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1522
-
1523
-							// if sharing was disabled for the user we remove the share permissions
1524
-							if (\OCP\Util::isSharingDisabledForUser()) {
1525
-								$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1526
-							}
1527
-
1528
-							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1529
-							$files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1530
-						}
1531
-					}
1532
-				}
1533
-			}
1534
-
1535
-			if ($mimetype_filter) {
1536
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1537
-					if (strpos($mimetype_filter, '/')) {
1538
-						return $file->getMimetype() === $mimetype_filter;
1539
-					} else {
1540
-						return $file->getMimePart() === $mimetype_filter;
1541
-					}
1542
-				});
1543
-			}
1544
-
1545
-			return array_values($files);
1546
-		} else {
1547
-			return [];
1548
-		}
1549
-	}
1550
-
1551
-	/**
1552
-	 * change file metadata
1553
-	 *
1554
-	 * @param string $path
1555
-	 * @param array|\OCP\Files\FileInfo $data
1556
-	 * @return int
1557
-	 *
1558
-	 * returns the fileid of the updated file
1559
-	 */
1560
-	public function putFileInfo($path, $data) {
1561
-		$this->assertPathLength($path);
1562
-		if ($data instanceof FileInfo) {
1563
-			$data = $data->getData();
1564
-		}
1565
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1566
-		/**
1567
-		 * @var \OC\Files\Storage\Storage $storage
1568
-		 * @var string $internalPath
1569
-		 */
1570
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
1571
-		if ($storage) {
1572
-			$cache = $storage->getCache($path);
1573
-
1574
-			if (!$cache->inCache($internalPath)) {
1575
-				$scanner = $storage->getScanner($internalPath);
1576
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1577
-			}
1578
-
1579
-			return $cache->put($internalPath, $data);
1580
-		} else {
1581
-			return -1;
1582
-		}
1583
-	}
1584
-
1585
-	/**
1586
-	 * search for files with the name matching $query
1587
-	 *
1588
-	 * @param string $query
1589
-	 * @return FileInfo[]
1590
-	 */
1591
-	public function search($query) {
1592
-		return $this->searchCommon('search', array('%' . $query . '%'));
1593
-	}
1594
-
1595
-	/**
1596
-	 * search for files with the name matching $query
1597
-	 *
1598
-	 * @param string $query
1599
-	 * @return FileInfo[]
1600
-	 */
1601
-	public function searchRaw($query) {
1602
-		return $this->searchCommon('search', array($query));
1603
-	}
1604
-
1605
-	/**
1606
-	 * search for files by mimetype
1607
-	 *
1608
-	 * @param string $mimetype
1609
-	 * @return FileInfo[]
1610
-	 */
1611
-	public function searchByMime($mimetype) {
1612
-		return $this->searchCommon('searchByMime', array($mimetype));
1613
-	}
1614
-
1615
-	/**
1616
-	 * search for files by tag
1617
-	 *
1618
-	 * @param string|int $tag name or tag id
1619
-	 * @param string $userId owner of the tags
1620
-	 * @return FileInfo[]
1621
-	 */
1622
-	public function searchByTag($tag, $userId) {
1623
-		return $this->searchCommon('searchByTag', array($tag, $userId));
1624
-	}
1625
-
1626
-	/**
1627
-	 * @param string $method cache method
1628
-	 * @param array $args
1629
-	 * @return FileInfo[]
1630
-	 */
1631
-	private function searchCommon($method, $args) {
1632
-		$files = array();
1633
-		$rootLength = strlen($this->fakeRoot);
1634
-
1635
-		$mount = $this->getMount('');
1636
-		$mountPoint = $mount->getMountPoint();
1637
-		$storage = $mount->getStorage();
1638
-		if ($storage) {
1639
-			$cache = $storage->getCache('');
1640
-
1641
-			$results = call_user_func_array(array($cache, $method), $args);
1642
-			foreach ($results as $result) {
1643
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1644
-					$internalPath = $result['path'];
1645
-					$path = $mountPoint . $result['path'];
1646
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1647
-					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1648
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1649
-				}
1650
-			}
1651
-
1652
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1653
-			foreach ($mounts as $mount) {
1654
-				$mountPoint = $mount->getMountPoint();
1655
-				$storage = $mount->getStorage();
1656
-				if ($storage) {
1657
-					$cache = $storage->getCache('');
1658
-
1659
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1660
-					$results = call_user_func_array(array($cache, $method), $args);
1661
-					if ($results) {
1662
-						foreach ($results as $result) {
1663
-							$internalPath = $result['path'];
1664
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1665
-							$path = rtrim($mountPoint . $internalPath, '/');
1666
-							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1667
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1668
-						}
1669
-					}
1670
-				}
1671
-			}
1672
-		}
1673
-		return $files;
1674
-	}
1675
-
1676
-	/**
1677
-	 * Get the owner for a file or folder
1678
-	 *
1679
-	 * @param string $path
1680
-	 * @return string the user id of the owner
1681
-	 * @throws NotFoundException
1682
-	 */
1683
-	public function getOwner($path) {
1684
-		$info = $this->getFileInfo($path);
1685
-		if (!$info) {
1686
-			throw new NotFoundException($path . ' not found while trying to get owner');
1687
-		}
1688
-		return $info->getOwner()->getUID();
1689
-	}
1690
-
1691
-	/**
1692
-	 * get the ETag for a file or folder
1693
-	 *
1694
-	 * @param string $path
1695
-	 * @return string
1696
-	 */
1697
-	public function getETag($path) {
1698
-		/**
1699
-		 * @var Storage\Storage $storage
1700
-		 * @var string $internalPath
1701
-		 */
1702
-		list($storage, $internalPath) = $this->resolvePath($path);
1703
-		if ($storage) {
1704
-			return $storage->getETag($internalPath);
1705
-		} else {
1706
-			return null;
1707
-		}
1708
-	}
1709
-
1710
-	/**
1711
-	 * Get the path of a file by id, relative to the view
1712
-	 *
1713
-	 * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1714
-	 *
1715
-	 * @param int $id
1716
-	 * @throws NotFoundException
1717
-	 * @return string
1718
-	 */
1719
-	public function getPath($id) {
1720
-		$id = (int)$id;
1721
-		$manager = Filesystem::getMountManager();
1722
-		$mounts = $manager->findIn($this->fakeRoot);
1723
-		$mounts[] = $manager->find($this->fakeRoot);
1724
-		// reverse the array so we start with the storage this view is in
1725
-		// which is the most likely to contain the file we're looking for
1726
-		$mounts = array_reverse($mounts);
1727
-
1728
-		// put non shared mounts in front of the shared mount
1729
-		// this prevent unneeded recursion into shares
1730
-		usort($mounts, function(IMountPoint $a, IMountPoint $b) {
1731
-			return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1732
-		});
1733
-
1734
-		foreach ($mounts as $mount) {
1735
-			/**
1736
-			 * @var \OC\Files\Mount\MountPoint $mount
1737
-			 */
1738
-			if ($mount->getStorage()) {
1739
-				$cache = $mount->getStorage()->getCache();
1740
-				$internalPath = $cache->getPathById($id);
1741
-				if (is_string($internalPath)) {
1742
-					$fullPath = $mount->getMountPoint() . $internalPath;
1743
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1744
-						return $path;
1745
-					}
1746
-				}
1747
-			}
1748
-		}
1749
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1750
-	}
1751
-
1752
-	/**
1753
-	 * @param string $path
1754
-	 * @throws InvalidPathException
1755
-	 */
1756
-	private function assertPathLength($path) {
1757
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1758
-		// Check for the string length - performed using isset() instead of strlen()
1759
-		// because isset() is about 5x-40x faster.
1760
-		if (isset($path[$maxLen])) {
1761
-			$pathLen = strlen($path);
1762
-			throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1763
-		}
1764
-	}
1765
-
1766
-	/**
1767
-	 * check if it is allowed to move a mount point to a given target.
1768
-	 * It is not allowed to move a mount point into a different mount point or
1769
-	 * into an already shared folder
1770
-	 *
1771
-	 * @param IStorage $targetStorage
1772
-	 * @param string $targetInternalPath
1773
-	 * @return boolean
1774
-	 */
1775
-	private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath) {
1776
-
1777
-		// note: cannot use the view because the target is already locked
1778
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1779
-		if ($fileId === -1) {
1780
-			// target might not exist, need to check parent instead
1781
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1782
-		}
1783
-
1784
-		// check if any of the parents were shared by the current owner (include collections)
1785
-		$shares = \OCP\Share::getItemShared(
1786
-			'folder',
1787
-			$fileId,
1788
-			\OCP\Share::FORMAT_NONE,
1789
-			null,
1790
-			true
1791
-		);
1792
-
1793
-		if (count($shares) > 0) {
1794
-			\OCP\Util::writeLog('files',
1795
-				'It is not allowed to move one mount point into a shared folder',
1796
-				ILogger::DEBUG);
1797
-			return false;
1798
-		}
1799
-
1800
-		return true;
1801
-	}
1802
-
1803
-	/**
1804
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1805
-	 *
1806
-	 * @param string $path
1807
-	 * @return \OCP\Files\FileInfo
1808
-	 */
1809
-	private function getPartFileInfo($path) {
1810
-		$mount = $this->getMount($path);
1811
-		$storage = $mount->getStorage();
1812
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1813
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1814
-		return new FileInfo(
1815
-			$this->getAbsolutePath($path),
1816
-			$storage,
1817
-			$internalPath,
1818
-			[
1819
-				'fileid' => null,
1820
-				'mimetype' => $storage->getMimeType($internalPath),
1821
-				'name' => basename($path),
1822
-				'etag' => null,
1823
-				'size' => $storage->filesize($internalPath),
1824
-				'mtime' => $storage->filemtime($internalPath),
1825
-				'encrypted' => false,
1826
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1827
-			],
1828
-			$mount,
1829
-			$owner
1830
-		);
1831
-	}
1832
-
1833
-	/**
1834
-	 * @param string $path
1835
-	 * @param string $fileName
1836
-	 * @throws InvalidPathException
1837
-	 */
1838
-	public function verifyPath($path, $fileName) {
1839
-		try {
1840
-			/** @type \OCP\Files\Storage $storage */
1841
-			list($storage, $internalPath) = $this->resolvePath($path);
1842
-			$storage->verifyPath($internalPath, $fileName);
1843
-		} catch (ReservedWordException $ex) {
1844
-			$l = \OC::$server->getL10N('lib');
1845
-			throw new InvalidPathException($l->t('File name is a reserved word'));
1846
-		} catch (InvalidCharacterInPathException $ex) {
1847
-			$l = \OC::$server->getL10N('lib');
1848
-			throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1849
-		} catch (FileNameTooLongException $ex) {
1850
-			$l = \OC::$server->getL10N('lib');
1851
-			throw new InvalidPathException($l->t('File name is too long'));
1852
-		} catch (InvalidDirectoryException $ex) {
1853
-			$l = \OC::$server->getL10N('lib');
1854
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1855
-		} catch (EmptyFileNameException $ex) {
1856
-			$l = \OC::$server->getL10N('lib');
1857
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1858
-		}
1859
-	}
1860
-
1861
-	/**
1862
-	 * get all parent folders of $path
1863
-	 *
1864
-	 * @param string $path
1865
-	 * @return string[]
1866
-	 */
1867
-	private function getParents($path) {
1868
-		$path = trim($path, '/');
1869
-		if (!$path) {
1870
-			return [];
1871
-		}
1872
-
1873
-		$parts = explode('/', $path);
1874
-
1875
-		// remove the single file
1876
-		array_pop($parts);
1877
-		$result = array('/');
1878
-		$resultPath = '';
1879
-		foreach ($parts as $part) {
1880
-			if ($part) {
1881
-				$resultPath .= '/' . $part;
1882
-				$result[] = $resultPath;
1883
-			}
1884
-		}
1885
-		return $result;
1886
-	}
1887
-
1888
-	/**
1889
-	 * Returns the mount point for which to lock
1890
-	 *
1891
-	 * @param string $absolutePath absolute path
1892
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1893
-	 * is mounted directly on the given path, false otherwise
1894
-	 * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1895
-	 */
1896
-	private function getMountForLock($absolutePath, $useParentMount = false) {
1897
-		$results = [];
1898
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1899
-		if (!$mount) {
1900
-			return $results;
1901
-		}
1902
-
1903
-		if ($useParentMount) {
1904
-			// find out if something is mounted directly on the path
1905
-			$internalPath = $mount->getInternalPath($absolutePath);
1906
-			if ($internalPath === '') {
1907
-				// resolve the parent mount instead
1908
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1909
-			}
1910
-		}
1911
-
1912
-		return $mount;
1913
-	}
1914
-
1915
-	/**
1916
-	 * Lock the given path
1917
-	 *
1918
-	 * @param string $path the path of the file to lock, relative to the view
1919
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1920
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1921
-	 *
1922
-	 * @return bool False if the path is excluded from locking, true otherwise
1923
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1924
-	 */
1925
-	private function lockPath($path, $type, $lockMountPoint = false) {
1926
-		$absolutePath = $this->getAbsolutePath($path);
1927
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1928
-		if (!$this->shouldLockFile($absolutePath)) {
1929
-			return false;
1930
-		}
1931
-
1932
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1933
-		if ($mount) {
1934
-			try {
1935
-				$storage = $mount->getStorage();
1936
-				if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1937
-					$storage->acquireLock(
1938
-						$mount->getInternalPath($absolutePath),
1939
-						$type,
1940
-						$this->lockingProvider
1941
-					);
1942
-				}
1943
-			} catch (\OCP\Lock\LockedException $e) {
1944
-				// rethrow with the a human-readable path
1945
-				throw new \OCP\Lock\LockedException(
1946
-					$this->getPathRelativeToFiles($absolutePath),
1947
-					$e
1948
-				);
1949
-			}
1950
-		}
1951
-
1952
-		return true;
1953
-	}
1954
-
1955
-	/**
1956
-	 * Change the lock type
1957
-	 *
1958
-	 * @param string $path the path of the file to lock, relative to the view
1959
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1960
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1961
-	 *
1962
-	 * @return bool False if the path is excluded from locking, true otherwise
1963
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1964
-	 */
1965
-	public function changeLock($path, $type, $lockMountPoint = false) {
1966
-		$path = Filesystem::normalizePath($path);
1967
-		$absolutePath = $this->getAbsolutePath($path);
1968
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1969
-		if (!$this->shouldLockFile($absolutePath)) {
1970
-			return false;
1971
-		}
1972
-
1973
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1974
-		if ($mount) {
1975
-			try {
1976
-				$storage = $mount->getStorage();
1977
-				if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1978
-					$storage->changeLock(
1979
-						$mount->getInternalPath($absolutePath),
1980
-						$type,
1981
-						$this->lockingProvider
1982
-					);
1983
-				}
1984
-			} catch (\OCP\Lock\LockedException $e) {
1985
-				try {
1986
-					// rethrow with the a human-readable path
1987
-					throw new \OCP\Lock\LockedException(
1988
-						$this->getPathRelativeToFiles($absolutePath),
1989
-						$e
1990
-					);
1991
-				} catch (\InvalidArgumentException $e) {
1992
-					throw new \OCP\Lock\LockedException(
1993
-						$absolutePath,
1994
-						$e
1995
-					);
1996
-				}
1997
-			}
1998
-		}
1999
-
2000
-		return true;
2001
-	}
2002
-
2003
-	/**
2004
-	 * Unlock the given path
2005
-	 *
2006
-	 * @param string $path the path of the file to unlock, relative to the view
2007
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2008
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2009
-	 *
2010
-	 * @return bool False if the path is excluded from locking, true otherwise
2011
-	 */
2012
-	private function unlockPath($path, $type, $lockMountPoint = false) {
2013
-		$absolutePath = $this->getAbsolutePath($path);
2014
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2015
-		if (!$this->shouldLockFile($absolutePath)) {
2016
-			return false;
2017
-		}
2018
-
2019
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2020
-		if ($mount) {
2021
-			$storage = $mount->getStorage();
2022
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2023
-				$storage->releaseLock(
2024
-					$mount->getInternalPath($absolutePath),
2025
-					$type,
2026
-					$this->lockingProvider
2027
-				);
2028
-			}
2029
-		}
2030
-
2031
-		return true;
2032
-	}
2033
-
2034
-	/**
2035
-	 * Lock a path and all its parents up to the root of the view
2036
-	 *
2037
-	 * @param string $path the path of the file to lock relative to the view
2038
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2039
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2040
-	 *
2041
-	 * @return bool False if the path is excluded from locking, true otherwise
2042
-	 */
2043
-	public function lockFile($path, $type, $lockMountPoint = false) {
2044
-		$absolutePath = $this->getAbsolutePath($path);
2045
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2046
-		if (!$this->shouldLockFile($absolutePath)) {
2047
-			return false;
2048
-		}
2049
-
2050
-		$this->lockPath($path, $type, $lockMountPoint);
2051
-
2052
-		$parents = $this->getParents($path);
2053
-		foreach ($parents as $parent) {
2054
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2055
-		}
2056
-
2057
-		return true;
2058
-	}
2059
-
2060
-	/**
2061
-	 * Unlock a path and all its parents up to the root of the view
2062
-	 *
2063
-	 * @param string $path the path of the file to lock relative to the view
2064
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2065
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2066
-	 *
2067
-	 * @return bool False if the path is excluded from locking, true otherwise
2068
-	 */
2069
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2070
-		$absolutePath = $this->getAbsolutePath($path);
2071
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2072
-		if (!$this->shouldLockFile($absolutePath)) {
2073
-			return false;
2074
-		}
2075
-
2076
-		$this->unlockPath($path, $type, $lockMountPoint);
2077
-
2078
-		$parents = $this->getParents($path);
2079
-		foreach ($parents as $parent) {
2080
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2081
-		}
2082
-
2083
-		return true;
2084
-	}
2085
-
2086
-	/**
2087
-	 * Only lock files in data/user/files/
2088
-	 *
2089
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2090
-	 * @return bool
2091
-	 */
2092
-	protected function shouldLockFile($path) {
2093
-		$path = Filesystem::normalizePath($path);
2094
-
2095
-		$pathSegments = explode('/', $path);
2096
-		if (isset($pathSegments[2])) {
2097
-			// E.g.: /username/files/path-to-file
2098
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2099
-		}
2100
-
2101
-		return strpos($path, '/appdata_') !== 0;
2102
-	}
2103
-
2104
-	/**
2105
-	 * Shortens the given absolute path to be relative to
2106
-	 * "$user/files".
2107
-	 *
2108
-	 * @param string $absolutePath absolute path which is under "files"
2109
-	 *
2110
-	 * @return string path relative to "files" with trimmed slashes or null
2111
-	 * if the path was NOT relative to files
2112
-	 *
2113
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2114
-	 * @since 8.1.0
2115
-	 */
2116
-	public function getPathRelativeToFiles($absolutePath) {
2117
-		$path = Filesystem::normalizePath($absolutePath);
2118
-		$parts = explode('/', trim($path, '/'), 3);
2119
-		// "$user", "files", "path/to/dir"
2120
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2121
-			$this->logger->error(
2122
-				'$absolutePath must be relative to "files", value is "%s"',
2123
-				[
2124
-					$absolutePath
2125
-				]
2126
-			);
2127
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2128
-		}
2129
-		if (isset($parts[2])) {
2130
-			return $parts[2];
2131
-		}
2132
-		return '';
2133
-	}
2134
-
2135
-	/**
2136
-	 * @param string $filename
2137
-	 * @return array
2138
-	 * @throws \OC\User\NoUserException
2139
-	 * @throws NotFoundException
2140
-	 */
2141
-	public function getUidAndFilename($filename) {
2142
-		$info = $this->getFileInfo($filename);
2143
-		if (!$info instanceof \OCP\Files\FileInfo) {
2144
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2145
-		}
2146
-		$uid = $info->getOwner()->getUID();
2147
-		if ($uid != \OCP\User::getUser()) {
2148
-			Filesystem::initMountPoints($uid);
2149
-			$ownerView = new View('/' . $uid . '/files');
2150
-			try {
2151
-				$filename = $ownerView->getPath($info['fileid']);
2152
-			} catch (NotFoundException $e) {
2153
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2154
-			}
2155
-		}
2156
-		return [$uid, $filename];
2157
-	}
2158
-
2159
-	/**
2160
-	 * Creates parent non-existing folders
2161
-	 *
2162
-	 * @param string $filePath
2163
-	 * @return bool
2164
-	 */
2165
-	private function createParentDirectories($filePath) {
2166
-		$directoryParts = explode('/', $filePath);
2167
-		$directoryParts = array_filter($directoryParts);
2168
-		foreach ($directoryParts as $key => $part) {
2169
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2170
-			$currentPath = '/' . implode('/', $currentPathElements);
2171
-			if ($this->is_file($currentPath)) {
2172
-				return false;
2173
-			}
2174
-			if (!$this->file_exists($currentPath)) {
2175
-				$this->mkdir($currentPath);
2176
-			}
2177
-		}
2178
-
2179
-		return true;
2180
-	}
86
+    /** @var string */
87
+    private $fakeRoot = '';
88
+
89
+    /**
90
+     * @var \OCP\Lock\ILockingProvider
91
+     */
92
+    protected $lockingProvider;
93
+
94
+    private $lockingEnabled;
95
+
96
+    private $updaterEnabled = true;
97
+
98
+    /** @var \OC\User\Manager */
99
+    private $userManager;
100
+
101
+    /** @var \OCP\ILogger */
102
+    private $logger;
103
+
104
+    /**
105
+     * @param string $root
106
+     * @throws \Exception If $root contains an invalid path
107
+     */
108
+    public function __construct($root = '') {
109
+        if (is_null($root)) {
110
+            throw new \InvalidArgumentException('Root can\'t be null');
111
+        }
112
+        if (!Filesystem::isValidPath($root)) {
113
+            throw new \Exception();
114
+        }
115
+
116
+        $this->fakeRoot = $root;
117
+        $this->lockingProvider = \OC::$server->getLockingProvider();
118
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
119
+        $this->userManager = \OC::$server->getUserManager();
120
+        $this->logger = \OC::$server->getLogger();
121
+    }
122
+
123
+    public function getAbsolutePath($path = '/') {
124
+        if ($path === null) {
125
+            return null;
126
+        }
127
+        $this->assertPathLength($path);
128
+        if ($path === '') {
129
+            $path = '/';
130
+        }
131
+        if ($path[0] !== '/') {
132
+            $path = '/' . $path;
133
+        }
134
+        return $this->fakeRoot . $path;
135
+    }
136
+
137
+    /**
138
+     * change the root to a fake root
139
+     *
140
+     * @param string $fakeRoot
141
+     * @return boolean|null
142
+     */
143
+    public function chroot($fakeRoot) {
144
+        if (!$fakeRoot == '') {
145
+            if ($fakeRoot[0] !== '/') {
146
+                $fakeRoot = '/' . $fakeRoot;
147
+            }
148
+        }
149
+        $this->fakeRoot = $fakeRoot;
150
+    }
151
+
152
+    /**
153
+     * get the fake root
154
+     *
155
+     * @return string
156
+     */
157
+    public function getRoot() {
158
+        return $this->fakeRoot;
159
+    }
160
+
161
+    /**
162
+     * get path relative to the root of the view
163
+     *
164
+     * @param string $path
165
+     * @return string
166
+     */
167
+    public function getRelativePath($path) {
168
+        $this->assertPathLength($path);
169
+        if ($this->fakeRoot == '') {
170
+            return $path;
171
+        }
172
+
173
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
174
+            return '/';
175
+        }
176
+
177
+        // missing slashes can cause wrong matches!
178
+        $root = rtrim($this->fakeRoot, '/') . '/';
179
+
180
+        if (strpos($path, $root) !== 0) {
181
+            return null;
182
+        } else {
183
+            $path = substr($path, strlen($this->fakeRoot));
184
+            if (strlen($path) === 0) {
185
+                return '/';
186
+            } else {
187
+                return $path;
188
+            }
189
+        }
190
+    }
191
+
192
+    /**
193
+     * get the mountpoint of the storage object for a path
194
+     * ( note: because a storage is not always mounted inside the fakeroot, the
195
+     * returned mountpoint is relative to the absolute root of the filesystem
196
+     * and does not take the chroot into account )
197
+     *
198
+     * @param string $path
199
+     * @return string
200
+     */
201
+    public function getMountPoint($path) {
202
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
203
+    }
204
+
205
+    /**
206
+     * get the mountpoint of the storage object for a path
207
+     * ( note: because a storage is not always mounted inside the fakeroot, the
208
+     * returned mountpoint is relative to the absolute root of the filesystem
209
+     * and does not take the chroot into account )
210
+     *
211
+     * @param string $path
212
+     * @return \OCP\Files\Mount\IMountPoint
213
+     */
214
+    public function getMount($path) {
215
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
216
+    }
217
+
218
+    /**
219
+     * resolve a path to a storage and internal path
220
+     *
221
+     * @param string $path
222
+     * @return array an array consisting of the storage and the internal path
223
+     */
224
+    public function resolvePath($path) {
225
+        $a = $this->getAbsolutePath($path);
226
+        $p = Filesystem::normalizePath($a);
227
+        return Filesystem::resolvePath($p);
228
+    }
229
+
230
+    /**
231
+     * return the path to a local version of the file
232
+     * we need this because we can't know if a file is stored local or not from
233
+     * outside the filestorage and for some purposes a local file is needed
234
+     *
235
+     * @param string $path
236
+     * @return string
237
+     */
238
+    public function getLocalFile($path) {
239
+        $parent = substr($path, 0, strrpos($path, '/'));
240
+        $path = $this->getAbsolutePath($path);
241
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
242
+        if (Filesystem::isValidPath($parent) and $storage) {
243
+            return $storage->getLocalFile($internalPath);
244
+        } else {
245
+            return null;
246
+        }
247
+    }
248
+
249
+    /**
250
+     * @param string $path
251
+     * @return string
252
+     */
253
+    public function getLocalFolder($path) {
254
+        $parent = substr($path, 0, strrpos($path, '/'));
255
+        $path = $this->getAbsolutePath($path);
256
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
257
+        if (Filesystem::isValidPath($parent) and $storage) {
258
+            return $storage->getLocalFolder($internalPath);
259
+        } else {
260
+            return null;
261
+        }
262
+    }
263
+
264
+    /**
265
+     * the following functions operate with arguments and return values identical
266
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
267
+     * for \OC\Files\Storage\Storage via basicOperation().
268
+     */
269
+    public function mkdir($path) {
270
+        return $this->basicOperation('mkdir', $path, array('create', 'write'));
271
+    }
272
+
273
+    /**
274
+     * remove mount point
275
+     *
276
+     * @param \OC\Files\Mount\MoveableMount $mount
277
+     * @param string $path relative to data/
278
+     * @return boolean
279
+     */
280
+    protected function removeMount($mount, $path) {
281
+        if ($mount instanceof MoveableMount) {
282
+            // cut of /user/files to get the relative path to data/user/files
283
+            $pathParts = explode('/', $path, 4);
284
+            $relPath = '/' . $pathParts[3];
285
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
286
+            \OC_Hook::emit(
287
+                Filesystem::CLASSNAME, "umount",
288
+                array(Filesystem::signal_param_path => $relPath)
289
+            );
290
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
291
+            $result = $mount->removeMount();
292
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
293
+            if ($result) {
294
+                \OC_Hook::emit(
295
+                    Filesystem::CLASSNAME, "post_umount",
296
+                    array(Filesystem::signal_param_path => $relPath)
297
+                );
298
+            }
299
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
300
+            return $result;
301
+        } else {
302
+            // do not allow deleting the storage's root / the mount point
303
+            // because for some storages it might delete the whole contents
304
+            // but isn't supposed to work that way
305
+            return false;
306
+        }
307
+    }
308
+
309
+    public function disableCacheUpdate() {
310
+        $this->updaterEnabled = false;
311
+    }
312
+
313
+    public function enableCacheUpdate() {
314
+        $this->updaterEnabled = true;
315
+    }
316
+
317
+    protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
318
+        if ($this->updaterEnabled) {
319
+            if (is_null($time)) {
320
+                $time = time();
321
+            }
322
+            $storage->getUpdater()->update($internalPath, $time);
323
+        }
324
+    }
325
+
326
+    protected function removeUpdate(Storage $storage, $internalPath) {
327
+        if ($this->updaterEnabled) {
328
+            $storage->getUpdater()->remove($internalPath);
329
+        }
330
+    }
331
+
332
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
333
+        if ($this->updaterEnabled) {
334
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
335
+        }
336
+    }
337
+
338
+    /**
339
+     * @param string $path
340
+     * @return bool|mixed
341
+     */
342
+    public function rmdir($path) {
343
+        $absolutePath = $this->getAbsolutePath($path);
344
+        $mount = Filesystem::getMountManager()->find($absolutePath);
345
+        if ($mount->getInternalPath($absolutePath) === '') {
346
+            return $this->removeMount($mount, $absolutePath);
347
+        }
348
+        if ($this->is_dir($path)) {
349
+            $result = $this->basicOperation('rmdir', $path, array('delete'));
350
+        } else {
351
+            $result = false;
352
+        }
353
+
354
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
355
+            $storage = $mount->getStorage();
356
+            $internalPath = $mount->getInternalPath($absolutePath);
357
+            $storage->getUpdater()->remove($internalPath);
358
+        }
359
+        return $result;
360
+    }
361
+
362
+    /**
363
+     * @param string $path
364
+     * @return resource
365
+     */
366
+    public function opendir($path) {
367
+        return $this->basicOperation('opendir', $path, array('read'));
368
+    }
369
+
370
+    /**
371
+     * @param string $path
372
+     * @return bool|mixed
373
+     */
374
+    public function is_dir($path) {
375
+        if ($path == '/') {
376
+            return true;
377
+        }
378
+        return $this->basicOperation('is_dir', $path);
379
+    }
380
+
381
+    /**
382
+     * @param string $path
383
+     * @return bool|mixed
384
+     */
385
+    public function is_file($path) {
386
+        if ($path == '/') {
387
+            return false;
388
+        }
389
+        return $this->basicOperation('is_file', $path);
390
+    }
391
+
392
+    /**
393
+     * @param string $path
394
+     * @return mixed
395
+     */
396
+    public function stat($path) {
397
+        return $this->basicOperation('stat', $path);
398
+    }
399
+
400
+    /**
401
+     * @param string $path
402
+     * @return mixed
403
+     */
404
+    public function filetype($path) {
405
+        return $this->basicOperation('filetype', $path);
406
+    }
407
+
408
+    /**
409
+     * @param string $path
410
+     * @return mixed
411
+     */
412
+    public function filesize($path) {
413
+        return $this->basicOperation('filesize', $path);
414
+    }
415
+
416
+    /**
417
+     * @param string $path
418
+     * @return bool|mixed
419
+     * @throws \OCP\Files\InvalidPathException
420
+     */
421
+    public function readfile($path) {
422
+        $this->assertPathLength($path);
423
+        @ob_end_clean();
424
+        $handle = $this->fopen($path, 'rb');
425
+        if ($handle) {
426
+            $chunkSize = 8192; // 8 kB chunks
427
+            while (!feof($handle)) {
428
+                echo fread($handle, $chunkSize);
429
+                flush();
430
+            }
431
+            fclose($handle);
432
+            return $this->filesize($path);
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
+                return ftell($handle) - $from;
482
+            }
483
+
484
+            throw new \OCP\Files\UnseekableException('fseek error');
485
+        }
486
+        return false;
487
+    }
488
+
489
+    /**
490
+     * @param string $path
491
+     * @return mixed
492
+     */
493
+    public function isCreatable($path) {
494
+        return $this->basicOperation('isCreatable', $path);
495
+    }
496
+
497
+    /**
498
+     * @param string $path
499
+     * @return mixed
500
+     */
501
+    public function isReadable($path) {
502
+        return $this->basicOperation('isReadable', $path);
503
+    }
504
+
505
+    /**
506
+     * @param string $path
507
+     * @return mixed
508
+     */
509
+    public function isUpdatable($path) {
510
+        return $this->basicOperation('isUpdatable', $path);
511
+    }
512
+
513
+    /**
514
+     * @param string $path
515
+     * @return bool|mixed
516
+     */
517
+    public function isDeletable($path) {
518
+        $absolutePath = $this->getAbsolutePath($path);
519
+        $mount = Filesystem::getMountManager()->find($absolutePath);
520
+        if ($mount->getInternalPath($absolutePath) === '') {
521
+            return $mount instanceof MoveableMount;
522
+        }
523
+        return $this->basicOperation('isDeletable', $path);
524
+    }
525
+
526
+    /**
527
+     * @param string $path
528
+     * @return mixed
529
+     */
530
+    public function isSharable($path) {
531
+        return $this->basicOperation('isSharable', $path);
532
+    }
533
+
534
+    /**
535
+     * @param string $path
536
+     * @return bool|mixed
537
+     */
538
+    public function file_exists($path) {
539
+        if ($path == '/') {
540
+            return true;
541
+        }
542
+        return $this->basicOperation('file_exists', $path);
543
+    }
544
+
545
+    /**
546
+     * @param string $path
547
+     * @return mixed
548
+     */
549
+    public function filemtime($path) {
550
+        return $this->basicOperation('filemtime', $path);
551
+    }
552
+
553
+    /**
554
+     * @param string $path
555
+     * @param int|string $mtime
556
+     * @return bool
557
+     */
558
+    public function touch($path, $mtime = null) {
559
+        if (!is_null($mtime) and !is_numeric($mtime)) {
560
+            $mtime = strtotime($mtime);
561
+        }
562
+
563
+        $hooks = array('touch');
564
+
565
+        if (!$this->file_exists($path)) {
566
+            $hooks[] = 'create';
567
+            $hooks[] = 'write';
568
+        }
569
+        try {
570
+            $result = $this->basicOperation('touch', $path, $hooks, $mtime);
571
+        } catch (\Exception $e) {
572
+            $this->logger->logException($e, ['level' => ILogger::INFO, 'message' => 'Error while setting modified time']);
573
+            $result = false;
574
+        }
575
+        if (!$result) {
576
+            // If create file fails because of permissions on external storage like SMB folders,
577
+            // check file exists and return false if not.
578
+            if (!$this->file_exists($path)) {
579
+                return false;
580
+            }
581
+            if (is_null($mtime)) {
582
+                $mtime = time();
583
+            }
584
+            //if native touch fails, we emulate it by changing the mtime in the cache
585
+            $this->putFileInfo($path, array('mtime' => floor($mtime)));
586
+        }
587
+        return true;
588
+    }
589
+
590
+    /**
591
+     * @param string $path
592
+     * @return mixed
593
+     */
594
+    public function file_get_contents($path) {
595
+        return $this->basicOperation('file_get_contents', $path, array('read'));
596
+    }
597
+
598
+    /**
599
+     * @param bool $exists
600
+     * @param string $path
601
+     * @param bool $run
602
+     */
603
+    protected function emit_file_hooks_pre($exists, $path, &$run) {
604
+        if (!$exists) {
605
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
606
+                Filesystem::signal_param_path => $this->getHookPath($path),
607
+                Filesystem::signal_param_run => &$run,
608
+            ));
609
+        } else {
610
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
611
+                Filesystem::signal_param_path => $this->getHookPath($path),
612
+                Filesystem::signal_param_run => &$run,
613
+            ));
614
+        }
615
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
616
+            Filesystem::signal_param_path => $this->getHookPath($path),
617
+            Filesystem::signal_param_run => &$run,
618
+        ));
619
+    }
620
+
621
+    /**
622
+     * @param bool $exists
623
+     * @param string $path
624
+     */
625
+    protected function emit_file_hooks_post($exists, $path) {
626
+        if (!$exists) {
627
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
628
+                Filesystem::signal_param_path => $this->getHookPath($path),
629
+            ));
630
+        } else {
631
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
632
+                Filesystem::signal_param_path => $this->getHookPath($path),
633
+            ));
634
+        }
635
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
636
+            Filesystem::signal_param_path => $this->getHookPath($path),
637
+        ));
638
+    }
639
+
640
+    /**
641
+     * @param string $path
642
+     * @param string|resource $data
643
+     * @return bool|mixed
644
+     * @throws \Exception
645
+     */
646
+    public function file_put_contents($path, $data) {
647
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
648
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
649
+            if (Filesystem::isValidPath($path)
650
+                and !Filesystem::isFileBlacklisted($path)
651
+            ) {
652
+                $path = $this->getRelativePath($absolutePath);
653
+
654
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
655
+
656
+                $exists = $this->file_exists($path);
657
+                $run = true;
658
+                if ($this->shouldEmitHooks($path)) {
659
+                    $this->emit_file_hooks_pre($exists, $path, $run);
660
+                }
661
+                if (!$run) {
662
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
663
+                    return false;
664
+                }
665
+
666
+                $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
667
+
668
+                /** @var \OC\Files\Storage\Storage $storage */
669
+                list($storage, $internalPath) = $this->resolvePath($path);
670
+                $target = $storage->fopen($internalPath, 'w');
671
+                if ($target) {
672
+                    list (, $result) = \OC_Helper::streamCopy($data, $target);
673
+                    fclose($target);
674
+                    fclose($data);
675
+
676
+                    $this->writeUpdate($storage, $internalPath);
677
+
678
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
679
+
680
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
681
+                        $this->emit_file_hooks_post($exists, $path);
682
+                    }
683
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
684
+                    return $result;
685
+                } else {
686
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
687
+                    return false;
688
+                }
689
+            } else {
690
+                return false;
691
+            }
692
+        } else {
693
+            $hooks = $this->file_exists($path) ? array('update', 'write') : array('create', 'write');
694
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
695
+        }
696
+    }
697
+
698
+    /**
699
+     * @param string $path
700
+     * @return bool|mixed
701
+     */
702
+    public function unlink($path) {
703
+        if ($path === '' || $path === '/') {
704
+            // do not allow deleting the root
705
+            return false;
706
+        }
707
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
708
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
709
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
710
+        if ($mount and $mount->getInternalPath($absolutePath) === '') {
711
+            return $this->removeMount($mount, $absolutePath);
712
+        }
713
+        if ($this->is_dir($path)) {
714
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
715
+        } else {
716
+            $result = $this->basicOperation('unlink', $path, ['delete']);
717
+        }
718
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
719
+            $storage = $mount->getStorage();
720
+            $internalPath = $mount->getInternalPath($absolutePath);
721
+            $storage->getUpdater()->remove($internalPath);
722
+            return true;
723
+        } else {
724
+            return $result;
725
+        }
726
+    }
727
+
728
+    /**
729
+     * @param string $directory
730
+     * @return bool|mixed
731
+     */
732
+    public function deleteAll($directory) {
733
+        return $this->rmdir($directory);
734
+    }
735
+
736
+    /**
737
+     * Rename/move a file or folder from the source path to target path.
738
+     *
739
+     * @param string $path1 source path
740
+     * @param string $path2 target path
741
+     *
742
+     * @return bool|mixed
743
+     */
744
+    public function rename($path1, $path2) {
745
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
746
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
747
+        $result = false;
748
+        if (
749
+            Filesystem::isValidPath($path2)
750
+            and Filesystem::isValidPath($path1)
751
+            and !Filesystem::isFileBlacklisted($path2)
752
+        ) {
753
+            $path1 = $this->getRelativePath($absolutePath1);
754
+            $path2 = $this->getRelativePath($absolutePath2);
755
+            $exists = $this->file_exists($path2);
756
+
757
+            if ($path1 == null or $path2 == null) {
758
+                return false;
759
+            }
760
+
761
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
762
+            try {
763
+                $this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
764
+
765
+                $run = true;
766
+                if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
767
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
768
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
769
+                } elseif ($this->shouldEmitHooks($path1)) {
770
+                    \OC_Hook::emit(
771
+                        Filesystem::CLASSNAME, Filesystem::signal_rename,
772
+                        array(
773
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
774
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
775
+                            Filesystem::signal_param_run => &$run
776
+                        )
777
+                    );
778
+                }
779
+                if ($run) {
780
+                    $this->verifyPath(dirname($path2), basename($path2));
781
+
782
+                    $manager = Filesystem::getMountManager();
783
+                    $mount1 = $this->getMount($path1);
784
+                    $mount2 = $this->getMount($path2);
785
+                    $storage1 = $mount1->getStorage();
786
+                    $storage2 = $mount2->getStorage();
787
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
788
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
789
+
790
+                    $this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
791
+                    try {
792
+                        $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
793
+
794
+                        if ($internalPath1 === '') {
795
+                            if ($mount1 instanceof MoveableMount) {
796
+                                $sourceParentMount = $this->getMount(dirname($path1));
797
+                                if ($sourceParentMount === $mount2 && $this->targetIsNotShared($storage2, $internalPath2)) {
798
+                                    /**
799
+                                     * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
800
+                                     */
801
+                                    $sourceMountPoint = $mount1->getMountPoint();
802
+                                    $result = $mount1->moveMount($absolutePath2);
803
+                                    $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
804
+                                } else {
805
+                                    $result = false;
806
+                                }
807
+                            } else {
808
+                                $result = false;
809
+                            }
810
+                            // moving a file/folder within the same mount point
811
+                        } elseif ($storage1 === $storage2) {
812
+                            if ($storage1) {
813
+                                $result = $storage1->rename($internalPath1, $internalPath2);
814
+                            } else {
815
+                                $result = false;
816
+                            }
817
+                            // moving a file/folder between storages (from $storage1 to $storage2)
818
+                        } else {
819
+                            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
820
+                        }
821
+
822
+                        if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
823
+                            // if it was a rename from a part file to a regular file it was a write and not a rename operation
824
+                            $this->writeUpdate($storage2, $internalPath2);
825
+                        } else if ($result) {
826
+                            if ($internalPath1 !== '') { // don't do a cache update for moved mounts
827
+                                $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
828
+                            }
829
+                        }
830
+                    } catch(\Exception $e) {
831
+                        throw $e;
832
+                    } finally {
833
+                        $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
834
+                        $this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
835
+                    }
836
+
837
+                    if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
838
+                        if ($this->shouldEmitHooks()) {
839
+                            $this->emit_file_hooks_post($exists, $path2);
840
+                        }
841
+                    } elseif ($result) {
842
+                        if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
843
+                            \OC_Hook::emit(
844
+                                Filesystem::CLASSNAME,
845
+                                Filesystem::signal_post_rename,
846
+                                array(
847
+                                    Filesystem::signal_param_oldpath => $this->getHookPath($path1),
848
+                                    Filesystem::signal_param_newpath => $this->getHookPath($path2)
849
+                                )
850
+                            );
851
+                        }
852
+                    }
853
+                }
854
+            } catch(\Exception $e) {
855
+                throw $e;
856
+            } finally {
857
+                $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
858
+                $this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
859
+            }
860
+        }
861
+        return $result;
862
+    }
863
+
864
+    /**
865
+     * Copy a file/folder from the source path to target path
866
+     *
867
+     * @param string $path1 source path
868
+     * @param string $path2 target path
869
+     * @param bool $preserveMtime whether to preserve mtime on the copy
870
+     *
871
+     * @return bool|mixed
872
+     */
873
+    public function copy($path1, $path2, $preserveMtime = false) {
874
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
875
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
876
+        $result = false;
877
+        if (
878
+            Filesystem::isValidPath($path2)
879
+            and Filesystem::isValidPath($path1)
880
+            and !Filesystem::isFileBlacklisted($path2)
881
+        ) {
882
+            $path1 = $this->getRelativePath($absolutePath1);
883
+            $path2 = $this->getRelativePath($absolutePath2);
884
+
885
+            if ($path1 == null or $path2 == null) {
886
+                return false;
887
+            }
888
+            $run = true;
889
+
890
+            $this->lockFile($path2, ILockingProvider::LOCK_SHARED);
891
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED);
892
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
893
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
894
+
895
+            try {
896
+
897
+                $exists = $this->file_exists($path2);
898
+                if ($this->shouldEmitHooks()) {
899
+                    \OC_Hook::emit(
900
+                        Filesystem::CLASSNAME,
901
+                        Filesystem::signal_copy,
902
+                        array(
903
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
904
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
905
+                            Filesystem::signal_param_run => &$run
906
+                        )
907
+                    );
908
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
909
+                }
910
+                if ($run) {
911
+                    $mount1 = $this->getMount($path1);
912
+                    $mount2 = $this->getMount($path2);
913
+                    $storage1 = $mount1->getStorage();
914
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
915
+                    $storage2 = $mount2->getStorage();
916
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
917
+
918
+                    $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
919
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
920
+
921
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
922
+                        if ($storage1) {
923
+                            $result = $storage1->copy($internalPath1, $internalPath2);
924
+                        } else {
925
+                            $result = false;
926
+                        }
927
+                    } else {
928
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
929
+                    }
930
+
931
+                    $this->writeUpdate($storage2, $internalPath2);
932
+
933
+                    $this->changeLock($path2, ILockingProvider::LOCK_SHARED);
934
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
935
+
936
+                    if ($this->shouldEmitHooks() && $result !== false) {
937
+                        \OC_Hook::emit(
938
+                            Filesystem::CLASSNAME,
939
+                            Filesystem::signal_post_copy,
940
+                            array(
941
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
942
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
943
+                            )
944
+                        );
945
+                        $this->emit_file_hooks_post($exists, $path2);
946
+                    }
947
+
948
+                }
949
+            } catch (\Exception $e) {
950
+                $this->unlockFile($path2, $lockTypePath2);
951
+                $this->unlockFile($path1, $lockTypePath1);
952
+                throw $e;
953
+            }
954
+
955
+            $this->unlockFile($path2, $lockTypePath2);
956
+            $this->unlockFile($path1, $lockTypePath1);
957
+
958
+        }
959
+        return $result;
960
+    }
961
+
962
+    /**
963
+     * @param string $path
964
+     * @param string $mode 'r' or 'w'
965
+     * @return resource
966
+     */
967
+    public function fopen($path, $mode) {
968
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
969
+        $hooks = array();
970
+        switch ($mode) {
971
+            case 'r':
972
+                $hooks[] = 'read';
973
+                break;
974
+            case 'r+':
975
+            case 'w+':
976
+            case 'x+':
977
+            case 'a+':
978
+                $hooks[] = 'read';
979
+                $hooks[] = 'write';
980
+                break;
981
+            case 'w':
982
+            case 'x':
983
+            case 'a':
984
+                $hooks[] = 'write';
985
+                break;
986
+            default:
987
+                \OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, ILogger::ERROR);
988
+        }
989
+
990
+        if ($mode !== 'r' && $mode !== 'w') {
991
+            \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');
992
+        }
993
+
994
+        return $this->basicOperation('fopen', $path, $hooks, $mode);
995
+    }
996
+
997
+    /**
998
+     * @param string $path
999
+     * @return bool|string
1000
+     * @throws \OCP\Files\InvalidPathException
1001
+     */
1002
+    public function toTmpFile($path) {
1003
+        $this->assertPathLength($path);
1004
+        if (Filesystem::isValidPath($path)) {
1005
+            $source = $this->fopen($path, 'r');
1006
+            if ($source) {
1007
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
1008
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1009
+                file_put_contents($tmpFile, $source);
1010
+                return $tmpFile;
1011
+            } else {
1012
+                return false;
1013
+            }
1014
+        } else {
1015
+            return false;
1016
+        }
1017
+    }
1018
+
1019
+    /**
1020
+     * @param string $tmpFile
1021
+     * @param string $path
1022
+     * @return bool|mixed
1023
+     * @throws \OCP\Files\InvalidPathException
1024
+     */
1025
+    public function fromTmpFile($tmpFile, $path) {
1026
+        $this->assertPathLength($path);
1027
+        if (Filesystem::isValidPath($path)) {
1028
+
1029
+            // Get directory that the file is going into
1030
+            $filePath = dirname($path);
1031
+
1032
+            // Create the directories if any
1033
+            if (!$this->file_exists($filePath)) {
1034
+                $result = $this->createParentDirectories($filePath);
1035
+                if ($result === false) {
1036
+                    return false;
1037
+                }
1038
+            }
1039
+
1040
+            $source = fopen($tmpFile, 'r');
1041
+            if ($source) {
1042
+                $result = $this->file_put_contents($path, $source);
1043
+                // $this->file_put_contents() might have already closed
1044
+                // the resource, so we check it, before trying to close it
1045
+                // to avoid messages in the error log.
1046
+                if (is_resource($source)) {
1047
+                    fclose($source);
1048
+                }
1049
+                unlink($tmpFile);
1050
+                return $result;
1051
+            } else {
1052
+                return false;
1053
+            }
1054
+        } else {
1055
+            return false;
1056
+        }
1057
+    }
1058
+
1059
+
1060
+    /**
1061
+     * @param string $path
1062
+     * @return mixed
1063
+     * @throws \OCP\Files\InvalidPathException
1064
+     */
1065
+    public function getMimeType($path) {
1066
+        $this->assertPathLength($path);
1067
+        return $this->basicOperation('getMimeType', $path);
1068
+    }
1069
+
1070
+    /**
1071
+     * @param string $type
1072
+     * @param string $path
1073
+     * @param bool $raw
1074
+     * @return bool|null|string
1075
+     */
1076
+    public function hash($type, $path, $raw = false) {
1077
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1078
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1079
+        if (Filesystem::isValidPath($path)) {
1080
+            $path = $this->getRelativePath($absolutePath);
1081
+            if ($path == null) {
1082
+                return false;
1083
+            }
1084
+            if ($this->shouldEmitHooks($path)) {
1085
+                \OC_Hook::emit(
1086
+                    Filesystem::CLASSNAME,
1087
+                    Filesystem::signal_read,
1088
+                    array(Filesystem::signal_param_path => $this->getHookPath($path))
1089
+                );
1090
+            }
1091
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1092
+            if ($storage) {
1093
+                return $storage->hash($type, $internalPath, $raw);
1094
+            }
1095
+        }
1096
+        return null;
1097
+    }
1098
+
1099
+    /**
1100
+     * @param string $path
1101
+     * @return mixed
1102
+     * @throws \OCP\Files\InvalidPathException
1103
+     */
1104
+    public function free_space($path = '/') {
1105
+        $this->assertPathLength($path);
1106
+        $result = $this->basicOperation('free_space', $path);
1107
+        if ($result === null) {
1108
+            throw new InvalidPathException();
1109
+        }
1110
+        return $result;
1111
+    }
1112
+
1113
+    /**
1114
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1115
+     *
1116
+     * @param string $operation
1117
+     * @param string $path
1118
+     * @param array $hooks (optional)
1119
+     * @param mixed $extraParam (optional)
1120
+     * @return mixed
1121
+     * @throws \Exception
1122
+     *
1123
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1124
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1125
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1126
+     */
1127
+    private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1128
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1129
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1130
+        if (Filesystem::isValidPath($path)
1131
+            and !Filesystem::isFileBlacklisted($path)
1132
+        ) {
1133
+            $path = $this->getRelativePath($absolutePath);
1134
+            if ($path == null) {
1135
+                return false;
1136
+            }
1137
+
1138
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1139
+                // always a shared lock during pre-hooks so the hook can read the file
1140
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1141
+            }
1142
+
1143
+            $run = $this->runHooks($hooks, $path);
1144
+            /** @var \OC\Files\Storage\Storage $storage */
1145
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1146
+            if ($run and $storage) {
1147
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1148
+                    try {
1149
+                        $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1150
+                    } catch (LockedException $e) {
1151
+                        // release the shared lock we acquired before quiting
1152
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1153
+                        throw $e;
1154
+                    }
1155
+                }
1156
+                try {
1157
+                    if (!is_null($extraParam)) {
1158
+                        $result = $storage->$operation($internalPath, $extraParam);
1159
+                    } else {
1160
+                        $result = $storage->$operation($internalPath);
1161
+                    }
1162
+                } catch (\Exception $e) {
1163
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1164
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1165
+                    } else if (in_array('read', $hooks)) {
1166
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1167
+                    }
1168
+                    throw $e;
1169
+                }
1170
+
1171
+                if ($result && in_array('delete', $hooks) and $result) {
1172
+                    $this->removeUpdate($storage, $internalPath);
1173
+                }
1174
+                if ($result && in_array('write', $hooks,  true) && $operation !== 'fopen' && $operation !== 'touch') {
1175
+                    $this->writeUpdate($storage, $internalPath);
1176
+                }
1177
+                if ($result && in_array('touch', $hooks)) {
1178
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1179
+                }
1180
+
1181
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1182
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1183
+                }
1184
+
1185
+                $unlockLater = false;
1186
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1187
+                    $unlockLater = true;
1188
+                    // make sure our unlocking callback will still be called if connection is aborted
1189
+                    ignore_user_abort(true);
1190
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1191
+                        if (in_array('write', $hooks)) {
1192
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1193
+                        } else if (in_array('read', $hooks)) {
1194
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1195
+                        }
1196
+                    });
1197
+                }
1198
+
1199
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1200
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1201
+                        $this->runHooks($hooks, $path, true);
1202
+                    }
1203
+                }
1204
+
1205
+                if (!$unlockLater
1206
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1207
+                ) {
1208
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1209
+                }
1210
+                return $result;
1211
+            } else {
1212
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1213
+            }
1214
+        }
1215
+        return null;
1216
+    }
1217
+
1218
+    /**
1219
+     * get the path relative to the default root for hook usage
1220
+     *
1221
+     * @param string $path
1222
+     * @return string
1223
+     */
1224
+    private function getHookPath($path) {
1225
+        if (!Filesystem::getView()) {
1226
+            return $path;
1227
+        }
1228
+        return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1229
+    }
1230
+
1231
+    private function shouldEmitHooks($path = '') {
1232
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1233
+            return false;
1234
+        }
1235
+        if (!Filesystem::$loaded) {
1236
+            return false;
1237
+        }
1238
+        $defaultRoot = Filesystem::getRoot();
1239
+        if ($defaultRoot === null) {
1240
+            return false;
1241
+        }
1242
+        if ($this->fakeRoot === $defaultRoot) {
1243
+            return true;
1244
+        }
1245
+        $fullPath = $this->getAbsolutePath($path);
1246
+
1247
+        if ($fullPath === $defaultRoot) {
1248
+            return true;
1249
+        }
1250
+
1251
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1252
+    }
1253
+
1254
+    /**
1255
+     * @param string[] $hooks
1256
+     * @param string $path
1257
+     * @param bool $post
1258
+     * @return bool
1259
+     */
1260
+    private function runHooks($hooks, $path, $post = false) {
1261
+        $relativePath = $path;
1262
+        $path = $this->getHookPath($path);
1263
+        $prefix = $post ? 'post_' : '';
1264
+        $run = true;
1265
+        if ($this->shouldEmitHooks($relativePath)) {
1266
+            foreach ($hooks as $hook) {
1267
+                if ($hook != 'read') {
1268
+                    \OC_Hook::emit(
1269
+                        Filesystem::CLASSNAME,
1270
+                        $prefix . $hook,
1271
+                        array(
1272
+                            Filesystem::signal_param_run => &$run,
1273
+                            Filesystem::signal_param_path => $path
1274
+                        )
1275
+                    );
1276
+                } elseif (!$post) {
1277
+                    \OC_Hook::emit(
1278
+                        Filesystem::CLASSNAME,
1279
+                        $prefix . $hook,
1280
+                        array(
1281
+                            Filesystem::signal_param_path => $path
1282
+                        )
1283
+                    );
1284
+                }
1285
+            }
1286
+        }
1287
+        return $run;
1288
+    }
1289
+
1290
+    /**
1291
+     * check if a file or folder has been updated since $time
1292
+     *
1293
+     * @param string $path
1294
+     * @param int $time
1295
+     * @return bool
1296
+     */
1297
+    public function hasUpdated($path, $time) {
1298
+        return $this->basicOperation('hasUpdated', $path, array(), $time);
1299
+    }
1300
+
1301
+    /**
1302
+     * @param string $ownerId
1303
+     * @return \OC\User\User
1304
+     */
1305
+    private function getUserObjectForOwner($ownerId) {
1306
+        $owner = $this->userManager->get($ownerId);
1307
+        if ($owner instanceof IUser) {
1308
+            return $owner;
1309
+        } else {
1310
+            return new User($ownerId, null, \OC::$server->getEventDispatcher());
1311
+        }
1312
+    }
1313
+
1314
+    /**
1315
+     * Get file info from cache
1316
+     *
1317
+     * If the file is not in cached it will be scanned
1318
+     * If the file has changed on storage the cache will be updated
1319
+     *
1320
+     * @param \OC\Files\Storage\Storage $storage
1321
+     * @param string $internalPath
1322
+     * @param string $relativePath
1323
+     * @return ICacheEntry|bool
1324
+     */
1325
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1326
+        $cache = $storage->getCache($internalPath);
1327
+        $data = $cache->get($internalPath);
1328
+        $watcher = $storage->getWatcher($internalPath);
1329
+
1330
+        try {
1331
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1332
+            if (!$data || $data['size'] === -1) {
1333
+                if (!$storage->file_exists($internalPath)) {
1334
+                    return false;
1335
+                }
1336
+                // don't need to get a lock here since the scanner does it's own locking
1337
+                $scanner = $storage->getScanner($internalPath);
1338
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1339
+                $data = $cache->get($internalPath);
1340
+            } else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1341
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1342
+                $watcher->update($internalPath, $data);
1343
+                $storage->getPropagator()->propagateChange($internalPath, time());
1344
+                $data = $cache->get($internalPath);
1345
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1346
+            }
1347
+        } catch (LockedException $e) {
1348
+            // if the file is locked we just use the old cache info
1349
+        }
1350
+
1351
+        return $data;
1352
+    }
1353
+
1354
+    /**
1355
+     * get the filesystem info
1356
+     *
1357
+     * @param string $path
1358
+     * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1359
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1360
+     * defaults to true
1361
+     * @return \OC\Files\FileInfo|false False if file does not exist
1362
+     */
1363
+    public function getFileInfo($path, $includeMountPoints = true) {
1364
+        $this->assertPathLength($path);
1365
+        if (!Filesystem::isValidPath($path)) {
1366
+            return false;
1367
+        }
1368
+        if (Cache\Scanner::isPartialFile($path)) {
1369
+            return $this->getPartFileInfo($path);
1370
+        }
1371
+        $relativePath = $path;
1372
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1373
+
1374
+        $mount = Filesystem::getMountManager()->find($path);
1375
+        if (!$mount) {
1376
+            \OC::$server->getLogger()->warning('Mountpoint not found for path: ' . $path);
1377
+            return false;
1378
+        }
1379
+        $storage = $mount->getStorage();
1380
+        $internalPath = $mount->getInternalPath($path);
1381
+        if ($storage) {
1382
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1383
+
1384
+            if (!$data instanceof ICacheEntry) {
1385
+                return false;
1386
+            }
1387
+
1388
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1389
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1390
+            }
1391
+            $ownerId = $storage->getOwner($internalPath);
1392
+            $owner = null;
1393
+            if ($ownerId !== null) {
1394
+                // ownerId might be null if files are accessed with an access token without file system access
1395
+                $owner = $this->getUserObjectForOwner($ownerId);
1396
+            }
1397
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1398
+
1399
+            if ($data and isset($data['fileid'])) {
1400
+                if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1401
+                    //add the sizes of other mount points to the folder
1402
+                    $extOnly = ($includeMountPoints === 'ext');
1403
+                    $mounts = Filesystem::getMountManager()->findIn($path);
1404
+                    $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1405
+                        $subStorage = $mount->getStorage();
1406
+                        return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1407
+                    }));
1408
+                }
1409
+            }
1410
+
1411
+            return $info;
1412
+        } else {
1413
+            \OC::$server->getLogger()->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint());
1414
+        }
1415
+
1416
+        return false;
1417
+    }
1418
+
1419
+    /**
1420
+     * get the content of a directory
1421
+     *
1422
+     * @param string $directory path under datadirectory
1423
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1424
+     * @return FileInfo[]
1425
+     */
1426
+    public function getDirectoryContent($directory, $mimetype_filter = '') {
1427
+        $this->assertPathLength($directory);
1428
+        if (!Filesystem::isValidPath($directory)) {
1429
+            return [];
1430
+        }
1431
+        $path = $this->getAbsolutePath($directory);
1432
+        $path = Filesystem::normalizePath($path);
1433
+        $mount = $this->getMount($directory);
1434
+        if (!$mount) {
1435
+            return [];
1436
+        }
1437
+        $storage = $mount->getStorage();
1438
+        $internalPath = $mount->getInternalPath($path);
1439
+        if ($storage) {
1440
+            $cache = $storage->getCache($internalPath);
1441
+            $user = \OC_User::getUser();
1442
+
1443
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1444
+
1445
+            if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1446
+                return [];
1447
+            }
1448
+
1449
+            $folderId = $data['fileid'];
1450
+            $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1451
+
1452
+            $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1453
+
1454
+            $fileNames = array_map(function(ICacheEntry $content) {
1455
+                return $content->getName();
1456
+            }, $contents);
1457
+            /**
1458
+             * @var \OC\Files\FileInfo[] $fileInfos
1459
+             */
1460
+            $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1461
+                if ($sharingDisabled) {
1462
+                    $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1463
+                }
1464
+                $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1465
+                return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1466
+            }, $contents);
1467
+            $files = array_combine($fileNames, $fileInfos);
1468
+
1469
+            //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1470
+            $mounts = Filesystem::getMountManager()->findIn($path);
1471
+            $dirLength = strlen($path);
1472
+            foreach ($mounts as $mount) {
1473
+                $mountPoint = $mount->getMountPoint();
1474
+                $subStorage = $mount->getStorage();
1475
+                if ($subStorage) {
1476
+                    $subCache = $subStorage->getCache('');
1477
+
1478
+                    $rootEntry = $subCache->get('');
1479
+                    if (!$rootEntry) {
1480
+                        $subScanner = $subStorage->getScanner('');
1481
+                        try {
1482
+                            $subScanner->scanFile('');
1483
+                        } catch (\OCP\Files\StorageNotAvailableException $e) {
1484
+                            continue;
1485
+                        } catch (\OCP\Files\StorageInvalidException $e) {
1486
+                            continue;
1487
+                        } catch (\Exception $e) {
1488
+                            // sometimes when the storage is not available it can be any exception
1489
+                            \OC::$server->getLogger()->logException($e, [
1490
+                                'message' => 'Exception while scanning storage "' . $subStorage->getId() . '"',
1491
+                                'level' => ILogger::ERROR,
1492
+                                'app' => 'lib',
1493
+                            ]);
1494
+                            continue;
1495
+                        }
1496
+                        $rootEntry = $subCache->get('');
1497
+                    }
1498
+
1499
+                    if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1500
+                        $relativePath = trim(substr($mountPoint, $dirLength), '/');
1501
+                        if ($pos = strpos($relativePath, '/')) {
1502
+                            //mountpoint inside subfolder add size to the correct folder
1503
+                            $entryName = substr($relativePath, 0, $pos);
1504
+                            foreach ($files as &$entry) {
1505
+                                if ($entry->getName() === $entryName) {
1506
+                                    $entry->addSubEntry($rootEntry, $mountPoint);
1507
+                                }
1508
+                            }
1509
+                        } else { //mountpoint in this folder, add an entry for it
1510
+                            $rootEntry['name'] = $relativePath;
1511
+                            $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1512
+                            $permissions = $rootEntry['permissions'];
1513
+                            // do not allow renaming/deleting the mount point if they are not shared files/folders
1514
+                            // for shared files/folders we use the permissions given by the owner
1515
+                            if ($mount instanceof MoveableMount) {
1516
+                                $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1517
+                            } else {
1518
+                                $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1519
+                            }
1520
+
1521
+                            $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1522
+
1523
+                            // if sharing was disabled for the user we remove the share permissions
1524
+                            if (\OCP\Util::isSharingDisabledForUser()) {
1525
+                                $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1526
+                            }
1527
+
1528
+                            $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1529
+                            $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1530
+                        }
1531
+                    }
1532
+                }
1533
+            }
1534
+
1535
+            if ($mimetype_filter) {
1536
+                $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1537
+                    if (strpos($mimetype_filter, '/')) {
1538
+                        return $file->getMimetype() === $mimetype_filter;
1539
+                    } else {
1540
+                        return $file->getMimePart() === $mimetype_filter;
1541
+                    }
1542
+                });
1543
+            }
1544
+
1545
+            return array_values($files);
1546
+        } else {
1547
+            return [];
1548
+        }
1549
+    }
1550
+
1551
+    /**
1552
+     * change file metadata
1553
+     *
1554
+     * @param string $path
1555
+     * @param array|\OCP\Files\FileInfo $data
1556
+     * @return int
1557
+     *
1558
+     * returns the fileid of the updated file
1559
+     */
1560
+    public function putFileInfo($path, $data) {
1561
+        $this->assertPathLength($path);
1562
+        if ($data instanceof FileInfo) {
1563
+            $data = $data->getData();
1564
+        }
1565
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1566
+        /**
1567
+         * @var \OC\Files\Storage\Storage $storage
1568
+         * @var string $internalPath
1569
+         */
1570
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
1571
+        if ($storage) {
1572
+            $cache = $storage->getCache($path);
1573
+
1574
+            if (!$cache->inCache($internalPath)) {
1575
+                $scanner = $storage->getScanner($internalPath);
1576
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1577
+            }
1578
+
1579
+            return $cache->put($internalPath, $data);
1580
+        } else {
1581
+            return -1;
1582
+        }
1583
+    }
1584
+
1585
+    /**
1586
+     * search for files with the name matching $query
1587
+     *
1588
+     * @param string $query
1589
+     * @return FileInfo[]
1590
+     */
1591
+    public function search($query) {
1592
+        return $this->searchCommon('search', array('%' . $query . '%'));
1593
+    }
1594
+
1595
+    /**
1596
+     * search for files with the name matching $query
1597
+     *
1598
+     * @param string $query
1599
+     * @return FileInfo[]
1600
+     */
1601
+    public function searchRaw($query) {
1602
+        return $this->searchCommon('search', array($query));
1603
+    }
1604
+
1605
+    /**
1606
+     * search for files by mimetype
1607
+     *
1608
+     * @param string $mimetype
1609
+     * @return FileInfo[]
1610
+     */
1611
+    public function searchByMime($mimetype) {
1612
+        return $this->searchCommon('searchByMime', array($mimetype));
1613
+    }
1614
+
1615
+    /**
1616
+     * search for files by tag
1617
+     *
1618
+     * @param string|int $tag name or tag id
1619
+     * @param string $userId owner of the tags
1620
+     * @return FileInfo[]
1621
+     */
1622
+    public function searchByTag($tag, $userId) {
1623
+        return $this->searchCommon('searchByTag', array($tag, $userId));
1624
+    }
1625
+
1626
+    /**
1627
+     * @param string $method cache method
1628
+     * @param array $args
1629
+     * @return FileInfo[]
1630
+     */
1631
+    private function searchCommon($method, $args) {
1632
+        $files = array();
1633
+        $rootLength = strlen($this->fakeRoot);
1634
+
1635
+        $mount = $this->getMount('');
1636
+        $mountPoint = $mount->getMountPoint();
1637
+        $storage = $mount->getStorage();
1638
+        if ($storage) {
1639
+            $cache = $storage->getCache('');
1640
+
1641
+            $results = call_user_func_array(array($cache, $method), $args);
1642
+            foreach ($results as $result) {
1643
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1644
+                    $internalPath = $result['path'];
1645
+                    $path = $mountPoint . $result['path'];
1646
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1647
+                    $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1648
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1649
+                }
1650
+            }
1651
+
1652
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1653
+            foreach ($mounts as $mount) {
1654
+                $mountPoint = $mount->getMountPoint();
1655
+                $storage = $mount->getStorage();
1656
+                if ($storage) {
1657
+                    $cache = $storage->getCache('');
1658
+
1659
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1660
+                    $results = call_user_func_array(array($cache, $method), $args);
1661
+                    if ($results) {
1662
+                        foreach ($results as $result) {
1663
+                            $internalPath = $result['path'];
1664
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1665
+                            $path = rtrim($mountPoint . $internalPath, '/');
1666
+                            $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1667
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1668
+                        }
1669
+                    }
1670
+                }
1671
+            }
1672
+        }
1673
+        return $files;
1674
+    }
1675
+
1676
+    /**
1677
+     * Get the owner for a file or folder
1678
+     *
1679
+     * @param string $path
1680
+     * @return string the user id of the owner
1681
+     * @throws NotFoundException
1682
+     */
1683
+    public function getOwner($path) {
1684
+        $info = $this->getFileInfo($path);
1685
+        if (!$info) {
1686
+            throw new NotFoundException($path . ' not found while trying to get owner');
1687
+        }
1688
+        return $info->getOwner()->getUID();
1689
+    }
1690
+
1691
+    /**
1692
+     * get the ETag for a file or folder
1693
+     *
1694
+     * @param string $path
1695
+     * @return string
1696
+     */
1697
+    public function getETag($path) {
1698
+        /**
1699
+         * @var Storage\Storage $storage
1700
+         * @var string $internalPath
1701
+         */
1702
+        list($storage, $internalPath) = $this->resolvePath($path);
1703
+        if ($storage) {
1704
+            return $storage->getETag($internalPath);
1705
+        } else {
1706
+            return null;
1707
+        }
1708
+    }
1709
+
1710
+    /**
1711
+     * Get the path of a file by id, relative to the view
1712
+     *
1713
+     * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1714
+     *
1715
+     * @param int $id
1716
+     * @throws NotFoundException
1717
+     * @return string
1718
+     */
1719
+    public function getPath($id) {
1720
+        $id = (int)$id;
1721
+        $manager = Filesystem::getMountManager();
1722
+        $mounts = $manager->findIn($this->fakeRoot);
1723
+        $mounts[] = $manager->find($this->fakeRoot);
1724
+        // reverse the array so we start with the storage this view is in
1725
+        // which is the most likely to contain the file we're looking for
1726
+        $mounts = array_reverse($mounts);
1727
+
1728
+        // put non shared mounts in front of the shared mount
1729
+        // this prevent unneeded recursion into shares
1730
+        usort($mounts, function(IMountPoint $a, IMountPoint $b) {
1731
+            return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1732
+        });
1733
+
1734
+        foreach ($mounts as $mount) {
1735
+            /**
1736
+             * @var \OC\Files\Mount\MountPoint $mount
1737
+             */
1738
+            if ($mount->getStorage()) {
1739
+                $cache = $mount->getStorage()->getCache();
1740
+                $internalPath = $cache->getPathById($id);
1741
+                if (is_string($internalPath)) {
1742
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1743
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1744
+                        return $path;
1745
+                    }
1746
+                }
1747
+            }
1748
+        }
1749
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1750
+    }
1751
+
1752
+    /**
1753
+     * @param string $path
1754
+     * @throws InvalidPathException
1755
+     */
1756
+    private function assertPathLength($path) {
1757
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1758
+        // Check for the string length - performed using isset() instead of strlen()
1759
+        // because isset() is about 5x-40x faster.
1760
+        if (isset($path[$maxLen])) {
1761
+            $pathLen = strlen($path);
1762
+            throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1763
+        }
1764
+    }
1765
+
1766
+    /**
1767
+     * check if it is allowed to move a mount point to a given target.
1768
+     * It is not allowed to move a mount point into a different mount point or
1769
+     * into an already shared folder
1770
+     *
1771
+     * @param IStorage $targetStorage
1772
+     * @param string $targetInternalPath
1773
+     * @return boolean
1774
+     */
1775
+    private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath) {
1776
+
1777
+        // note: cannot use the view because the target is already locked
1778
+        $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1779
+        if ($fileId === -1) {
1780
+            // target might not exist, need to check parent instead
1781
+            $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1782
+        }
1783
+
1784
+        // check if any of the parents were shared by the current owner (include collections)
1785
+        $shares = \OCP\Share::getItemShared(
1786
+            'folder',
1787
+            $fileId,
1788
+            \OCP\Share::FORMAT_NONE,
1789
+            null,
1790
+            true
1791
+        );
1792
+
1793
+        if (count($shares) > 0) {
1794
+            \OCP\Util::writeLog('files',
1795
+                'It is not allowed to move one mount point into a shared folder',
1796
+                ILogger::DEBUG);
1797
+            return false;
1798
+        }
1799
+
1800
+        return true;
1801
+    }
1802
+
1803
+    /**
1804
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1805
+     *
1806
+     * @param string $path
1807
+     * @return \OCP\Files\FileInfo
1808
+     */
1809
+    private function getPartFileInfo($path) {
1810
+        $mount = $this->getMount($path);
1811
+        $storage = $mount->getStorage();
1812
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1813
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1814
+        return new FileInfo(
1815
+            $this->getAbsolutePath($path),
1816
+            $storage,
1817
+            $internalPath,
1818
+            [
1819
+                'fileid' => null,
1820
+                'mimetype' => $storage->getMimeType($internalPath),
1821
+                'name' => basename($path),
1822
+                'etag' => null,
1823
+                'size' => $storage->filesize($internalPath),
1824
+                'mtime' => $storage->filemtime($internalPath),
1825
+                'encrypted' => false,
1826
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1827
+            ],
1828
+            $mount,
1829
+            $owner
1830
+        );
1831
+    }
1832
+
1833
+    /**
1834
+     * @param string $path
1835
+     * @param string $fileName
1836
+     * @throws InvalidPathException
1837
+     */
1838
+    public function verifyPath($path, $fileName) {
1839
+        try {
1840
+            /** @type \OCP\Files\Storage $storage */
1841
+            list($storage, $internalPath) = $this->resolvePath($path);
1842
+            $storage->verifyPath($internalPath, $fileName);
1843
+        } catch (ReservedWordException $ex) {
1844
+            $l = \OC::$server->getL10N('lib');
1845
+            throw new InvalidPathException($l->t('File name is a reserved word'));
1846
+        } catch (InvalidCharacterInPathException $ex) {
1847
+            $l = \OC::$server->getL10N('lib');
1848
+            throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1849
+        } catch (FileNameTooLongException $ex) {
1850
+            $l = \OC::$server->getL10N('lib');
1851
+            throw new InvalidPathException($l->t('File name is too long'));
1852
+        } catch (InvalidDirectoryException $ex) {
1853
+            $l = \OC::$server->getL10N('lib');
1854
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1855
+        } catch (EmptyFileNameException $ex) {
1856
+            $l = \OC::$server->getL10N('lib');
1857
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1858
+        }
1859
+    }
1860
+
1861
+    /**
1862
+     * get all parent folders of $path
1863
+     *
1864
+     * @param string $path
1865
+     * @return string[]
1866
+     */
1867
+    private function getParents($path) {
1868
+        $path = trim($path, '/');
1869
+        if (!$path) {
1870
+            return [];
1871
+        }
1872
+
1873
+        $parts = explode('/', $path);
1874
+
1875
+        // remove the single file
1876
+        array_pop($parts);
1877
+        $result = array('/');
1878
+        $resultPath = '';
1879
+        foreach ($parts as $part) {
1880
+            if ($part) {
1881
+                $resultPath .= '/' . $part;
1882
+                $result[] = $resultPath;
1883
+            }
1884
+        }
1885
+        return $result;
1886
+    }
1887
+
1888
+    /**
1889
+     * Returns the mount point for which to lock
1890
+     *
1891
+     * @param string $absolutePath absolute path
1892
+     * @param bool $useParentMount true to return parent mount instead of whatever
1893
+     * is mounted directly on the given path, false otherwise
1894
+     * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1895
+     */
1896
+    private function getMountForLock($absolutePath, $useParentMount = false) {
1897
+        $results = [];
1898
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1899
+        if (!$mount) {
1900
+            return $results;
1901
+        }
1902
+
1903
+        if ($useParentMount) {
1904
+            // find out if something is mounted directly on the path
1905
+            $internalPath = $mount->getInternalPath($absolutePath);
1906
+            if ($internalPath === '') {
1907
+                // resolve the parent mount instead
1908
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1909
+            }
1910
+        }
1911
+
1912
+        return $mount;
1913
+    }
1914
+
1915
+    /**
1916
+     * Lock the given path
1917
+     *
1918
+     * @param string $path the path of the file to lock, relative to the view
1919
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1920
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1921
+     *
1922
+     * @return bool False if the path is excluded from locking, true otherwise
1923
+     * @throws \OCP\Lock\LockedException if the path is already locked
1924
+     */
1925
+    private function lockPath($path, $type, $lockMountPoint = false) {
1926
+        $absolutePath = $this->getAbsolutePath($path);
1927
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1928
+        if (!$this->shouldLockFile($absolutePath)) {
1929
+            return false;
1930
+        }
1931
+
1932
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1933
+        if ($mount) {
1934
+            try {
1935
+                $storage = $mount->getStorage();
1936
+                if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1937
+                    $storage->acquireLock(
1938
+                        $mount->getInternalPath($absolutePath),
1939
+                        $type,
1940
+                        $this->lockingProvider
1941
+                    );
1942
+                }
1943
+            } catch (\OCP\Lock\LockedException $e) {
1944
+                // rethrow with the a human-readable path
1945
+                throw new \OCP\Lock\LockedException(
1946
+                    $this->getPathRelativeToFiles($absolutePath),
1947
+                    $e
1948
+                );
1949
+            }
1950
+        }
1951
+
1952
+        return true;
1953
+    }
1954
+
1955
+    /**
1956
+     * Change the lock type
1957
+     *
1958
+     * @param string $path the path of the file to lock, relative to the view
1959
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1960
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1961
+     *
1962
+     * @return bool False if the path is excluded from locking, true otherwise
1963
+     * @throws \OCP\Lock\LockedException if the path is already locked
1964
+     */
1965
+    public function changeLock($path, $type, $lockMountPoint = false) {
1966
+        $path = Filesystem::normalizePath($path);
1967
+        $absolutePath = $this->getAbsolutePath($path);
1968
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1969
+        if (!$this->shouldLockFile($absolutePath)) {
1970
+            return false;
1971
+        }
1972
+
1973
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1974
+        if ($mount) {
1975
+            try {
1976
+                $storage = $mount->getStorage();
1977
+                if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1978
+                    $storage->changeLock(
1979
+                        $mount->getInternalPath($absolutePath),
1980
+                        $type,
1981
+                        $this->lockingProvider
1982
+                    );
1983
+                }
1984
+            } catch (\OCP\Lock\LockedException $e) {
1985
+                try {
1986
+                    // rethrow with the a human-readable path
1987
+                    throw new \OCP\Lock\LockedException(
1988
+                        $this->getPathRelativeToFiles($absolutePath),
1989
+                        $e
1990
+                    );
1991
+                } catch (\InvalidArgumentException $e) {
1992
+                    throw new \OCP\Lock\LockedException(
1993
+                        $absolutePath,
1994
+                        $e
1995
+                    );
1996
+                }
1997
+            }
1998
+        }
1999
+
2000
+        return true;
2001
+    }
2002
+
2003
+    /**
2004
+     * Unlock the given path
2005
+     *
2006
+     * @param string $path the path of the file to unlock, relative to the view
2007
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2008
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2009
+     *
2010
+     * @return bool False if the path is excluded from locking, true otherwise
2011
+     */
2012
+    private function unlockPath($path, $type, $lockMountPoint = false) {
2013
+        $absolutePath = $this->getAbsolutePath($path);
2014
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2015
+        if (!$this->shouldLockFile($absolutePath)) {
2016
+            return false;
2017
+        }
2018
+
2019
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2020
+        if ($mount) {
2021
+            $storage = $mount->getStorage();
2022
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2023
+                $storage->releaseLock(
2024
+                    $mount->getInternalPath($absolutePath),
2025
+                    $type,
2026
+                    $this->lockingProvider
2027
+                );
2028
+            }
2029
+        }
2030
+
2031
+        return true;
2032
+    }
2033
+
2034
+    /**
2035
+     * Lock a path and all its parents up to the root of the view
2036
+     *
2037
+     * @param string $path the path of the file to lock relative to the view
2038
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2039
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2040
+     *
2041
+     * @return bool False if the path is excluded from locking, true otherwise
2042
+     */
2043
+    public function lockFile($path, $type, $lockMountPoint = false) {
2044
+        $absolutePath = $this->getAbsolutePath($path);
2045
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2046
+        if (!$this->shouldLockFile($absolutePath)) {
2047
+            return false;
2048
+        }
2049
+
2050
+        $this->lockPath($path, $type, $lockMountPoint);
2051
+
2052
+        $parents = $this->getParents($path);
2053
+        foreach ($parents as $parent) {
2054
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2055
+        }
2056
+
2057
+        return true;
2058
+    }
2059
+
2060
+    /**
2061
+     * Unlock a path and all its parents up to the root of the view
2062
+     *
2063
+     * @param string $path the path of the file to lock relative to the view
2064
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2065
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2066
+     *
2067
+     * @return bool False if the path is excluded from locking, true otherwise
2068
+     */
2069
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2070
+        $absolutePath = $this->getAbsolutePath($path);
2071
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2072
+        if (!$this->shouldLockFile($absolutePath)) {
2073
+            return false;
2074
+        }
2075
+
2076
+        $this->unlockPath($path, $type, $lockMountPoint);
2077
+
2078
+        $parents = $this->getParents($path);
2079
+        foreach ($parents as $parent) {
2080
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2081
+        }
2082
+
2083
+        return true;
2084
+    }
2085
+
2086
+    /**
2087
+     * Only lock files in data/user/files/
2088
+     *
2089
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2090
+     * @return bool
2091
+     */
2092
+    protected function shouldLockFile($path) {
2093
+        $path = Filesystem::normalizePath($path);
2094
+
2095
+        $pathSegments = explode('/', $path);
2096
+        if (isset($pathSegments[2])) {
2097
+            // E.g.: /username/files/path-to-file
2098
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2099
+        }
2100
+
2101
+        return strpos($path, '/appdata_') !== 0;
2102
+    }
2103
+
2104
+    /**
2105
+     * Shortens the given absolute path to be relative to
2106
+     * "$user/files".
2107
+     *
2108
+     * @param string $absolutePath absolute path which is under "files"
2109
+     *
2110
+     * @return string path relative to "files" with trimmed slashes or null
2111
+     * if the path was NOT relative to files
2112
+     *
2113
+     * @throws \InvalidArgumentException if the given path was not under "files"
2114
+     * @since 8.1.0
2115
+     */
2116
+    public function getPathRelativeToFiles($absolutePath) {
2117
+        $path = Filesystem::normalizePath($absolutePath);
2118
+        $parts = explode('/', trim($path, '/'), 3);
2119
+        // "$user", "files", "path/to/dir"
2120
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2121
+            $this->logger->error(
2122
+                '$absolutePath must be relative to "files", value is "%s"',
2123
+                [
2124
+                    $absolutePath
2125
+                ]
2126
+            );
2127
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2128
+        }
2129
+        if (isset($parts[2])) {
2130
+            return $parts[2];
2131
+        }
2132
+        return '';
2133
+    }
2134
+
2135
+    /**
2136
+     * @param string $filename
2137
+     * @return array
2138
+     * @throws \OC\User\NoUserException
2139
+     * @throws NotFoundException
2140
+     */
2141
+    public function getUidAndFilename($filename) {
2142
+        $info = $this->getFileInfo($filename);
2143
+        if (!$info instanceof \OCP\Files\FileInfo) {
2144
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2145
+        }
2146
+        $uid = $info->getOwner()->getUID();
2147
+        if ($uid != \OCP\User::getUser()) {
2148
+            Filesystem::initMountPoints($uid);
2149
+            $ownerView = new View('/' . $uid . '/files');
2150
+            try {
2151
+                $filename = $ownerView->getPath($info['fileid']);
2152
+            } catch (NotFoundException $e) {
2153
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2154
+            }
2155
+        }
2156
+        return [$uid, $filename];
2157
+    }
2158
+
2159
+    /**
2160
+     * Creates parent non-existing folders
2161
+     *
2162
+     * @param string $filePath
2163
+     * @return bool
2164
+     */
2165
+    private function createParentDirectories($filePath) {
2166
+        $directoryParts = explode('/', $filePath);
2167
+        $directoryParts = array_filter($directoryParts);
2168
+        foreach ($directoryParts as $key => $part) {
2169
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2170
+            $currentPath = '/' . implode('/', $currentPathElements);
2171
+            if ($this->is_file($currentPath)) {
2172
+                return false;
2173
+            }
2174
+            if (!$this->file_exists($currentPath)) {
2175
+                $this->mkdir($currentPath);
2176
+            }
2177
+        }
2178
+
2179
+        return true;
2180
+    }
2181 2181
 }
Please login to merge, or discard this patch.