Completed
Branch master (69e0e2)
by Johannes
13:43 queued 40s
created
lib/private/Share20/Manager.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -1101,6 +1101,9 @@
 block discarded – undo
1101 1101
 		return $share;
1102 1102
 	}
1103 1103
 
1104
+	/**
1105
+	 * @param IShare $share
1106
+	 */
1104 1107
 	protected function checkExpireDate($share) {
1105 1108
 		if ($share->getExpirationDate() !== null &&
1106 1109
 			$share->getExpirationDate() <= new \DateTime()) {
Please login to merge, or discard this patch.
Indentation   +1350 added lines, -1350 removed lines patch added patch discarded remove patch
@@ -58,1378 +58,1378 @@
 block discarded – undo
58 58
  */
59 59
 class Manager implements IManager {
60 60
 
61
-	/** @var IProviderFactory */
62
-	private $factory;
63
-	/** @var ILogger */
64
-	private $logger;
65
-	/** @var IConfig */
66
-	private $config;
67
-	/** @var ISecureRandom */
68
-	private $secureRandom;
69
-	/** @var IHasher */
70
-	private $hasher;
71
-	/** @var IMountManager */
72
-	private $mountManager;
73
-	/** @var IGroupManager */
74
-	private $groupManager;
75
-	/** @var IL10N */
76
-	private $l;
77
-	/** @var IUserManager */
78
-	private $userManager;
79
-	/** @var IRootFolder */
80
-	private $rootFolder;
81
-	/** @var CappedMemoryCache */
82
-	private $sharingDisabledForUsersCache;
83
-	/** @var EventDispatcher */
84
-	private $eventDispatcher;
85
-	/** @var LegacyHooks */
86
-	private $legacyHooks;
87
-
88
-
89
-	/**
90
-	 * Manager constructor.
91
-	 *
92
-	 * @param ILogger $logger
93
-	 * @param IConfig $config
94
-	 * @param ISecureRandom $secureRandom
95
-	 * @param IHasher $hasher
96
-	 * @param IMountManager $mountManager
97
-	 * @param IGroupManager $groupManager
98
-	 * @param IL10N $l
99
-	 * @param IProviderFactory $factory
100
-	 * @param IUserManager $userManager
101
-	 * @param IRootFolder $rootFolder
102
-	 * @param EventDispatcher $eventDispatcher
103
-	 */
104
-	public function __construct(
105
-			ILogger $logger,
106
-			IConfig $config,
107
-			ISecureRandom $secureRandom,
108
-			IHasher $hasher,
109
-			IMountManager $mountManager,
110
-			IGroupManager $groupManager,
111
-			IL10N $l,
112
-			IProviderFactory $factory,
113
-			IUserManager $userManager,
114
-			IRootFolder $rootFolder,
115
-			EventDispatcher $eventDispatcher
116
-	) {
117
-		$this->logger = $logger;
118
-		$this->config = $config;
119
-		$this->secureRandom = $secureRandom;
120
-		$this->hasher = $hasher;
121
-		$this->mountManager = $mountManager;
122
-		$this->groupManager = $groupManager;
123
-		$this->l = $l;
124
-		$this->factory = $factory;
125
-		$this->userManager = $userManager;
126
-		$this->rootFolder = $rootFolder;
127
-		$this->eventDispatcher = $eventDispatcher;
128
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
129
-		$this->legacyHooks = new LegacyHooks($this->eventDispatcher);
130
-	}
131
-
132
-	/**
133
-	 * Convert from a full share id to a tuple (providerId, shareId)
134
-	 *
135
-	 * @param string $id
136
-	 * @return string[]
137
-	 */
138
-	private function splitFullId($id) {
139
-		return explode(':', $id, 2);
140
-	}
141
-
142
-	/**
143
-	 * Verify if a password meets all requirements
144
-	 *
145
-	 * @param string $password
146
-	 * @throws \Exception
147
-	 */
148
-	protected function verifyPassword($password) {
149
-		if ($password === null) {
150
-			// No password is set, check if this is allowed.
151
-			if ($this->shareApiLinkEnforcePassword()) {
152
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
153
-			}
154
-
155
-			return;
156
-		}
157
-
158
-		// Let others verify the password
159
-		try {
160
-			$event = new GenericEvent($password);
161
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
162
-		} catch (HintException $e) {
163
-			throw new \Exception($e->getHint());
164
-		}
165
-	}
166
-
167
-	/**
168
-	 * Check for generic requirements before creating a share
169
-	 *
170
-	 * @param \OCP\Share\IShare $share
171
-	 * @throws \InvalidArgumentException
172
-	 * @throws GenericShareException
173
-	 */
174
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
175
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
176
-			// We expect a valid user as sharedWith for user shares
177
-			if (!$this->userManager->userExists($share->getSharedWith())) {
178
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
179
-			}
180
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
181
-			// We expect a valid group as sharedWith for group shares
182
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
183
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
184
-			}
185
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
186
-			if ($share->getSharedWith() !== null) {
187
-				throw new \InvalidArgumentException('SharedWith should be empty');
188
-			}
189
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
190
-			if ($share->getSharedWith() === null) {
191
-				throw new \InvalidArgumentException('SharedWith should not be empty');
192
-			}
193
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
194
-			if ($share->getSharedWith() === null) {
195
-				throw new \InvalidArgumentException('SharedWith should not be empty');
196
-			}
197
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
198
-			$circle = \OCA\Circles\Api\Circles::detailsCircle($share->getSharedWith());
199
-			if ($circle === null) {
200
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
201
-			}
202
-		} else {
203
-			// We can't handle other types yet
204
-			throw new \InvalidArgumentException('unknown share type');
205
-		}
206
-
207
-		// Verify the initiator of the share is set
208
-		if ($share->getSharedBy() === null) {
209
-			throw new \InvalidArgumentException('SharedBy should be set');
210
-		}
211
-
212
-		// Cannot share with yourself
213
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
214
-			$share->getSharedWith() === $share->getSharedBy()) {
215
-			throw new \InvalidArgumentException('Can\'t share with yourself');
216
-		}
217
-
218
-		// The path should be set
219
-		if ($share->getNode() === null) {
220
-			throw new \InvalidArgumentException('Path should be set');
221
-		}
222
-
223
-		// And it should be a file or a folder
224
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
225
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
226
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
227
-		}
228
-
229
-		// And you can't share your rootfolder
230
-		if ($this->userManager->userExists($share->getSharedBy())) {
231
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
232
-		} else {
233
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
234
-		}
235
-		if ($sharedPath === $share->getNode()->getPath()) {
236
-			throw new \InvalidArgumentException('You can\'t share your root folder');
237
-		}
238
-
239
-		// Check if we actually have share permissions
240
-		if (!$share->getNode()->isShareable()) {
241
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
242
-			throw new GenericShareException($message_t, $message_t, 404);
243
-		}
244
-
245
-		// Permissions should be set
246
-		if ($share->getPermissions() === null) {
247
-			throw new \InvalidArgumentException('A share requires permissions');
248
-		}
249
-
250
-		/*
61
+    /** @var IProviderFactory */
62
+    private $factory;
63
+    /** @var ILogger */
64
+    private $logger;
65
+    /** @var IConfig */
66
+    private $config;
67
+    /** @var ISecureRandom */
68
+    private $secureRandom;
69
+    /** @var IHasher */
70
+    private $hasher;
71
+    /** @var IMountManager */
72
+    private $mountManager;
73
+    /** @var IGroupManager */
74
+    private $groupManager;
75
+    /** @var IL10N */
76
+    private $l;
77
+    /** @var IUserManager */
78
+    private $userManager;
79
+    /** @var IRootFolder */
80
+    private $rootFolder;
81
+    /** @var CappedMemoryCache */
82
+    private $sharingDisabledForUsersCache;
83
+    /** @var EventDispatcher */
84
+    private $eventDispatcher;
85
+    /** @var LegacyHooks */
86
+    private $legacyHooks;
87
+
88
+
89
+    /**
90
+     * Manager constructor.
91
+     *
92
+     * @param ILogger $logger
93
+     * @param IConfig $config
94
+     * @param ISecureRandom $secureRandom
95
+     * @param IHasher $hasher
96
+     * @param IMountManager $mountManager
97
+     * @param IGroupManager $groupManager
98
+     * @param IL10N $l
99
+     * @param IProviderFactory $factory
100
+     * @param IUserManager $userManager
101
+     * @param IRootFolder $rootFolder
102
+     * @param EventDispatcher $eventDispatcher
103
+     */
104
+    public function __construct(
105
+            ILogger $logger,
106
+            IConfig $config,
107
+            ISecureRandom $secureRandom,
108
+            IHasher $hasher,
109
+            IMountManager $mountManager,
110
+            IGroupManager $groupManager,
111
+            IL10N $l,
112
+            IProviderFactory $factory,
113
+            IUserManager $userManager,
114
+            IRootFolder $rootFolder,
115
+            EventDispatcher $eventDispatcher
116
+    ) {
117
+        $this->logger = $logger;
118
+        $this->config = $config;
119
+        $this->secureRandom = $secureRandom;
120
+        $this->hasher = $hasher;
121
+        $this->mountManager = $mountManager;
122
+        $this->groupManager = $groupManager;
123
+        $this->l = $l;
124
+        $this->factory = $factory;
125
+        $this->userManager = $userManager;
126
+        $this->rootFolder = $rootFolder;
127
+        $this->eventDispatcher = $eventDispatcher;
128
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
129
+        $this->legacyHooks = new LegacyHooks($this->eventDispatcher);
130
+    }
131
+
132
+    /**
133
+     * Convert from a full share id to a tuple (providerId, shareId)
134
+     *
135
+     * @param string $id
136
+     * @return string[]
137
+     */
138
+    private function splitFullId($id) {
139
+        return explode(':', $id, 2);
140
+    }
141
+
142
+    /**
143
+     * Verify if a password meets all requirements
144
+     *
145
+     * @param string $password
146
+     * @throws \Exception
147
+     */
148
+    protected function verifyPassword($password) {
149
+        if ($password === null) {
150
+            // No password is set, check if this is allowed.
151
+            if ($this->shareApiLinkEnforcePassword()) {
152
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
153
+            }
154
+
155
+            return;
156
+        }
157
+
158
+        // Let others verify the password
159
+        try {
160
+            $event = new GenericEvent($password);
161
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
162
+        } catch (HintException $e) {
163
+            throw new \Exception($e->getHint());
164
+        }
165
+    }
166
+
167
+    /**
168
+     * Check for generic requirements before creating a share
169
+     *
170
+     * @param \OCP\Share\IShare $share
171
+     * @throws \InvalidArgumentException
172
+     * @throws GenericShareException
173
+     */
174
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
175
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
176
+            // We expect a valid user as sharedWith for user shares
177
+            if (!$this->userManager->userExists($share->getSharedWith())) {
178
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
179
+            }
180
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
181
+            // We expect a valid group as sharedWith for group shares
182
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
183
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
184
+            }
185
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
186
+            if ($share->getSharedWith() !== null) {
187
+                throw new \InvalidArgumentException('SharedWith should be empty');
188
+            }
189
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
190
+            if ($share->getSharedWith() === null) {
191
+                throw new \InvalidArgumentException('SharedWith should not be empty');
192
+            }
193
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
194
+            if ($share->getSharedWith() === null) {
195
+                throw new \InvalidArgumentException('SharedWith should not be empty');
196
+            }
197
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
198
+            $circle = \OCA\Circles\Api\Circles::detailsCircle($share->getSharedWith());
199
+            if ($circle === null) {
200
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
201
+            }
202
+        } else {
203
+            // We can't handle other types yet
204
+            throw new \InvalidArgumentException('unknown share type');
205
+        }
206
+
207
+        // Verify the initiator of the share is set
208
+        if ($share->getSharedBy() === null) {
209
+            throw new \InvalidArgumentException('SharedBy should be set');
210
+        }
211
+
212
+        // Cannot share with yourself
213
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
214
+            $share->getSharedWith() === $share->getSharedBy()) {
215
+            throw new \InvalidArgumentException('Can\'t share with yourself');
216
+        }
217
+
218
+        // The path should be set
219
+        if ($share->getNode() === null) {
220
+            throw new \InvalidArgumentException('Path should be set');
221
+        }
222
+
223
+        // And it should be a file or a folder
224
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
225
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
226
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
227
+        }
228
+
229
+        // And you can't share your rootfolder
230
+        if ($this->userManager->userExists($share->getSharedBy())) {
231
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
232
+        } else {
233
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
234
+        }
235
+        if ($sharedPath === $share->getNode()->getPath()) {
236
+            throw new \InvalidArgumentException('You can\'t share your root folder');
237
+        }
238
+
239
+        // Check if we actually have share permissions
240
+        if (!$share->getNode()->isShareable()) {
241
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
242
+            throw new GenericShareException($message_t, $message_t, 404);
243
+        }
244
+
245
+        // Permissions should be set
246
+        if ($share->getPermissions() === null) {
247
+            throw new \InvalidArgumentException('A share requires permissions');
248
+        }
249
+
250
+        /*
251 251
 		 * Quick fix for #23536
252 252
 		 * Non moveable mount points do not have update and delete permissions
253 253
 		 * while we 'most likely' do have that on the storage.
254 254
 		 */
255
-		$permissions = $share->getNode()->getPermissions();
256
-		$mount = $share->getNode()->getMountPoint();
257
-		if (!($mount instanceof MoveableMount)) {
258
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
259
-		}
260
-
261
-		// Check that we do not share with more permissions than we have
262
-		if ($share->getPermissions() & ~$permissions) {
263
-			$message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
264
-			throw new GenericShareException($message_t, $message_t, 404);
265
-		}
266
-
267
-
268
-		// Check that read permissions are always set
269
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
270
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
271
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
272
-		if (!$noReadPermissionRequired &&
273
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
274
-			throw new \InvalidArgumentException('Shares need at least read permissions');
275
-		}
276
-
277
-		if ($share->getNode() instanceof \OCP\Files\File) {
278
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
279
-				$message_t = $this->l->t('Files can\'t be shared with delete permissions');
280
-				throw new GenericShareException($message_t);
281
-			}
282
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
283
-				$message_t = $this->l->t('Files can\'t be shared with create permissions');
284
-				throw new GenericShareException($message_t);
285
-			}
286
-		}
287
-	}
288
-
289
-	/**
290
-	 * Validate if the expiration date fits the system settings
291
-	 *
292
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
293
-	 * @return \OCP\Share\IShare The modified share object
294
-	 * @throws GenericShareException
295
-	 * @throws \InvalidArgumentException
296
-	 * @throws \Exception
297
-	 */
298
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
299
-
300
-		$expirationDate = $share->getExpirationDate();
301
-
302
-		if ($expirationDate !== null) {
303
-			//Make sure the expiration date is a date
304
-			$expirationDate->setTime(0, 0, 0);
305
-
306
-			$date = new \DateTime();
307
-			$date->setTime(0, 0, 0);
308
-			if ($date >= $expirationDate) {
309
-				$message = $this->l->t('Expiration date is in the past');
310
-				throw new GenericShareException($message, $message, 404);
311
-			}
312
-		}
313
-
314
-		// If expiredate is empty set a default one if there is a default
315
-		$fullId = null;
316
-		try {
317
-			$fullId = $share->getFullId();
318
-		} catch (\UnexpectedValueException $e) {
319
-			// This is a new share
320
-		}
321
-
322
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
323
-			$expirationDate = new \DateTime();
324
-			$expirationDate->setTime(0,0,0);
325
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
326
-		}
327
-
328
-		// If we enforce the expiration date check that is does not exceed
329
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
330
-			if ($expirationDate === null) {
331
-				throw new \InvalidArgumentException('Expiration date is enforced');
332
-			}
333
-
334
-			$date = new \DateTime();
335
-			$date->setTime(0, 0, 0);
336
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
337
-			if ($date < $expirationDate) {
338
-				$message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
339
-				throw new GenericShareException($message, $message, 404);
340
-			}
341
-		}
342
-
343
-		$accepted = true;
344
-		$message = '';
345
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
346
-			'expirationDate' => &$expirationDate,
347
-			'accepted' => &$accepted,
348
-			'message' => &$message,
349
-			'passwordSet' => $share->getPassword() !== null,
350
-		]);
351
-
352
-		if (!$accepted) {
353
-			throw new \Exception($message);
354
-		}
355
-
356
-		$share->setExpirationDate($expirationDate);
357
-
358
-		return $share;
359
-	}
360
-
361
-	/**
362
-	 * Check for pre share requirements for user shares
363
-	 *
364
-	 * @param \OCP\Share\IShare $share
365
-	 * @throws \Exception
366
-	 */
367
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
368
-		// Check if we can share with group members only
369
-		if ($this->shareWithGroupMembersOnly()) {
370
-			$sharedBy = $this->userManager->get($share->getSharedBy());
371
-			$sharedWith = $this->userManager->get($share->getSharedWith());
372
-			// Verify we can share with this user
373
-			$groups = array_intersect(
374
-					$this->groupManager->getUserGroupIds($sharedBy),
375
-					$this->groupManager->getUserGroupIds($sharedWith)
376
-			);
377
-			if (empty($groups)) {
378
-				throw new \Exception('Only sharing with group members is allowed');
379
-			}
380
-		}
381
-
382
-		/*
255
+        $permissions = $share->getNode()->getPermissions();
256
+        $mount = $share->getNode()->getMountPoint();
257
+        if (!($mount instanceof MoveableMount)) {
258
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
259
+        }
260
+
261
+        // Check that we do not share with more permissions than we have
262
+        if ($share->getPermissions() & ~$permissions) {
263
+            $message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
264
+            throw new GenericShareException($message_t, $message_t, 404);
265
+        }
266
+
267
+
268
+        // Check that read permissions are always set
269
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
270
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
271
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
272
+        if (!$noReadPermissionRequired &&
273
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
274
+            throw new \InvalidArgumentException('Shares need at least read permissions');
275
+        }
276
+
277
+        if ($share->getNode() instanceof \OCP\Files\File) {
278
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
279
+                $message_t = $this->l->t('Files can\'t be shared with delete permissions');
280
+                throw new GenericShareException($message_t);
281
+            }
282
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
283
+                $message_t = $this->l->t('Files can\'t be shared with create permissions');
284
+                throw new GenericShareException($message_t);
285
+            }
286
+        }
287
+    }
288
+
289
+    /**
290
+     * Validate if the expiration date fits the system settings
291
+     *
292
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
293
+     * @return \OCP\Share\IShare The modified share object
294
+     * @throws GenericShareException
295
+     * @throws \InvalidArgumentException
296
+     * @throws \Exception
297
+     */
298
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
299
+
300
+        $expirationDate = $share->getExpirationDate();
301
+
302
+        if ($expirationDate !== null) {
303
+            //Make sure the expiration date is a date
304
+            $expirationDate->setTime(0, 0, 0);
305
+
306
+            $date = new \DateTime();
307
+            $date->setTime(0, 0, 0);
308
+            if ($date >= $expirationDate) {
309
+                $message = $this->l->t('Expiration date is in the past');
310
+                throw new GenericShareException($message, $message, 404);
311
+            }
312
+        }
313
+
314
+        // If expiredate is empty set a default one if there is a default
315
+        $fullId = null;
316
+        try {
317
+            $fullId = $share->getFullId();
318
+        } catch (\UnexpectedValueException $e) {
319
+            // This is a new share
320
+        }
321
+
322
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
323
+            $expirationDate = new \DateTime();
324
+            $expirationDate->setTime(0,0,0);
325
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
326
+        }
327
+
328
+        // If we enforce the expiration date check that is does not exceed
329
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
330
+            if ($expirationDate === null) {
331
+                throw new \InvalidArgumentException('Expiration date is enforced');
332
+            }
333
+
334
+            $date = new \DateTime();
335
+            $date->setTime(0, 0, 0);
336
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
337
+            if ($date < $expirationDate) {
338
+                $message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
339
+                throw new GenericShareException($message, $message, 404);
340
+            }
341
+        }
342
+
343
+        $accepted = true;
344
+        $message = '';
345
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
346
+            'expirationDate' => &$expirationDate,
347
+            'accepted' => &$accepted,
348
+            'message' => &$message,
349
+            'passwordSet' => $share->getPassword() !== null,
350
+        ]);
351
+
352
+        if (!$accepted) {
353
+            throw new \Exception($message);
354
+        }
355
+
356
+        $share->setExpirationDate($expirationDate);
357
+
358
+        return $share;
359
+    }
360
+
361
+    /**
362
+     * Check for pre share requirements for user shares
363
+     *
364
+     * @param \OCP\Share\IShare $share
365
+     * @throws \Exception
366
+     */
367
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
368
+        // Check if we can share with group members only
369
+        if ($this->shareWithGroupMembersOnly()) {
370
+            $sharedBy = $this->userManager->get($share->getSharedBy());
371
+            $sharedWith = $this->userManager->get($share->getSharedWith());
372
+            // Verify we can share with this user
373
+            $groups = array_intersect(
374
+                    $this->groupManager->getUserGroupIds($sharedBy),
375
+                    $this->groupManager->getUserGroupIds($sharedWith)
376
+            );
377
+            if (empty($groups)) {
378
+                throw new \Exception('Only sharing with group members is allowed');
379
+            }
380
+        }
381
+
382
+        /*
383 383
 		 * TODO: Could be costly, fix
384 384
 		 *
385 385
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
386 386
 		 */
387
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
388
-		$existingShares = $provider->getSharesByPath($share->getNode());
389
-		foreach($existingShares as $existingShare) {
390
-			// Ignore if it is the same share
391
-			try {
392
-				if ($existingShare->getFullId() === $share->getFullId()) {
393
-					continue;
394
-				}
395
-			} catch (\UnexpectedValueException $e) {
396
-				//Shares are not identical
397
-			}
398
-
399
-			// Identical share already existst
400
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
401
-				throw new \Exception('Path already shared with this user');
402
-			}
403
-
404
-			// The share is already shared with this user via a group share
405
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
406
-				$group = $this->groupManager->get($existingShare->getSharedWith());
407
-				if (!is_null($group)) {
408
-					$user = $this->userManager->get($share->getSharedWith());
409
-
410
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
411
-						throw new \Exception('Path already shared with this user');
412
-					}
413
-				}
414
-			}
415
-		}
416
-	}
417
-
418
-	/**
419
-	 * Check for pre share requirements for group shares
420
-	 *
421
-	 * @param \OCP\Share\IShare $share
422
-	 * @throws \Exception
423
-	 */
424
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
425
-		// Verify group shares are allowed
426
-		if (!$this->allowGroupSharing()) {
427
-			throw new \Exception('Group sharing is now allowed');
428
-		}
429
-
430
-		// Verify if the user can share with this group
431
-		if ($this->shareWithGroupMembersOnly()) {
432
-			$sharedBy = $this->userManager->get($share->getSharedBy());
433
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
434
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
435
-				throw new \Exception('Only sharing within your own groups is allowed');
436
-			}
437
-		}
438
-
439
-		/*
387
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
388
+        $existingShares = $provider->getSharesByPath($share->getNode());
389
+        foreach($existingShares as $existingShare) {
390
+            // Ignore if it is the same share
391
+            try {
392
+                if ($existingShare->getFullId() === $share->getFullId()) {
393
+                    continue;
394
+                }
395
+            } catch (\UnexpectedValueException $e) {
396
+                //Shares are not identical
397
+            }
398
+
399
+            // Identical share already existst
400
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
401
+                throw new \Exception('Path already shared with this user');
402
+            }
403
+
404
+            // The share is already shared with this user via a group share
405
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
406
+                $group = $this->groupManager->get($existingShare->getSharedWith());
407
+                if (!is_null($group)) {
408
+                    $user = $this->userManager->get($share->getSharedWith());
409
+
410
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
411
+                        throw new \Exception('Path already shared with this user');
412
+                    }
413
+                }
414
+            }
415
+        }
416
+    }
417
+
418
+    /**
419
+     * Check for pre share requirements for group shares
420
+     *
421
+     * @param \OCP\Share\IShare $share
422
+     * @throws \Exception
423
+     */
424
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
425
+        // Verify group shares are allowed
426
+        if (!$this->allowGroupSharing()) {
427
+            throw new \Exception('Group sharing is now allowed');
428
+        }
429
+
430
+        // Verify if the user can share with this group
431
+        if ($this->shareWithGroupMembersOnly()) {
432
+            $sharedBy = $this->userManager->get($share->getSharedBy());
433
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
434
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
435
+                throw new \Exception('Only sharing within your own groups is allowed');
436
+            }
437
+        }
438
+
439
+        /*
440 440
 		 * TODO: Could be costly, fix
441 441
 		 *
442 442
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
443 443
 		 */
444
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
445
-		$existingShares = $provider->getSharesByPath($share->getNode());
446
-		foreach($existingShares as $existingShare) {
447
-			try {
448
-				if ($existingShare->getFullId() === $share->getFullId()) {
449
-					continue;
450
-				}
451
-			} catch (\UnexpectedValueException $e) {
452
-				//It is a new share so just continue
453
-			}
454
-
455
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
456
-				throw new \Exception('Path already shared with this group');
457
-			}
458
-		}
459
-	}
460
-
461
-	/**
462
-	 * Check for pre share requirements for link shares
463
-	 *
464
-	 * @param \OCP\Share\IShare $share
465
-	 * @throws \Exception
466
-	 */
467
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
468
-		// Are link shares allowed?
469
-		if (!$this->shareApiAllowLinks()) {
470
-			throw new \Exception('Link sharing not allowed');
471
-		}
472
-
473
-		// Link shares by definition can't have share permissions
474
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
475
-			throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
476
-		}
477
-
478
-		// Check if public upload is allowed
479
-		if (!$this->shareApiLinkAllowPublicUpload() &&
480
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
481
-			throw new \InvalidArgumentException('Public upload not allowed');
482
-		}
483
-	}
484
-
485
-	/**
486
-	 * To make sure we don't get invisible link shares we set the parent
487
-	 * of a link if it is a reshare. This is a quick word around
488
-	 * until we can properly display multiple link shares in the UI
489
-	 *
490
-	 * See: https://github.com/owncloud/core/issues/22295
491
-	 *
492
-	 * FIXME: Remove once multiple link shares can be properly displayed
493
-	 *
494
-	 * @param \OCP\Share\IShare $share
495
-	 */
496
-	protected function setLinkParent(\OCP\Share\IShare $share) {
497
-
498
-		// No sense in checking if the method is not there.
499
-		if (method_exists($share, 'setParent')) {
500
-			$storage = $share->getNode()->getStorage();
501
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
502
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
503
-				$share->setParent($storage->getShareId());
504
-			}
505
-		};
506
-	}
507
-
508
-	/**
509
-	 * @param File|Folder $path
510
-	 */
511
-	protected function pathCreateChecks($path) {
512
-		// Make sure that we do not share a path that contains a shared mountpoint
513
-		if ($path instanceof \OCP\Files\Folder) {
514
-			$mounts = $this->mountManager->findIn($path->getPath());
515
-			foreach($mounts as $mount) {
516
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
517
-					throw new \InvalidArgumentException('Path contains files shared with you');
518
-				}
519
-			}
520
-		}
521
-	}
522
-
523
-	/**
524
-	 * Check if the user that is sharing can actually share
525
-	 *
526
-	 * @param \OCP\Share\IShare $share
527
-	 * @throws \Exception
528
-	 */
529
-	protected function canShare(\OCP\Share\IShare $share) {
530
-		if (!$this->shareApiEnabled()) {
531
-			throw new \Exception('The share API is disabled');
532
-		}
533
-
534
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
535
-			throw new \Exception('You are not allowed to share');
536
-		}
537
-	}
538
-
539
-	/**
540
-	 * Share a path
541
-	 *
542
-	 * @param \OCP\Share\IShare $share
543
-	 * @return Share The share object
544
-	 * @throws \Exception
545
-	 *
546
-	 * TODO: handle link share permissions or check them
547
-	 */
548
-	public function createShare(\OCP\Share\IShare $share) {
549
-		$this->canShare($share);
550
-
551
-		$this->generalCreateChecks($share);
552
-
553
-		// Verify if there are any issues with the path
554
-		$this->pathCreateChecks($share->getNode());
555
-
556
-		/*
444
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
445
+        $existingShares = $provider->getSharesByPath($share->getNode());
446
+        foreach($existingShares as $existingShare) {
447
+            try {
448
+                if ($existingShare->getFullId() === $share->getFullId()) {
449
+                    continue;
450
+                }
451
+            } catch (\UnexpectedValueException $e) {
452
+                //It is a new share so just continue
453
+            }
454
+
455
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
456
+                throw new \Exception('Path already shared with this group');
457
+            }
458
+        }
459
+    }
460
+
461
+    /**
462
+     * Check for pre share requirements for link shares
463
+     *
464
+     * @param \OCP\Share\IShare $share
465
+     * @throws \Exception
466
+     */
467
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
468
+        // Are link shares allowed?
469
+        if (!$this->shareApiAllowLinks()) {
470
+            throw new \Exception('Link sharing not allowed');
471
+        }
472
+
473
+        // Link shares by definition can't have share permissions
474
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
475
+            throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
476
+        }
477
+
478
+        // Check if public upload is allowed
479
+        if (!$this->shareApiLinkAllowPublicUpload() &&
480
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
481
+            throw new \InvalidArgumentException('Public upload not allowed');
482
+        }
483
+    }
484
+
485
+    /**
486
+     * To make sure we don't get invisible link shares we set the parent
487
+     * of a link if it is a reshare. This is a quick word around
488
+     * until we can properly display multiple link shares in the UI
489
+     *
490
+     * See: https://github.com/owncloud/core/issues/22295
491
+     *
492
+     * FIXME: Remove once multiple link shares can be properly displayed
493
+     *
494
+     * @param \OCP\Share\IShare $share
495
+     */
496
+    protected function setLinkParent(\OCP\Share\IShare $share) {
497
+
498
+        // No sense in checking if the method is not there.
499
+        if (method_exists($share, 'setParent')) {
500
+            $storage = $share->getNode()->getStorage();
501
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
502
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
503
+                $share->setParent($storage->getShareId());
504
+            }
505
+        };
506
+    }
507
+
508
+    /**
509
+     * @param File|Folder $path
510
+     */
511
+    protected function pathCreateChecks($path) {
512
+        // Make sure that we do not share a path that contains a shared mountpoint
513
+        if ($path instanceof \OCP\Files\Folder) {
514
+            $mounts = $this->mountManager->findIn($path->getPath());
515
+            foreach($mounts as $mount) {
516
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
517
+                    throw new \InvalidArgumentException('Path contains files shared with you');
518
+                }
519
+            }
520
+        }
521
+    }
522
+
523
+    /**
524
+     * Check if the user that is sharing can actually share
525
+     *
526
+     * @param \OCP\Share\IShare $share
527
+     * @throws \Exception
528
+     */
529
+    protected function canShare(\OCP\Share\IShare $share) {
530
+        if (!$this->shareApiEnabled()) {
531
+            throw new \Exception('The share API is disabled');
532
+        }
533
+
534
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
535
+            throw new \Exception('You are not allowed to share');
536
+        }
537
+    }
538
+
539
+    /**
540
+     * Share a path
541
+     *
542
+     * @param \OCP\Share\IShare $share
543
+     * @return Share The share object
544
+     * @throws \Exception
545
+     *
546
+     * TODO: handle link share permissions or check them
547
+     */
548
+    public function createShare(\OCP\Share\IShare $share) {
549
+        $this->canShare($share);
550
+
551
+        $this->generalCreateChecks($share);
552
+
553
+        // Verify if there are any issues with the path
554
+        $this->pathCreateChecks($share->getNode());
555
+
556
+        /*
557 557
 		 * On creation of a share the owner is always the owner of the path
558 558
 		 * Except for mounted federated shares.
559 559
 		 */
560
-		$storage = $share->getNode()->getStorage();
561
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
562
-			$parent = $share->getNode()->getParent();
563
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
564
-				$parent = $parent->getParent();
565
-			}
566
-			$share->setShareOwner($parent->getOwner()->getUID());
567
-		} else {
568
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
569
-		}
570
-
571
-		//Verify share type
572
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
573
-			$this->userCreateChecks($share);
574
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
575
-			$this->groupCreateChecks($share);
576
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
577
-			$this->linkCreateChecks($share);
578
-			$this->setLinkParent($share);
579
-
580
-			/*
560
+        $storage = $share->getNode()->getStorage();
561
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
562
+            $parent = $share->getNode()->getParent();
563
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
564
+                $parent = $parent->getParent();
565
+            }
566
+            $share->setShareOwner($parent->getOwner()->getUID());
567
+        } else {
568
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
569
+        }
570
+
571
+        //Verify share type
572
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
573
+            $this->userCreateChecks($share);
574
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
575
+            $this->groupCreateChecks($share);
576
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
577
+            $this->linkCreateChecks($share);
578
+            $this->setLinkParent($share);
579
+
580
+            /*
581 581
 			 * For now ignore a set token.
582 582
 			 */
583
-			$share->setToken(
584
-				$this->secureRandom->generate(
585
-					\OC\Share\Constants::TOKEN_LENGTH,
586
-					\OCP\Security\ISecureRandom::CHAR_LOWER.
587
-					\OCP\Security\ISecureRandom::CHAR_UPPER.
588
-					\OCP\Security\ISecureRandom::CHAR_DIGITS
589
-				)
590
-			);
591
-
592
-			//Verify the expiration date
593
-			$this->validateExpirationDate($share);
594
-
595
-			//Verify the password
596
-			$this->verifyPassword($share->getPassword());
597
-
598
-			// If a password is set. Hash it!
599
-			if ($share->getPassword() !== null) {
600
-				$share->setPassword($this->hasher->hash($share->getPassword()));
601
-			}
602
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
603
-			$share->setToken(
604
-				$this->secureRandom->generate(
605
-					\OC\Share\Constants::TOKEN_LENGTH,
606
-					\OCP\Security\ISecureRandom::CHAR_LOWER.
607
-					\OCP\Security\ISecureRandom::CHAR_UPPER.
608
-					\OCP\Security\ISecureRandom::CHAR_DIGITS
609
-				)
610
-			);
611
-		}
612
-
613
-		// Cannot share with the owner
614
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
615
-			$share->getSharedWith() === $share->getShareOwner()) {
616
-			throw new \InvalidArgumentException('Can\'t share with the share owner');
617
-		}
618
-
619
-		// Generate the target
620
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
621
-		$target = \OC\Files\Filesystem::normalizePath($target);
622
-		$share->setTarget($target);
623
-
624
-		// Pre share hook
625
-		$run = true;
626
-		$error = '';
627
-		$preHookData = [
628
-			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
629
-			'itemSource' => $share->getNode()->getId(),
630
-			'shareType' => $share->getShareType(),
631
-			'uidOwner' => $share->getSharedBy(),
632
-			'permissions' => $share->getPermissions(),
633
-			'fileSource' => $share->getNode()->getId(),
634
-			'expiration' => $share->getExpirationDate(),
635
-			'token' => $share->getToken(),
636
-			'itemTarget' => $share->getTarget(),
637
-			'shareWith' => $share->getSharedWith(),
638
-			'run' => &$run,
639
-			'error' => &$error,
640
-		];
641
-		\OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
642
-
643
-		if ($run === false) {
644
-			throw new \Exception($error);
645
-		}
646
-
647
-		$oldShare = $share;
648
-		$provider = $this->factory->getProviderForType($share->getShareType());
649
-		$share = $provider->create($share);
650
-		//reuse the node we already have
651
-		$share->setNode($oldShare->getNode());
652
-
653
-		// Post share hook
654
-		$postHookData = [
655
-			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
656
-			'itemSource' => $share->getNode()->getId(),
657
-			'shareType' => $share->getShareType(),
658
-			'uidOwner' => $share->getSharedBy(),
659
-			'permissions' => $share->getPermissions(),
660
-			'fileSource' => $share->getNode()->getId(),
661
-			'expiration' => $share->getExpirationDate(),
662
-			'token' => $share->getToken(),
663
-			'id' => $share->getId(),
664
-			'shareWith' => $share->getSharedWith(),
665
-			'itemTarget' => $share->getTarget(),
666
-			'fileTarget' => $share->getTarget(),
667
-		];
668
-
669
-		\OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
670
-
671
-		return $share;
672
-	}
673
-
674
-	/**
675
-	 * Update a share
676
-	 *
677
-	 * @param \OCP\Share\IShare $share
678
-	 * @return \OCP\Share\IShare The share object
679
-	 * @throws \InvalidArgumentException
680
-	 */
681
-	public function updateShare(\OCP\Share\IShare $share) {
682
-		$expirationDateUpdated = false;
683
-
684
-		$this->canShare($share);
685
-
686
-		try {
687
-			$originalShare = $this->getShareById($share->getFullId());
688
-		} catch (\UnexpectedValueException $e) {
689
-			throw new \InvalidArgumentException('Share does not have a full id');
690
-		}
691
-
692
-		// We can't change the share type!
693
-		if ($share->getShareType() !== $originalShare->getShareType()) {
694
-			throw new \InvalidArgumentException('Can\'t change share type');
695
-		}
696
-
697
-		// We can only change the recipient on user shares
698
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
699
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
700
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
701
-		}
702
-
703
-		// Cannot share with the owner
704
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
705
-			$share->getSharedWith() === $share->getShareOwner()) {
706
-			throw new \InvalidArgumentException('Can\'t share with the share owner');
707
-		}
708
-
709
-		$this->generalCreateChecks($share);
710
-
711
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
712
-			$this->userCreateChecks($share);
713
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
714
-			$this->groupCreateChecks($share);
715
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
716
-			$this->linkCreateChecks($share);
717
-
718
-			// Password updated.
719
-			if ($share->getPassword() !== $originalShare->getPassword()) {
720
-				//Verify the password
721
-				$this->verifyPassword($share->getPassword());
722
-
723
-				// If a password is set. Hash it!
724
-				if ($share->getPassword() !== null) {
725
-					$share->setPassword($this->hasher->hash($share->getPassword()));
726
-				}
727
-			}
728
-
729
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
730
-				//Verify the expiration date
731
-				$this->validateExpirationDate($share);
732
-				$expirationDateUpdated = true;
733
-			}
734
-		}
735
-
736
-		$plainTextPassword = null;
737
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
738
-			// Password updated.
739
-			if ($share->getPassword() !== $originalShare->getPassword()) {
740
-				//Verify the password
741
-				$this->verifyPassword($share->getPassword());
742
-
743
-				// If a password is set. Hash it!
744
-				if ($share->getPassword() !== null) {
745
-					$plainTextPassword = $share->getPassword();
746
-					$share->setPassword($this->hasher->hash($plainTextPassword));
747
-				}
748
-			}
749
-		}
750
-
751
-		$this->pathCreateChecks($share->getNode());
752
-
753
-		// Now update the share!
754
-		$provider = $this->factory->getProviderForType($share->getShareType());
755
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
756
-			$share = $provider->update($share, $plainTextPassword);
757
-		} else {
758
-			$share = $provider->update($share);
759
-		}
760
-
761
-		if ($expirationDateUpdated === true) {
762
-			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
763
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
764
-				'itemSource' => $share->getNode()->getId(),
765
-				'date' => $share->getExpirationDate(),
766
-				'uidOwner' => $share->getSharedBy(),
767
-			]);
768
-		}
769
-
770
-		if ($share->getPassword() !== $originalShare->getPassword()) {
771
-			\OC_Hook::emit('OCP\Share', 'post_update_password', [
772
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
773
-				'itemSource' => $share->getNode()->getId(),
774
-				'uidOwner' => $share->getSharedBy(),
775
-				'token' => $share->getToken(),
776
-				'disabled' => is_null($share->getPassword()),
777
-			]);
778
-		}
779
-
780
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
781
-			if ($this->userManager->userExists($share->getShareOwner())) {
782
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
783
-			} else {
784
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
785
-			}
786
-			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
787
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
788
-				'itemSource' => $share->getNode()->getId(),
789
-				'shareType' => $share->getShareType(),
790
-				'shareWith' => $share->getSharedWith(),
791
-				'uidOwner' => $share->getSharedBy(),
792
-				'permissions' => $share->getPermissions(),
793
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
794
-			));
795
-		}
796
-
797
-		return $share;
798
-	}
799
-
800
-	/**
801
-	 * Delete all the children of this share
802
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
803
-	 *
804
-	 * @param \OCP\Share\IShare $share
805
-	 * @return \OCP\Share\IShare[] List of deleted shares
806
-	 */
807
-	protected function deleteChildren(\OCP\Share\IShare $share) {
808
-		$deletedShares = [];
809
-
810
-		$provider = $this->factory->getProviderForType($share->getShareType());
811
-
812
-		foreach ($provider->getChildren($share) as $child) {
813
-			$deletedChildren = $this->deleteChildren($child);
814
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
815
-
816
-			$provider->delete($child);
817
-			$deletedShares[] = $child;
818
-		}
819
-
820
-		return $deletedShares;
821
-	}
822
-
823
-	/**
824
-	 * Delete a share
825
-	 *
826
-	 * @param \OCP\Share\IShare $share
827
-	 * @throws ShareNotFound
828
-	 * @throws \InvalidArgumentException
829
-	 */
830
-	public function deleteShare(\OCP\Share\IShare $share) {
831
-
832
-		try {
833
-			$share->getFullId();
834
-		} catch (\UnexpectedValueException $e) {
835
-			throw new \InvalidArgumentException('Share does not have a full id');
836
-		}
837
-
838
-		$event = new GenericEvent($share);
839
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
840
-
841
-		// Get all children and delete them as well
842
-		$deletedShares = $this->deleteChildren($share);
843
-
844
-		// Do the actual delete
845
-		$provider = $this->factory->getProviderForType($share->getShareType());
846
-		$provider->delete($share);
847
-
848
-		// All the deleted shares caused by this delete
849
-		$deletedShares[] = $share;
850
-
851
-		// Emit post hook
852
-		$event->setArgument('deletedShares', $deletedShares);
853
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
854
-	}
855
-
856
-
857
-	/**
858
-	 * Unshare a file as the recipient.
859
-	 * This can be different from a regular delete for example when one of
860
-	 * the users in a groups deletes that share. But the provider should
861
-	 * handle this.
862
-	 *
863
-	 * @param \OCP\Share\IShare $share
864
-	 * @param string $recipientId
865
-	 */
866
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
867
-		list($providerId, ) = $this->splitFullId($share->getFullId());
868
-		$provider = $this->factory->getProvider($providerId);
869
-
870
-		$provider->deleteFromSelf($share, $recipientId);
871
-	}
872
-
873
-	/**
874
-	 * @inheritdoc
875
-	 */
876
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
877
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
878
-			throw new \InvalidArgumentException('Can\'t change target of link share');
879
-		}
880
-
881
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
882
-			throw new \InvalidArgumentException('Invalid recipient');
883
-		}
884
-
885
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
886
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
887
-			if (is_null($sharedWith)) {
888
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
889
-			}
890
-			$recipient = $this->userManager->get($recipientId);
891
-			if (!$sharedWith->inGroup($recipient)) {
892
-				throw new \InvalidArgumentException('Invalid recipient');
893
-			}
894
-		}
895
-
896
-		list($providerId, ) = $this->splitFullId($share->getFullId());
897
-		$provider = $this->factory->getProvider($providerId);
898
-
899
-		$provider->move($share, $recipientId);
900
-	}
901
-
902
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
903
-		$providers = $this->factory->getAllProviders();
904
-
905
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
906
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
907
-			foreach ($newShares as $fid => $data) {
908
-				if (!isset($shares[$fid])) {
909
-					$shares[$fid] = [];
910
-				}
911
-
912
-				$shares[$fid] = array_merge($shares[$fid], $data);
913
-			}
914
-			return $shares;
915
-		}, []);
916
-	}
917
-
918
-	/**
919
-	 * @inheritdoc
920
-	 */
921
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
922
-		if ($path !== null &&
923
-				!($path instanceof \OCP\Files\File) &&
924
-				!($path instanceof \OCP\Files\Folder)) {
925
-			throw new \InvalidArgumentException('invalid path');
926
-		}
927
-
928
-		try {
929
-			$provider = $this->factory->getProviderForType($shareType);
930
-		} catch (ProviderException $e) {
931
-			return [];
932
-		}
933
-
934
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
935
-
936
-		/*
583
+            $share->setToken(
584
+                $this->secureRandom->generate(
585
+                    \OC\Share\Constants::TOKEN_LENGTH,
586
+                    \OCP\Security\ISecureRandom::CHAR_LOWER.
587
+                    \OCP\Security\ISecureRandom::CHAR_UPPER.
588
+                    \OCP\Security\ISecureRandom::CHAR_DIGITS
589
+                )
590
+            );
591
+
592
+            //Verify the expiration date
593
+            $this->validateExpirationDate($share);
594
+
595
+            //Verify the password
596
+            $this->verifyPassword($share->getPassword());
597
+
598
+            // If a password is set. Hash it!
599
+            if ($share->getPassword() !== null) {
600
+                $share->setPassword($this->hasher->hash($share->getPassword()));
601
+            }
602
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
603
+            $share->setToken(
604
+                $this->secureRandom->generate(
605
+                    \OC\Share\Constants::TOKEN_LENGTH,
606
+                    \OCP\Security\ISecureRandom::CHAR_LOWER.
607
+                    \OCP\Security\ISecureRandom::CHAR_UPPER.
608
+                    \OCP\Security\ISecureRandom::CHAR_DIGITS
609
+                )
610
+            );
611
+        }
612
+
613
+        // Cannot share with the owner
614
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
615
+            $share->getSharedWith() === $share->getShareOwner()) {
616
+            throw new \InvalidArgumentException('Can\'t share with the share owner');
617
+        }
618
+
619
+        // Generate the target
620
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
621
+        $target = \OC\Files\Filesystem::normalizePath($target);
622
+        $share->setTarget($target);
623
+
624
+        // Pre share hook
625
+        $run = true;
626
+        $error = '';
627
+        $preHookData = [
628
+            'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
629
+            'itemSource' => $share->getNode()->getId(),
630
+            'shareType' => $share->getShareType(),
631
+            'uidOwner' => $share->getSharedBy(),
632
+            'permissions' => $share->getPermissions(),
633
+            'fileSource' => $share->getNode()->getId(),
634
+            'expiration' => $share->getExpirationDate(),
635
+            'token' => $share->getToken(),
636
+            'itemTarget' => $share->getTarget(),
637
+            'shareWith' => $share->getSharedWith(),
638
+            'run' => &$run,
639
+            'error' => &$error,
640
+        ];
641
+        \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
642
+
643
+        if ($run === false) {
644
+            throw new \Exception($error);
645
+        }
646
+
647
+        $oldShare = $share;
648
+        $provider = $this->factory->getProviderForType($share->getShareType());
649
+        $share = $provider->create($share);
650
+        //reuse the node we already have
651
+        $share->setNode($oldShare->getNode());
652
+
653
+        // Post share hook
654
+        $postHookData = [
655
+            'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
656
+            'itemSource' => $share->getNode()->getId(),
657
+            'shareType' => $share->getShareType(),
658
+            'uidOwner' => $share->getSharedBy(),
659
+            'permissions' => $share->getPermissions(),
660
+            'fileSource' => $share->getNode()->getId(),
661
+            'expiration' => $share->getExpirationDate(),
662
+            'token' => $share->getToken(),
663
+            'id' => $share->getId(),
664
+            'shareWith' => $share->getSharedWith(),
665
+            'itemTarget' => $share->getTarget(),
666
+            'fileTarget' => $share->getTarget(),
667
+        ];
668
+
669
+        \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
670
+
671
+        return $share;
672
+    }
673
+
674
+    /**
675
+     * Update a share
676
+     *
677
+     * @param \OCP\Share\IShare $share
678
+     * @return \OCP\Share\IShare The share object
679
+     * @throws \InvalidArgumentException
680
+     */
681
+    public function updateShare(\OCP\Share\IShare $share) {
682
+        $expirationDateUpdated = false;
683
+
684
+        $this->canShare($share);
685
+
686
+        try {
687
+            $originalShare = $this->getShareById($share->getFullId());
688
+        } catch (\UnexpectedValueException $e) {
689
+            throw new \InvalidArgumentException('Share does not have a full id');
690
+        }
691
+
692
+        // We can't change the share type!
693
+        if ($share->getShareType() !== $originalShare->getShareType()) {
694
+            throw new \InvalidArgumentException('Can\'t change share type');
695
+        }
696
+
697
+        // We can only change the recipient on user shares
698
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
699
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
700
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
701
+        }
702
+
703
+        // Cannot share with the owner
704
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
705
+            $share->getSharedWith() === $share->getShareOwner()) {
706
+            throw new \InvalidArgumentException('Can\'t share with the share owner');
707
+        }
708
+
709
+        $this->generalCreateChecks($share);
710
+
711
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
712
+            $this->userCreateChecks($share);
713
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
714
+            $this->groupCreateChecks($share);
715
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
716
+            $this->linkCreateChecks($share);
717
+
718
+            // Password updated.
719
+            if ($share->getPassword() !== $originalShare->getPassword()) {
720
+                //Verify the password
721
+                $this->verifyPassword($share->getPassword());
722
+
723
+                // If a password is set. Hash it!
724
+                if ($share->getPassword() !== null) {
725
+                    $share->setPassword($this->hasher->hash($share->getPassword()));
726
+                }
727
+            }
728
+
729
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
730
+                //Verify the expiration date
731
+                $this->validateExpirationDate($share);
732
+                $expirationDateUpdated = true;
733
+            }
734
+        }
735
+
736
+        $plainTextPassword = null;
737
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
738
+            // Password updated.
739
+            if ($share->getPassword() !== $originalShare->getPassword()) {
740
+                //Verify the password
741
+                $this->verifyPassword($share->getPassword());
742
+
743
+                // If a password is set. Hash it!
744
+                if ($share->getPassword() !== null) {
745
+                    $plainTextPassword = $share->getPassword();
746
+                    $share->setPassword($this->hasher->hash($plainTextPassword));
747
+                }
748
+            }
749
+        }
750
+
751
+        $this->pathCreateChecks($share->getNode());
752
+
753
+        // Now update the share!
754
+        $provider = $this->factory->getProviderForType($share->getShareType());
755
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
756
+            $share = $provider->update($share, $plainTextPassword);
757
+        } else {
758
+            $share = $provider->update($share);
759
+        }
760
+
761
+        if ($expirationDateUpdated === true) {
762
+            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
763
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
764
+                'itemSource' => $share->getNode()->getId(),
765
+                'date' => $share->getExpirationDate(),
766
+                'uidOwner' => $share->getSharedBy(),
767
+            ]);
768
+        }
769
+
770
+        if ($share->getPassword() !== $originalShare->getPassword()) {
771
+            \OC_Hook::emit('OCP\Share', 'post_update_password', [
772
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
773
+                'itemSource' => $share->getNode()->getId(),
774
+                'uidOwner' => $share->getSharedBy(),
775
+                'token' => $share->getToken(),
776
+                'disabled' => is_null($share->getPassword()),
777
+            ]);
778
+        }
779
+
780
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
781
+            if ($this->userManager->userExists($share->getShareOwner())) {
782
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
783
+            } else {
784
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
785
+            }
786
+            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
787
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
788
+                'itemSource' => $share->getNode()->getId(),
789
+                'shareType' => $share->getShareType(),
790
+                'shareWith' => $share->getSharedWith(),
791
+                'uidOwner' => $share->getSharedBy(),
792
+                'permissions' => $share->getPermissions(),
793
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
794
+            ));
795
+        }
796
+
797
+        return $share;
798
+    }
799
+
800
+    /**
801
+     * Delete all the children of this share
802
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
803
+     *
804
+     * @param \OCP\Share\IShare $share
805
+     * @return \OCP\Share\IShare[] List of deleted shares
806
+     */
807
+    protected function deleteChildren(\OCP\Share\IShare $share) {
808
+        $deletedShares = [];
809
+
810
+        $provider = $this->factory->getProviderForType($share->getShareType());
811
+
812
+        foreach ($provider->getChildren($share) as $child) {
813
+            $deletedChildren = $this->deleteChildren($child);
814
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
815
+
816
+            $provider->delete($child);
817
+            $deletedShares[] = $child;
818
+        }
819
+
820
+        return $deletedShares;
821
+    }
822
+
823
+    /**
824
+     * Delete a share
825
+     *
826
+     * @param \OCP\Share\IShare $share
827
+     * @throws ShareNotFound
828
+     * @throws \InvalidArgumentException
829
+     */
830
+    public function deleteShare(\OCP\Share\IShare $share) {
831
+
832
+        try {
833
+            $share->getFullId();
834
+        } catch (\UnexpectedValueException $e) {
835
+            throw new \InvalidArgumentException('Share does not have a full id');
836
+        }
837
+
838
+        $event = new GenericEvent($share);
839
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
840
+
841
+        // Get all children and delete them as well
842
+        $deletedShares = $this->deleteChildren($share);
843
+
844
+        // Do the actual delete
845
+        $provider = $this->factory->getProviderForType($share->getShareType());
846
+        $provider->delete($share);
847
+
848
+        // All the deleted shares caused by this delete
849
+        $deletedShares[] = $share;
850
+
851
+        // Emit post hook
852
+        $event->setArgument('deletedShares', $deletedShares);
853
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
854
+    }
855
+
856
+
857
+    /**
858
+     * Unshare a file as the recipient.
859
+     * This can be different from a regular delete for example when one of
860
+     * the users in a groups deletes that share. But the provider should
861
+     * handle this.
862
+     *
863
+     * @param \OCP\Share\IShare $share
864
+     * @param string $recipientId
865
+     */
866
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
867
+        list($providerId, ) = $this->splitFullId($share->getFullId());
868
+        $provider = $this->factory->getProvider($providerId);
869
+
870
+        $provider->deleteFromSelf($share, $recipientId);
871
+    }
872
+
873
+    /**
874
+     * @inheritdoc
875
+     */
876
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
877
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
878
+            throw new \InvalidArgumentException('Can\'t change target of link share');
879
+        }
880
+
881
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
882
+            throw new \InvalidArgumentException('Invalid recipient');
883
+        }
884
+
885
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
886
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
887
+            if (is_null($sharedWith)) {
888
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
889
+            }
890
+            $recipient = $this->userManager->get($recipientId);
891
+            if (!$sharedWith->inGroup($recipient)) {
892
+                throw new \InvalidArgumentException('Invalid recipient');
893
+            }
894
+        }
895
+
896
+        list($providerId, ) = $this->splitFullId($share->getFullId());
897
+        $provider = $this->factory->getProvider($providerId);
898
+
899
+        $provider->move($share, $recipientId);
900
+    }
901
+
902
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
903
+        $providers = $this->factory->getAllProviders();
904
+
905
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
906
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
907
+            foreach ($newShares as $fid => $data) {
908
+                if (!isset($shares[$fid])) {
909
+                    $shares[$fid] = [];
910
+                }
911
+
912
+                $shares[$fid] = array_merge($shares[$fid], $data);
913
+            }
914
+            return $shares;
915
+        }, []);
916
+    }
917
+
918
+    /**
919
+     * @inheritdoc
920
+     */
921
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
922
+        if ($path !== null &&
923
+                !($path instanceof \OCP\Files\File) &&
924
+                !($path instanceof \OCP\Files\Folder)) {
925
+            throw new \InvalidArgumentException('invalid path');
926
+        }
927
+
928
+        try {
929
+            $provider = $this->factory->getProviderForType($shareType);
930
+        } catch (ProviderException $e) {
931
+            return [];
932
+        }
933
+
934
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
935
+
936
+        /*
937 937
 		 * Work around so we don't return expired shares but still follow
938 938
 		 * proper pagination.
939 939
 		 */
940 940
 
941
-		$shares2 = [];
942
-
943
-		while(true) {
944
-			$added = 0;
945
-			foreach ($shares as $share) {
946
-
947
-				try {
948
-					$this->checkExpireDate($share);
949
-				} catch (ShareNotFound $e) {
950
-					//Ignore since this basically means the share is deleted
951
-					continue;
952
-				}
953
-
954
-				$added++;
955
-				$shares2[] = $share;
956
-
957
-				if (count($shares2) === $limit) {
958
-					break;
959
-				}
960
-			}
961
-
962
-			if (count($shares2) === $limit) {
963
-				break;
964
-			}
965
-
966
-			// If there was no limit on the select we are done
967
-			if ($limit === -1) {
968
-				break;
969
-			}
970
-
971
-			$offset += $added;
972
-
973
-			// Fetch again $limit shares
974
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
975
-
976
-			// No more shares means we are done
977
-			if (empty($shares)) {
978
-				break;
979
-			}
980
-		}
981
-
982
-		$shares = $shares2;
983
-
984
-		return $shares;
985
-	}
986
-
987
-	/**
988
-	 * @inheritdoc
989
-	 */
990
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
991
-		try {
992
-			$provider = $this->factory->getProviderForType($shareType);
993
-		} catch (ProviderException $e) {
994
-			return [];
995
-		}
996
-
997
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
998
-
999
-		// remove all shares which are already expired
1000
-		foreach ($shares as $key => $share) {
1001
-			try {
1002
-				$this->checkExpireDate($share);
1003
-			} catch (ShareNotFound $e) {
1004
-				unset($shares[$key]);
1005
-			}
1006
-		}
1007
-
1008
-		return $shares;
1009
-	}
1010
-
1011
-	/**
1012
-	 * @inheritdoc
1013
-	 */
1014
-	public function getShareById($id, $recipient = null) {
1015
-		if ($id === null) {
1016
-			throw new ShareNotFound();
1017
-		}
1018
-
1019
-		list($providerId, $id) = $this->splitFullId($id);
1020
-
1021
-		try {
1022
-			$provider = $this->factory->getProvider($providerId);
1023
-		} catch (ProviderException $e) {
1024
-			throw new ShareNotFound();
1025
-		}
1026
-
1027
-		$share = $provider->getShareById($id, $recipient);
1028
-
1029
-		$this->checkExpireDate($share);
1030
-
1031
-		return $share;
1032
-	}
1033
-
1034
-	/**
1035
-	 * Get all the shares for a given path
1036
-	 *
1037
-	 * @param \OCP\Files\Node $path
1038
-	 * @param int $page
1039
-	 * @param int $perPage
1040
-	 *
1041
-	 * @return Share[]
1042
-	 */
1043
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1044
-		return [];
1045
-	}
1046
-
1047
-	/**
1048
-	 * Get the share by token possible with password
1049
-	 *
1050
-	 * @param string $token
1051
-	 * @return Share
1052
-	 *
1053
-	 * @throws ShareNotFound
1054
-	 */
1055
-	public function getShareByToken($token) {
1056
-		$share = null;
1057
-		try {
1058
-			if($this->shareApiAllowLinks()) {
1059
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1060
-				$share = $provider->getShareByToken($token);
1061
-			}
1062
-		} catch (ProviderException $e) {
1063
-		} catch (ShareNotFound $e) {
1064
-		}
1065
-
1066
-
1067
-		// If it is not a link share try to fetch a federated share by token
1068
-		if ($share === null) {
1069
-			try {
1070
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1071
-				$share = $provider->getShareByToken($token);
1072
-			} catch (ProviderException $e) {
1073
-			} catch (ShareNotFound $e) {
1074
-			}
1075
-		}
1076
-
1077
-		// If it is not a link share try to fetch a mail share by token
1078
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1079
-			try {
1080
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1081
-				$share = $provider->getShareByToken($token);
1082
-			} catch (ProviderException $e) {
1083
-			} catch (ShareNotFound $e) {
1084
-			}
1085
-		}
1086
-
1087
-		if ($share === null) {
1088
-			throw new ShareNotFound();
1089
-		}
1090
-
1091
-		$this->checkExpireDate($share);
1092
-
1093
-		/*
941
+        $shares2 = [];
942
+
943
+        while(true) {
944
+            $added = 0;
945
+            foreach ($shares as $share) {
946
+
947
+                try {
948
+                    $this->checkExpireDate($share);
949
+                } catch (ShareNotFound $e) {
950
+                    //Ignore since this basically means the share is deleted
951
+                    continue;
952
+                }
953
+
954
+                $added++;
955
+                $shares2[] = $share;
956
+
957
+                if (count($shares2) === $limit) {
958
+                    break;
959
+                }
960
+            }
961
+
962
+            if (count($shares2) === $limit) {
963
+                break;
964
+            }
965
+
966
+            // If there was no limit on the select we are done
967
+            if ($limit === -1) {
968
+                break;
969
+            }
970
+
971
+            $offset += $added;
972
+
973
+            // Fetch again $limit shares
974
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
975
+
976
+            // No more shares means we are done
977
+            if (empty($shares)) {
978
+                break;
979
+            }
980
+        }
981
+
982
+        $shares = $shares2;
983
+
984
+        return $shares;
985
+    }
986
+
987
+    /**
988
+     * @inheritdoc
989
+     */
990
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
991
+        try {
992
+            $provider = $this->factory->getProviderForType($shareType);
993
+        } catch (ProviderException $e) {
994
+            return [];
995
+        }
996
+
997
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
998
+
999
+        // remove all shares which are already expired
1000
+        foreach ($shares as $key => $share) {
1001
+            try {
1002
+                $this->checkExpireDate($share);
1003
+            } catch (ShareNotFound $e) {
1004
+                unset($shares[$key]);
1005
+            }
1006
+        }
1007
+
1008
+        return $shares;
1009
+    }
1010
+
1011
+    /**
1012
+     * @inheritdoc
1013
+     */
1014
+    public function getShareById($id, $recipient = null) {
1015
+        if ($id === null) {
1016
+            throw new ShareNotFound();
1017
+        }
1018
+
1019
+        list($providerId, $id) = $this->splitFullId($id);
1020
+
1021
+        try {
1022
+            $provider = $this->factory->getProvider($providerId);
1023
+        } catch (ProviderException $e) {
1024
+            throw new ShareNotFound();
1025
+        }
1026
+
1027
+        $share = $provider->getShareById($id, $recipient);
1028
+
1029
+        $this->checkExpireDate($share);
1030
+
1031
+        return $share;
1032
+    }
1033
+
1034
+    /**
1035
+     * Get all the shares for a given path
1036
+     *
1037
+     * @param \OCP\Files\Node $path
1038
+     * @param int $page
1039
+     * @param int $perPage
1040
+     *
1041
+     * @return Share[]
1042
+     */
1043
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1044
+        return [];
1045
+    }
1046
+
1047
+    /**
1048
+     * Get the share by token possible with password
1049
+     *
1050
+     * @param string $token
1051
+     * @return Share
1052
+     *
1053
+     * @throws ShareNotFound
1054
+     */
1055
+    public function getShareByToken($token) {
1056
+        $share = null;
1057
+        try {
1058
+            if($this->shareApiAllowLinks()) {
1059
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1060
+                $share = $provider->getShareByToken($token);
1061
+            }
1062
+        } catch (ProviderException $e) {
1063
+        } catch (ShareNotFound $e) {
1064
+        }
1065
+
1066
+
1067
+        // If it is not a link share try to fetch a federated share by token
1068
+        if ($share === null) {
1069
+            try {
1070
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1071
+                $share = $provider->getShareByToken($token);
1072
+            } catch (ProviderException $e) {
1073
+            } catch (ShareNotFound $e) {
1074
+            }
1075
+        }
1076
+
1077
+        // If it is not a link share try to fetch a mail share by token
1078
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1079
+            try {
1080
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1081
+                $share = $provider->getShareByToken($token);
1082
+            } catch (ProviderException $e) {
1083
+            } catch (ShareNotFound $e) {
1084
+            }
1085
+        }
1086
+
1087
+        if ($share === null) {
1088
+            throw new ShareNotFound();
1089
+        }
1090
+
1091
+        $this->checkExpireDate($share);
1092
+
1093
+        /*
1094 1094
 		 * Reduce the permissions for link shares if public upload is not enabled
1095 1095
 		 */
1096
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1097
-			!$this->shareApiLinkAllowPublicUpload()) {
1098
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1099
-		}
1100
-
1101
-		return $share;
1102
-	}
1103
-
1104
-	protected function checkExpireDate($share) {
1105
-		if ($share->getExpirationDate() !== null &&
1106
-			$share->getExpirationDate() <= new \DateTime()) {
1107
-			$this->deleteShare($share);
1108
-			throw new ShareNotFound();
1109
-		}
1110
-
1111
-	}
1112
-
1113
-	/**
1114
-	 * Verify the password of a public share
1115
-	 *
1116
-	 * @param \OCP\Share\IShare $share
1117
-	 * @param string $password
1118
-	 * @return bool
1119
-	 */
1120
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1121
-		$passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1122
-			|| $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1123
-		if (!$passwordProtected) {
1124
-			//TODO maybe exception?
1125
-			return false;
1126
-		}
1127
-
1128
-		if ($password === null || $share->getPassword() === null) {
1129
-			return false;
1130
-		}
1131
-
1132
-		$newHash = '';
1133
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1134
-			return false;
1135
-		}
1136
-
1137
-		if (!empty($newHash)) {
1138
-			$share->setPassword($newHash);
1139
-			$provider = $this->factory->getProviderForType($share->getShareType());
1140
-			$provider->update($share);
1141
-		}
1142
-
1143
-		return true;
1144
-	}
1145
-
1146
-	/**
1147
-	 * @inheritdoc
1148
-	 */
1149
-	public function userDeleted($uid) {
1150
-		$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];
1151
-
1152
-		foreach ($types as $type) {
1153
-			try {
1154
-				$provider = $this->factory->getProviderForType($type);
1155
-			} catch (ProviderException $e) {
1156
-				continue;
1157
-			}
1158
-			$provider->userDeleted($uid, $type);
1159
-		}
1160
-	}
1161
-
1162
-	/**
1163
-	 * @inheritdoc
1164
-	 */
1165
-	public function groupDeleted($gid) {
1166
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1167
-		$provider->groupDeleted($gid);
1168
-	}
1169
-
1170
-	/**
1171
-	 * @inheritdoc
1172
-	 */
1173
-	public function userDeletedFromGroup($uid, $gid) {
1174
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1175
-		$provider->userDeletedFromGroup($uid, $gid);
1176
-	}
1177
-
1178
-	/**
1179
-	 * Get access list to a path. This means
1180
-	 * all the users that can access a given path.
1181
-	 *
1182
-	 * Consider:
1183
-	 * -root
1184
-	 * |-folder1 (23)
1185
-	 *  |-folder2 (32)
1186
-	 *   |-fileA (42)
1187
-	 *
1188
-	 * fileA is shared with user1 and user1@server1
1189
-	 * folder2 is shared with group2 (user4 is a member of group2)
1190
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1191
-	 *
1192
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1193
-	 * [
1194
-	 *  users  => [
1195
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1196
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1197
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1198
-	 *  ],
1199
-	 *  remote => [
1200
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1201
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1202
-	 *  ],
1203
-	 *  public => bool
1204
-	 *  mail => bool
1205
-	 * ]
1206
-	 *
1207
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1208
-	 * [
1209
-	 *  users  => ['user1', 'user2', 'user4'],
1210
-	 *  remote => bool,
1211
-	 *  public => bool
1212
-	 *  mail => bool
1213
-	 * ]
1214
-	 *
1215
-	 * This is required for encryption/activity
1216
-	 *
1217
-	 * @param \OCP\Files\Node $path
1218
-	 * @param bool $recursive Should we check all parent folders as well
1219
-	 * @param bool $currentAccess Should the user have currently access to the file
1220
-	 * @return array
1221
-	 */
1222
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1223
-		$owner = $path->getOwner()->getUID();
1224
-
1225
-		if ($currentAccess) {
1226
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1227
-		} else {
1228
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1229
-		}
1230
-		if (!$this->userManager->userExists($owner)) {
1231
-			return $al;
1232
-		}
1233
-
1234
-		//Get node for the owner
1235
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1236
-		if (!$userFolder->isSubNode($path)) {
1237
-			$path = $userFolder->getById($path->getId())[0];
1238
-		}
1239
-
1240
-		$providers = $this->factory->getAllProviders();
1241
-
1242
-		/** @var Node[] $nodes */
1243
-		$nodes = [];
1244
-
1245
-
1246
-		if ($currentAccess) {
1247
-			$ownerPath = $path->getPath();
1248
-			list(, , , $ownerPath) = explode('/', $ownerPath, 4);
1249
-			$al['users'][$owner] = [
1250
-				'node_id' => $path->getId(),
1251
-				'node_path' => '/' . $ownerPath,
1252
-			];
1253
-		} else {
1254
-			$al['users'][] = $owner;
1255
-		}
1256
-
1257
-		// Collect all the shares
1258
-		while ($path->getPath() !== $userFolder->getPath()) {
1259
-			$nodes[] = $path;
1260
-			if (!$recursive) {
1261
-				break;
1262
-			}
1263
-			$path = $path->getParent();
1264
-		}
1265
-
1266
-		foreach ($providers as $provider) {
1267
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1268
-
1269
-			foreach ($tmp as $k => $v) {
1270
-				if (isset($al[$k])) {
1271
-					if (is_array($al[$k])) {
1272
-						$al[$k] = array_merge($al[$k], $v);
1273
-					} else {
1274
-						$al[$k] = $al[$k] || $v;
1275
-					}
1276
-				} else {
1277
-					$al[$k] = $v;
1278
-				}
1279
-			}
1280
-		}
1281
-
1282
-		return $al;
1283
-	}
1284
-
1285
-	/**
1286
-	 * Create a new share
1287
-	 * @return \OCP\Share\IShare;
1288
-	 */
1289
-	public function newShare() {
1290
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1291
-	}
1292
-
1293
-	/**
1294
-	 * Is the share API enabled
1295
-	 *
1296
-	 * @return bool
1297
-	 */
1298
-	public function shareApiEnabled() {
1299
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1300
-	}
1301
-
1302
-	/**
1303
-	 * Is public link sharing enabled
1304
-	 *
1305
-	 * @return bool
1306
-	 */
1307
-	public function shareApiAllowLinks() {
1308
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1309
-	}
1310
-
1311
-	/**
1312
-	 * Is password on public link requires
1313
-	 *
1314
-	 * @return bool
1315
-	 */
1316
-	public function shareApiLinkEnforcePassword() {
1317
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1318
-	}
1319
-
1320
-	/**
1321
-	 * Is default expire date enabled
1322
-	 *
1323
-	 * @return bool
1324
-	 */
1325
-	public function shareApiLinkDefaultExpireDate() {
1326
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1327
-	}
1328
-
1329
-	/**
1330
-	 * Is default expire date enforced
1331
-	 *`
1332
-	 * @return bool
1333
-	 */
1334
-	public function shareApiLinkDefaultExpireDateEnforced() {
1335
-		return $this->shareApiLinkDefaultExpireDate() &&
1336
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1337
-	}
1338
-
1339
-	/**
1340
-	 * Number of default expire days
1341
-	 *shareApiLinkAllowPublicUpload
1342
-	 * @return int
1343
-	 */
1344
-	public function shareApiLinkDefaultExpireDays() {
1345
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1346
-	}
1347
-
1348
-	/**
1349
-	 * Allow public upload on link shares
1350
-	 *
1351
-	 * @return bool
1352
-	 */
1353
-	public function shareApiLinkAllowPublicUpload() {
1354
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1355
-	}
1356
-
1357
-	/**
1358
-	 * check if user can only share with group members
1359
-	 * @return bool
1360
-	 */
1361
-	public function shareWithGroupMembersOnly() {
1362
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1363
-	}
1364
-
1365
-	/**
1366
-	 * Check if users can share with groups
1367
-	 * @return bool
1368
-	 */
1369
-	public function allowGroupSharing() {
1370
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1371
-	}
1372
-
1373
-	/**
1374
-	 * Copied from \OC_Util::isSharingDisabledForUser
1375
-	 *
1376
-	 * TODO: Deprecate fuction from OC_Util
1377
-	 *
1378
-	 * @param string $userId
1379
-	 * @return bool
1380
-	 */
1381
-	public function sharingDisabledForUser($userId) {
1382
-		if ($userId === null) {
1383
-			return false;
1384
-		}
1385
-
1386
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1387
-			return $this->sharingDisabledForUsersCache[$userId];
1388
-		}
1389
-
1390
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1391
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1392
-			$excludedGroups = json_decode($groupsList);
1393
-			if (is_null($excludedGroups)) {
1394
-				$excludedGroups = explode(',', $groupsList);
1395
-				$newValue = json_encode($excludedGroups);
1396
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1397
-			}
1398
-			$user = $this->userManager->get($userId);
1399
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1400
-			if (!empty($usersGroups)) {
1401
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1402
-				// if the user is only in groups which are disabled for sharing then
1403
-				// sharing is also disabled for the user
1404
-				if (empty($remainingGroups)) {
1405
-					$this->sharingDisabledForUsersCache[$userId] = true;
1406
-					return true;
1407
-				}
1408
-			}
1409
-		}
1410
-
1411
-		$this->sharingDisabledForUsersCache[$userId] = false;
1412
-		return false;
1413
-	}
1414
-
1415
-	/**
1416
-	 * @inheritdoc
1417
-	 */
1418
-	public function outgoingServer2ServerSharesAllowed() {
1419
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1420
-	}
1421
-
1422
-	/**
1423
-	 * @inheritdoc
1424
-	 */
1425
-	public function shareProviderExists($shareType) {
1426
-		try {
1427
-			$this->factory->getProviderForType($shareType);
1428
-		} catch (ProviderException $e) {
1429
-			return false;
1430
-		}
1431
-
1432
-		return true;
1433
-	}
1096
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1097
+            !$this->shareApiLinkAllowPublicUpload()) {
1098
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1099
+        }
1100
+
1101
+        return $share;
1102
+    }
1103
+
1104
+    protected function checkExpireDate($share) {
1105
+        if ($share->getExpirationDate() !== null &&
1106
+            $share->getExpirationDate() <= new \DateTime()) {
1107
+            $this->deleteShare($share);
1108
+            throw new ShareNotFound();
1109
+        }
1110
+
1111
+    }
1112
+
1113
+    /**
1114
+     * Verify the password of a public share
1115
+     *
1116
+     * @param \OCP\Share\IShare $share
1117
+     * @param string $password
1118
+     * @return bool
1119
+     */
1120
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1121
+        $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1122
+            || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1123
+        if (!$passwordProtected) {
1124
+            //TODO maybe exception?
1125
+            return false;
1126
+        }
1127
+
1128
+        if ($password === null || $share->getPassword() === null) {
1129
+            return false;
1130
+        }
1131
+
1132
+        $newHash = '';
1133
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1134
+            return false;
1135
+        }
1136
+
1137
+        if (!empty($newHash)) {
1138
+            $share->setPassword($newHash);
1139
+            $provider = $this->factory->getProviderForType($share->getShareType());
1140
+            $provider->update($share);
1141
+        }
1142
+
1143
+        return true;
1144
+    }
1145
+
1146
+    /**
1147
+     * @inheritdoc
1148
+     */
1149
+    public function userDeleted($uid) {
1150
+        $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];
1151
+
1152
+        foreach ($types as $type) {
1153
+            try {
1154
+                $provider = $this->factory->getProviderForType($type);
1155
+            } catch (ProviderException $e) {
1156
+                continue;
1157
+            }
1158
+            $provider->userDeleted($uid, $type);
1159
+        }
1160
+    }
1161
+
1162
+    /**
1163
+     * @inheritdoc
1164
+     */
1165
+    public function groupDeleted($gid) {
1166
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1167
+        $provider->groupDeleted($gid);
1168
+    }
1169
+
1170
+    /**
1171
+     * @inheritdoc
1172
+     */
1173
+    public function userDeletedFromGroup($uid, $gid) {
1174
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1175
+        $provider->userDeletedFromGroup($uid, $gid);
1176
+    }
1177
+
1178
+    /**
1179
+     * Get access list to a path. This means
1180
+     * all the users that can access a given path.
1181
+     *
1182
+     * Consider:
1183
+     * -root
1184
+     * |-folder1 (23)
1185
+     *  |-folder2 (32)
1186
+     *   |-fileA (42)
1187
+     *
1188
+     * fileA is shared with user1 and user1@server1
1189
+     * folder2 is shared with group2 (user4 is a member of group2)
1190
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1191
+     *
1192
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1193
+     * [
1194
+     *  users  => [
1195
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1196
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1197
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1198
+     *  ],
1199
+     *  remote => [
1200
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1201
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1202
+     *  ],
1203
+     *  public => bool
1204
+     *  mail => bool
1205
+     * ]
1206
+     *
1207
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1208
+     * [
1209
+     *  users  => ['user1', 'user2', 'user4'],
1210
+     *  remote => bool,
1211
+     *  public => bool
1212
+     *  mail => bool
1213
+     * ]
1214
+     *
1215
+     * This is required for encryption/activity
1216
+     *
1217
+     * @param \OCP\Files\Node $path
1218
+     * @param bool $recursive Should we check all parent folders as well
1219
+     * @param bool $currentAccess Should the user have currently access to the file
1220
+     * @return array
1221
+     */
1222
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1223
+        $owner = $path->getOwner()->getUID();
1224
+
1225
+        if ($currentAccess) {
1226
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1227
+        } else {
1228
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1229
+        }
1230
+        if (!$this->userManager->userExists($owner)) {
1231
+            return $al;
1232
+        }
1233
+
1234
+        //Get node for the owner
1235
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1236
+        if (!$userFolder->isSubNode($path)) {
1237
+            $path = $userFolder->getById($path->getId())[0];
1238
+        }
1239
+
1240
+        $providers = $this->factory->getAllProviders();
1241
+
1242
+        /** @var Node[] $nodes */
1243
+        $nodes = [];
1244
+
1245
+
1246
+        if ($currentAccess) {
1247
+            $ownerPath = $path->getPath();
1248
+            list(, , , $ownerPath) = explode('/', $ownerPath, 4);
1249
+            $al['users'][$owner] = [
1250
+                'node_id' => $path->getId(),
1251
+                'node_path' => '/' . $ownerPath,
1252
+            ];
1253
+        } else {
1254
+            $al['users'][] = $owner;
1255
+        }
1256
+
1257
+        // Collect all the shares
1258
+        while ($path->getPath() !== $userFolder->getPath()) {
1259
+            $nodes[] = $path;
1260
+            if (!$recursive) {
1261
+                break;
1262
+            }
1263
+            $path = $path->getParent();
1264
+        }
1265
+
1266
+        foreach ($providers as $provider) {
1267
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1268
+
1269
+            foreach ($tmp as $k => $v) {
1270
+                if (isset($al[$k])) {
1271
+                    if (is_array($al[$k])) {
1272
+                        $al[$k] = array_merge($al[$k], $v);
1273
+                    } else {
1274
+                        $al[$k] = $al[$k] || $v;
1275
+                    }
1276
+                } else {
1277
+                    $al[$k] = $v;
1278
+                }
1279
+            }
1280
+        }
1281
+
1282
+        return $al;
1283
+    }
1284
+
1285
+    /**
1286
+     * Create a new share
1287
+     * @return \OCP\Share\IShare;
1288
+     */
1289
+    public function newShare() {
1290
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1291
+    }
1292
+
1293
+    /**
1294
+     * Is the share API enabled
1295
+     *
1296
+     * @return bool
1297
+     */
1298
+    public function shareApiEnabled() {
1299
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1300
+    }
1301
+
1302
+    /**
1303
+     * Is public link sharing enabled
1304
+     *
1305
+     * @return bool
1306
+     */
1307
+    public function shareApiAllowLinks() {
1308
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1309
+    }
1310
+
1311
+    /**
1312
+     * Is password on public link requires
1313
+     *
1314
+     * @return bool
1315
+     */
1316
+    public function shareApiLinkEnforcePassword() {
1317
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1318
+    }
1319
+
1320
+    /**
1321
+     * Is default expire date enabled
1322
+     *
1323
+     * @return bool
1324
+     */
1325
+    public function shareApiLinkDefaultExpireDate() {
1326
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1327
+    }
1328
+
1329
+    /**
1330
+     * Is default expire date enforced
1331
+     *`
1332
+     * @return bool
1333
+     */
1334
+    public function shareApiLinkDefaultExpireDateEnforced() {
1335
+        return $this->shareApiLinkDefaultExpireDate() &&
1336
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1337
+    }
1338
+
1339
+    /**
1340
+     * Number of default expire days
1341
+     *shareApiLinkAllowPublicUpload
1342
+     * @return int
1343
+     */
1344
+    public function shareApiLinkDefaultExpireDays() {
1345
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1346
+    }
1347
+
1348
+    /**
1349
+     * Allow public upload on link shares
1350
+     *
1351
+     * @return bool
1352
+     */
1353
+    public function shareApiLinkAllowPublicUpload() {
1354
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1355
+    }
1356
+
1357
+    /**
1358
+     * check if user can only share with group members
1359
+     * @return bool
1360
+     */
1361
+    public function shareWithGroupMembersOnly() {
1362
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1363
+    }
1364
+
1365
+    /**
1366
+     * Check if users can share with groups
1367
+     * @return bool
1368
+     */
1369
+    public function allowGroupSharing() {
1370
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1371
+    }
1372
+
1373
+    /**
1374
+     * Copied from \OC_Util::isSharingDisabledForUser
1375
+     *
1376
+     * TODO: Deprecate fuction from OC_Util
1377
+     *
1378
+     * @param string $userId
1379
+     * @return bool
1380
+     */
1381
+    public function sharingDisabledForUser($userId) {
1382
+        if ($userId === null) {
1383
+            return false;
1384
+        }
1385
+
1386
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1387
+            return $this->sharingDisabledForUsersCache[$userId];
1388
+        }
1389
+
1390
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1391
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1392
+            $excludedGroups = json_decode($groupsList);
1393
+            if (is_null($excludedGroups)) {
1394
+                $excludedGroups = explode(',', $groupsList);
1395
+                $newValue = json_encode($excludedGroups);
1396
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1397
+            }
1398
+            $user = $this->userManager->get($userId);
1399
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1400
+            if (!empty($usersGroups)) {
1401
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1402
+                // if the user is only in groups which are disabled for sharing then
1403
+                // sharing is also disabled for the user
1404
+                if (empty($remainingGroups)) {
1405
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1406
+                    return true;
1407
+                }
1408
+            }
1409
+        }
1410
+
1411
+        $this->sharingDisabledForUsersCache[$userId] = false;
1412
+        return false;
1413
+    }
1414
+
1415
+    /**
1416
+     * @inheritdoc
1417
+     */
1418
+    public function outgoingServer2ServerSharesAllowed() {
1419
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1420
+    }
1421
+
1422
+    /**
1423
+     * @inheritdoc
1424
+     */
1425
+    public function shareProviderExists($shareType) {
1426
+        try {
1427
+            $this->factory->getProviderForType($shareType);
1428
+        } catch (ProviderException $e) {
1429
+            return false;
1430
+        }
1431
+
1432
+        return true;
1433
+    }
1434 1434
 
1435 1435
 }
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
 
322 322
 		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
323 323
 			$expirationDate = new \DateTime();
324
-			$expirationDate->setTime(0,0,0);
324
+			$expirationDate->setTime(0, 0, 0);
325 325
 			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
326 326
 		}
327 327
 
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 
334 334
 			$date = new \DateTime();
335 335
 			$date->setTime(0, 0, 0);
336
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
336
+			$date->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
337 337
 			if ($date < $expirationDate) {
338 338
 				$message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
339 339
 				throw new GenericShareException($message, $message, 404);
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
 		 */
387 387
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
388 388
 		$existingShares = $provider->getSharesByPath($share->getNode());
389
-		foreach($existingShares as $existingShare) {
389
+		foreach ($existingShares as $existingShare) {
390 390
 			// Ignore if it is the same share
391 391
 			try {
392 392
 				if ($existingShare->getFullId() === $share->getFullId()) {
@@ -443,7 +443,7 @@  discard block
 block discarded – undo
443 443
 		 */
444 444
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
445 445
 		$existingShares = $provider->getSharesByPath($share->getNode());
446
-		foreach($existingShares as $existingShare) {
446
+		foreach ($existingShares as $existingShare) {
447 447
 			try {
448 448
 				if ($existingShare->getFullId() === $share->getFullId()) {
449 449
 					continue;
@@ -512,7 +512,7 @@  discard block
 block discarded – undo
512 512
 		// Make sure that we do not share a path that contains a shared mountpoint
513 513
 		if ($path instanceof \OCP\Files\Folder) {
514 514
 			$mounts = $this->mountManager->findIn($path->getPath());
515
-			foreach($mounts as $mount) {
515
+			foreach ($mounts as $mount) {
516 516
 				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
517 517
 					throw new \InvalidArgumentException('Path contains files shared with you');
518 518
 				}
@@ -560,7 +560,7 @@  discard block
 block discarded – undo
560 560
 		$storage = $share->getNode()->getStorage();
561 561
 		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
562 562
 			$parent = $share->getNode()->getParent();
563
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
563
+			while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
564 564
 				$parent = $parent->getParent();
565 565
 			}
566 566
 			$share->setShareOwner($parent->getOwner()->getUID());
@@ -617,7 +617,7 @@  discard block
 block discarded – undo
617 617
 		}
618 618
 
619 619
 		// Generate the target
620
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
620
+		$target = $this->config->getSystemValue('share_folder', '/').'/'.$share->getNode()->getName();
621 621
 		$target = \OC\Files\Filesystem::normalizePath($target);
622 622
 		$share->setTarget($target);
623 623
 
@@ -864,7 +864,7 @@  discard block
 block discarded – undo
864 864
 	 * @param string $recipientId
865 865
 	 */
866 866
 	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
867
-		list($providerId, ) = $this->splitFullId($share->getFullId());
867
+		list($providerId,) = $this->splitFullId($share->getFullId());
868 868
 		$provider = $this->factory->getProvider($providerId);
869 869
 
870 870
 		$provider->deleteFromSelf($share, $recipientId);
@@ -885,7 +885,7 @@  discard block
 block discarded – undo
885 885
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
886 886
 			$sharedWith = $this->groupManager->get($share->getSharedWith());
887 887
 			if (is_null($sharedWith)) {
888
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
888
+				throw new \InvalidArgumentException('Group "'.$share->getSharedWith().'" does not exist');
889 889
 			}
890 890
 			$recipient = $this->userManager->get($recipientId);
891 891
 			if (!$sharedWith->inGroup($recipient)) {
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
 			}
894 894
 		}
895 895
 
896
-		list($providerId, ) = $this->splitFullId($share->getFullId());
896
+		list($providerId,) = $this->splitFullId($share->getFullId());
897 897
 		$provider = $this->factory->getProvider($providerId);
898 898
 
899 899
 		$provider->move($share, $recipientId);
@@ -940,7 +940,7 @@  discard block
 block discarded – undo
940 940
 
941 941
 		$shares2 = [];
942 942
 
943
-		while(true) {
943
+		while (true) {
944 944
 			$added = 0;
945 945
 			foreach ($shares as $share) {
946 946
 
@@ -1040,7 +1040,7 @@  discard block
 block discarded – undo
1040 1040
 	 *
1041 1041
 	 * @return Share[]
1042 1042
 	 */
1043
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1043
+	public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) {
1044 1044
 		return [];
1045 1045
 	}
1046 1046
 
@@ -1055,7 +1055,7 @@  discard block
 block discarded – undo
1055 1055
 	public function getShareByToken($token) {
1056 1056
 		$share = null;
1057 1057
 		try {
1058
-			if($this->shareApiAllowLinks()) {
1058
+			if ($this->shareApiAllowLinks()) {
1059 1059
 				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1060 1060
 				$share = $provider->getShareByToken($token);
1061 1061
 			}
@@ -1245,10 +1245,10 @@  discard block
 block discarded – undo
1245 1245
 
1246 1246
 		if ($currentAccess) {
1247 1247
 			$ownerPath = $path->getPath();
1248
-			list(, , , $ownerPath) = explode('/', $ownerPath, 4);
1248
+			list(,,, $ownerPath) = explode('/', $ownerPath, 4);
1249 1249
 			$al['users'][$owner] = [
1250 1250
 				'node_id' => $path->getId(),
1251
-				'node_path' => '/' . $ownerPath,
1251
+				'node_path' => '/'.$ownerPath,
1252 1252
 			];
1253 1253
 		} else {
1254 1254
 			$al['users'][] = $owner;
@@ -1342,7 +1342,7 @@  discard block
 block discarded – undo
1342 1342
 	 * @return int
1343 1343
 	 */
1344 1344
 	public function shareApiLinkDefaultExpireDays() {
1345
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1345
+		return (int) $this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1346 1346
 	}
1347 1347
 
1348 1348
 	/**
Please login to merge, or discard this patch.
lib/public/Share/IShareHelper.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -32,10 +32,10 @@
 block discarded – undo
32 32
  */
33 33
 interface IShareHelper {
34 34
 
35
-	/**
36
-	 * @param Node $node
37
-	 * @return array [ users => [Mapping $uid => $pathForUser], remotes => [Mapping $cloudId => $pathToMountRoot]]
38
-	 * @since 12
39
-	 */
40
-	public function getPathsForAccessList(Node $node);
35
+    /**
36
+     * @param Node $node
37
+     * @return array [ users => [Mapping $uid => $pathForUser], remotes => [Mapping $cloudId => $pathToMountRoot]]
38
+     * @since 12
39
+     */
40
+    public function getPathsForAccessList(Node $node);
41 41
 }
Please login to merge, or discard this patch.
lib/private/Encryption/File.php 1 patch
Indentation   +90 added lines, -90 removed lines patch added patch discarded remove patch
@@ -31,95 +31,95 @@
 block discarded – undo
31 31
 
32 32
 class File implements \OCP\Encryption\IFile {
33 33
 
34
-	/** @var Util */
35
-	protected $util;
36
-
37
-	/** @var IRootFolder */
38
-	private $rootFolder;
39
-
40
-	/** @var IManager */
41
-	private $shareManager;
42
-
43
-	/**
44
-	 * cache results of already checked folders
45
-	 *
46
-	 * @var array
47
-	 */
48
-	protected $cache;
49
-
50
-	public function __construct(Util $util,
51
-								IRootFolder $rootFolder,
52
-								IManager $shareManager) {
53
-		$this->util = $util;
54
-		$this->cache = new CappedMemoryCache();
55
-		$this->rootFolder = $rootFolder;
56
-		$this->shareManager = $shareManager;
57
-	}
58
-
59
-
60
-	/**
61
-	 * get list of users with access to the file
62
-	 *
63
-	 * @param string $path to the file
64
-	 * @return array  ['users' => $uniqueUserIds, 'public' => $public]
65
-	 */
66
-	public function getAccessList($path) {
67
-
68
-		// Make sure that a share key is generated for the owner too
69
-		list($owner, $ownerPath) = $this->util->getUidAndFilename($path);
70
-
71
-		// always add owner to the list of users with access to the file
72
-		$userIds = array($owner);
73
-
74
-		if (!$this->util->isFile($owner . '/' . $ownerPath)) {
75
-			return array('users' => $userIds, 'public' => false);
76
-		}
77
-
78
-		$ownerPath = substr($ownerPath, strlen('/files'));
79
-		$userFolder = $this->rootFolder->getUserFolder($owner);
80
-		try {
81
-			$file = $userFolder->get($ownerPath);
82
-		} catch (NotFoundException $e) {
83
-			$file = null;
84
-		}
85
-		$ownerPath = $this->util->stripPartialFileExtension($ownerPath);
86
-
87
-		// first get the shares for the parent and cache the result so that we don't
88
-		// need to check all parents for every file
89
-		$parent = dirname($ownerPath);
90
-		$parentNode = $userFolder->get($parent);
91
-		if (isset($this->cache[$parent])) {
92
-			$resultForParents = $this->cache[$parent];
93
-		} else {
94
-			$resultForParents = $this->shareManager->getAccessList($parentNode);
95
-			$this->cache[$parent] = $resultForParents;
96
-		}
97
-		$userIds = array_merge($userIds, $resultForParents['users']);
98
-		$public = $resultForParents['public'] || $resultForParents['remote'];
99
-
100
-
101
-		// Find out who, if anyone, is sharing the file
102
-		if ($file !== null) {
103
-			$resultForFile = $this->shareManager->getAccessList($file, false);
104
-			$userIds = array_merge($userIds, $resultForFile['users']);
105
-			$public = $resultForFile['public'] || $resultForFile['remote'] || $public;
106
-		}
107
-
108
-		// check if it is a group mount
109
-		if (\OCP\App::isEnabled("files_external")) {
110
-			$mounts = \OC_Mount_Config::getSystemMountPoints();
111
-			foreach ($mounts as $mount) {
112
-				if ($mount['mountpoint'] == substr($ownerPath, 1, strlen($mount['mountpoint']))) {
113
-					$mountedFor = $this->util->getUserWithAccessToMountPoint($mount['applicable']['users'], $mount['applicable']['groups']);
114
-					$userIds = array_merge($userIds, $mountedFor);
115
-				}
116
-			}
117
-		}
118
-
119
-		// Remove duplicate UIDs
120
-		$uniqueUserIds = array_unique($userIds);
121
-
122
-		return array('users' => $uniqueUserIds, 'public' => $public);
123
-	}
34
+    /** @var Util */
35
+    protected $util;
36
+
37
+    /** @var IRootFolder */
38
+    private $rootFolder;
39
+
40
+    /** @var IManager */
41
+    private $shareManager;
42
+
43
+    /**
44
+     * cache results of already checked folders
45
+     *
46
+     * @var array
47
+     */
48
+    protected $cache;
49
+
50
+    public function __construct(Util $util,
51
+                                IRootFolder $rootFolder,
52
+                                IManager $shareManager) {
53
+        $this->util = $util;
54
+        $this->cache = new CappedMemoryCache();
55
+        $this->rootFolder = $rootFolder;
56
+        $this->shareManager = $shareManager;
57
+    }
58
+
59
+
60
+    /**
61
+     * get list of users with access to the file
62
+     *
63
+     * @param string $path to the file
64
+     * @return array  ['users' => $uniqueUserIds, 'public' => $public]
65
+     */
66
+    public function getAccessList($path) {
67
+
68
+        // Make sure that a share key is generated for the owner too
69
+        list($owner, $ownerPath) = $this->util->getUidAndFilename($path);
70
+
71
+        // always add owner to the list of users with access to the file
72
+        $userIds = array($owner);
73
+
74
+        if (!$this->util->isFile($owner . '/' . $ownerPath)) {
75
+            return array('users' => $userIds, 'public' => false);
76
+        }
77
+
78
+        $ownerPath = substr($ownerPath, strlen('/files'));
79
+        $userFolder = $this->rootFolder->getUserFolder($owner);
80
+        try {
81
+            $file = $userFolder->get($ownerPath);
82
+        } catch (NotFoundException $e) {
83
+            $file = null;
84
+        }
85
+        $ownerPath = $this->util->stripPartialFileExtension($ownerPath);
86
+
87
+        // first get the shares for the parent and cache the result so that we don't
88
+        // need to check all parents for every file
89
+        $parent = dirname($ownerPath);
90
+        $parentNode = $userFolder->get($parent);
91
+        if (isset($this->cache[$parent])) {
92
+            $resultForParents = $this->cache[$parent];
93
+        } else {
94
+            $resultForParents = $this->shareManager->getAccessList($parentNode);
95
+            $this->cache[$parent] = $resultForParents;
96
+        }
97
+        $userIds = array_merge($userIds, $resultForParents['users']);
98
+        $public = $resultForParents['public'] || $resultForParents['remote'];
99
+
100
+
101
+        // Find out who, if anyone, is sharing the file
102
+        if ($file !== null) {
103
+            $resultForFile = $this->shareManager->getAccessList($file, false);
104
+            $userIds = array_merge($userIds, $resultForFile['users']);
105
+            $public = $resultForFile['public'] || $resultForFile['remote'] || $public;
106
+        }
107
+
108
+        // check if it is a group mount
109
+        if (\OCP\App::isEnabled("files_external")) {
110
+            $mounts = \OC_Mount_Config::getSystemMountPoints();
111
+            foreach ($mounts as $mount) {
112
+                if ($mount['mountpoint'] == substr($ownerPath, 1, strlen($mount['mountpoint']))) {
113
+                    $mountedFor = $this->util->getUserWithAccessToMountPoint($mount['applicable']['users'], $mount['applicable']['groups']);
114
+                    $userIds = array_merge($userIds, $mountedFor);
115
+                }
116
+            }
117
+        }
118
+
119
+        // Remove duplicate UIDs
120
+        $uniqueUserIds = array_unique($userIds);
121
+
122
+        return array('users' => $uniqueUserIds, 'public' => $public);
123
+    }
124 124
 
125 125
 }
Please login to merge, or discard this patch.
lib/private/Share20/DefaultShareProvider.php 2 patches
Indentation   +1101 added lines, -1101 removed lines patch added patch discarded remove patch
@@ -47,1138 +47,1138 @@
 block discarded – undo
47 47
  */
48 48
 class DefaultShareProvider implements IShareProvider {
49 49
 
50
-	// Special share type for user modified group shares
51
-	const SHARE_TYPE_USERGROUP = 2;
52
-
53
-	/** @var IDBConnection */
54
-	private $dbConn;
55
-
56
-	/** @var IUserManager */
57
-	private $userManager;
58
-
59
-	/** @var IGroupManager */
60
-	private $groupManager;
61
-
62
-	/** @var IRootFolder */
63
-	private $rootFolder;
64
-
65
-	/**
66
-	 * DefaultShareProvider constructor.
67
-	 *
68
-	 * @param IDBConnection $connection
69
-	 * @param IUserManager $userManager
70
-	 * @param IGroupManager $groupManager
71
-	 * @param IRootFolder $rootFolder
72
-	 */
73
-	public function __construct(
74
-			IDBConnection $connection,
75
-			IUserManager $userManager,
76
-			IGroupManager $groupManager,
77
-			IRootFolder $rootFolder) {
78
-		$this->dbConn = $connection;
79
-		$this->userManager = $userManager;
80
-		$this->groupManager = $groupManager;
81
-		$this->rootFolder = $rootFolder;
82
-	}
83
-
84
-	/**
85
-	 * Return the identifier of this provider.
86
-	 *
87
-	 * @return string Containing only [a-zA-Z0-9]
88
-	 */
89
-	public function identifier() {
90
-		return 'ocinternal';
91
-	}
92
-
93
-	/**
94
-	 * Share a path
95
-	 *
96
-	 * @param \OCP\Share\IShare $share
97
-	 * @return \OCP\Share\IShare The share object
98
-	 * @throws ShareNotFound
99
-	 * @throws \Exception
100
-	 */
101
-	public function create(\OCP\Share\IShare $share) {
102
-		$qb = $this->dbConn->getQueryBuilder();
103
-
104
-		$qb->insert('share');
105
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
-
107
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
-			//Set the UID of the user we share with
109
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
-			//Set the GID of the group we share with
112
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
-			//Set the token of the share
115
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
-
117
-			//If a password is set store it
118
-			if ($share->getPassword() !== null) {
119
-				$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
120
-			}
121
-
122
-			//If an expiration date is set store it
123
-			if ($share->getExpirationDate() !== null) {
124
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
-			}
126
-
127
-			if (method_exists($share, 'getParent')) {
128
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
-			}
130
-		} else {
131
-			throw new \Exception('invalid share type!');
132
-		}
133
-
134
-		// Set what is shares
135
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
136
-		if ($share->getNode() instanceof \OCP\Files\File) {
137
-			$qb->setParameter('itemType', 'file');
138
-		} else {
139
-			$qb->setParameter('itemType', 'folder');
140
-		}
141
-
142
-		// Set the file id
143
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
-
146
-		// set the permissions
147
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
-
149
-		// Set who created this share
150
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
-
152
-		// Set who is the owner of this file/folder (and this the owner of the share)
153
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
-
155
-		// Set the file target
156
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
-
158
-		// Set the time this share was created
159
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
160
-
161
-		// insert the data and fetch the id of the share
162
-		$this->dbConn->beginTransaction();
163
-		$qb->execute();
164
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
165
-
166
-		// Now fetch the inserted share and create a complete share object
167
-		$qb = $this->dbConn->getQueryBuilder();
168
-		$qb->select('*')
169
-			->from('share')
170
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
-
172
-		$cursor = $qb->execute();
173
-		$data = $cursor->fetch();
174
-		$this->dbConn->commit();
175
-		$cursor->closeCursor();
176
-
177
-		if ($data === false) {
178
-			throw new ShareNotFound();
179
-		}
180
-
181
-		$share = $this->createShare($data);
182
-		return $share;
183
-	}
184
-
185
-	/**
186
-	 * Update a share
187
-	 *
188
-	 * @param \OCP\Share\IShare $share
189
-	 * @return \OCP\Share\IShare The share object
190
-	 */
191
-	public function update(\OCP\Share\IShare $share) {
192
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
-			/*
50
+    // Special share type for user modified group shares
51
+    const SHARE_TYPE_USERGROUP = 2;
52
+
53
+    /** @var IDBConnection */
54
+    private $dbConn;
55
+
56
+    /** @var IUserManager */
57
+    private $userManager;
58
+
59
+    /** @var IGroupManager */
60
+    private $groupManager;
61
+
62
+    /** @var IRootFolder */
63
+    private $rootFolder;
64
+
65
+    /**
66
+     * DefaultShareProvider constructor.
67
+     *
68
+     * @param IDBConnection $connection
69
+     * @param IUserManager $userManager
70
+     * @param IGroupManager $groupManager
71
+     * @param IRootFolder $rootFolder
72
+     */
73
+    public function __construct(
74
+            IDBConnection $connection,
75
+            IUserManager $userManager,
76
+            IGroupManager $groupManager,
77
+            IRootFolder $rootFolder) {
78
+        $this->dbConn = $connection;
79
+        $this->userManager = $userManager;
80
+        $this->groupManager = $groupManager;
81
+        $this->rootFolder = $rootFolder;
82
+    }
83
+
84
+    /**
85
+     * Return the identifier of this provider.
86
+     *
87
+     * @return string Containing only [a-zA-Z0-9]
88
+     */
89
+    public function identifier() {
90
+        return 'ocinternal';
91
+    }
92
+
93
+    /**
94
+     * Share a path
95
+     *
96
+     * @param \OCP\Share\IShare $share
97
+     * @return \OCP\Share\IShare The share object
98
+     * @throws ShareNotFound
99
+     * @throws \Exception
100
+     */
101
+    public function create(\OCP\Share\IShare $share) {
102
+        $qb = $this->dbConn->getQueryBuilder();
103
+
104
+        $qb->insert('share');
105
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
+
107
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
+            //Set the UID of the user we share with
109
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
+            //Set the GID of the group we share with
112
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
+            //Set the token of the share
115
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
+
117
+            //If a password is set store it
118
+            if ($share->getPassword() !== null) {
119
+                $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
120
+            }
121
+
122
+            //If an expiration date is set store it
123
+            if ($share->getExpirationDate() !== null) {
124
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
+            }
126
+
127
+            if (method_exists($share, 'getParent')) {
128
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
+            }
130
+        } else {
131
+            throw new \Exception('invalid share type!');
132
+        }
133
+
134
+        // Set what is shares
135
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
136
+        if ($share->getNode() instanceof \OCP\Files\File) {
137
+            $qb->setParameter('itemType', 'file');
138
+        } else {
139
+            $qb->setParameter('itemType', 'folder');
140
+        }
141
+
142
+        // Set the file id
143
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
+
146
+        // set the permissions
147
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
+
149
+        // Set who created this share
150
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
+
152
+        // Set who is the owner of this file/folder (and this the owner of the share)
153
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
+
155
+        // Set the file target
156
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
+
158
+        // Set the time this share was created
159
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
160
+
161
+        // insert the data and fetch the id of the share
162
+        $this->dbConn->beginTransaction();
163
+        $qb->execute();
164
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
165
+
166
+        // Now fetch the inserted share and create a complete share object
167
+        $qb = $this->dbConn->getQueryBuilder();
168
+        $qb->select('*')
169
+            ->from('share')
170
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
+
172
+        $cursor = $qb->execute();
173
+        $data = $cursor->fetch();
174
+        $this->dbConn->commit();
175
+        $cursor->closeCursor();
176
+
177
+        if ($data === false) {
178
+            throw new ShareNotFound();
179
+        }
180
+
181
+        $share = $this->createShare($data);
182
+        return $share;
183
+    }
184
+
185
+    /**
186
+     * Update a share
187
+     *
188
+     * @param \OCP\Share\IShare $share
189
+     * @return \OCP\Share\IShare The share object
190
+     */
191
+    public function update(\OCP\Share\IShare $share) {
192
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
+            /*
194 194
 			 * We allow updating the recipient on user shares.
195 195
 			 */
196
-			$qb = $this->dbConn->getQueryBuilder();
197
-			$qb->update('share')
198
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
206
-				->execute();
207
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
208
-			$qb = $this->dbConn->getQueryBuilder();
209
-			$qb->update('share')
210
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
211
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
212
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
213
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
214
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
215
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
216
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
217
-				->execute();
218
-
219
-			/*
196
+            $qb = $this->dbConn->getQueryBuilder();
197
+            $qb->update('share')
198
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
206
+                ->execute();
207
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
208
+            $qb = $this->dbConn->getQueryBuilder();
209
+            $qb->update('share')
210
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
211
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
212
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
213
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
214
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
215
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
216
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
217
+                ->execute();
218
+
219
+            /*
220 220
 			 * Update all user defined group shares
221 221
 			 */
222
-			$qb = $this->dbConn->getQueryBuilder();
223
-			$qb->update('share')
224
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
225
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
226
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
227
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
228
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
229
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
230
-				->execute();
231
-
232
-			/*
222
+            $qb = $this->dbConn->getQueryBuilder();
223
+            $qb->update('share')
224
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
225
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
226
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
227
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
228
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
229
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
230
+                ->execute();
231
+
232
+            /*
233 233
 			 * Now update the permissions for all children that have not set it to 0
234 234
 			 */
235
-			$qb = $this->dbConn->getQueryBuilder();
236
-			$qb->update('share')
237
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
238
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
239
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
240
-				->execute();
241
-
242
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
243
-			$qb = $this->dbConn->getQueryBuilder();
244
-			$qb->update('share')
245
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
246
-				->set('password', $qb->createNamedParameter($share->getPassword()))
247
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
248
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
249
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
250
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
251
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
252
-				->set('token', $qb->createNamedParameter($share->getToken()))
253
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
254
-				->execute();
255
-		}
256
-
257
-		return $share;
258
-	}
259
-
260
-	/**
261
-	 * Get all children of this share
262
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
263
-	 *
264
-	 * @param \OCP\Share\IShare $parent
265
-	 * @return \OCP\Share\IShare[]
266
-	 */
267
-	public function getChildren(\OCP\Share\IShare $parent) {
268
-		$children = [];
269
-
270
-		$qb = $this->dbConn->getQueryBuilder();
271
-		$qb->select('*')
272
-			->from('share')
273
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
274
-			->andWhere(
275
-				$qb->expr()->in(
276
-					'share_type',
277
-					$qb->createNamedParameter([
278
-						\OCP\Share::SHARE_TYPE_USER,
279
-						\OCP\Share::SHARE_TYPE_GROUP,
280
-						\OCP\Share::SHARE_TYPE_LINK,
281
-					], IQueryBuilder::PARAM_INT_ARRAY)
282
-				)
283
-			)
284
-			->andWhere($qb->expr()->orX(
285
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
286
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
287
-			))
288
-			->orderBy('id');
289
-
290
-		$cursor = $qb->execute();
291
-		while($data = $cursor->fetch()) {
292
-			$children[] = $this->createShare($data);
293
-		}
294
-		$cursor->closeCursor();
295
-
296
-		return $children;
297
-	}
298
-
299
-	/**
300
-	 * Delete a share
301
-	 *
302
-	 * @param \OCP\Share\IShare $share
303
-	 */
304
-	public function delete(\OCP\Share\IShare $share) {
305
-		$qb = $this->dbConn->getQueryBuilder();
306
-		$qb->delete('share')
307
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
308
-
309
-		/*
235
+            $qb = $this->dbConn->getQueryBuilder();
236
+            $qb->update('share')
237
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
238
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
239
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
240
+                ->execute();
241
+
242
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
243
+            $qb = $this->dbConn->getQueryBuilder();
244
+            $qb->update('share')
245
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
246
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
247
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
248
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
249
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
250
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
251
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
252
+                ->set('token', $qb->createNamedParameter($share->getToken()))
253
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
254
+                ->execute();
255
+        }
256
+
257
+        return $share;
258
+    }
259
+
260
+    /**
261
+     * Get all children of this share
262
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
263
+     *
264
+     * @param \OCP\Share\IShare $parent
265
+     * @return \OCP\Share\IShare[]
266
+     */
267
+    public function getChildren(\OCP\Share\IShare $parent) {
268
+        $children = [];
269
+
270
+        $qb = $this->dbConn->getQueryBuilder();
271
+        $qb->select('*')
272
+            ->from('share')
273
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
274
+            ->andWhere(
275
+                $qb->expr()->in(
276
+                    'share_type',
277
+                    $qb->createNamedParameter([
278
+                        \OCP\Share::SHARE_TYPE_USER,
279
+                        \OCP\Share::SHARE_TYPE_GROUP,
280
+                        \OCP\Share::SHARE_TYPE_LINK,
281
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
282
+                )
283
+            )
284
+            ->andWhere($qb->expr()->orX(
285
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
286
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
287
+            ))
288
+            ->orderBy('id');
289
+
290
+        $cursor = $qb->execute();
291
+        while($data = $cursor->fetch()) {
292
+            $children[] = $this->createShare($data);
293
+        }
294
+        $cursor->closeCursor();
295
+
296
+        return $children;
297
+    }
298
+
299
+    /**
300
+     * Delete a share
301
+     *
302
+     * @param \OCP\Share\IShare $share
303
+     */
304
+    public function delete(\OCP\Share\IShare $share) {
305
+        $qb = $this->dbConn->getQueryBuilder();
306
+        $qb->delete('share')
307
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
308
+
309
+        /*
310 310
 		 * If the share is a group share delete all possible
311 311
 		 * user defined groups shares.
312 312
 		 */
313
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
314
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
315
-		}
316
-
317
-		$qb->execute();
318
-	}
319
-
320
-	/**
321
-	 * Unshare a share from the recipient. If this is a group share
322
-	 * this means we need a special entry in the share db.
323
-	 *
324
-	 * @param \OCP\Share\IShare $share
325
-	 * @param string $recipient UserId of recipient
326
-	 * @throws BackendError
327
-	 * @throws ProviderException
328
-	 */
329
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
330
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
331
-
332
-			$group = $this->groupManager->get($share->getSharedWith());
333
-			$user = $this->userManager->get($recipient);
334
-
335
-			if (is_null($group)) {
336
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
337
-			}
338
-
339
-			if (!$group->inGroup($user)) {
340
-				throw new ProviderException('Recipient not in receiving group');
341
-			}
342
-
343
-			// Try to fetch user specific share
344
-			$qb = $this->dbConn->getQueryBuilder();
345
-			$stmt = $qb->select('*')
346
-				->from('share')
347
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
348
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
349
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
350
-				->andWhere($qb->expr()->orX(
351
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
352
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
353
-				))
354
-				->execute();
355
-
356
-			$data = $stmt->fetch();
357
-
358
-			/*
313
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
314
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
315
+        }
316
+
317
+        $qb->execute();
318
+    }
319
+
320
+    /**
321
+     * Unshare a share from the recipient. If this is a group share
322
+     * this means we need a special entry in the share db.
323
+     *
324
+     * @param \OCP\Share\IShare $share
325
+     * @param string $recipient UserId of recipient
326
+     * @throws BackendError
327
+     * @throws ProviderException
328
+     */
329
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
330
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
331
+
332
+            $group = $this->groupManager->get($share->getSharedWith());
333
+            $user = $this->userManager->get($recipient);
334
+
335
+            if (is_null($group)) {
336
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
337
+            }
338
+
339
+            if (!$group->inGroup($user)) {
340
+                throw new ProviderException('Recipient not in receiving group');
341
+            }
342
+
343
+            // Try to fetch user specific share
344
+            $qb = $this->dbConn->getQueryBuilder();
345
+            $stmt = $qb->select('*')
346
+                ->from('share')
347
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
348
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
349
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
350
+                ->andWhere($qb->expr()->orX(
351
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
352
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
353
+                ))
354
+                ->execute();
355
+
356
+            $data = $stmt->fetch();
357
+
358
+            /*
359 359
 			 * Check if there already is a user specific group share.
360 360
 			 * If there is update it (if required).
361 361
 			 */
362
-			if ($data === false) {
363
-				$qb = $this->dbConn->getQueryBuilder();
364
-
365
-				$type = $share->getNodeType();
366
-
367
-				//Insert new share
368
-				$qb->insert('share')
369
-					->values([
370
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
371
-						'share_with' => $qb->createNamedParameter($recipient),
372
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
373
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
374
-						'parent' => $qb->createNamedParameter($share->getId()),
375
-						'item_type' => $qb->createNamedParameter($type),
376
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
377
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
378
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
379
-						'permissions' => $qb->createNamedParameter(0),
380
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
381
-					])->execute();
382
-
383
-			} else if ($data['permissions'] !== 0) {
384
-
385
-				// Update existing usergroup share
386
-				$qb = $this->dbConn->getQueryBuilder();
387
-				$qb->update('share')
388
-					->set('permissions', $qb->createNamedParameter(0))
389
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
390
-					->execute();
391
-			}
392
-
393
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
394
-
395
-			if ($share->getSharedWith() !== $recipient) {
396
-				throw new ProviderException('Recipient does not match');
397
-			}
398
-
399
-			// We can just delete user and link shares
400
-			$this->delete($share);
401
-		} else {
402
-			throw new ProviderException('Invalid shareType');
403
-		}
404
-	}
405
-
406
-	/**
407
-	 * @inheritdoc
408
-	 */
409
-	public function move(\OCP\Share\IShare $share, $recipient) {
410
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
411
-			// Just update the target
412
-			$qb = $this->dbConn->getQueryBuilder();
413
-			$qb->update('share')
414
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
415
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
416
-				->execute();
417
-
418
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
419
-
420
-			// Check if there is a usergroup share
421
-			$qb = $this->dbConn->getQueryBuilder();
422
-			$stmt = $qb->select('id')
423
-				->from('share')
424
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
425
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
426
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
427
-				->andWhere($qb->expr()->orX(
428
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
429
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
430
-				))
431
-				->setMaxResults(1)
432
-				->execute();
433
-
434
-			$data = $stmt->fetch();
435
-			$stmt->closeCursor();
436
-
437
-			if ($data === false) {
438
-				// No usergroup share yet. Create one.
439
-				$qb = $this->dbConn->getQueryBuilder();
440
-				$qb->insert('share')
441
-					->values([
442
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
443
-						'share_with' => $qb->createNamedParameter($recipient),
444
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
445
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
446
-						'parent' => $qb->createNamedParameter($share->getId()),
447
-						'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
448
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
449
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
450
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
451
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
452
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
453
-					])->execute();
454
-			} else {
455
-				// Already a usergroup share. Update it.
456
-				$qb = $this->dbConn->getQueryBuilder();
457
-				$qb->update('share')
458
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
459
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
460
-					->execute();
461
-			}
462
-		}
463
-
464
-		return $share;
465
-	}
466
-
467
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
468
-		$qb = $this->dbConn->getQueryBuilder();
469
-		$qb->select('*')
470
-			->from('share', 's')
471
-			->andWhere($qb->expr()->orX(
472
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
473
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
474
-			));
475
-
476
-		$qb->andWhere($qb->expr()->orX(
477
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
478
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
479
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
480
-		));
481
-
482
-		/**
483
-		 * Reshares for this user are shares where they are the owner.
484
-		 */
485
-		if ($reshares === false) {
486
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
487
-		} else {
488
-			$qb->andWhere(
489
-				$qb->expr()->orX(
490
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
491
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
492
-				)
493
-			);
494
-		}
495
-
496
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
497
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498
-
499
-		$qb->orderBy('id');
500
-
501
-		$cursor = $qb->execute();
502
-		$shares = [];
503
-		while ($data = $cursor->fetch()) {
504
-			$shares[$data['fileid']][] = $this->createShare($data);
505
-		}
506
-		$cursor->closeCursor();
507
-
508
-		return $shares;
509
-	}
510
-
511
-	/**
512
-	 * @inheritdoc
513
-	 */
514
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
515
-		$qb = $this->dbConn->getQueryBuilder();
516
-		$qb->select('*')
517
-			->from('share')
518
-			->andWhere($qb->expr()->orX(
519
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
520
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
521
-			));
522
-
523
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
524
-
525
-		/**
526
-		 * Reshares for this user are shares where they are the owner.
527
-		 */
528
-		if ($reshares === false) {
529
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
530
-		} else {
531
-			$qb->andWhere(
532
-				$qb->expr()->orX(
533
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
534
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
535
-				)
536
-			);
537
-		}
538
-
539
-		if ($node !== null) {
540
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
541
-		}
542
-
543
-		if ($limit !== -1) {
544
-			$qb->setMaxResults($limit);
545
-		}
546
-
547
-		$qb->setFirstResult($offset);
548
-		$qb->orderBy('id');
549
-
550
-		$cursor = $qb->execute();
551
-		$shares = [];
552
-		while($data = $cursor->fetch()) {
553
-			$shares[] = $this->createShare($data);
554
-		}
555
-		$cursor->closeCursor();
556
-
557
-		return $shares;
558
-	}
559
-
560
-	/**
561
-	 * @inheritdoc
562
-	 */
563
-	public function getShareById($id, $recipientId = null) {
564
-		$qb = $this->dbConn->getQueryBuilder();
565
-
566
-		$qb->select('*')
567
-			->from('share')
568
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
569
-			->andWhere(
570
-				$qb->expr()->in(
571
-					'share_type',
572
-					$qb->createNamedParameter([
573
-						\OCP\Share::SHARE_TYPE_USER,
574
-						\OCP\Share::SHARE_TYPE_GROUP,
575
-						\OCP\Share::SHARE_TYPE_LINK,
576
-					], IQueryBuilder::PARAM_INT_ARRAY)
577
-				)
578
-			)
579
-			->andWhere($qb->expr()->orX(
580
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
581
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
582
-			));
583
-
584
-		$cursor = $qb->execute();
585
-		$data = $cursor->fetch();
586
-		$cursor->closeCursor();
587
-
588
-		if ($data === false) {
589
-			throw new ShareNotFound();
590
-		}
591
-
592
-		try {
593
-			$share = $this->createShare($data);
594
-		} catch (InvalidShare $e) {
595
-			throw new ShareNotFound();
596
-		}
597
-
598
-		// If the recipient is set for a group share resolve to that user
599
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
600
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
601
-		}
602
-
603
-		return $share;
604
-	}
605
-
606
-	/**
607
-	 * Get shares for a given path
608
-	 *
609
-	 * @param \OCP\Files\Node $path
610
-	 * @return \OCP\Share\IShare[]
611
-	 */
612
-	public function getSharesByPath(Node $path) {
613
-		$qb = $this->dbConn->getQueryBuilder();
614
-
615
-		$cursor = $qb->select('*')
616
-			->from('share')
617
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
618
-			->andWhere(
619
-				$qb->expr()->orX(
620
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
621
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
622
-				)
623
-			)
624
-			->andWhere($qb->expr()->orX(
625
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
626
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
627
-			))
628
-			->execute();
629
-
630
-		$shares = [];
631
-		while($data = $cursor->fetch()) {
632
-			$shares[] = $this->createShare($data);
633
-		}
634
-		$cursor->closeCursor();
635
-
636
-		return $shares;
637
-	}
638
-
639
-	/**
640
-	 * Returns whether the given database result can be interpreted as
641
-	 * a share with accessible file (not trashed, not deleted)
642
-	 */
643
-	private function isAccessibleResult($data) {
644
-		// exclude shares leading to deleted file entries
645
-		if ($data['fileid'] === null) {
646
-			return false;
647
-		}
648
-
649
-		// exclude shares leading to trashbin on home storages
650
-		$pathSections = explode('/', $data['path'], 2);
651
-		// FIXME: would not detect rare md5'd home storage case properly
652
-		if ($pathSections[0] !== 'files'
653
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
654
-			return false;
655
-		}
656
-		return true;
657
-	}
658
-
659
-	/**
660
-	 * @inheritdoc
661
-	 */
662
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
663
-		/** @var Share[] $shares */
664
-		$shares = [];
665
-
666
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
667
-			//Get shares directly with this user
668
-			$qb = $this->dbConn->getQueryBuilder();
669
-			$qb->select('s.*',
670
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
671
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
672
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
673
-			)
674
-				->selectAlias('st.id', 'storage_string_id')
675
-				->from('share', 's')
676
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
677
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
678
-
679
-			// Order by id
680
-			$qb->orderBy('s.id');
681
-
682
-			// Set limit and offset
683
-			if ($limit !== -1) {
684
-				$qb->setMaxResults($limit);
685
-			}
686
-			$qb->setFirstResult($offset);
687
-
688
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
689
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
690
-				->andWhere($qb->expr()->orX(
691
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
692
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
693
-				));
694
-
695
-			// Filter by node if provided
696
-			if ($node !== null) {
697
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
698
-			}
699
-
700
-			$cursor = $qb->execute();
701
-
702
-			while($data = $cursor->fetch()) {
703
-				if ($this->isAccessibleResult($data)) {
704
-					$shares[] = $this->createShare($data);
705
-				}
706
-			}
707
-			$cursor->closeCursor();
708
-
709
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
710
-			$user = $this->userManager->get($userId);
711
-			$allGroups = $this->groupManager->getUserGroups($user);
712
-
713
-			/** @var Share[] $shares2 */
714
-			$shares2 = [];
715
-
716
-			$start = 0;
717
-			while(true) {
718
-				$groups = array_slice($allGroups, $start, 100);
719
-				$start += 100;
720
-
721
-				if ($groups === []) {
722
-					break;
723
-				}
724
-
725
-				$qb = $this->dbConn->getQueryBuilder();
726
-				$qb->select('s.*',
727
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
728
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
729
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
730
-				)
731
-					->selectAlias('st.id', 'storage_string_id')
732
-					->from('share', 's')
733
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
734
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
735
-					->orderBy('s.id')
736
-					->setFirstResult(0);
737
-
738
-				if ($limit !== -1) {
739
-					$qb->setMaxResults($limit - count($shares));
740
-				}
741
-
742
-				// Filter by node if provided
743
-				if ($node !== null) {
744
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
745
-				}
746
-
747
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
748
-
749
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
750
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
751
-						$groups,
752
-						IQueryBuilder::PARAM_STR_ARRAY
753
-					)))
754
-					->andWhere($qb->expr()->orX(
755
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
756
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
757
-					));
758
-
759
-				$cursor = $qb->execute();
760
-				while($data = $cursor->fetch()) {
761
-					if ($offset > 0) {
762
-						$offset--;
763
-						continue;
764
-					}
765
-
766
-					if ($this->isAccessibleResult($data)) {
767
-						$shares2[] = $this->createShare($data);
768
-					}
769
-				}
770
-				$cursor->closeCursor();
771
-			}
772
-
773
-			/*
362
+            if ($data === false) {
363
+                $qb = $this->dbConn->getQueryBuilder();
364
+
365
+                $type = $share->getNodeType();
366
+
367
+                //Insert new share
368
+                $qb->insert('share')
369
+                    ->values([
370
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
371
+                        'share_with' => $qb->createNamedParameter($recipient),
372
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
373
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
374
+                        'parent' => $qb->createNamedParameter($share->getId()),
375
+                        'item_type' => $qb->createNamedParameter($type),
376
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
377
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
378
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
379
+                        'permissions' => $qb->createNamedParameter(0),
380
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
381
+                    ])->execute();
382
+
383
+            } else if ($data['permissions'] !== 0) {
384
+
385
+                // Update existing usergroup share
386
+                $qb = $this->dbConn->getQueryBuilder();
387
+                $qb->update('share')
388
+                    ->set('permissions', $qb->createNamedParameter(0))
389
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
390
+                    ->execute();
391
+            }
392
+
393
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
394
+
395
+            if ($share->getSharedWith() !== $recipient) {
396
+                throw new ProviderException('Recipient does not match');
397
+            }
398
+
399
+            // We can just delete user and link shares
400
+            $this->delete($share);
401
+        } else {
402
+            throw new ProviderException('Invalid shareType');
403
+        }
404
+    }
405
+
406
+    /**
407
+     * @inheritdoc
408
+     */
409
+    public function move(\OCP\Share\IShare $share, $recipient) {
410
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
411
+            // Just update the target
412
+            $qb = $this->dbConn->getQueryBuilder();
413
+            $qb->update('share')
414
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
415
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
416
+                ->execute();
417
+
418
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
419
+
420
+            // Check if there is a usergroup share
421
+            $qb = $this->dbConn->getQueryBuilder();
422
+            $stmt = $qb->select('id')
423
+                ->from('share')
424
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
425
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
426
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
427
+                ->andWhere($qb->expr()->orX(
428
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
429
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
430
+                ))
431
+                ->setMaxResults(1)
432
+                ->execute();
433
+
434
+            $data = $stmt->fetch();
435
+            $stmt->closeCursor();
436
+
437
+            if ($data === false) {
438
+                // No usergroup share yet. Create one.
439
+                $qb = $this->dbConn->getQueryBuilder();
440
+                $qb->insert('share')
441
+                    ->values([
442
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
443
+                        'share_with' => $qb->createNamedParameter($recipient),
444
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
445
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
446
+                        'parent' => $qb->createNamedParameter($share->getId()),
447
+                        'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
448
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
449
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
450
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
451
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
452
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
453
+                    ])->execute();
454
+            } else {
455
+                // Already a usergroup share. Update it.
456
+                $qb = $this->dbConn->getQueryBuilder();
457
+                $qb->update('share')
458
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
459
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
460
+                    ->execute();
461
+            }
462
+        }
463
+
464
+        return $share;
465
+    }
466
+
467
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
468
+        $qb = $this->dbConn->getQueryBuilder();
469
+        $qb->select('*')
470
+            ->from('share', 's')
471
+            ->andWhere($qb->expr()->orX(
472
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
473
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
474
+            ));
475
+
476
+        $qb->andWhere($qb->expr()->orX(
477
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
478
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
479
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
480
+        ));
481
+
482
+        /**
483
+         * Reshares for this user are shares where they are the owner.
484
+         */
485
+        if ($reshares === false) {
486
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
487
+        } else {
488
+            $qb->andWhere(
489
+                $qb->expr()->orX(
490
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
491
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
492
+                )
493
+            );
494
+        }
495
+
496
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
497
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498
+
499
+        $qb->orderBy('id');
500
+
501
+        $cursor = $qb->execute();
502
+        $shares = [];
503
+        while ($data = $cursor->fetch()) {
504
+            $shares[$data['fileid']][] = $this->createShare($data);
505
+        }
506
+        $cursor->closeCursor();
507
+
508
+        return $shares;
509
+    }
510
+
511
+    /**
512
+     * @inheritdoc
513
+     */
514
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
515
+        $qb = $this->dbConn->getQueryBuilder();
516
+        $qb->select('*')
517
+            ->from('share')
518
+            ->andWhere($qb->expr()->orX(
519
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
520
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
521
+            ));
522
+
523
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
524
+
525
+        /**
526
+         * Reshares for this user are shares where they are the owner.
527
+         */
528
+        if ($reshares === false) {
529
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
530
+        } else {
531
+            $qb->andWhere(
532
+                $qb->expr()->orX(
533
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
534
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
535
+                )
536
+            );
537
+        }
538
+
539
+        if ($node !== null) {
540
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
541
+        }
542
+
543
+        if ($limit !== -1) {
544
+            $qb->setMaxResults($limit);
545
+        }
546
+
547
+        $qb->setFirstResult($offset);
548
+        $qb->orderBy('id');
549
+
550
+        $cursor = $qb->execute();
551
+        $shares = [];
552
+        while($data = $cursor->fetch()) {
553
+            $shares[] = $this->createShare($data);
554
+        }
555
+        $cursor->closeCursor();
556
+
557
+        return $shares;
558
+    }
559
+
560
+    /**
561
+     * @inheritdoc
562
+     */
563
+    public function getShareById($id, $recipientId = null) {
564
+        $qb = $this->dbConn->getQueryBuilder();
565
+
566
+        $qb->select('*')
567
+            ->from('share')
568
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
569
+            ->andWhere(
570
+                $qb->expr()->in(
571
+                    'share_type',
572
+                    $qb->createNamedParameter([
573
+                        \OCP\Share::SHARE_TYPE_USER,
574
+                        \OCP\Share::SHARE_TYPE_GROUP,
575
+                        \OCP\Share::SHARE_TYPE_LINK,
576
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
577
+                )
578
+            )
579
+            ->andWhere($qb->expr()->orX(
580
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
581
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
582
+            ));
583
+
584
+        $cursor = $qb->execute();
585
+        $data = $cursor->fetch();
586
+        $cursor->closeCursor();
587
+
588
+        if ($data === false) {
589
+            throw new ShareNotFound();
590
+        }
591
+
592
+        try {
593
+            $share = $this->createShare($data);
594
+        } catch (InvalidShare $e) {
595
+            throw new ShareNotFound();
596
+        }
597
+
598
+        // If the recipient is set for a group share resolve to that user
599
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
600
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
601
+        }
602
+
603
+        return $share;
604
+    }
605
+
606
+    /**
607
+     * Get shares for a given path
608
+     *
609
+     * @param \OCP\Files\Node $path
610
+     * @return \OCP\Share\IShare[]
611
+     */
612
+    public function getSharesByPath(Node $path) {
613
+        $qb = $this->dbConn->getQueryBuilder();
614
+
615
+        $cursor = $qb->select('*')
616
+            ->from('share')
617
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
618
+            ->andWhere(
619
+                $qb->expr()->orX(
620
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
621
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
622
+                )
623
+            )
624
+            ->andWhere($qb->expr()->orX(
625
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
626
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
627
+            ))
628
+            ->execute();
629
+
630
+        $shares = [];
631
+        while($data = $cursor->fetch()) {
632
+            $shares[] = $this->createShare($data);
633
+        }
634
+        $cursor->closeCursor();
635
+
636
+        return $shares;
637
+    }
638
+
639
+    /**
640
+     * Returns whether the given database result can be interpreted as
641
+     * a share with accessible file (not trashed, not deleted)
642
+     */
643
+    private function isAccessibleResult($data) {
644
+        // exclude shares leading to deleted file entries
645
+        if ($data['fileid'] === null) {
646
+            return false;
647
+        }
648
+
649
+        // exclude shares leading to trashbin on home storages
650
+        $pathSections = explode('/', $data['path'], 2);
651
+        // FIXME: would not detect rare md5'd home storage case properly
652
+        if ($pathSections[0] !== 'files'
653
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
654
+            return false;
655
+        }
656
+        return true;
657
+    }
658
+
659
+    /**
660
+     * @inheritdoc
661
+     */
662
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
663
+        /** @var Share[] $shares */
664
+        $shares = [];
665
+
666
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
667
+            //Get shares directly with this user
668
+            $qb = $this->dbConn->getQueryBuilder();
669
+            $qb->select('s.*',
670
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
671
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
672
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
673
+            )
674
+                ->selectAlias('st.id', 'storage_string_id')
675
+                ->from('share', 's')
676
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
677
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
678
+
679
+            // Order by id
680
+            $qb->orderBy('s.id');
681
+
682
+            // Set limit and offset
683
+            if ($limit !== -1) {
684
+                $qb->setMaxResults($limit);
685
+            }
686
+            $qb->setFirstResult($offset);
687
+
688
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
689
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
690
+                ->andWhere($qb->expr()->orX(
691
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
692
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
693
+                ));
694
+
695
+            // Filter by node if provided
696
+            if ($node !== null) {
697
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
698
+            }
699
+
700
+            $cursor = $qb->execute();
701
+
702
+            while($data = $cursor->fetch()) {
703
+                if ($this->isAccessibleResult($data)) {
704
+                    $shares[] = $this->createShare($data);
705
+                }
706
+            }
707
+            $cursor->closeCursor();
708
+
709
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
710
+            $user = $this->userManager->get($userId);
711
+            $allGroups = $this->groupManager->getUserGroups($user);
712
+
713
+            /** @var Share[] $shares2 */
714
+            $shares2 = [];
715
+
716
+            $start = 0;
717
+            while(true) {
718
+                $groups = array_slice($allGroups, $start, 100);
719
+                $start += 100;
720
+
721
+                if ($groups === []) {
722
+                    break;
723
+                }
724
+
725
+                $qb = $this->dbConn->getQueryBuilder();
726
+                $qb->select('s.*',
727
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
728
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
729
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
730
+                )
731
+                    ->selectAlias('st.id', 'storage_string_id')
732
+                    ->from('share', 's')
733
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
734
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
735
+                    ->orderBy('s.id')
736
+                    ->setFirstResult(0);
737
+
738
+                if ($limit !== -1) {
739
+                    $qb->setMaxResults($limit - count($shares));
740
+                }
741
+
742
+                // Filter by node if provided
743
+                if ($node !== null) {
744
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
745
+                }
746
+
747
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
748
+
749
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
750
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
751
+                        $groups,
752
+                        IQueryBuilder::PARAM_STR_ARRAY
753
+                    )))
754
+                    ->andWhere($qb->expr()->orX(
755
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
756
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
757
+                    ));
758
+
759
+                $cursor = $qb->execute();
760
+                while($data = $cursor->fetch()) {
761
+                    if ($offset > 0) {
762
+                        $offset--;
763
+                        continue;
764
+                    }
765
+
766
+                    if ($this->isAccessibleResult($data)) {
767
+                        $shares2[] = $this->createShare($data);
768
+                    }
769
+                }
770
+                $cursor->closeCursor();
771
+            }
772
+
773
+            /*
774 774
  			 * Resolve all group shares to user specific shares
775 775
  			 */
776
-			$shares = $this->resolveGroupShares($shares2, $userId);
777
-		} else {
778
-			throw new BackendError('Invalid backend');
779
-		}
780
-
781
-
782
-		return $shares;
783
-	}
784
-
785
-	/**
786
-	 * Get a share by token
787
-	 *
788
-	 * @param string $token
789
-	 * @return \OCP\Share\IShare
790
-	 * @throws ShareNotFound
791
-	 */
792
-	public function getShareByToken($token) {
793
-		$qb = $this->dbConn->getQueryBuilder();
794
-
795
-		$cursor = $qb->select('*')
796
-			->from('share')
797
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
798
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
799
-			->andWhere($qb->expr()->orX(
800
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
801
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
802
-			))
803
-			->execute();
804
-
805
-		$data = $cursor->fetch();
806
-
807
-		if ($data === false) {
808
-			throw new ShareNotFound();
809
-		}
810
-
811
-		try {
812
-			$share = $this->createShare($data);
813
-		} catch (InvalidShare $e) {
814
-			throw new ShareNotFound();
815
-		}
816
-
817
-		return $share;
818
-	}
819
-
820
-	/**
821
-	 * Create a share object from an database row
822
-	 *
823
-	 * @param mixed[] $data
824
-	 * @return \OCP\Share\IShare
825
-	 * @throws InvalidShare
826
-	 */
827
-	private function createShare($data) {
828
-		$share = new Share($this->rootFolder, $this->userManager);
829
-		$share->setId((int)$data['id'])
830
-			->setShareType((int)$data['share_type'])
831
-			->setPermissions((int)$data['permissions'])
832
-			->setTarget($data['file_target'])
833
-			->setMailSend((bool)$data['mail_send']);
834
-
835
-		$shareTime = new \DateTime();
836
-		$shareTime->setTimestamp((int)$data['stime']);
837
-		$share->setShareTime($shareTime);
838
-
839
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
840
-			$share->setSharedWith($data['share_with']);
841
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
842
-			$share->setSharedWith($data['share_with']);
843
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
844
-			$share->setPassword($data['password']);
845
-			$share->setToken($data['token']);
846
-		}
847
-
848
-		$share->setSharedBy($data['uid_initiator']);
849
-		$share->setShareOwner($data['uid_owner']);
850
-
851
-		$share->setNodeId((int)$data['file_source']);
852
-		$share->setNodeType($data['item_type']);
853
-
854
-		if ($data['expiration'] !== null) {
855
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
856
-			$share->setExpirationDate($expiration);
857
-		}
858
-
859
-		if (isset($data['f_permissions'])) {
860
-			$entryData = $data;
861
-			$entryData['permissions'] = $entryData['f_permissions'];
862
-			$entryData['parent'] = $entryData['f_parent'];;
863
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864
-				\OC::$server->getMimeTypeLoader()));
865
-		}
866
-
867
-		$share->setProviderId($this->identifier());
868
-
869
-		return $share;
870
-	}
871
-
872
-	/**
873
-	 * @param Share[] $shares
874
-	 * @param $userId
875
-	 * @return Share[] The updates shares if no update is found for a share return the original
876
-	 */
877
-	private function resolveGroupShares($shares, $userId) {
878
-		$result = [];
879
-
880
-		$start = 0;
881
-		while(true) {
882
-			/** @var Share[] $shareSlice */
883
-			$shareSlice = array_slice($shares, $start, 100);
884
-			$start += 100;
885
-
886
-			if ($shareSlice === []) {
887
-				break;
888
-			}
889
-
890
-			/** @var int[] $ids */
891
-			$ids = [];
892
-			/** @var Share[] $shareMap */
893
-			$shareMap = [];
894
-
895
-			foreach ($shareSlice as $share) {
896
-				$ids[] = (int)$share->getId();
897
-				$shareMap[$share->getId()] = $share;
898
-			}
899
-
900
-			$qb = $this->dbConn->getQueryBuilder();
901
-
902
-			$query = $qb->select('*')
903
-				->from('share')
904
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
905
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
906
-				->andWhere($qb->expr()->orX(
907
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
908
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
909
-				));
910
-
911
-			$stmt = $query->execute();
912
-
913
-			while($data = $stmt->fetch()) {
914
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
915
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
916
-			}
917
-
918
-			$stmt->closeCursor();
919
-
920
-			foreach ($shareMap as $share) {
921
-				$result[] = $share;
922
-			}
923
-		}
924
-
925
-		return $result;
926
-	}
927
-
928
-	/**
929
-	 * A user is deleted from the system
930
-	 * So clean up the relevant shares.
931
-	 *
932
-	 * @param string $uid
933
-	 * @param int $shareType
934
-	 */
935
-	public function userDeleted($uid, $shareType) {
936
-		$qb = $this->dbConn->getQueryBuilder();
937
-
938
-		$qb->delete('share');
939
-
940
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
941
-			/*
776
+            $shares = $this->resolveGroupShares($shares2, $userId);
777
+        } else {
778
+            throw new BackendError('Invalid backend');
779
+        }
780
+
781
+
782
+        return $shares;
783
+    }
784
+
785
+    /**
786
+     * Get a share by token
787
+     *
788
+     * @param string $token
789
+     * @return \OCP\Share\IShare
790
+     * @throws ShareNotFound
791
+     */
792
+    public function getShareByToken($token) {
793
+        $qb = $this->dbConn->getQueryBuilder();
794
+
795
+        $cursor = $qb->select('*')
796
+            ->from('share')
797
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
798
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
799
+            ->andWhere($qb->expr()->orX(
800
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
801
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
802
+            ))
803
+            ->execute();
804
+
805
+        $data = $cursor->fetch();
806
+
807
+        if ($data === false) {
808
+            throw new ShareNotFound();
809
+        }
810
+
811
+        try {
812
+            $share = $this->createShare($data);
813
+        } catch (InvalidShare $e) {
814
+            throw new ShareNotFound();
815
+        }
816
+
817
+        return $share;
818
+    }
819
+
820
+    /**
821
+     * Create a share object from an database row
822
+     *
823
+     * @param mixed[] $data
824
+     * @return \OCP\Share\IShare
825
+     * @throws InvalidShare
826
+     */
827
+    private function createShare($data) {
828
+        $share = new Share($this->rootFolder, $this->userManager);
829
+        $share->setId((int)$data['id'])
830
+            ->setShareType((int)$data['share_type'])
831
+            ->setPermissions((int)$data['permissions'])
832
+            ->setTarget($data['file_target'])
833
+            ->setMailSend((bool)$data['mail_send']);
834
+
835
+        $shareTime = new \DateTime();
836
+        $shareTime->setTimestamp((int)$data['stime']);
837
+        $share->setShareTime($shareTime);
838
+
839
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
840
+            $share->setSharedWith($data['share_with']);
841
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
842
+            $share->setSharedWith($data['share_with']);
843
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
844
+            $share->setPassword($data['password']);
845
+            $share->setToken($data['token']);
846
+        }
847
+
848
+        $share->setSharedBy($data['uid_initiator']);
849
+        $share->setShareOwner($data['uid_owner']);
850
+
851
+        $share->setNodeId((int)$data['file_source']);
852
+        $share->setNodeType($data['item_type']);
853
+
854
+        if ($data['expiration'] !== null) {
855
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
856
+            $share->setExpirationDate($expiration);
857
+        }
858
+
859
+        if (isset($data['f_permissions'])) {
860
+            $entryData = $data;
861
+            $entryData['permissions'] = $entryData['f_permissions'];
862
+            $entryData['parent'] = $entryData['f_parent'];;
863
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864
+                \OC::$server->getMimeTypeLoader()));
865
+        }
866
+
867
+        $share->setProviderId($this->identifier());
868
+
869
+        return $share;
870
+    }
871
+
872
+    /**
873
+     * @param Share[] $shares
874
+     * @param $userId
875
+     * @return Share[] The updates shares if no update is found for a share return the original
876
+     */
877
+    private function resolveGroupShares($shares, $userId) {
878
+        $result = [];
879
+
880
+        $start = 0;
881
+        while(true) {
882
+            /** @var Share[] $shareSlice */
883
+            $shareSlice = array_slice($shares, $start, 100);
884
+            $start += 100;
885
+
886
+            if ($shareSlice === []) {
887
+                break;
888
+            }
889
+
890
+            /** @var int[] $ids */
891
+            $ids = [];
892
+            /** @var Share[] $shareMap */
893
+            $shareMap = [];
894
+
895
+            foreach ($shareSlice as $share) {
896
+                $ids[] = (int)$share->getId();
897
+                $shareMap[$share->getId()] = $share;
898
+            }
899
+
900
+            $qb = $this->dbConn->getQueryBuilder();
901
+
902
+            $query = $qb->select('*')
903
+                ->from('share')
904
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
905
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
906
+                ->andWhere($qb->expr()->orX(
907
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
908
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
909
+                ));
910
+
911
+            $stmt = $query->execute();
912
+
913
+            while($data = $stmt->fetch()) {
914
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
915
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
916
+            }
917
+
918
+            $stmt->closeCursor();
919
+
920
+            foreach ($shareMap as $share) {
921
+                $result[] = $share;
922
+            }
923
+        }
924
+
925
+        return $result;
926
+    }
927
+
928
+    /**
929
+     * A user is deleted from the system
930
+     * So clean up the relevant shares.
931
+     *
932
+     * @param string $uid
933
+     * @param int $shareType
934
+     */
935
+    public function userDeleted($uid, $shareType) {
936
+        $qb = $this->dbConn->getQueryBuilder();
937
+
938
+        $qb->delete('share');
939
+
940
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
941
+            /*
942 942
 			 * Delete all user shares that are owned by this user
943 943
 			 * or that are received by this user
944 944
 			 */
945 945
 
946
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
946
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
947 947
 
948
-			$qb->andWhere(
949
-				$qb->expr()->orX(
950
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
951
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
952
-				)
953
-			);
954
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
955
-			/*
948
+            $qb->andWhere(
949
+                $qb->expr()->orX(
950
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
951
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
952
+                )
953
+            );
954
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
955
+            /*
956 956
 			 * Delete all group shares that are owned by this user
957 957
 			 * Or special user group shares that are received by this user
958 958
 			 */
959
-			$qb->where(
960
-				$qb->expr()->andX(
961
-					$qb->expr()->orX(
962
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
963
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
964
-					),
965
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
966
-				)
967
-			);
968
-
969
-			$qb->orWhere(
970
-				$qb->expr()->andX(
971
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
972
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
973
-				)
974
-			);
975
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
976
-			/*
959
+            $qb->where(
960
+                $qb->expr()->andX(
961
+                    $qb->expr()->orX(
962
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
963
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
964
+                    ),
965
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
966
+                )
967
+            );
968
+
969
+            $qb->orWhere(
970
+                $qb->expr()->andX(
971
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
972
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
973
+                )
974
+            );
975
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
976
+            /*
977 977
 			 * Delete all link shares owned by this user.
978 978
 			 * And all link shares initiated by this user (until #22327 is in)
979 979
 			 */
980
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
981
-
982
-			$qb->andWhere(
983
-				$qb->expr()->orX(
984
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
985
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
986
-				)
987
-			);
988
-		}
989
-
990
-		$qb->execute();
991
-	}
992
-
993
-	/**
994
-	 * Delete all shares received by this group. As well as any custom group
995
-	 * shares for group members.
996
-	 *
997
-	 * @param string $gid
998
-	 */
999
-	public function groupDeleted($gid) {
1000
-		/*
980
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
981
+
982
+            $qb->andWhere(
983
+                $qb->expr()->orX(
984
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
985
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
986
+                )
987
+            );
988
+        }
989
+
990
+        $qb->execute();
991
+    }
992
+
993
+    /**
994
+     * Delete all shares received by this group. As well as any custom group
995
+     * shares for group members.
996
+     *
997
+     * @param string $gid
998
+     */
999
+    public function groupDeleted($gid) {
1000
+        /*
1001 1001
 		 * First delete all custom group shares for group members
1002 1002
 		 */
1003
-		$qb = $this->dbConn->getQueryBuilder();
1004
-		$qb->select('id')
1005
-			->from('share')
1006
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1007
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1008
-
1009
-		$cursor = $qb->execute();
1010
-		$ids = [];
1011
-		while($row = $cursor->fetch()) {
1012
-			$ids[] = (int)$row['id'];
1013
-		}
1014
-		$cursor->closeCursor();
1015
-
1016
-		if (!empty($ids)) {
1017
-			$chunks = array_chunk($ids, 100);
1018
-			foreach ($chunks as $chunk) {
1019
-				$qb->delete('share')
1020
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1021
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1022
-				$qb->execute();
1023
-			}
1024
-		}
1025
-
1026
-		/*
1003
+        $qb = $this->dbConn->getQueryBuilder();
1004
+        $qb->select('id')
1005
+            ->from('share')
1006
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1007
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1008
+
1009
+        $cursor = $qb->execute();
1010
+        $ids = [];
1011
+        while($row = $cursor->fetch()) {
1012
+            $ids[] = (int)$row['id'];
1013
+        }
1014
+        $cursor->closeCursor();
1015
+
1016
+        if (!empty($ids)) {
1017
+            $chunks = array_chunk($ids, 100);
1018
+            foreach ($chunks as $chunk) {
1019
+                $qb->delete('share')
1020
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1021
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1022
+                $qb->execute();
1023
+            }
1024
+        }
1025
+
1026
+        /*
1027 1027
 		 * Now delete all the group shares
1028 1028
 		 */
1029
-		$qb = $this->dbConn->getQueryBuilder();
1030
-		$qb->delete('share')
1031
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1032
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1033
-		$qb->execute();
1034
-	}
1035
-
1036
-	/**
1037
-	 * Delete custom group shares to this group for this user
1038
-	 *
1039
-	 * @param string $uid
1040
-	 * @param string $gid
1041
-	 */
1042
-	public function userDeletedFromGroup($uid, $gid) {
1043
-		/*
1029
+        $qb = $this->dbConn->getQueryBuilder();
1030
+        $qb->delete('share')
1031
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1032
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1033
+        $qb->execute();
1034
+    }
1035
+
1036
+    /**
1037
+     * Delete custom group shares to this group for this user
1038
+     *
1039
+     * @param string $uid
1040
+     * @param string $gid
1041
+     */
1042
+    public function userDeletedFromGroup($uid, $gid) {
1043
+        /*
1044 1044
 		 * Get all group shares
1045 1045
 		 */
1046
-		$qb = $this->dbConn->getQueryBuilder();
1047
-		$qb->select('id')
1048
-			->from('share')
1049
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1050
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1051
-
1052
-		$cursor = $qb->execute();
1053
-		$ids = [];
1054
-		while($row = $cursor->fetch()) {
1055
-			$ids[] = (int)$row['id'];
1056
-		}
1057
-		$cursor->closeCursor();
1058
-
1059
-		if (!empty($ids)) {
1060
-			$chunks = array_chunk($ids, 100);
1061
-			foreach ($chunks as $chunk) {
1062
-				/*
1046
+        $qb = $this->dbConn->getQueryBuilder();
1047
+        $qb->select('id')
1048
+            ->from('share')
1049
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1050
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1051
+
1052
+        $cursor = $qb->execute();
1053
+        $ids = [];
1054
+        while($row = $cursor->fetch()) {
1055
+            $ids[] = (int)$row['id'];
1056
+        }
1057
+        $cursor->closeCursor();
1058
+
1059
+        if (!empty($ids)) {
1060
+            $chunks = array_chunk($ids, 100);
1061
+            foreach ($chunks as $chunk) {
1062
+                /*
1063 1063
 				 * Delete all special shares wit this users for the found group shares
1064 1064
 				 */
1065
-				$qb->delete('share')
1066
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1067
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1068
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1069
-				$qb->execute();
1070
-			}
1071
-		}
1072
-	}
1073
-
1074
-	/**
1075
-	 * @inheritdoc
1076
-	 */
1077
-	public function getAccessList($nodes, $currentAccess) {
1078
-		$ids = [];
1079
-		foreach ($nodes as $node) {
1080
-			$ids[] = $node->getId();
1081
-		}
1082
-
1083
-		$qb = $this->dbConn->getQueryBuilder();
1084
-
1085
-		$or = $qb->expr()->orX(
1086
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1087
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1088
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1089
-		);
1090
-
1091
-		if ($currentAccess) {
1092
-			$or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1093
-		}
1094
-
1095
-		$qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1096
-			->from('share')
1097
-			->where(
1098
-				$or
1099
-			)
1100
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1101
-			->andWhere($qb->expr()->orX(
1102
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1103
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1104
-			));
1105
-		$cursor = $qb->execute();
1106
-
1107
-		$users = [];
1108
-		$link = false;
1109
-		while($row = $cursor->fetch()) {
1110
-			$type = (int)$row['share_type'];
1111
-			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1112
-				$uid = $row['share_with'];
1113
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1114
-				$users[$uid][$row['id']] = $row;
1115
-			} else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1116
-				$gid = $row['share_with'];
1117
-				$group = $this->groupManager->get($gid);
1118
-
1119
-				if ($gid === null) {
1120
-					continue;
1121
-				}
1122
-
1123
-				$userList = $group->getUsers();
1124
-				foreach ($userList as $user) {
1125
-					$uid = $user->getUID();
1126
-					$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1127
-					$users[$uid][$row['id']] = $row;
1128
-				}
1129
-			} else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1130
-				$link = true;
1131
-			} else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1132
-				$uid = $row['share_with'];
1133
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1134
-				$users[$uid][$row['id']] = $row;
1135
-			}
1136
-		}
1137
-		$cursor->closeCursor();
1138
-
1139
-		if ($currentAccess === true) {
1140
-			$users = array_map([$this, 'filterSharesOfUser'], $users);
1141
-			$users = array_filter($users);
1142
-		} else {
1143
-			$users = array_keys($users);
1144
-		}
1145
-
1146
-		return ['users' => $users, 'public' => $link];
1147
-	}
1148
-
1149
-	/**
1150
-	 * For each user the path with the fewest slashes is returned
1151
-	 * @param array $shares
1152
-	 * @return array
1153
-	 */
1154
-	protected function filterSharesOfUser(array $shares) {
1155
-		// Group shares when the user has a share exception
1156
-		foreach ($shares as $id => $share) {
1157
-			$type = (int) $share['share_type'];
1158
-			$permissions = (int) $share['permissions'];
1159
-
1160
-			if ($type === self::SHARE_TYPE_USERGROUP) {
1161
-				unset($shares[$share['parent']]);
1162
-
1163
-				if ($permissions === 0) {
1164
-					unset($shares[$id]);
1165
-				}
1166
-			}
1167
-		}
1168
-
1169
-		$best = [];
1170
-		$bestDepth = 0;
1171
-		foreach ($shares as $id => $share) {
1172
-			$depth = substr_count($share['file_target'], '/');
1173
-			if (empty($best) || $depth < $bestDepth) {
1174
-				$bestDepth = $depth;
1175
-				$best = [
1176
-					'node_id' => $share['file_source'],
1177
-					'node_path' => $share['file_target'],
1178
-				];
1179
-			}
1180
-		}
1181
-
1182
-		return $best;
1183
-	}
1065
+                $qb->delete('share')
1066
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1067
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1068
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1069
+                $qb->execute();
1070
+            }
1071
+        }
1072
+    }
1073
+
1074
+    /**
1075
+     * @inheritdoc
1076
+     */
1077
+    public function getAccessList($nodes, $currentAccess) {
1078
+        $ids = [];
1079
+        foreach ($nodes as $node) {
1080
+            $ids[] = $node->getId();
1081
+        }
1082
+
1083
+        $qb = $this->dbConn->getQueryBuilder();
1084
+
1085
+        $or = $qb->expr()->orX(
1086
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1087
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1088
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1089
+        );
1090
+
1091
+        if ($currentAccess) {
1092
+            $or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1093
+        }
1094
+
1095
+        $qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1096
+            ->from('share')
1097
+            ->where(
1098
+                $or
1099
+            )
1100
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1101
+            ->andWhere($qb->expr()->orX(
1102
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1103
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1104
+            ));
1105
+        $cursor = $qb->execute();
1106
+
1107
+        $users = [];
1108
+        $link = false;
1109
+        while($row = $cursor->fetch()) {
1110
+            $type = (int)$row['share_type'];
1111
+            if ($type === \OCP\Share::SHARE_TYPE_USER) {
1112
+                $uid = $row['share_with'];
1113
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1114
+                $users[$uid][$row['id']] = $row;
1115
+            } else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1116
+                $gid = $row['share_with'];
1117
+                $group = $this->groupManager->get($gid);
1118
+
1119
+                if ($gid === null) {
1120
+                    continue;
1121
+                }
1122
+
1123
+                $userList = $group->getUsers();
1124
+                foreach ($userList as $user) {
1125
+                    $uid = $user->getUID();
1126
+                    $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1127
+                    $users[$uid][$row['id']] = $row;
1128
+                }
1129
+            } else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1130
+                $link = true;
1131
+            } else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1132
+                $uid = $row['share_with'];
1133
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1134
+                $users[$uid][$row['id']] = $row;
1135
+            }
1136
+        }
1137
+        $cursor->closeCursor();
1138
+
1139
+        if ($currentAccess === true) {
1140
+            $users = array_map([$this, 'filterSharesOfUser'], $users);
1141
+            $users = array_filter($users);
1142
+        } else {
1143
+            $users = array_keys($users);
1144
+        }
1145
+
1146
+        return ['users' => $users, 'public' => $link];
1147
+    }
1148
+
1149
+    /**
1150
+     * For each user the path with the fewest slashes is returned
1151
+     * @param array $shares
1152
+     * @return array
1153
+     */
1154
+    protected function filterSharesOfUser(array $shares) {
1155
+        // Group shares when the user has a share exception
1156
+        foreach ($shares as $id => $share) {
1157
+            $type = (int) $share['share_type'];
1158
+            $permissions = (int) $share['permissions'];
1159
+
1160
+            if ($type === self::SHARE_TYPE_USERGROUP) {
1161
+                unset($shares[$share['parent']]);
1162
+
1163
+                if ($permissions === 0) {
1164
+                    unset($shares[$id]);
1165
+                }
1166
+            }
1167
+        }
1168
+
1169
+        $best = [];
1170
+        $bestDepth = 0;
1171
+        foreach ($shares as $id => $share) {
1172
+            $depth = substr_count($share['file_target'], '/');
1173
+            if (empty($best) || $depth < $bestDepth) {
1174
+                $bestDepth = $depth;
1175
+                $best = [
1176
+                    'node_id' => $share['file_source'],
1177
+                    'node_path' => $share['file_target'],
1178
+                ];
1179
+            }
1180
+        }
1181
+
1182
+        return $best;
1183
+    }
1184 1184
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
 			->orderBy('id');
289 289
 
290 290
 		$cursor = $qb->execute();
291
-		while($data = $cursor->fetch()) {
291
+		while ($data = $cursor->fetch()) {
292 292
 			$children[] = $this->createShare($data);
293 293
 		}
294 294
 		$cursor->closeCursor();
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 			$user = $this->userManager->get($recipient);
334 334
 
335 335
 			if (is_null($group)) {
336
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
336
+				throw new ProviderException('Group "'.$share->getSharedWith().'" does not exist');
337 337
 			}
338 338
 
339 339
 			if (!$group->inGroup($user)) {
@@ -493,7 +493,7 @@  discard block
 block discarded – undo
493 493
 			);
494 494
 		}
495 495
 
496
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
496
+		$qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
497 497
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498 498
 
499 499
 		$qb->orderBy('id');
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
 
550 550
 		$cursor = $qb->execute();
551 551
 		$shares = [];
552
-		while($data = $cursor->fetch()) {
552
+		while ($data = $cursor->fetch()) {
553 553
 			$shares[] = $this->createShare($data);
554 554
 		}
555 555
 		$cursor->closeCursor();
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
 			->execute();
629 629
 
630 630
 		$shares = [];
631
-		while($data = $cursor->fetch()) {
631
+		while ($data = $cursor->fetch()) {
632 632
 			$shares[] = $this->createShare($data);
633 633
 		}
634 634
 		$cursor->closeCursor();
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
 
700 700
 			$cursor = $qb->execute();
701 701
 
702
-			while($data = $cursor->fetch()) {
702
+			while ($data = $cursor->fetch()) {
703 703
 				if ($this->isAccessibleResult($data)) {
704 704
 					$shares[] = $this->createShare($data);
705 705
 				}
@@ -714,7 +714,7 @@  discard block
 block discarded – undo
714 714
 			$shares2 = [];
715 715
 
716 716
 			$start = 0;
717
-			while(true) {
717
+			while (true) {
718 718
 				$groups = array_slice($allGroups, $start, 100);
719 719
 				$start += 100;
720 720
 
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
 					));
758 758
 
759 759
 				$cursor = $qb->execute();
760
-				while($data = $cursor->fetch()) {
760
+				while ($data = $cursor->fetch()) {
761 761
 					if ($offset > 0) {
762 762
 						$offset--;
763 763
 						continue;
@@ -826,14 +826,14 @@  discard block
 block discarded – undo
826 826
 	 */
827 827
 	private function createShare($data) {
828 828
 		$share = new Share($this->rootFolder, $this->userManager);
829
-		$share->setId((int)$data['id'])
830
-			->setShareType((int)$data['share_type'])
831
-			->setPermissions((int)$data['permissions'])
829
+		$share->setId((int) $data['id'])
830
+			->setShareType((int) $data['share_type'])
831
+			->setPermissions((int) $data['permissions'])
832 832
 			->setTarget($data['file_target'])
833
-			->setMailSend((bool)$data['mail_send']);
833
+			->setMailSend((bool) $data['mail_send']);
834 834
 
835 835
 		$shareTime = new \DateTime();
836
-		$shareTime->setTimestamp((int)$data['stime']);
836
+		$shareTime->setTimestamp((int) $data['stime']);
837 837
 		$share->setShareTime($shareTime);
838 838
 
839 839
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
@@ -848,7 +848,7 @@  discard block
 block discarded – undo
848 848
 		$share->setSharedBy($data['uid_initiator']);
849 849
 		$share->setShareOwner($data['uid_owner']);
850 850
 
851
-		$share->setNodeId((int)$data['file_source']);
851
+		$share->setNodeId((int) $data['file_source']);
852 852
 		$share->setNodeType($data['item_type']);
853 853
 
854 854
 		if ($data['expiration'] !== null) {
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
 		if (isset($data['f_permissions'])) {
860 860
 			$entryData = $data;
861 861
 			$entryData['permissions'] = $entryData['f_permissions'];
862
-			$entryData['parent'] = $entryData['f_parent'];;
862
+			$entryData['parent'] = $entryData['f_parent']; ;
863 863
 			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864 864
 				\OC::$server->getMimeTypeLoader()));
865 865
 		}
@@ -878,7 +878,7 @@  discard block
 block discarded – undo
878 878
 		$result = [];
879 879
 
880 880
 		$start = 0;
881
-		while(true) {
881
+		while (true) {
882 882
 			/** @var Share[] $shareSlice */
883 883
 			$shareSlice = array_slice($shares, $start, 100);
884 884
 			$start += 100;
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
 			$shareMap = [];
894 894
 
895 895
 			foreach ($shareSlice as $share) {
896
-				$ids[] = (int)$share->getId();
896
+				$ids[] = (int) $share->getId();
897 897
 				$shareMap[$share->getId()] = $share;
898 898
 			}
899 899
 
@@ -910,8 +910,8 @@  discard block
 block discarded – undo
910 910
 
911 911
 			$stmt = $query->execute();
912 912
 
913
-			while($data = $stmt->fetch()) {
914
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
913
+			while ($data = $stmt->fetch()) {
914
+				$shareMap[$data['parent']]->setPermissions((int) $data['permissions']);
915 915
 				$shareMap[$data['parent']]->setTarget($data['file_target']);
916 916
 			}
917 917
 
@@ -1008,8 +1008,8 @@  discard block
 block discarded – undo
1008 1008
 
1009 1009
 		$cursor = $qb->execute();
1010 1010
 		$ids = [];
1011
-		while($row = $cursor->fetch()) {
1012
-			$ids[] = (int)$row['id'];
1011
+		while ($row = $cursor->fetch()) {
1012
+			$ids[] = (int) $row['id'];
1013 1013
 		}
1014 1014
 		$cursor->closeCursor();
1015 1015
 
@@ -1051,8 +1051,8 @@  discard block
 block discarded – undo
1051 1051
 
1052 1052
 		$cursor = $qb->execute();
1053 1053
 		$ids = [];
1054
-		while($row = $cursor->fetch()) {
1055
-			$ids[] = (int)$row['id'];
1054
+		while ($row = $cursor->fetch()) {
1055
+			$ids[] = (int) $row['id'];
1056 1056
 		}
1057 1057
 		$cursor->closeCursor();
1058 1058
 
@@ -1106,8 +1106,8 @@  discard block
 block discarded – undo
1106 1106
 
1107 1107
 		$users = [];
1108 1108
 		$link = false;
1109
-		while($row = $cursor->fetch()) {
1110
-			$type = (int)$row['share_type'];
1109
+		while ($row = $cursor->fetch()) {
1110
+			$type = (int) $row['share_type'];
1111 1111
 			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1112 1112
 				$uid = $row['share_with'];
1113 1113
 				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
Please login to merge, or discard this patch.
lib/public/Share/IShareProvider.php 1 patch
Indentation   +168 added lines, -168 removed lines patch added patch discarded remove patch
@@ -34,172 +34,172 @@
 block discarded – undo
34 34
  */
35 35
 interface IShareProvider {
36 36
 
37
-	/**
38
-	 * Return the identifier of this provider.
39
-	 *
40
-	 * @return string Containing only [a-zA-Z0-9]
41
-	 * @since 9.0.0
42
-	 */
43
-	public function identifier();
44
-
45
-	/**
46
-	 * Create a share
47
-	 * 
48
-	 * @param \OCP\Share\IShare $share
49
-	 * @return \OCP\Share\IShare The share object
50
-	 * @since 9.0.0
51
-	 */
52
-	public function create(\OCP\Share\IShare $share);
53
-
54
-	/**
55
-	 * Update a share
56
-	 *
57
-	 * @param \OCP\Share\IShare $share
58
-	 * @return \OCP\Share\IShare The share object
59
-	 * @since 9.0.0
60
-	 */
61
-	public function update(\OCP\Share\IShare $share);
62
-
63
-	/**
64
-	 * Delete a share
65
-	 *
66
-	 * @param \OCP\Share\IShare $share
67
-	 * @since 9.0.0
68
-	 */
69
-	public function delete(\OCP\Share\IShare $share);
70
-
71
-	/**
72
-	 * Unshare a file from self as recipient.
73
-	 * This may require special handling. If a user unshares a group
74
-	 * share from their self then the original group share should still exist.
75
-	 *
76
-	 * @param \OCP\Share\IShare $share
77
-	 * @param string $recipient UserId of the recipient
78
-	 * @since 9.0.0
79
-	 */
80
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient);
81
-
82
-	/**
83
-	 * Move a share as a recipient.
84
-	 * This is updating the share target. Thus the mount point of the recipient.
85
-	 * This may require special handling. If a user moves a group share
86
-	 * the target should only be changed for them.
87
-	 *
88
-	 * @param \OCP\Share\IShare $share
89
-	 * @param string $recipient userId of recipient
90
-	 * @return \OCP\Share\IShare
91
-	 * @since 9.0.0
92
-	 */
93
-	public function move(\OCP\Share\IShare $share, $recipient);
94
-
95
-	/**
96
-	 * Get all shares by the given user in a folder
97
-	 *
98
-	 * @param string $userId
99
-	 * @param Folder $node
100
-	 * @param bool $reshares Also get the shares where $user is the owner instead of just the shares where $user is the initiator
101
-	 * @return \OCP\Share\IShare[]
102
-	 * @since 11.0.0
103
-	 */
104
-	public function getSharesInFolder($userId, Folder $node, $reshares);
105
-
106
-	/**
107
-	 * Get all shares by the given user
108
-	 *
109
-	 * @param string $userId
110
-	 * @param int $shareType
111
-	 * @param Node|null $node
112
-	 * @param bool $reshares Also get the shares where $user is the owner instead of just the shares where $user is the initiator
113
-	 * @param int $limit The maximum number of shares to be returned, -1 for all shares
114
-	 * @param int $offset
115
-	 * @return \OCP\Share\IShare[]
116
-	 * @since 9.0.0
117
-	 */
118
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset);
119
-
120
-	/**
121
-	 * Get share by id
122
-	 *
123
-	 * @param int $id
124
-	 * @param string|null $recipientId
125
-	 * @return \OCP\Share\IShare
126
-	 * @throws ShareNotFound
127
-	 * @since 9.0.0
128
-	 */
129
-	public function getShareById($id, $recipientId = null);
130
-
131
-	/**
132
-	 * Get shares for a given path
133
-	 *
134
-	 * @param Node $path
135
-	 * @return \OCP\Share\IShare[]
136
-	 * @since 9.0.0
137
-	 */
138
-	public function getSharesByPath(Node $path);
139
-
140
-	/**
141
-	 * Get shared with the given user
142
-	 *
143
-	 * @param string $userId get shares where this user is the recipient
144
-	 * @param int $shareType
145
-	 * @param Node|null $node
146
-	 * @param int $limit The max number of entries returned, -1 for all
147
-	 * @param int $offset
148
-	 * @return \OCP\Share\IShare[]
149
-	 * @since 9.0.0
150
-	 */
151
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset);
152
-
153
-	/**
154
-	 * Get a share by token
155
-	 *
156
-	 * @param string $token
157
-	 * @return \OCP\Share\IShare
158
-	 * @throws ShareNotFound
159
-	 * @since 9.0.0
160
-	 */
161
-	public function getShareByToken($token);
162
-
163
-	/**
164
-	 * A user is deleted from the system
165
-	 * So clean up the relevant shares.
166
-	 *
167
-	 * @param string $uid
168
-	 * @param int $shareType
169
-	 * @since 9.1.0
170
-	 */
171
-	public function userDeleted($uid, $shareType);
172
-
173
-	/**
174
-	 * A group is deleted from the system.
175
-	 * We have to clean up all shares to this group.
176
-	 * Providers not handling group shares should just return
177
-	 *
178
-	 * @param string $gid
179
-	 * @since 9.1.0
180
-	 */
181
-	public function groupDeleted($gid);
182
-
183
-	/**
184
-	 * A user is deleted from a group
185
-	 * We have to clean up all the related user specific group shares
186
-	 * Providers not handling group shares should just return
187
-	 *
188
-	 * @param string $uid
189
-	 * @param string $gid
190
-	 * @since 9.1.0
191
-	 */
192
-	public function userDeletedFromGroup($uid, $gid);
193
-
194
-	/**
195
-	 * Get the access list to the array of provided nodes.
196
-	 *
197
-	 * @see IManager::getAccessList() for sample docs
198
-	 *
199
-	 * @param Node[] $nodes The list of nodes to get access for
200
-	 * @param bool $currentAccess If current access is required (like for removed shares that might get revived later)
201
-	 * @return array
202
-	 * @since 12
203
-	 */
204
-	public function getAccessList($nodes, $currentAccess);
37
+    /**
38
+     * Return the identifier of this provider.
39
+     *
40
+     * @return string Containing only [a-zA-Z0-9]
41
+     * @since 9.0.0
42
+     */
43
+    public function identifier();
44
+
45
+    /**
46
+     * Create a share
47
+     * 
48
+     * @param \OCP\Share\IShare $share
49
+     * @return \OCP\Share\IShare The share object
50
+     * @since 9.0.0
51
+     */
52
+    public function create(\OCP\Share\IShare $share);
53
+
54
+    /**
55
+     * Update a share
56
+     *
57
+     * @param \OCP\Share\IShare $share
58
+     * @return \OCP\Share\IShare The share object
59
+     * @since 9.0.0
60
+     */
61
+    public function update(\OCP\Share\IShare $share);
62
+
63
+    /**
64
+     * Delete a share
65
+     *
66
+     * @param \OCP\Share\IShare $share
67
+     * @since 9.0.0
68
+     */
69
+    public function delete(\OCP\Share\IShare $share);
70
+
71
+    /**
72
+     * Unshare a file from self as recipient.
73
+     * This may require special handling. If a user unshares a group
74
+     * share from their self then the original group share should still exist.
75
+     *
76
+     * @param \OCP\Share\IShare $share
77
+     * @param string $recipient UserId of the recipient
78
+     * @since 9.0.0
79
+     */
80
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient);
81
+
82
+    /**
83
+     * Move a share as a recipient.
84
+     * This is updating the share target. Thus the mount point of the recipient.
85
+     * This may require special handling. If a user moves a group share
86
+     * the target should only be changed for them.
87
+     *
88
+     * @param \OCP\Share\IShare $share
89
+     * @param string $recipient userId of recipient
90
+     * @return \OCP\Share\IShare
91
+     * @since 9.0.0
92
+     */
93
+    public function move(\OCP\Share\IShare $share, $recipient);
94
+
95
+    /**
96
+     * Get all shares by the given user in a folder
97
+     *
98
+     * @param string $userId
99
+     * @param Folder $node
100
+     * @param bool $reshares Also get the shares where $user is the owner instead of just the shares where $user is the initiator
101
+     * @return \OCP\Share\IShare[]
102
+     * @since 11.0.0
103
+     */
104
+    public function getSharesInFolder($userId, Folder $node, $reshares);
105
+
106
+    /**
107
+     * Get all shares by the given user
108
+     *
109
+     * @param string $userId
110
+     * @param int $shareType
111
+     * @param Node|null $node
112
+     * @param bool $reshares Also get the shares where $user is the owner instead of just the shares where $user is the initiator
113
+     * @param int $limit The maximum number of shares to be returned, -1 for all shares
114
+     * @param int $offset
115
+     * @return \OCP\Share\IShare[]
116
+     * @since 9.0.0
117
+     */
118
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset);
119
+
120
+    /**
121
+     * Get share by id
122
+     *
123
+     * @param int $id
124
+     * @param string|null $recipientId
125
+     * @return \OCP\Share\IShare
126
+     * @throws ShareNotFound
127
+     * @since 9.0.0
128
+     */
129
+    public function getShareById($id, $recipientId = null);
130
+
131
+    /**
132
+     * Get shares for a given path
133
+     *
134
+     * @param Node $path
135
+     * @return \OCP\Share\IShare[]
136
+     * @since 9.0.0
137
+     */
138
+    public function getSharesByPath(Node $path);
139
+
140
+    /**
141
+     * Get shared with the given user
142
+     *
143
+     * @param string $userId get shares where this user is the recipient
144
+     * @param int $shareType
145
+     * @param Node|null $node
146
+     * @param int $limit The max number of entries returned, -1 for all
147
+     * @param int $offset
148
+     * @return \OCP\Share\IShare[]
149
+     * @since 9.0.0
150
+     */
151
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset);
152
+
153
+    /**
154
+     * Get a share by token
155
+     *
156
+     * @param string $token
157
+     * @return \OCP\Share\IShare
158
+     * @throws ShareNotFound
159
+     * @since 9.0.0
160
+     */
161
+    public function getShareByToken($token);
162
+
163
+    /**
164
+     * A user is deleted from the system
165
+     * So clean up the relevant shares.
166
+     *
167
+     * @param string $uid
168
+     * @param int $shareType
169
+     * @since 9.1.0
170
+     */
171
+    public function userDeleted($uid, $shareType);
172
+
173
+    /**
174
+     * A group is deleted from the system.
175
+     * We have to clean up all shares to this group.
176
+     * Providers not handling group shares should just return
177
+     *
178
+     * @param string $gid
179
+     * @since 9.1.0
180
+     */
181
+    public function groupDeleted($gid);
182
+
183
+    /**
184
+     * A user is deleted from a group
185
+     * We have to clean up all the related user specific group shares
186
+     * Providers not handling group shares should just return
187
+     *
188
+     * @param string $uid
189
+     * @param string $gid
190
+     * @since 9.1.0
191
+     */
192
+    public function userDeletedFromGroup($uid, $gid);
193
+
194
+    /**
195
+     * Get the access list to the array of provided nodes.
196
+     *
197
+     * @see IManager::getAccessList() for sample docs
198
+     *
199
+     * @param Node[] $nodes The list of nodes to get access for
200
+     * @param bool $currentAccess If current access is required (like for removed shares that might get revived later)
201
+     * @return array
202
+     * @since 12
203
+     */
204
+    public function getAccessList($nodes, $currentAccess);
205 205
 }
Please login to merge, or discard this patch.
lib/public/Share/IManager.php 1 patch
Indentation   +305 added lines, -305 removed lines patch added patch discarded remove patch
@@ -35,310 +35,310 @@
 block discarded – undo
35 35
  */
36 36
 interface IManager {
37 37
 
38
-	/**
39
-	 * Create a Share
40
-	 *
41
-	 * @param IShare $share
42
-	 * @return IShare The share object
43
-	 * @since 9.0.0
44
-	 */
45
-	public function createShare(IShare $share);
46
-
47
-	/**
48
-	 * Update a share.
49
-	 * The target of the share can't be changed this way: use moveShare
50
-	 * The share can't be removed this way (permission 0): use deleteShare
51
-	 *
52
-	 * @param IShare $share
53
-	 * @return IShare The share object
54
-	 * @since 9.0.0
55
-	 */
56
-	public function updateShare(IShare $share);
57
-
58
-	/**
59
-	 * Delete a share
60
-	 *
61
-	 * @param IShare $share
62
-	 * @throws ShareNotFound
63
-	 * @since 9.0.0
64
-	 */
65
-	public function deleteShare(IShare $share);
66
-
67
-	/**
68
-	 * Unshare a file as the recipient.
69
-	 * This can be different from a regular delete for example when one of
70
-	 * the users in a groups deletes that share. But the provider should
71
-	 * handle this.
72
-	 *
73
-	 * @param IShare $share
74
-	 * @param string $recipientId
75
-	 * @since 9.0.0
76
-	 */
77
-	public function deleteFromSelf(IShare $share, $recipientId);
78
-
79
-	/**
80
-	 * Move the share as a recipient of the share.
81
-	 * This is updating the share target. So where the recipient has the share mounted.
82
-	 *
83
-	 * @param IShare $share
84
-	 * @param string $recipientId
85
-	 * @return IShare
86
-	 * @throws \InvalidArgumentException If $share is a link share or the $recipient does not match
87
-	 * @since 9.0.0
88
-	 */
89
-	public function moveShare(IShare $share, $recipientId);
90
-
91
-	/**
92
-	 * Get all shares shared by (initiated) by the provided user in a folder.
93
-	 *
94
-	 * @param string $userId
95
-	 * @param Folder $node
96
-	 * @param bool $reshares
97
-	 * @return IShare[][] [$fileId => IShare[], ...]
98
-	 * @since 11.0.0
99
-	 */
100
-	public function getSharesInFolder($userId, Folder $node, $reshares = false);
101
-
102
-	/**
103
-	 * Get shares shared by (initiated) by the provided user.
104
-	 *
105
-	 * @param string $userId
106
-	 * @param int $shareType
107
-	 * @param Node|null $path
108
-	 * @param bool $reshares
109
-	 * @param int $limit The maximum number of returned results, -1 for all results
110
-	 * @param int $offset
111
-	 * @return IShare[]
112
-	 * @since 9.0.0
113
-	 */
114
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0);
115
-
116
-	/**
117
-	 * Get shares shared with $user.
118
-	 * Filter by $node if provided
119
-	 *
120
-	 * @param string $userId
121
-	 * @param int $shareType
122
-	 * @param Node|null $node
123
-	 * @param int $limit The maximum number of shares returned, -1 for all
124
-	 * @param int $offset
125
-	 * @return IShare[]
126
-	 * @since 9.0.0
127
-	 */
128
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0);
129
-
130
-	/**
131
-	 * Retrieve a share by the share id.
132
-	 * If the recipient is set make sure to retrieve the file for that user.
133
-	 * This makes sure that if a user has moved/deleted a group share this
134
-	 * is reflected.
135
-	 *
136
-	 * @param string $id
137
-	 * @param string|null $recipient userID of the recipient
138
-	 * @return IShare
139
-	 * @throws ShareNotFound
140
-	 * @since 9.0.0
141
-	 */
142
-	public function getShareById($id, $recipient = null);
143
-
144
-	/**
145
-	 * Get the share by token possible with password
146
-	 *
147
-	 * @param string $token
148
-	 * @return IShare
149
-	 * @throws ShareNotFound
150
-	 * @since 9.0.0
151
-	 */
152
-	public function getShareByToken($token);
153
-
154
-	/**
155
-	 * Verify the password of a public share
156
-	 *
157
-	 * @param IShare $share
158
-	 * @param string $password
159
-	 * @return bool
160
-	 * @since 9.0.0
161
-	 */
162
-	public function checkPassword(IShare $share, $password);
163
-
164
-	/**
165
-	 * The user with UID is deleted.
166
-	 * All share providers have to cleanup the shares with this user as well
167
-	 * as shares owned by this user.
168
-	 * Shares only initiated by this user are fine.
169
-	 *
170
-	 * @param string $uid
171
-	 * @since 9.1.0
172
-	 */
173
-	public function userDeleted($uid);
174
-
175
-	/**
176
-	 * The group with $gid is deleted
177
-	 * We need to clear up all shares to this group
178
-	 *
179
-	 * @param string $gid
180
-	 * @since 9.1.0
181
-	 */
182
-	public function groupDeleted($gid);
183
-
184
-	/**
185
-	 * The user $uid is deleted from the group $gid
186
-	 * All user specific group shares have to be removed
187
-	 *
188
-	 * @param string $uid
189
-	 * @param string $gid
190
-	 * @since 9.1.0
191
-	 */
192
-	public function userDeletedFromGroup($uid, $gid);
193
-
194
-	/**
195
-	 * Get access list to a path. This means
196
-	 * all the users that can access a given path.
197
-	 *
198
-	 * Consider:
199
-	 * -root
200
-	 * |-folder1 (23)
201
-	 *  |-folder2 (32)
202
-	 *   |-fileA (42)
203
-	 *
204
-	 * fileA is shared with user1 and user1@server1
205
-	 * folder2 is shared with group2 (user4 is a member of group2)
206
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
207
-	 *
208
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
209
-	 * [
210
-	 *  users  => [
211
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
212
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
213
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
214
-	 *  ],
215
-	 *  remote => [
216
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
217
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
218
-	 *  ],
219
-	 *  public => bool
220
-	 *  mail => bool
221
-	 * ]
222
-	 *
223
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
224
-	 * [
225
-	 *  users  => ['user1', 'user2', 'user4'],
226
-	 *  remote => bool,
227
-	 *  public => bool
228
-	 *  mail => bool
229
-	 * ]
230
-	 *
231
-	 * This is required for encryption/activity
232
-	 *
233
-	 * @param \OCP\Files\Node $path
234
-	 * @param bool $recursive Should we check all parent folders as well
235
-	 * @param bool $currentAccess Should the user have currently access to the file
236
-	 * @return array
237
-	 * @since 12
238
-	 */
239
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false);
240
-
241
-	/**
242
-	 * Instantiates a new share object. This is to be passed to
243
-	 * createShare.
244
-	 *
245
-	 * @return IShare
246
-	 * @since 9.0.0
247
-	 */
248
-	public function newShare();
249
-
250
-	/**
251
-	 * Is the share API enabled
252
-	 *
253
-	 * @return bool
254
-	 * @since 9.0.0
255
-	 */
256
-	public function shareApiEnabled();
257
-
258
-	/**
259
-	 * Is public link sharing enabled
260
-	 *
261
-	 * @return bool
262
-	 * @since 9.0.0
263
-	 */
264
-	public function shareApiAllowLinks();
265
-
266
-	/**
267
-	 * Is password on public link requires
268
-	 *
269
-	 * @return bool
270
-	 * @since 9.0.0
271
-	 */
272
-	public function shareApiLinkEnforcePassword();
273
-
274
-	/**
275
-	 * Is default expire date enabled
276
-	 *
277
-	 * @return bool
278
-	 * @since 9.0.0
279
-	 */
280
-	public function shareApiLinkDefaultExpireDate();
281
-
282
-	/**
283
-	 * Is default expire date enforced
284
-	 *`
285
-	 * @return bool
286
-	 * @since 9.0.0
287
-	 */
288
-	public function shareApiLinkDefaultExpireDateEnforced();
289
-
290
-	/**
291
-	 * Number of default expire days
292
-	 *
293
-	 * @return int
294
-	 * @since 9.0.0
295
-	 */
296
-	public function shareApiLinkDefaultExpireDays();
297
-
298
-	/**
299
-	 * Allow public upload on link shares
300
-	 *
301
-	 * @return bool
302
-	 * @since 9.0.0
303
-	 */
304
-	public function shareApiLinkAllowPublicUpload();
305
-
306
-	/**
307
-	 * check if user can only share with group members
308
-	 * @return bool
309
-	 * @since 9.0.0
310
-	 */
311
-	public function shareWithGroupMembersOnly();
312
-
313
-	/**
314
-	 * Check if users can share with groups
315
-	 * @return bool
316
-	 * @since 9.0.1
317
-	 */
318
-	public function allowGroupSharing();
319
-
320
-	/**
321
-	 * Check if sharing is disabled for the given user
322
-	 *
323
-	 * @param string $userId
324
-	 * @return bool
325
-	 * @since 9.0.0
326
-	 */
327
-	public function sharingDisabledForUser($userId);
328
-
329
-	/**
330
-	 * Check if outgoing server2server shares are allowed
331
-	 * @return bool
332
-	 * @since 9.0.0
333
-	 */
334
-	public function outgoingServer2ServerSharesAllowed();
335
-
336
-	/**
337
-	 * Check if a given share provider exists
338
-	 * @param int $shareType
339
-	 * @return bool
340
-	 * @since 11.0.0
341
-	 */
342
-	public function shareProviderExists($shareType);
38
+    /**
39
+     * Create a Share
40
+     *
41
+     * @param IShare $share
42
+     * @return IShare The share object
43
+     * @since 9.0.0
44
+     */
45
+    public function createShare(IShare $share);
46
+
47
+    /**
48
+     * Update a share.
49
+     * The target of the share can't be changed this way: use moveShare
50
+     * The share can't be removed this way (permission 0): use deleteShare
51
+     *
52
+     * @param IShare $share
53
+     * @return IShare The share object
54
+     * @since 9.0.0
55
+     */
56
+    public function updateShare(IShare $share);
57
+
58
+    /**
59
+     * Delete a share
60
+     *
61
+     * @param IShare $share
62
+     * @throws ShareNotFound
63
+     * @since 9.0.0
64
+     */
65
+    public function deleteShare(IShare $share);
66
+
67
+    /**
68
+     * Unshare a file as the recipient.
69
+     * This can be different from a regular delete for example when one of
70
+     * the users in a groups deletes that share. But the provider should
71
+     * handle this.
72
+     *
73
+     * @param IShare $share
74
+     * @param string $recipientId
75
+     * @since 9.0.0
76
+     */
77
+    public function deleteFromSelf(IShare $share, $recipientId);
78
+
79
+    /**
80
+     * Move the share as a recipient of the share.
81
+     * This is updating the share target. So where the recipient has the share mounted.
82
+     *
83
+     * @param IShare $share
84
+     * @param string $recipientId
85
+     * @return IShare
86
+     * @throws \InvalidArgumentException If $share is a link share or the $recipient does not match
87
+     * @since 9.0.0
88
+     */
89
+    public function moveShare(IShare $share, $recipientId);
90
+
91
+    /**
92
+     * Get all shares shared by (initiated) by the provided user in a folder.
93
+     *
94
+     * @param string $userId
95
+     * @param Folder $node
96
+     * @param bool $reshares
97
+     * @return IShare[][] [$fileId => IShare[], ...]
98
+     * @since 11.0.0
99
+     */
100
+    public function getSharesInFolder($userId, Folder $node, $reshares = false);
101
+
102
+    /**
103
+     * Get shares shared by (initiated) by the provided user.
104
+     *
105
+     * @param string $userId
106
+     * @param int $shareType
107
+     * @param Node|null $path
108
+     * @param bool $reshares
109
+     * @param int $limit The maximum number of returned results, -1 for all results
110
+     * @param int $offset
111
+     * @return IShare[]
112
+     * @since 9.0.0
113
+     */
114
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0);
115
+
116
+    /**
117
+     * Get shares shared with $user.
118
+     * Filter by $node if provided
119
+     *
120
+     * @param string $userId
121
+     * @param int $shareType
122
+     * @param Node|null $node
123
+     * @param int $limit The maximum number of shares returned, -1 for all
124
+     * @param int $offset
125
+     * @return IShare[]
126
+     * @since 9.0.0
127
+     */
128
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0);
129
+
130
+    /**
131
+     * Retrieve a share by the share id.
132
+     * If the recipient is set make sure to retrieve the file for that user.
133
+     * This makes sure that if a user has moved/deleted a group share this
134
+     * is reflected.
135
+     *
136
+     * @param string $id
137
+     * @param string|null $recipient userID of the recipient
138
+     * @return IShare
139
+     * @throws ShareNotFound
140
+     * @since 9.0.0
141
+     */
142
+    public function getShareById($id, $recipient = null);
143
+
144
+    /**
145
+     * Get the share by token possible with password
146
+     *
147
+     * @param string $token
148
+     * @return IShare
149
+     * @throws ShareNotFound
150
+     * @since 9.0.0
151
+     */
152
+    public function getShareByToken($token);
153
+
154
+    /**
155
+     * Verify the password of a public share
156
+     *
157
+     * @param IShare $share
158
+     * @param string $password
159
+     * @return bool
160
+     * @since 9.0.0
161
+     */
162
+    public function checkPassword(IShare $share, $password);
163
+
164
+    /**
165
+     * The user with UID is deleted.
166
+     * All share providers have to cleanup the shares with this user as well
167
+     * as shares owned by this user.
168
+     * Shares only initiated by this user are fine.
169
+     *
170
+     * @param string $uid
171
+     * @since 9.1.0
172
+     */
173
+    public function userDeleted($uid);
174
+
175
+    /**
176
+     * The group with $gid is deleted
177
+     * We need to clear up all shares to this group
178
+     *
179
+     * @param string $gid
180
+     * @since 9.1.0
181
+     */
182
+    public function groupDeleted($gid);
183
+
184
+    /**
185
+     * The user $uid is deleted from the group $gid
186
+     * All user specific group shares have to be removed
187
+     *
188
+     * @param string $uid
189
+     * @param string $gid
190
+     * @since 9.1.0
191
+     */
192
+    public function userDeletedFromGroup($uid, $gid);
193
+
194
+    /**
195
+     * Get access list to a path. This means
196
+     * all the users that can access a given path.
197
+     *
198
+     * Consider:
199
+     * -root
200
+     * |-folder1 (23)
201
+     *  |-folder2 (32)
202
+     *   |-fileA (42)
203
+     *
204
+     * fileA is shared with user1 and user1@server1
205
+     * folder2 is shared with group2 (user4 is a member of group2)
206
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
207
+     *
208
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
209
+     * [
210
+     *  users  => [
211
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
212
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
213
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
214
+     *  ],
215
+     *  remote => [
216
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
217
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
218
+     *  ],
219
+     *  public => bool
220
+     *  mail => bool
221
+     * ]
222
+     *
223
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
224
+     * [
225
+     *  users  => ['user1', 'user2', 'user4'],
226
+     *  remote => bool,
227
+     *  public => bool
228
+     *  mail => bool
229
+     * ]
230
+     *
231
+     * This is required for encryption/activity
232
+     *
233
+     * @param \OCP\Files\Node $path
234
+     * @param bool $recursive Should we check all parent folders as well
235
+     * @param bool $currentAccess Should the user have currently access to the file
236
+     * @return array
237
+     * @since 12
238
+     */
239
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false);
240
+
241
+    /**
242
+     * Instantiates a new share object. This is to be passed to
243
+     * createShare.
244
+     *
245
+     * @return IShare
246
+     * @since 9.0.0
247
+     */
248
+    public function newShare();
249
+
250
+    /**
251
+     * Is the share API enabled
252
+     *
253
+     * @return bool
254
+     * @since 9.0.0
255
+     */
256
+    public function shareApiEnabled();
257
+
258
+    /**
259
+     * Is public link sharing enabled
260
+     *
261
+     * @return bool
262
+     * @since 9.0.0
263
+     */
264
+    public function shareApiAllowLinks();
265
+
266
+    /**
267
+     * Is password on public link requires
268
+     *
269
+     * @return bool
270
+     * @since 9.0.0
271
+     */
272
+    public function shareApiLinkEnforcePassword();
273
+
274
+    /**
275
+     * Is default expire date enabled
276
+     *
277
+     * @return bool
278
+     * @since 9.0.0
279
+     */
280
+    public function shareApiLinkDefaultExpireDate();
281
+
282
+    /**
283
+     * Is default expire date enforced
284
+     *`
285
+     * @return bool
286
+     * @since 9.0.0
287
+     */
288
+    public function shareApiLinkDefaultExpireDateEnforced();
289
+
290
+    /**
291
+     * Number of default expire days
292
+     *
293
+     * @return int
294
+     * @since 9.0.0
295
+     */
296
+    public function shareApiLinkDefaultExpireDays();
297
+
298
+    /**
299
+     * Allow public upload on link shares
300
+     *
301
+     * @return bool
302
+     * @since 9.0.0
303
+     */
304
+    public function shareApiLinkAllowPublicUpload();
305
+
306
+    /**
307
+     * check if user can only share with group members
308
+     * @return bool
309
+     * @since 9.0.0
310
+     */
311
+    public function shareWithGroupMembersOnly();
312
+
313
+    /**
314
+     * Check if users can share with groups
315
+     * @return bool
316
+     * @since 9.0.1
317
+     */
318
+    public function allowGroupSharing();
319
+
320
+    /**
321
+     * Check if sharing is disabled for the given user
322
+     *
323
+     * @param string $userId
324
+     * @return bool
325
+     * @since 9.0.0
326
+     */
327
+    public function sharingDisabledForUser($userId);
328
+
329
+    /**
330
+     * Check if outgoing server2server shares are allowed
331
+     * @return bool
332
+     * @since 9.0.0
333
+     */
334
+    public function outgoingServer2ServerSharesAllowed();
335
+
336
+    /**
337
+     * Check if a given share provider exists
338
+     * @param int $shareType
339
+     * @return bool
340
+     * @since 11.0.0
341
+     */
342
+    public function shareProviderExists($shareType);
343 343
 
344 344
 }
Please login to merge, or discard this patch.
lib/private/Share20/ShareHelper.php 2 patches
Indentation   +183 added lines, -183 removed lines patch added patch discarded remove patch
@@ -31,187 +31,187 @@
 block discarded – undo
31 31
 
32 32
 class ShareHelper implements IShareHelper {
33 33
 
34
-	/** @var IManager */
35
-	private $shareManager;
36
-
37
-	public function __construct(IManager $shareManager) {
38
-		$this->shareManager = $shareManager;
39
-	}
40
-
41
-	/**
42
-	 * @param Node $node
43
-	 * @return array [ users => [Mapping $uid => $pathForUser], remotes => [Mapping $cloudId => $pathToMountRoot]]
44
-	 */
45
-	public function getPathsForAccessList(Node $node) {
46
-		$result = [
47
-			'users' => [],
48
-			'remotes' => [],
49
-		];
50
-
51
-		$accessList = $this->shareManager->getAccessList($node, true, true);
52
-		if (!empty($accessList['users'])) {
53
-			$result['users'] = $this->getPathsForUsers($node, $accessList['users']);
54
-		}
55
-		if (!empty($accessList['remote'])) {
56
-			$result['remotes'] = $this->getPathsForRemotes($node, $accessList['remote']);
57
-		}
58
-
59
-		return $result;
60
-	}
61
-
62
-	/**
63
-	 * Sample:
64
-	 * $users = [
65
-	 *   'test1' => ['node_id' => 16, 'node_path' => '/foo'],
66
-	 *   'test2' => ['node_id' => 23, 'node_path' => '/bar'],
67
-	 *   'test3' => ['node_id' => 42, 'node_path' => '/cat'],
68
-	 *   'test4' => ['node_id' => 48, 'node_path' => '/dog'],
69
-	 * ];
70
-	 *
71
-	 * Node tree:
72
-	 * - SixTeen is the parent of TwentyThree
73
-	 * - TwentyThree is the parent of FortyTwo
74
-	 * - FortyEight does not exist
75
-	 *
76
-	 * $return = [
77
-	 *   'test1' => '/foo/TwentyThree/FortyTwo',
78
-	 *   'test2' => '/bar/FortyTwo',
79
-	 *   'test3' => '/cat',
80
-	 * ],
81
-	 *
82
-	 * @param Node $node
83
-	 * @param array[] $users
84
-	 * @return array
85
-	 */
86
-	protected function getPathsForUsers(Node $node, array $users) {
87
-		/** @var array[] $byId */
88
-		$byId = [];
89
-		/** @var array[] $results */
90
-		$results = [];
91
-
92
-		foreach ($users as $uid => $info) {
93
-			if (!isset($byId[$info['node_id']])) {
94
-				$byId[$info['node_id']] = [];
95
-			}
96
-			$byId[$info['node_id']][$uid] = $info['node_path'];
97
-		}
98
-
99
-		try {
100
-			if (isset($byId[$node->getId()])) {
101
-				foreach ($byId[$node->getId()] as $uid => $path) {
102
-					$results[$uid] = $path;
103
-				}
104
-				unset($byId[$node->getId()]);
105
-			}
106
-		} catch (NotFoundException $e) {
107
-			return $results;
108
-		} catch (InvalidPathException $e) {
109
-			return $results;
110
-		}
111
-
112
-		if (empty($byId)) {
113
-			return $results;
114
-		}
115
-
116
-		$item = $node;
117
-		$appendix = '/' . $node->getName();
118
-		while (!empty($byId)) {
119
-			try {
120
-				/** @var Node $item */
121
-				$item = $item->getParent();
122
-
123
-				if (!empty($byId[$item->getId()])) {
124
-					foreach ($byId[$item->getId()] as $uid => $path) {
125
-						$results[$uid] = $path . $appendix;
126
-					}
127
-					unset($byId[$item->getId()]);
128
-				}
129
-
130
-				$appendix = '/' . $item->getName() . $appendix;
131
-			} catch (NotFoundException $e) {
132
-				return $results;
133
-			} catch (InvalidPathException $e) {
134
-				return $results;
135
-			} catch (NotPermittedException $e) {
136
-				return $results;
137
-			}
138
-		}
139
-
140
-		return $results;
141
-	}
142
-
143
-	/**
144
-	 * Sample:
145
-	 * $remotes = [
146
-	 *   'test1' => ['node_id' => 16, 'token' => 't1'],
147
-	 *   'test2' => ['node_id' => 23, 'token' => 't2'],
148
-	 *   'test3' => ['node_id' => 42, 'token' => 't3'],
149
-	 *   'test4' => ['node_id' => 48, 'token' => 't4'],
150
-	 * ];
151
-	 *
152
-	 * Node tree:
153
-	 * - SixTeen is the parent of TwentyThree
154
-	 * - TwentyThree is the parent of FortyTwo
155
-	 * - FortyEight does not exist
156
-	 *
157
-	 * $return = [
158
-	 *   'test1' => ['token' => 't1', 'node_path' => '/SixTeen'],
159
-	 *   'test2' => ['token' => 't2', 'node_path' => '/SixTeen/TwentyThree'],
160
-	 *   'test3' => ['token' => 't3', 'node_path' => '/SixTeen/TwentyThree/FortyTwo'],
161
-	 * ],
162
-	 *
163
-	 * @param Node $node
164
-	 * @param array[] $remotes
165
-	 * @return array
166
-	 */
167
-	protected function getPathsForRemotes(Node $node, array $remotes) {
168
-		/** @var array[] $byId */
169
-		$byId = [];
170
-		/** @var array[] $results */
171
-		$results = [];
172
-
173
-		foreach ($remotes as $cloudId => $info) {
174
-			if (!isset($byId[$info['node_id']])) {
175
-				$byId[$info['node_id']] = [];
176
-			}
177
-			$byId[$info['node_id']][$cloudId] = $info['token'];
178
-		}
179
-
180
-		$item = $node;
181
-		while (!empty($byId)) {
182
-			try {
183
-				if (!empty($byId[$item->getId()])) {
184
-					$path = $this->getMountedPath($item);
185
-					foreach ($byId[$item->getId()] as $uid => $token) {
186
-						$results[$uid] = [
187
-							'node_path' => $path,
188
-							'token' => $token,
189
-						];
190
-					}
191
-					unset($byId[$item->getId()]);
192
-				}
193
-
194
-				/** @var Node $item */
195
-				$item = $item->getParent();
196
-			} catch (NotFoundException $e) {
197
-				return $results;
198
-			} catch (InvalidPathException $e) {
199
-				return $results;
200
-			} catch (NotPermittedException $e) {
201
-				return $results;
202
-			}
203
-		}
204
-
205
-		return $results;
206
-	}
207
-
208
-	/**
209
-	 * @param Node $node
210
-	 * @return string
211
-	 */
212
-	protected function getMountedPath(Node $node) {
213
-		$path = $node->getPath();
214
-		$sections = explode('/', $path, 4);
215
-		return '/' . $sections[3];
216
-	}
34
+    /** @var IManager */
35
+    private $shareManager;
36
+
37
+    public function __construct(IManager $shareManager) {
38
+        $this->shareManager = $shareManager;
39
+    }
40
+
41
+    /**
42
+     * @param Node $node
43
+     * @return array [ users => [Mapping $uid => $pathForUser], remotes => [Mapping $cloudId => $pathToMountRoot]]
44
+     */
45
+    public function getPathsForAccessList(Node $node) {
46
+        $result = [
47
+            'users' => [],
48
+            'remotes' => [],
49
+        ];
50
+
51
+        $accessList = $this->shareManager->getAccessList($node, true, true);
52
+        if (!empty($accessList['users'])) {
53
+            $result['users'] = $this->getPathsForUsers($node, $accessList['users']);
54
+        }
55
+        if (!empty($accessList['remote'])) {
56
+            $result['remotes'] = $this->getPathsForRemotes($node, $accessList['remote']);
57
+        }
58
+
59
+        return $result;
60
+    }
61
+
62
+    /**
63
+     * Sample:
64
+     * $users = [
65
+     *   'test1' => ['node_id' => 16, 'node_path' => '/foo'],
66
+     *   'test2' => ['node_id' => 23, 'node_path' => '/bar'],
67
+     *   'test3' => ['node_id' => 42, 'node_path' => '/cat'],
68
+     *   'test4' => ['node_id' => 48, 'node_path' => '/dog'],
69
+     * ];
70
+     *
71
+     * Node tree:
72
+     * - SixTeen is the parent of TwentyThree
73
+     * - TwentyThree is the parent of FortyTwo
74
+     * - FortyEight does not exist
75
+     *
76
+     * $return = [
77
+     *   'test1' => '/foo/TwentyThree/FortyTwo',
78
+     *   'test2' => '/bar/FortyTwo',
79
+     *   'test3' => '/cat',
80
+     * ],
81
+     *
82
+     * @param Node $node
83
+     * @param array[] $users
84
+     * @return array
85
+     */
86
+    protected function getPathsForUsers(Node $node, array $users) {
87
+        /** @var array[] $byId */
88
+        $byId = [];
89
+        /** @var array[] $results */
90
+        $results = [];
91
+
92
+        foreach ($users as $uid => $info) {
93
+            if (!isset($byId[$info['node_id']])) {
94
+                $byId[$info['node_id']] = [];
95
+            }
96
+            $byId[$info['node_id']][$uid] = $info['node_path'];
97
+        }
98
+
99
+        try {
100
+            if (isset($byId[$node->getId()])) {
101
+                foreach ($byId[$node->getId()] as $uid => $path) {
102
+                    $results[$uid] = $path;
103
+                }
104
+                unset($byId[$node->getId()]);
105
+            }
106
+        } catch (NotFoundException $e) {
107
+            return $results;
108
+        } catch (InvalidPathException $e) {
109
+            return $results;
110
+        }
111
+
112
+        if (empty($byId)) {
113
+            return $results;
114
+        }
115
+
116
+        $item = $node;
117
+        $appendix = '/' . $node->getName();
118
+        while (!empty($byId)) {
119
+            try {
120
+                /** @var Node $item */
121
+                $item = $item->getParent();
122
+
123
+                if (!empty($byId[$item->getId()])) {
124
+                    foreach ($byId[$item->getId()] as $uid => $path) {
125
+                        $results[$uid] = $path . $appendix;
126
+                    }
127
+                    unset($byId[$item->getId()]);
128
+                }
129
+
130
+                $appendix = '/' . $item->getName() . $appendix;
131
+            } catch (NotFoundException $e) {
132
+                return $results;
133
+            } catch (InvalidPathException $e) {
134
+                return $results;
135
+            } catch (NotPermittedException $e) {
136
+                return $results;
137
+            }
138
+        }
139
+
140
+        return $results;
141
+    }
142
+
143
+    /**
144
+     * Sample:
145
+     * $remotes = [
146
+     *   'test1' => ['node_id' => 16, 'token' => 't1'],
147
+     *   'test2' => ['node_id' => 23, 'token' => 't2'],
148
+     *   'test3' => ['node_id' => 42, 'token' => 't3'],
149
+     *   'test4' => ['node_id' => 48, 'token' => 't4'],
150
+     * ];
151
+     *
152
+     * Node tree:
153
+     * - SixTeen is the parent of TwentyThree
154
+     * - TwentyThree is the parent of FortyTwo
155
+     * - FortyEight does not exist
156
+     *
157
+     * $return = [
158
+     *   'test1' => ['token' => 't1', 'node_path' => '/SixTeen'],
159
+     *   'test2' => ['token' => 't2', 'node_path' => '/SixTeen/TwentyThree'],
160
+     *   'test3' => ['token' => 't3', 'node_path' => '/SixTeen/TwentyThree/FortyTwo'],
161
+     * ],
162
+     *
163
+     * @param Node $node
164
+     * @param array[] $remotes
165
+     * @return array
166
+     */
167
+    protected function getPathsForRemotes(Node $node, array $remotes) {
168
+        /** @var array[] $byId */
169
+        $byId = [];
170
+        /** @var array[] $results */
171
+        $results = [];
172
+
173
+        foreach ($remotes as $cloudId => $info) {
174
+            if (!isset($byId[$info['node_id']])) {
175
+                $byId[$info['node_id']] = [];
176
+            }
177
+            $byId[$info['node_id']][$cloudId] = $info['token'];
178
+        }
179
+
180
+        $item = $node;
181
+        while (!empty($byId)) {
182
+            try {
183
+                if (!empty($byId[$item->getId()])) {
184
+                    $path = $this->getMountedPath($item);
185
+                    foreach ($byId[$item->getId()] as $uid => $token) {
186
+                        $results[$uid] = [
187
+                            'node_path' => $path,
188
+                            'token' => $token,
189
+                        ];
190
+                    }
191
+                    unset($byId[$item->getId()]);
192
+                }
193
+
194
+                /** @var Node $item */
195
+                $item = $item->getParent();
196
+            } catch (NotFoundException $e) {
197
+                return $results;
198
+            } catch (InvalidPathException $e) {
199
+                return $results;
200
+            } catch (NotPermittedException $e) {
201
+                return $results;
202
+            }
203
+        }
204
+
205
+        return $results;
206
+    }
207
+
208
+    /**
209
+     * @param Node $node
210
+     * @return string
211
+     */
212
+    protected function getMountedPath(Node $node) {
213
+        $path = $node->getPath();
214
+        $sections = explode('/', $path, 4);
215
+        return '/' . $sections[3];
216
+    }
217 217
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 		}
115 115
 
116 116
 		$item = $node;
117
-		$appendix = '/' . $node->getName();
117
+		$appendix = '/'.$node->getName();
118 118
 		while (!empty($byId)) {
119 119
 			try {
120 120
 				/** @var Node $item */
@@ -122,12 +122,12 @@  discard block
 block discarded – undo
122 122
 
123 123
 				if (!empty($byId[$item->getId()])) {
124 124
 					foreach ($byId[$item->getId()] as $uid => $path) {
125
-						$results[$uid] = $path . $appendix;
125
+						$results[$uid] = $path.$appendix;
126 126
 					}
127 127
 					unset($byId[$item->getId()]);
128 128
 				}
129 129
 
130
-				$appendix = '/' . $item->getName() . $appendix;
130
+				$appendix = '/'.$item->getName().$appendix;
131 131
 			} catch (NotFoundException $e) {
132 132
 				return $results;
133 133
 			} catch (InvalidPathException $e) {
@@ -212,6 +212,6 @@  discard block
 block discarded – undo
212 212
 	protected function getMountedPath(Node $node) {
213 213
 		$path = $node->getPath();
214 214
 		$sections = explode('/', $path, 4);
215
-		return '/' . $sections[3];
215
+		return '/'.$sections[3];
216 216
 	}
217 217
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/FederatedShareProvider.php 1 patch
Indentation   +954 added lines, -954 removed lines patch added patch discarded remove patch
@@ -50,968 +50,968 @@
 block discarded – undo
50 50
  */
51 51
 class FederatedShareProvider implements IShareProvider {
52 52
 
53
-	const SHARE_TYPE_REMOTE = 6;
54
-
55
-	/** @var IDBConnection */
56
-	private $dbConnection;
57
-
58
-	/** @var AddressHandler */
59
-	private $addressHandler;
60
-
61
-	/** @var Notifications */
62
-	private $notifications;
63
-
64
-	/** @var TokenHandler */
65
-	private $tokenHandler;
66
-
67
-	/** @var IL10N */
68
-	private $l;
69
-
70
-	/** @var ILogger */
71
-	private $logger;
72
-
73
-	/** @var IRootFolder */
74
-	private $rootFolder;
75
-
76
-	/** @var IConfig */
77
-	private $config;
78
-
79
-	/** @var string */
80
-	private $externalShareTable = 'share_external';
81
-
82
-	/** @var IUserManager */
83
-	private $userManager;
84
-
85
-	/** @var ICloudIdManager */
86
-	private $cloudIdManager;
87
-
88
-	/**
89
-	 * DefaultShareProvider constructor.
90
-	 *
91
-	 * @param IDBConnection $connection
92
-	 * @param AddressHandler $addressHandler
93
-	 * @param Notifications $notifications
94
-	 * @param TokenHandler $tokenHandler
95
-	 * @param IL10N $l10n
96
-	 * @param ILogger $logger
97
-	 * @param IRootFolder $rootFolder
98
-	 * @param IConfig $config
99
-	 * @param IUserManager $userManager
100
-	 * @param ICloudIdManager $cloudIdManager
101
-	 */
102
-	public function __construct(
103
-			IDBConnection $connection,
104
-			AddressHandler $addressHandler,
105
-			Notifications $notifications,
106
-			TokenHandler $tokenHandler,
107
-			IL10N $l10n,
108
-			ILogger $logger,
109
-			IRootFolder $rootFolder,
110
-			IConfig $config,
111
-			IUserManager $userManager,
112
-			ICloudIdManager $cloudIdManager
113
-	) {
114
-		$this->dbConnection = $connection;
115
-		$this->addressHandler = $addressHandler;
116
-		$this->notifications = $notifications;
117
-		$this->tokenHandler = $tokenHandler;
118
-		$this->l = $l10n;
119
-		$this->logger = $logger;
120
-		$this->rootFolder = $rootFolder;
121
-		$this->config = $config;
122
-		$this->userManager = $userManager;
123
-		$this->cloudIdManager = $cloudIdManager;
124
-	}
125
-
126
-	/**
127
-	 * Return the identifier of this provider.
128
-	 *
129
-	 * @return string Containing only [a-zA-Z0-9]
130
-	 */
131
-	public function identifier() {
132
-		return 'ocFederatedSharing';
133
-	}
134
-
135
-	/**
136
-	 * Share a path
137
-	 *
138
-	 * @param IShare $share
139
-	 * @return IShare The share object
140
-	 * @throws ShareNotFound
141
-	 * @throws \Exception
142
-	 */
143
-	public function create(IShare $share) {
144
-
145
-		$shareWith = $share->getSharedWith();
146
-		$itemSource = $share->getNodeId();
147
-		$itemType = $share->getNodeType();
148
-		$permissions = $share->getPermissions();
149
-		$sharedBy = $share->getSharedBy();
150
-
151
-		/*
53
+    const SHARE_TYPE_REMOTE = 6;
54
+
55
+    /** @var IDBConnection */
56
+    private $dbConnection;
57
+
58
+    /** @var AddressHandler */
59
+    private $addressHandler;
60
+
61
+    /** @var Notifications */
62
+    private $notifications;
63
+
64
+    /** @var TokenHandler */
65
+    private $tokenHandler;
66
+
67
+    /** @var IL10N */
68
+    private $l;
69
+
70
+    /** @var ILogger */
71
+    private $logger;
72
+
73
+    /** @var IRootFolder */
74
+    private $rootFolder;
75
+
76
+    /** @var IConfig */
77
+    private $config;
78
+
79
+    /** @var string */
80
+    private $externalShareTable = 'share_external';
81
+
82
+    /** @var IUserManager */
83
+    private $userManager;
84
+
85
+    /** @var ICloudIdManager */
86
+    private $cloudIdManager;
87
+
88
+    /**
89
+     * DefaultShareProvider constructor.
90
+     *
91
+     * @param IDBConnection $connection
92
+     * @param AddressHandler $addressHandler
93
+     * @param Notifications $notifications
94
+     * @param TokenHandler $tokenHandler
95
+     * @param IL10N $l10n
96
+     * @param ILogger $logger
97
+     * @param IRootFolder $rootFolder
98
+     * @param IConfig $config
99
+     * @param IUserManager $userManager
100
+     * @param ICloudIdManager $cloudIdManager
101
+     */
102
+    public function __construct(
103
+            IDBConnection $connection,
104
+            AddressHandler $addressHandler,
105
+            Notifications $notifications,
106
+            TokenHandler $tokenHandler,
107
+            IL10N $l10n,
108
+            ILogger $logger,
109
+            IRootFolder $rootFolder,
110
+            IConfig $config,
111
+            IUserManager $userManager,
112
+            ICloudIdManager $cloudIdManager
113
+    ) {
114
+        $this->dbConnection = $connection;
115
+        $this->addressHandler = $addressHandler;
116
+        $this->notifications = $notifications;
117
+        $this->tokenHandler = $tokenHandler;
118
+        $this->l = $l10n;
119
+        $this->logger = $logger;
120
+        $this->rootFolder = $rootFolder;
121
+        $this->config = $config;
122
+        $this->userManager = $userManager;
123
+        $this->cloudIdManager = $cloudIdManager;
124
+    }
125
+
126
+    /**
127
+     * Return the identifier of this provider.
128
+     *
129
+     * @return string Containing only [a-zA-Z0-9]
130
+     */
131
+    public function identifier() {
132
+        return 'ocFederatedSharing';
133
+    }
134
+
135
+    /**
136
+     * Share a path
137
+     *
138
+     * @param IShare $share
139
+     * @return IShare The share object
140
+     * @throws ShareNotFound
141
+     * @throws \Exception
142
+     */
143
+    public function create(IShare $share) {
144
+
145
+        $shareWith = $share->getSharedWith();
146
+        $itemSource = $share->getNodeId();
147
+        $itemType = $share->getNodeType();
148
+        $permissions = $share->getPermissions();
149
+        $sharedBy = $share->getSharedBy();
150
+
151
+        /*
152 152
 		 * Check if file is not already shared with the remote user
153 153
 		 */
154
-		$alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
155
-		if (!empty($alreadyShared)) {
156
-			$message = 'Sharing %s failed, because this item is already shared with %s';
157
-			$message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
158
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
159
-			throw new \Exception($message_t);
160
-		}
161
-
162
-
163
-		// don't allow federated shares if source and target server are the same
164
-		$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
165
-		$currentServer = $this->addressHandler->generateRemoteURL();
166
-		$currentUser = $sharedBy;
167
-		if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
168
-			$message = 'Not allowed to create a federated share with the same user.';
169
-			$message_t = $this->l->t('Not allowed to create a federated share with the same user');
170
-			$this->logger->debug($message, ['app' => 'Federated File Sharing']);
171
-			throw new \Exception($message_t);
172
-		}
173
-
174
-
175
-		$share->setSharedWith($cloudId->getId());
176
-
177
-		try {
178
-			$remoteShare = $this->getShareFromExternalShareTable($share);
179
-		} catch (ShareNotFound $e) {
180
-			$remoteShare = null;
181
-		}
182
-
183
-		if ($remoteShare) {
184
-			try {
185
-				$ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
186
-				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
187
-				$share->setId($shareId);
188
-				list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
189
-				// remote share was create successfully if we get a valid token as return
190
-				$send = is_string($token) && $token !== '';
191
-			} catch (\Exception $e) {
192
-				// fall back to old re-share behavior if the remote server
193
-				// doesn't support flat re-shares (was introduced with Nextcloud 9.1)
194
-				$this->removeShareFromTable($share);
195
-				$shareId = $this->createFederatedShare($share);
196
-			}
197
-			if ($send) {
198
-				$this->updateSuccessfulReshare($shareId, $token);
199
-				$this->storeRemoteId($shareId, $remoteId);
200
-			} else {
201
-				$this->removeShareFromTable($share);
202
-				$message_t = $this->l->t('File is already shared with %s', [$shareWith]);
203
-				throw new \Exception($message_t);
204
-			}
205
-
206
-		} else {
207
-			$shareId = $this->createFederatedShare($share);
208
-		}
209
-
210
-		$data = $this->getRawShare($shareId);
211
-		return $this->createShareObject($data);
212
-	}
213
-
214
-	/**
215
-	 * create federated share and inform the recipient
216
-	 *
217
-	 * @param IShare $share
218
-	 * @return int
219
-	 * @throws ShareNotFound
220
-	 * @throws \Exception
221
-	 */
222
-	protected function createFederatedShare(IShare $share) {
223
-		$token = $this->tokenHandler->generateToken();
224
-		$shareId = $this->addShareToDB(
225
-			$share->getNodeId(),
226
-			$share->getNodeType(),
227
-			$share->getSharedWith(),
228
-			$share->getSharedBy(),
229
-			$share->getShareOwner(),
230
-			$share->getPermissions(),
231
-			$token
232
-		);
233
-
234
-		$failure = false;
235
-
236
-		try {
237
-			$sharedByFederatedId = $share->getSharedBy();
238
-			if ($this->userManager->userExists($sharedByFederatedId)) {
239
-				$cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
240
-				$sharedByFederatedId = $cloudId->getId();
241
-			}
242
-			$ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
243
-			$send = $this->notifications->sendRemoteShare(
244
-				$token,
245
-				$share->getSharedWith(),
246
-				$share->getNode()->getName(),
247
-				$shareId,
248
-				$share->getShareOwner(),
249
-				$ownerCloudId->getId(),
250
-				$share->getSharedBy(),
251
-				$sharedByFederatedId
252
-			);
253
-
254
-			if ($send === false) {
255
-				$failure = true;
256
-			}
257
-		} catch (\Exception $e) {
258
-			$this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')');
259
-			$failure = true;
260
-		}
261
-
262
-		if($failure) {
263
-			$this->removeShareFromTableById($shareId);
264
-			$message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
265
-				[$share->getNode()->getName(), $share->getSharedWith()]);
266
-			throw new \Exception($message_t);
267
-		}
268
-
269
-		return $shareId;
270
-
271
-	}
272
-
273
-	/**
274
-	 * @param string $shareWith
275
-	 * @param IShare $share
276
-	 * @param string $shareId internal share Id
277
-	 * @return array
278
-	 * @throws \Exception
279
-	 */
280
-	protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
281
-
282
-		$remoteShare = $this->getShareFromExternalShareTable($share);
283
-		$token = $remoteShare['share_token'];
284
-		$remoteId = $remoteShare['remote_id'];
285
-		$remote = $remoteShare['remote'];
286
-
287
-		list($token, $remoteId) = $this->notifications->requestReShare(
288
-			$token,
289
-			$remoteId,
290
-			$shareId,
291
-			$remote,
292
-			$shareWith,
293
-			$share->getPermissions()
294
-		);
295
-
296
-		return [$token, $remoteId];
297
-	}
298
-
299
-	/**
300
-	 * get federated share from the share_external table but exclude mounted link shares
301
-	 *
302
-	 * @param IShare $share
303
-	 * @return array
304
-	 * @throws ShareNotFound
305
-	 */
306
-	protected function getShareFromExternalShareTable(IShare $share) {
307
-		$query = $this->dbConnection->getQueryBuilder();
308
-		$query->select('*')->from($this->externalShareTable)
309
-			->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
310
-			->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
311
-		$result = $query->execute()->fetchAll();
312
-
313
-		if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
314
-			return $result[0];
315
-		}
316
-
317
-		throw new ShareNotFound('share not found in share_external table');
318
-	}
319
-
320
-	/**
321
-	 * add share to the database and return the ID
322
-	 *
323
-	 * @param int $itemSource
324
-	 * @param string $itemType
325
-	 * @param string $shareWith
326
-	 * @param string $sharedBy
327
-	 * @param string $uidOwner
328
-	 * @param int $permissions
329
-	 * @param string $token
330
-	 * @return int
331
-	 */
332
-	private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
333
-		$qb = $this->dbConnection->getQueryBuilder();
334
-		$qb->insert('share')
335
-			->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
336
-			->setValue('item_type', $qb->createNamedParameter($itemType))
337
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
338
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
339
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
340
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
341
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
342
-			->setValue('permissions', $qb->createNamedParameter($permissions))
343
-			->setValue('token', $qb->createNamedParameter($token))
344
-			->setValue('stime', $qb->createNamedParameter(time()));
345
-
346
-		/*
154
+        $alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
155
+        if (!empty($alreadyShared)) {
156
+            $message = 'Sharing %s failed, because this item is already shared with %s';
157
+            $message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
158
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
159
+            throw new \Exception($message_t);
160
+        }
161
+
162
+
163
+        // don't allow federated shares if source and target server are the same
164
+        $cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
165
+        $currentServer = $this->addressHandler->generateRemoteURL();
166
+        $currentUser = $sharedBy;
167
+        if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
168
+            $message = 'Not allowed to create a federated share with the same user.';
169
+            $message_t = $this->l->t('Not allowed to create a federated share with the same user');
170
+            $this->logger->debug($message, ['app' => 'Federated File Sharing']);
171
+            throw new \Exception($message_t);
172
+        }
173
+
174
+
175
+        $share->setSharedWith($cloudId->getId());
176
+
177
+        try {
178
+            $remoteShare = $this->getShareFromExternalShareTable($share);
179
+        } catch (ShareNotFound $e) {
180
+            $remoteShare = null;
181
+        }
182
+
183
+        if ($remoteShare) {
184
+            try {
185
+                $ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
186
+                $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
187
+                $share->setId($shareId);
188
+                list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
189
+                // remote share was create successfully if we get a valid token as return
190
+                $send = is_string($token) && $token !== '';
191
+            } catch (\Exception $e) {
192
+                // fall back to old re-share behavior if the remote server
193
+                // doesn't support flat re-shares (was introduced with Nextcloud 9.1)
194
+                $this->removeShareFromTable($share);
195
+                $shareId = $this->createFederatedShare($share);
196
+            }
197
+            if ($send) {
198
+                $this->updateSuccessfulReshare($shareId, $token);
199
+                $this->storeRemoteId($shareId, $remoteId);
200
+            } else {
201
+                $this->removeShareFromTable($share);
202
+                $message_t = $this->l->t('File is already shared with %s', [$shareWith]);
203
+                throw new \Exception($message_t);
204
+            }
205
+
206
+        } else {
207
+            $shareId = $this->createFederatedShare($share);
208
+        }
209
+
210
+        $data = $this->getRawShare($shareId);
211
+        return $this->createShareObject($data);
212
+    }
213
+
214
+    /**
215
+     * create federated share and inform the recipient
216
+     *
217
+     * @param IShare $share
218
+     * @return int
219
+     * @throws ShareNotFound
220
+     * @throws \Exception
221
+     */
222
+    protected function createFederatedShare(IShare $share) {
223
+        $token = $this->tokenHandler->generateToken();
224
+        $shareId = $this->addShareToDB(
225
+            $share->getNodeId(),
226
+            $share->getNodeType(),
227
+            $share->getSharedWith(),
228
+            $share->getSharedBy(),
229
+            $share->getShareOwner(),
230
+            $share->getPermissions(),
231
+            $token
232
+        );
233
+
234
+        $failure = false;
235
+
236
+        try {
237
+            $sharedByFederatedId = $share->getSharedBy();
238
+            if ($this->userManager->userExists($sharedByFederatedId)) {
239
+                $cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
240
+                $sharedByFederatedId = $cloudId->getId();
241
+            }
242
+            $ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
243
+            $send = $this->notifications->sendRemoteShare(
244
+                $token,
245
+                $share->getSharedWith(),
246
+                $share->getNode()->getName(),
247
+                $shareId,
248
+                $share->getShareOwner(),
249
+                $ownerCloudId->getId(),
250
+                $share->getSharedBy(),
251
+                $sharedByFederatedId
252
+            );
253
+
254
+            if ($send === false) {
255
+                $failure = true;
256
+            }
257
+        } catch (\Exception $e) {
258
+            $this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')');
259
+            $failure = true;
260
+        }
261
+
262
+        if($failure) {
263
+            $this->removeShareFromTableById($shareId);
264
+            $message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
265
+                [$share->getNode()->getName(), $share->getSharedWith()]);
266
+            throw new \Exception($message_t);
267
+        }
268
+
269
+        return $shareId;
270
+
271
+    }
272
+
273
+    /**
274
+     * @param string $shareWith
275
+     * @param IShare $share
276
+     * @param string $shareId internal share Id
277
+     * @return array
278
+     * @throws \Exception
279
+     */
280
+    protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
281
+
282
+        $remoteShare = $this->getShareFromExternalShareTable($share);
283
+        $token = $remoteShare['share_token'];
284
+        $remoteId = $remoteShare['remote_id'];
285
+        $remote = $remoteShare['remote'];
286
+
287
+        list($token, $remoteId) = $this->notifications->requestReShare(
288
+            $token,
289
+            $remoteId,
290
+            $shareId,
291
+            $remote,
292
+            $shareWith,
293
+            $share->getPermissions()
294
+        );
295
+
296
+        return [$token, $remoteId];
297
+    }
298
+
299
+    /**
300
+     * get federated share from the share_external table but exclude mounted link shares
301
+     *
302
+     * @param IShare $share
303
+     * @return array
304
+     * @throws ShareNotFound
305
+     */
306
+    protected function getShareFromExternalShareTable(IShare $share) {
307
+        $query = $this->dbConnection->getQueryBuilder();
308
+        $query->select('*')->from($this->externalShareTable)
309
+            ->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
310
+            ->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
311
+        $result = $query->execute()->fetchAll();
312
+
313
+        if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
314
+            return $result[0];
315
+        }
316
+
317
+        throw new ShareNotFound('share not found in share_external table');
318
+    }
319
+
320
+    /**
321
+     * add share to the database and return the ID
322
+     *
323
+     * @param int $itemSource
324
+     * @param string $itemType
325
+     * @param string $shareWith
326
+     * @param string $sharedBy
327
+     * @param string $uidOwner
328
+     * @param int $permissions
329
+     * @param string $token
330
+     * @return int
331
+     */
332
+    private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
333
+        $qb = $this->dbConnection->getQueryBuilder();
334
+        $qb->insert('share')
335
+            ->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
336
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
337
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
338
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
339
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
340
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
341
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
342
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
343
+            ->setValue('token', $qb->createNamedParameter($token))
344
+            ->setValue('stime', $qb->createNamedParameter(time()));
345
+
346
+        /*
347 347
 		 * Added to fix https://github.com/owncloud/core/issues/22215
348 348
 		 * Can be removed once we get rid of ajax/share.php
349 349
 		 */
350
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
351
-
352
-		$qb->execute();
353
-		$id = $qb->getLastInsertId();
354
-
355
-		return (int)$id;
356
-	}
357
-
358
-	/**
359
-	 * Update a share
360
-	 *
361
-	 * @param IShare $share
362
-	 * @return IShare The share object
363
-	 */
364
-	public function update(IShare $share) {
365
-		/*
350
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
351
+
352
+        $qb->execute();
353
+        $id = $qb->getLastInsertId();
354
+
355
+        return (int)$id;
356
+    }
357
+
358
+    /**
359
+     * Update a share
360
+     *
361
+     * @param IShare $share
362
+     * @return IShare The share object
363
+     */
364
+    public function update(IShare $share) {
365
+        /*
366 366
 		 * We allow updating the permissions of federated shares
367 367
 		 */
368
-		$qb = $this->dbConnection->getQueryBuilder();
369
-			$qb->update('share')
370
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
371
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
372
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
373
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
374
-				->execute();
375
-
376
-		// send the updated permission to the owner/initiator, if they are not the same
377
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
378
-			$this->sendPermissionUpdate($share);
379
-		}
380
-
381
-		return $share;
382
-	}
383
-
384
-	/**
385
-	 * send the updated permission to the owner/initiator, if they are not the same
386
-	 *
387
-	 * @param IShare $share
388
-	 * @throws ShareNotFound
389
-	 * @throws \OC\HintException
390
-	 */
391
-	protected function sendPermissionUpdate(IShare $share) {
392
-		$remoteId = $this->getRemoteId($share);
393
-		// if the local user is the owner we send the permission change to the initiator
394
-		if ($this->userManager->userExists($share->getShareOwner())) {
395
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
396
-		} else { // ... if not we send the permission change to the owner
397
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
398
-		}
399
-		$this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
400
-	}
401
-
402
-
403
-	/**
404
-	 * update successful reShare with the correct token
405
-	 *
406
-	 * @param int $shareId
407
-	 * @param string $token
408
-	 */
409
-	protected function updateSuccessfulReShare($shareId, $token) {
410
-		$query = $this->dbConnection->getQueryBuilder();
411
-		$query->update('share')
412
-			->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
413
-			->set('token', $query->createNamedParameter($token))
414
-			->execute();
415
-	}
416
-
417
-	/**
418
-	 * store remote ID in federated reShare table
419
-	 *
420
-	 * @param $shareId
421
-	 * @param $remoteId
422
-	 */
423
-	public function storeRemoteId($shareId, $remoteId) {
424
-		$query = $this->dbConnection->getQueryBuilder();
425
-		$query->insert('federated_reshares')
426
-			->values(
427
-				[
428
-					'share_id' =>  $query->createNamedParameter($shareId),
429
-					'remote_id' => $query->createNamedParameter($remoteId),
430
-				]
431
-			);
432
-		$query->execute();
433
-	}
434
-
435
-	/**
436
-	 * get share ID on remote server for federated re-shares
437
-	 *
438
-	 * @param IShare $share
439
-	 * @return int
440
-	 * @throws ShareNotFound
441
-	 */
442
-	public function getRemoteId(IShare $share) {
443
-		$query = $this->dbConnection->getQueryBuilder();
444
-		$query->select('remote_id')->from('federated_reshares')
445
-			->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
446
-		$data = $query->execute()->fetch();
447
-
448
-		if (!is_array($data) || !isset($data['remote_id'])) {
449
-			throw new ShareNotFound();
450
-		}
451
-
452
-		return (int)$data['remote_id'];
453
-	}
454
-
455
-	/**
456
-	 * @inheritdoc
457
-	 */
458
-	public function move(IShare $share, $recipient) {
459
-		/*
368
+        $qb = $this->dbConnection->getQueryBuilder();
369
+            $qb->update('share')
370
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
371
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
372
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
373
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
374
+                ->execute();
375
+
376
+        // send the updated permission to the owner/initiator, if they are not the same
377
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
378
+            $this->sendPermissionUpdate($share);
379
+        }
380
+
381
+        return $share;
382
+    }
383
+
384
+    /**
385
+     * send the updated permission to the owner/initiator, if they are not the same
386
+     *
387
+     * @param IShare $share
388
+     * @throws ShareNotFound
389
+     * @throws \OC\HintException
390
+     */
391
+    protected function sendPermissionUpdate(IShare $share) {
392
+        $remoteId = $this->getRemoteId($share);
393
+        // if the local user is the owner we send the permission change to the initiator
394
+        if ($this->userManager->userExists($share->getShareOwner())) {
395
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
396
+        } else { // ... if not we send the permission change to the owner
397
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
398
+        }
399
+        $this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
400
+    }
401
+
402
+
403
+    /**
404
+     * update successful reShare with the correct token
405
+     *
406
+     * @param int $shareId
407
+     * @param string $token
408
+     */
409
+    protected function updateSuccessfulReShare($shareId, $token) {
410
+        $query = $this->dbConnection->getQueryBuilder();
411
+        $query->update('share')
412
+            ->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
413
+            ->set('token', $query->createNamedParameter($token))
414
+            ->execute();
415
+    }
416
+
417
+    /**
418
+     * store remote ID in federated reShare table
419
+     *
420
+     * @param $shareId
421
+     * @param $remoteId
422
+     */
423
+    public function storeRemoteId($shareId, $remoteId) {
424
+        $query = $this->dbConnection->getQueryBuilder();
425
+        $query->insert('federated_reshares')
426
+            ->values(
427
+                [
428
+                    'share_id' =>  $query->createNamedParameter($shareId),
429
+                    'remote_id' => $query->createNamedParameter($remoteId),
430
+                ]
431
+            );
432
+        $query->execute();
433
+    }
434
+
435
+    /**
436
+     * get share ID on remote server for federated re-shares
437
+     *
438
+     * @param IShare $share
439
+     * @return int
440
+     * @throws ShareNotFound
441
+     */
442
+    public function getRemoteId(IShare $share) {
443
+        $query = $this->dbConnection->getQueryBuilder();
444
+        $query->select('remote_id')->from('federated_reshares')
445
+            ->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
446
+        $data = $query->execute()->fetch();
447
+
448
+        if (!is_array($data) || !isset($data['remote_id'])) {
449
+            throw new ShareNotFound();
450
+        }
451
+
452
+        return (int)$data['remote_id'];
453
+    }
454
+
455
+    /**
456
+     * @inheritdoc
457
+     */
458
+    public function move(IShare $share, $recipient) {
459
+        /*
460 460
 		 * This function does nothing yet as it is just for outgoing
461 461
 		 * federated shares.
462 462
 		 */
463
-		return $share;
464
-	}
465
-
466
-	/**
467
-	 * Get all children of this share
468
-	 *
469
-	 * @param IShare $parent
470
-	 * @return IShare[]
471
-	 */
472
-	public function getChildren(IShare $parent) {
473
-		$children = [];
474
-
475
-		$qb = $this->dbConnection->getQueryBuilder();
476
-		$qb->select('*')
477
-			->from('share')
478
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
479
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
480
-			->orderBy('id');
481
-
482
-		$cursor = $qb->execute();
483
-		while($data = $cursor->fetch()) {
484
-			$children[] = $this->createShareObject($data);
485
-		}
486
-		$cursor->closeCursor();
487
-
488
-		return $children;
489
-	}
490
-
491
-	/**
492
-	 * Delete a share (owner unShares the file)
493
-	 *
494
-	 * @param IShare $share
495
-	 */
496
-	public function delete(IShare $share) {
497
-
498
-		list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
499
-
500
-		$isOwner = false;
501
-
502
-		$this->removeShareFromTable($share);
503
-
504
-		// if the local user is the owner we can send the unShare request directly...
505
-		if ($this->userManager->userExists($share->getShareOwner())) {
506
-			$this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
507
-			$this->revokeShare($share, true);
508
-			$isOwner = true;
509
-		} else { // ... if not we need to correct ID for the unShare request
510
-			$remoteId = $this->getRemoteId($share);
511
-			$this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
512
-			$this->revokeShare($share, false);
513
-		}
514
-
515
-		// send revoke notification to the other user, if initiator and owner are not the same user
516
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
517
-			$remoteId = $this->getRemoteId($share);
518
-			if ($isOwner) {
519
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
520
-			} else {
521
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
522
-			}
523
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
524
-		}
525
-	}
526
-
527
-	/**
528
-	 * in case of a re-share we need to send the other use (initiator or owner)
529
-	 * a message that the file was unshared
530
-	 *
531
-	 * @param IShare $share
532
-	 * @param bool $isOwner the user can either be the owner or the user who re-sahred it
533
-	 * @throws ShareNotFound
534
-	 * @throws \OC\HintException
535
-	 */
536
-	protected function revokeShare($share, $isOwner) {
537
-		// also send a unShare request to the initiator, if this is a different user than the owner
538
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
539
-			if ($isOwner) {
540
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
541
-			} else {
542
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
543
-			}
544
-			$remoteId = $this->getRemoteId($share);
545
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
546
-		}
547
-	}
548
-
549
-	/**
550
-	 * remove share from table
551
-	 *
552
-	 * @param IShare $share
553
-	 */
554
-	public function removeShareFromTable(IShare $share) {
555
-		$this->removeShareFromTableById($share->getId());
556
-	}
557
-
558
-	/**
559
-	 * remove share from table
560
-	 *
561
-	 * @param string $shareId
562
-	 */
563
-	private function removeShareFromTableById($shareId) {
564
-		$qb = $this->dbConnection->getQueryBuilder();
565
-		$qb->delete('share')
566
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
567
-		$qb->execute();
568
-
569
-		$qb->delete('federated_reshares')
570
-			->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
571
-		$qb->execute();
572
-	}
573
-
574
-	/**
575
-	 * @inheritdoc
576
-	 */
577
-	public function deleteFromSelf(IShare $share, $recipient) {
578
-		// nothing to do here. Technically deleteFromSelf in the context of federated
579
-		// shares is a umount of a external storage. This is handled here
580
-		// apps/files_sharing/lib/external/manager.php
581
-		// TODO move this code over to this app
582
-		return;
583
-	}
584
-
585
-
586
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
587
-		$qb = $this->dbConnection->getQueryBuilder();
588
-		$qb->select('*')
589
-			->from('share', 's')
590
-			->andWhere($qb->expr()->orX(
591
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
592
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
593
-			))
594
-			->andWhere(
595
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))
596
-			);
597
-
598
-		/**
599
-		 * Reshares for this user are shares where they are the owner.
600
-		 */
601
-		if ($reshares === false) {
602
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
603
-		} else {
604
-			$qb->andWhere(
605
-				$qb->expr()->orX(
606
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
607
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
608
-				)
609
-			);
610
-		}
611
-
612
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
613
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
614
-
615
-		$qb->orderBy('id');
616
-
617
-		$cursor = $qb->execute();
618
-		$shares = [];
619
-		while ($data = $cursor->fetch()) {
620
-			$shares[$data['fileid']][] = $this->createShareObject($data);
621
-		}
622
-		$cursor->closeCursor();
623
-
624
-		return $shares;
625
-	}
626
-
627
-	/**
628
-	 * @inheritdoc
629
-	 */
630
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
631
-		$qb = $this->dbConnection->getQueryBuilder();
632
-		$qb->select('*')
633
-			->from('share');
634
-
635
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
636
-
637
-		/**
638
-		 * Reshares for this user are shares where they are the owner.
639
-		 */
640
-		if ($reshares === false) {
641
-			//Special case for old shares created via the web UI
642
-			$or1 = $qb->expr()->andX(
643
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
644
-				$qb->expr()->isNull('uid_initiator')
645
-			);
646
-
647
-			$qb->andWhere(
648
-				$qb->expr()->orX(
649
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
650
-					$or1
651
-				)
652
-			);
653
-		} else {
654
-			$qb->andWhere(
655
-				$qb->expr()->orX(
656
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
657
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
658
-				)
659
-			);
660
-		}
661
-
662
-		if ($node !== null) {
663
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
664
-		}
665
-
666
-		if ($limit !== -1) {
667
-			$qb->setMaxResults($limit);
668
-		}
669
-
670
-		$qb->setFirstResult($offset);
671
-		$qb->orderBy('id');
672
-
673
-		$cursor = $qb->execute();
674
-		$shares = [];
675
-		while($data = $cursor->fetch()) {
676
-			$shares[] = $this->createShareObject($data);
677
-		}
678
-		$cursor->closeCursor();
679
-
680
-		return $shares;
681
-	}
682
-
683
-	/**
684
-	 * @inheritdoc
685
-	 */
686
-	public function getShareById($id, $recipientId = null) {
687
-		$qb = $this->dbConnection->getQueryBuilder();
688
-
689
-		$qb->select('*')
690
-			->from('share')
691
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
692
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
693
-
694
-		$cursor = $qb->execute();
695
-		$data = $cursor->fetch();
696
-		$cursor->closeCursor();
697
-
698
-		if ($data === false) {
699
-			throw new ShareNotFound();
700
-		}
701
-
702
-		try {
703
-			$share = $this->createShareObject($data);
704
-		} catch (InvalidShare $e) {
705
-			throw new ShareNotFound();
706
-		}
707
-
708
-		return $share;
709
-	}
710
-
711
-	/**
712
-	 * Get shares for a given path
713
-	 *
714
-	 * @param \OCP\Files\Node $path
715
-	 * @return IShare[]
716
-	 */
717
-	public function getSharesByPath(Node $path) {
718
-		$qb = $this->dbConnection->getQueryBuilder();
719
-
720
-		$cursor = $qb->select('*')
721
-			->from('share')
722
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
723
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
724
-			->execute();
725
-
726
-		$shares = [];
727
-		while($data = $cursor->fetch()) {
728
-			$shares[] = $this->createShareObject($data);
729
-		}
730
-		$cursor->closeCursor();
731
-
732
-		return $shares;
733
-	}
734
-
735
-	/**
736
-	 * @inheritdoc
737
-	 */
738
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
739
-		/** @var IShare[] $shares */
740
-		$shares = [];
741
-
742
-		//Get shares directly with this user
743
-		$qb = $this->dbConnection->getQueryBuilder();
744
-		$qb->select('*')
745
-			->from('share');
746
-
747
-		// Order by id
748
-		$qb->orderBy('id');
749
-
750
-		// Set limit and offset
751
-		if ($limit !== -1) {
752
-			$qb->setMaxResults($limit);
753
-		}
754
-		$qb->setFirstResult($offset);
755
-
756
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
757
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
758
-
759
-		// Filter by node if provided
760
-		if ($node !== null) {
761
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
762
-		}
763
-
764
-		$cursor = $qb->execute();
765
-
766
-		while($data = $cursor->fetch()) {
767
-			$shares[] = $this->createShareObject($data);
768
-		}
769
-		$cursor->closeCursor();
770
-
771
-
772
-		return $shares;
773
-	}
774
-
775
-	/**
776
-	 * Get a share by token
777
-	 *
778
-	 * @param string $token
779
-	 * @return IShare
780
-	 * @throws ShareNotFound
781
-	 */
782
-	public function getShareByToken($token) {
783
-		$qb = $this->dbConnection->getQueryBuilder();
784
-
785
-		$cursor = $qb->select('*')
786
-			->from('share')
787
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
788
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
789
-			->execute();
790
-
791
-		$data = $cursor->fetch();
792
-
793
-		if ($data === false) {
794
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
795
-		}
796
-
797
-		try {
798
-			$share = $this->createShareObject($data);
799
-		} catch (InvalidShare $e) {
800
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
801
-		}
802
-
803
-		return $share;
804
-	}
805
-
806
-	/**
807
-	 * get database row of a give share
808
-	 *
809
-	 * @param $id
810
-	 * @return array
811
-	 * @throws ShareNotFound
812
-	 */
813
-	private function getRawShare($id) {
814
-
815
-		// Now fetch the inserted share and create a complete share object
816
-		$qb = $this->dbConnection->getQueryBuilder();
817
-		$qb->select('*')
818
-			->from('share')
819
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
820
-
821
-		$cursor = $qb->execute();
822
-		$data = $cursor->fetch();
823
-		$cursor->closeCursor();
824
-
825
-		if ($data === false) {
826
-			throw new ShareNotFound;
827
-		}
828
-
829
-		return $data;
830
-	}
831
-
832
-	/**
833
-	 * Create a share object from an database row
834
-	 *
835
-	 * @param array $data
836
-	 * @return IShare
837
-	 * @throws InvalidShare
838
-	 * @throws ShareNotFound
839
-	 */
840
-	private function createShareObject($data) {
841
-
842
-		$share = new Share($this->rootFolder, $this->userManager);
843
-		$share->setId((int)$data['id'])
844
-			->setShareType((int)$data['share_type'])
845
-			->setPermissions((int)$data['permissions'])
846
-			->setTarget($data['file_target'])
847
-			->setMailSend((bool)$data['mail_send'])
848
-			->setToken($data['token']);
849
-
850
-		$shareTime = new \DateTime();
851
-		$shareTime->setTimestamp((int)$data['stime']);
852
-		$share->setShareTime($shareTime);
853
-		$share->setSharedWith($data['share_with']);
854
-
855
-		if ($data['uid_initiator'] !== null) {
856
-			$share->setShareOwner($data['uid_owner']);
857
-			$share->setSharedBy($data['uid_initiator']);
858
-		} else {
859
-			//OLD SHARE
860
-			$share->setSharedBy($data['uid_owner']);
861
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
862
-
863
-			$owner = $path->getOwner();
864
-			$share->setShareOwner($owner->getUID());
865
-		}
866
-
867
-		$share->setNodeId((int)$data['file_source']);
868
-		$share->setNodeType($data['item_type']);
869
-
870
-		$share->setProviderId($this->identifier());
871
-
872
-		return $share;
873
-	}
874
-
875
-	/**
876
-	 * Get the node with file $id for $user
877
-	 *
878
-	 * @param string $userId
879
-	 * @param int $id
880
-	 * @return \OCP\Files\File|\OCP\Files\Folder
881
-	 * @throws InvalidShare
882
-	 */
883
-	private function getNode($userId, $id) {
884
-		try {
885
-			$userFolder = $this->rootFolder->getUserFolder($userId);
886
-		} catch (NotFoundException $e) {
887
-			throw new InvalidShare();
888
-		}
889
-
890
-		$nodes = $userFolder->getById($id);
891
-
892
-		if (empty($nodes)) {
893
-			throw new InvalidShare();
894
-		}
895
-
896
-		return $nodes[0];
897
-	}
898
-
899
-	/**
900
-	 * A user is deleted from the system
901
-	 * So clean up the relevant shares.
902
-	 *
903
-	 * @param string $uid
904
-	 * @param int $shareType
905
-	 */
906
-	public function userDeleted($uid, $shareType) {
907
-		//TODO: probabaly a good idea to send unshare info to remote servers
908
-
909
-		$qb = $this->dbConnection->getQueryBuilder();
910
-
911
-		$qb->delete('share')
912
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
913
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
914
-			->execute();
915
-	}
916
-
917
-	/**
918
-	 * This provider does not handle groups
919
-	 *
920
-	 * @param string $gid
921
-	 */
922
-	public function groupDeleted($gid) {
923
-		// We don't handle groups here
924
-		return;
925
-	}
926
-
927
-	/**
928
-	 * This provider does not handle groups
929
-	 *
930
-	 * @param string $uid
931
-	 * @param string $gid
932
-	 */
933
-	public function userDeletedFromGroup($uid, $gid) {
934
-		// We don't handle groups here
935
-		return;
936
-	}
937
-
938
-	/**
939
-	 * check if users from other Nextcloud instances are allowed to mount public links share by this instance
940
-	 *
941
-	 * @return bool
942
-	 */
943
-	public function isOutgoingServer2serverShareEnabled() {
944
-		$result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
945
-		return ($result === 'yes');
946
-	}
947
-
948
-	/**
949
-	 * check if users are allowed to mount public links from other Nextclouds
950
-	 *
951
-	 * @return bool
952
-	 */
953
-	public function isIncomingServer2serverShareEnabled() {
954
-		$result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
955
-		return ($result === 'yes');
956
-	}
957
-
958
-	/**
959
-	 * Check if querying sharees on the lookup server is enabled
960
-	 *
961
-	 * @return bool
962
-	 */
963
-	public function isLookupServerQueriesEnabled() {
964
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
965
-		return ($result === 'yes');
966
-	}
967
-
968
-
969
-	/**
970
-	 * Check if it is allowed to publish user specific data to the lookup server
971
-	 *
972
-	 * @return bool
973
-	 */
974
-	public function isLookupServerUploadEnabled() {
975
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
976
-		return ($result === 'yes');
977
-	}
978
-
979
-	/**
980
-	 * @inheritdoc
981
-	 */
982
-	public function getAccessList($nodes, $currentAccess) {
983
-		$ids = [];
984
-		foreach ($nodes as $node) {
985
-			$ids[] = $node->getId();
986
-		}
987
-
988
-		$qb = $this->dbConnection->getQueryBuilder();
989
-		$qb->select('share_with', 'token', 'file_source')
990
-			->from('share')
991
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
992
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
993
-			->andWhere($qb->expr()->orX(
994
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
995
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
996
-			));
997
-		$cursor = $qb->execute();
998
-
999
-		if ($currentAccess === false) {
1000
-			$remote = $cursor->fetch() !== false;
1001
-			$cursor->closeCursor();
1002
-
1003
-			return ['remote' => $remote];
1004
-		}
1005
-
1006
-		$remote = [];
1007
-		while ($row = $cursor->fetch()) {
1008
-			$remote[$row['share_with']] = [
1009
-				'node_id' => $row['file_source'],
1010
-				'token' => $row['token'],
1011
-			];
1012
-		}
1013
-		$cursor->closeCursor();
1014
-
1015
-		return ['remote' => $remote];
1016
-	}
463
+        return $share;
464
+    }
465
+
466
+    /**
467
+     * Get all children of this share
468
+     *
469
+     * @param IShare $parent
470
+     * @return IShare[]
471
+     */
472
+    public function getChildren(IShare $parent) {
473
+        $children = [];
474
+
475
+        $qb = $this->dbConnection->getQueryBuilder();
476
+        $qb->select('*')
477
+            ->from('share')
478
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
479
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
480
+            ->orderBy('id');
481
+
482
+        $cursor = $qb->execute();
483
+        while($data = $cursor->fetch()) {
484
+            $children[] = $this->createShareObject($data);
485
+        }
486
+        $cursor->closeCursor();
487
+
488
+        return $children;
489
+    }
490
+
491
+    /**
492
+     * Delete a share (owner unShares the file)
493
+     *
494
+     * @param IShare $share
495
+     */
496
+    public function delete(IShare $share) {
497
+
498
+        list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
499
+
500
+        $isOwner = false;
501
+
502
+        $this->removeShareFromTable($share);
503
+
504
+        // if the local user is the owner we can send the unShare request directly...
505
+        if ($this->userManager->userExists($share->getShareOwner())) {
506
+            $this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
507
+            $this->revokeShare($share, true);
508
+            $isOwner = true;
509
+        } else { // ... if not we need to correct ID for the unShare request
510
+            $remoteId = $this->getRemoteId($share);
511
+            $this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
512
+            $this->revokeShare($share, false);
513
+        }
514
+
515
+        // send revoke notification to the other user, if initiator and owner are not the same user
516
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
517
+            $remoteId = $this->getRemoteId($share);
518
+            if ($isOwner) {
519
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
520
+            } else {
521
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
522
+            }
523
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
524
+        }
525
+    }
526
+
527
+    /**
528
+     * in case of a re-share we need to send the other use (initiator or owner)
529
+     * a message that the file was unshared
530
+     *
531
+     * @param IShare $share
532
+     * @param bool $isOwner the user can either be the owner or the user who re-sahred it
533
+     * @throws ShareNotFound
534
+     * @throws \OC\HintException
535
+     */
536
+    protected function revokeShare($share, $isOwner) {
537
+        // also send a unShare request to the initiator, if this is a different user than the owner
538
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
539
+            if ($isOwner) {
540
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
541
+            } else {
542
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
543
+            }
544
+            $remoteId = $this->getRemoteId($share);
545
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
546
+        }
547
+    }
548
+
549
+    /**
550
+     * remove share from table
551
+     *
552
+     * @param IShare $share
553
+     */
554
+    public function removeShareFromTable(IShare $share) {
555
+        $this->removeShareFromTableById($share->getId());
556
+    }
557
+
558
+    /**
559
+     * remove share from table
560
+     *
561
+     * @param string $shareId
562
+     */
563
+    private function removeShareFromTableById($shareId) {
564
+        $qb = $this->dbConnection->getQueryBuilder();
565
+        $qb->delete('share')
566
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
567
+        $qb->execute();
568
+
569
+        $qb->delete('federated_reshares')
570
+            ->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
571
+        $qb->execute();
572
+    }
573
+
574
+    /**
575
+     * @inheritdoc
576
+     */
577
+    public function deleteFromSelf(IShare $share, $recipient) {
578
+        // nothing to do here. Technically deleteFromSelf in the context of federated
579
+        // shares is a umount of a external storage. This is handled here
580
+        // apps/files_sharing/lib/external/manager.php
581
+        // TODO move this code over to this app
582
+        return;
583
+    }
584
+
585
+
586
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
587
+        $qb = $this->dbConnection->getQueryBuilder();
588
+        $qb->select('*')
589
+            ->from('share', 's')
590
+            ->andWhere($qb->expr()->orX(
591
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
592
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
593
+            ))
594
+            ->andWhere(
595
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))
596
+            );
597
+
598
+        /**
599
+         * Reshares for this user are shares where they are the owner.
600
+         */
601
+        if ($reshares === false) {
602
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
603
+        } else {
604
+            $qb->andWhere(
605
+                $qb->expr()->orX(
606
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
607
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
608
+                )
609
+            );
610
+        }
611
+
612
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
613
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
614
+
615
+        $qb->orderBy('id');
616
+
617
+        $cursor = $qb->execute();
618
+        $shares = [];
619
+        while ($data = $cursor->fetch()) {
620
+            $shares[$data['fileid']][] = $this->createShareObject($data);
621
+        }
622
+        $cursor->closeCursor();
623
+
624
+        return $shares;
625
+    }
626
+
627
+    /**
628
+     * @inheritdoc
629
+     */
630
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
631
+        $qb = $this->dbConnection->getQueryBuilder();
632
+        $qb->select('*')
633
+            ->from('share');
634
+
635
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
636
+
637
+        /**
638
+         * Reshares for this user are shares where they are the owner.
639
+         */
640
+        if ($reshares === false) {
641
+            //Special case for old shares created via the web UI
642
+            $or1 = $qb->expr()->andX(
643
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
644
+                $qb->expr()->isNull('uid_initiator')
645
+            );
646
+
647
+            $qb->andWhere(
648
+                $qb->expr()->orX(
649
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
650
+                    $or1
651
+                )
652
+            );
653
+        } else {
654
+            $qb->andWhere(
655
+                $qb->expr()->orX(
656
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
657
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
658
+                )
659
+            );
660
+        }
661
+
662
+        if ($node !== null) {
663
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
664
+        }
665
+
666
+        if ($limit !== -1) {
667
+            $qb->setMaxResults($limit);
668
+        }
669
+
670
+        $qb->setFirstResult($offset);
671
+        $qb->orderBy('id');
672
+
673
+        $cursor = $qb->execute();
674
+        $shares = [];
675
+        while($data = $cursor->fetch()) {
676
+            $shares[] = $this->createShareObject($data);
677
+        }
678
+        $cursor->closeCursor();
679
+
680
+        return $shares;
681
+    }
682
+
683
+    /**
684
+     * @inheritdoc
685
+     */
686
+    public function getShareById($id, $recipientId = null) {
687
+        $qb = $this->dbConnection->getQueryBuilder();
688
+
689
+        $qb->select('*')
690
+            ->from('share')
691
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
692
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
693
+
694
+        $cursor = $qb->execute();
695
+        $data = $cursor->fetch();
696
+        $cursor->closeCursor();
697
+
698
+        if ($data === false) {
699
+            throw new ShareNotFound();
700
+        }
701
+
702
+        try {
703
+            $share = $this->createShareObject($data);
704
+        } catch (InvalidShare $e) {
705
+            throw new ShareNotFound();
706
+        }
707
+
708
+        return $share;
709
+    }
710
+
711
+    /**
712
+     * Get shares for a given path
713
+     *
714
+     * @param \OCP\Files\Node $path
715
+     * @return IShare[]
716
+     */
717
+    public function getSharesByPath(Node $path) {
718
+        $qb = $this->dbConnection->getQueryBuilder();
719
+
720
+        $cursor = $qb->select('*')
721
+            ->from('share')
722
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
723
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
724
+            ->execute();
725
+
726
+        $shares = [];
727
+        while($data = $cursor->fetch()) {
728
+            $shares[] = $this->createShareObject($data);
729
+        }
730
+        $cursor->closeCursor();
731
+
732
+        return $shares;
733
+    }
734
+
735
+    /**
736
+     * @inheritdoc
737
+     */
738
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
739
+        /** @var IShare[] $shares */
740
+        $shares = [];
741
+
742
+        //Get shares directly with this user
743
+        $qb = $this->dbConnection->getQueryBuilder();
744
+        $qb->select('*')
745
+            ->from('share');
746
+
747
+        // Order by id
748
+        $qb->orderBy('id');
749
+
750
+        // Set limit and offset
751
+        if ($limit !== -1) {
752
+            $qb->setMaxResults($limit);
753
+        }
754
+        $qb->setFirstResult($offset);
755
+
756
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
757
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
758
+
759
+        // Filter by node if provided
760
+        if ($node !== null) {
761
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
762
+        }
763
+
764
+        $cursor = $qb->execute();
765
+
766
+        while($data = $cursor->fetch()) {
767
+            $shares[] = $this->createShareObject($data);
768
+        }
769
+        $cursor->closeCursor();
770
+
771
+
772
+        return $shares;
773
+    }
774
+
775
+    /**
776
+     * Get a share by token
777
+     *
778
+     * @param string $token
779
+     * @return IShare
780
+     * @throws ShareNotFound
781
+     */
782
+    public function getShareByToken($token) {
783
+        $qb = $this->dbConnection->getQueryBuilder();
784
+
785
+        $cursor = $qb->select('*')
786
+            ->from('share')
787
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
788
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
789
+            ->execute();
790
+
791
+        $data = $cursor->fetch();
792
+
793
+        if ($data === false) {
794
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
795
+        }
796
+
797
+        try {
798
+            $share = $this->createShareObject($data);
799
+        } catch (InvalidShare $e) {
800
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
801
+        }
802
+
803
+        return $share;
804
+    }
805
+
806
+    /**
807
+     * get database row of a give share
808
+     *
809
+     * @param $id
810
+     * @return array
811
+     * @throws ShareNotFound
812
+     */
813
+    private function getRawShare($id) {
814
+
815
+        // Now fetch the inserted share and create a complete share object
816
+        $qb = $this->dbConnection->getQueryBuilder();
817
+        $qb->select('*')
818
+            ->from('share')
819
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
820
+
821
+        $cursor = $qb->execute();
822
+        $data = $cursor->fetch();
823
+        $cursor->closeCursor();
824
+
825
+        if ($data === false) {
826
+            throw new ShareNotFound;
827
+        }
828
+
829
+        return $data;
830
+    }
831
+
832
+    /**
833
+     * Create a share object from an database row
834
+     *
835
+     * @param array $data
836
+     * @return IShare
837
+     * @throws InvalidShare
838
+     * @throws ShareNotFound
839
+     */
840
+    private function createShareObject($data) {
841
+
842
+        $share = new Share($this->rootFolder, $this->userManager);
843
+        $share->setId((int)$data['id'])
844
+            ->setShareType((int)$data['share_type'])
845
+            ->setPermissions((int)$data['permissions'])
846
+            ->setTarget($data['file_target'])
847
+            ->setMailSend((bool)$data['mail_send'])
848
+            ->setToken($data['token']);
849
+
850
+        $shareTime = new \DateTime();
851
+        $shareTime->setTimestamp((int)$data['stime']);
852
+        $share->setShareTime($shareTime);
853
+        $share->setSharedWith($data['share_with']);
854
+
855
+        if ($data['uid_initiator'] !== null) {
856
+            $share->setShareOwner($data['uid_owner']);
857
+            $share->setSharedBy($data['uid_initiator']);
858
+        } else {
859
+            //OLD SHARE
860
+            $share->setSharedBy($data['uid_owner']);
861
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
862
+
863
+            $owner = $path->getOwner();
864
+            $share->setShareOwner($owner->getUID());
865
+        }
866
+
867
+        $share->setNodeId((int)$data['file_source']);
868
+        $share->setNodeType($data['item_type']);
869
+
870
+        $share->setProviderId($this->identifier());
871
+
872
+        return $share;
873
+    }
874
+
875
+    /**
876
+     * Get the node with file $id for $user
877
+     *
878
+     * @param string $userId
879
+     * @param int $id
880
+     * @return \OCP\Files\File|\OCP\Files\Folder
881
+     * @throws InvalidShare
882
+     */
883
+    private function getNode($userId, $id) {
884
+        try {
885
+            $userFolder = $this->rootFolder->getUserFolder($userId);
886
+        } catch (NotFoundException $e) {
887
+            throw new InvalidShare();
888
+        }
889
+
890
+        $nodes = $userFolder->getById($id);
891
+
892
+        if (empty($nodes)) {
893
+            throw new InvalidShare();
894
+        }
895
+
896
+        return $nodes[0];
897
+    }
898
+
899
+    /**
900
+     * A user is deleted from the system
901
+     * So clean up the relevant shares.
902
+     *
903
+     * @param string $uid
904
+     * @param int $shareType
905
+     */
906
+    public function userDeleted($uid, $shareType) {
907
+        //TODO: probabaly a good idea to send unshare info to remote servers
908
+
909
+        $qb = $this->dbConnection->getQueryBuilder();
910
+
911
+        $qb->delete('share')
912
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
913
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
914
+            ->execute();
915
+    }
916
+
917
+    /**
918
+     * This provider does not handle groups
919
+     *
920
+     * @param string $gid
921
+     */
922
+    public function groupDeleted($gid) {
923
+        // We don't handle groups here
924
+        return;
925
+    }
926
+
927
+    /**
928
+     * This provider does not handle groups
929
+     *
930
+     * @param string $uid
931
+     * @param string $gid
932
+     */
933
+    public function userDeletedFromGroup($uid, $gid) {
934
+        // We don't handle groups here
935
+        return;
936
+    }
937
+
938
+    /**
939
+     * check if users from other Nextcloud instances are allowed to mount public links share by this instance
940
+     *
941
+     * @return bool
942
+     */
943
+    public function isOutgoingServer2serverShareEnabled() {
944
+        $result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
945
+        return ($result === 'yes');
946
+    }
947
+
948
+    /**
949
+     * check if users are allowed to mount public links from other Nextclouds
950
+     *
951
+     * @return bool
952
+     */
953
+    public function isIncomingServer2serverShareEnabled() {
954
+        $result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
955
+        return ($result === 'yes');
956
+    }
957
+
958
+    /**
959
+     * Check if querying sharees on the lookup server is enabled
960
+     *
961
+     * @return bool
962
+     */
963
+    public function isLookupServerQueriesEnabled() {
964
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
965
+        return ($result === 'yes');
966
+    }
967
+
968
+
969
+    /**
970
+     * Check if it is allowed to publish user specific data to the lookup server
971
+     *
972
+     * @return bool
973
+     */
974
+    public function isLookupServerUploadEnabled() {
975
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
976
+        return ($result === 'yes');
977
+    }
978
+
979
+    /**
980
+     * @inheritdoc
981
+     */
982
+    public function getAccessList($nodes, $currentAccess) {
983
+        $ids = [];
984
+        foreach ($nodes as $node) {
985
+            $ids[] = $node->getId();
986
+        }
987
+
988
+        $qb = $this->dbConnection->getQueryBuilder();
989
+        $qb->select('share_with', 'token', 'file_source')
990
+            ->from('share')
991
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
992
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
993
+            ->andWhere($qb->expr()->orX(
994
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
995
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
996
+            ));
997
+        $cursor = $qb->execute();
998
+
999
+        if ($currentAccess === false) {
1000
+            $remote = $cursor->fetch() !== false;
1001
+            $cursor->closeCursor();
1002
+
1003
+            return ['remote' => $remote];
1004
+        }
1005
+
1006
+        $remote = [];
1007
+        while ($row = $cursor->fetch()) {
1008
+            $remote[$row['share_with']] = [
1009
+                'node_id' => $row['file_source'],
1010
+                'token' => $row['token'],
1011
+            ];
1012
+        }
1013
+        $cursor->closeCursor();
1014
+
1015
+        return ['remote' => $remote];
1016
+    }
1017 1017
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/ShareByMailProvider.php 1 patch
Indentation   +797 added lines, -797 removed lines patch added patch discarded remove patch
@@ -50,815 +50,815 @@
 block discarded – undo
50 50
  */
51 51
 class ShareByMailProvider implements IShareProvider {
52 52
 
53
-	/** @var  IDBConnection */
54
-	private $dbConnection;
55
-
56
-	/** @var ILogger */
57
-	private $logger;
58
-
59
-	/** @var ISecureRandom */
60
-	private $secureRandom;
61
-
62
-	/** @var IUserManager */
63
-	private $userManager;
64
-
65
-	/** @var IRootFolder */
66
-	private $rootFolder;
67
-
68
-	/** @var IL10N */
69
-	private $l;
70
-
71
-	/** @var IMailer */
72
-	private $mailer;
73
-
74
-	/** @var IURLGenerator */
75
-	private $urlGenerator;
76
-
77
-	/** @var IManager  */
78
-	private $activityManager;
79
-
80
-	/** @var SettingsManager */
81
-	private $settingsManager;
82
-
83
-	/**
84
-	 * Return the identifier of this provider.
85
-	 *
86
-	 * @return string Containing only [a-zA-Z0-9]
87
-	 */
88
-	public function identifier() {
89
-		return 'ocMailShare';
90
-	}
91
-
92
-	/**
93
-	 * DefaultShareProvider constructor.
94
-	 *
95
-	 * @param IDBConnection $connection
96
-	 * @param ISecureRandom $secureRandom
97
-	 * @param IUserManager $userManager
98
-	 * @param IRootFolder $rootFolder
99
-	 * @param IL10N $l
100
-	 * @param ILogger $logger
101
-	 * @param IMailer $mailer
102
-	 * @param IURLGenerator $urlGenerator
103
-	 * @param IManager $activityManager
104
-	 * @param SettingsManager $settingsManager
105
-	 */
106
-	public function __construct(
107
-		IDBConnection $connection,
108
-		ISecureRandom $secureRandom,
109
-		IUserManager $userManager,
110
-		IRootFolder $rootFolder,
111
-		IL10N $l,
112
-		ILogger $logger,
113
-		IMailer $mailer,
114
-		IURLGenerator $urlGenerator,
115
-		IManager $activityManager,
116
-		SettingsManager $settingsManager
117
-	) {
118
-		$this->dbConnection = $connection;
119
-		$this->secureRandom = $secureRandom;
120
-		$this->userManager = $userManager;
121
-		$this->rootFolder = $rootFolder;
122
-		$this->l = $l;
123
-		$this->logger = $logger;
124
-		$this->mailer = $mailer;
125
-		$this->urlGenerator = $urlGenerator;
126
-		$this->activityManager = $activityManager;
127
-		$this->settingsManager = $settingsManager;
128
-	}
129
-
130
-	/**
131
-	 * Share a path
132
-	 *
133
-	 * @param IShare $share
134
-	 * @return IShare The share object
135
-	 * @throws ShareNotFound
136
-	 * @throws \Exception
137
-	 */
138
-	public function create(IShare $share) {
139
-
140
-		$shareWith = $share->getSharedWith();
141
-		/*
53
+    /** @var  IDBConnection */
54
+    private $dbConnection;
55
+
56
+    /** @var ILogger */
57
+    private $logger;
58
+
59
+    /** @var ISecureRandom */
60
+    private $secureRandom;
61
+
62
+    /** @var IUserManager */
63
+    private $userManager;
64
+
65
+    /** @var IRootFolder */
66
+    private $rootFolder;
67
+
68
+    /** @var IL10N */
69
+    private $l;
70
+
71
+    /** @var IMailer */
72
+    private $mailer;
73
+
74
+    /** @var IURLGenerator */
75
+    private $urlGenerator;
76
+
77
+    /** @var IManager  */
78
+    private $activityManager;
79
+
80
+    /** @var SettingsManager */
81
+    private $settingsManager;
82
+
83
+    /**
84
+     * Return the identifier of this provider.
85
+     *
86
+     * @return string Containing only [a-zA-Z0-9]
87
+     */
88
+    public function identifier() {
89
+        return 'ocMailShare';
90
+    }
91
+
92
+    /**
93
+     * DefaultShareProvider constructor.
94
+     *
95
+     * @param IDBConnection $connection
96
+     * @param ISecureRandom $secureRandom
97
+     * @param IUserManager $userManager
98
+     * @param IRootFolder $rootFolder
99
+     * @param IL10N $l
100
+     * @param ILogger $logger
101
+     * @param IMailer $mailer
102
+     * @param IURLGenerator $urlGenerator
103
+     * @param IManager $activityManager
104
+     * @param SettingsManager $settingsManager
105
+     */
106
+    public function __construct(
107
+        IDBConnection $connection,
108
+        ISecureRandom $secureRandom,
109
+        IUserManager $userManager,
110
+        IRootFolder $rootFolder,
111
+        IL10N $l,
112
+        ILogger $logger,
113
+        IMailer $mailer,
114
+        IURLGenerator $urlGenerator,
115
+        IManager $activityManager,
116
+        SettingsManager $settingsManager
117
+    ) {
118
+        $this->dbConnection = $connection;
119
+        $this->secureRandom = $secureRandom;
120
+        $this->userManager = $userManager;
121
+        $this->rootFolder = $rootFolder;
122
+        $this->l = $l;
123
+        $this->logger = $logger;
124
+        $this->mailer = $mailer;
125
+        $this->urlGenerator = $urlGenerator;
126
+        $this->activityManager = $activityManager;
127
+        $this->settingsManager = $settingsManager;
128
+    }
129
+
130
+    /**
131
+     * Share a path
132
+     *
133
+     * @param IShare $share
134
+     * @return IShare The share object
135
+     * @throws ShareNotFound
136
+     * @throws \Exception
137
+     */
138
+    public function create(IShare $share) {
139
+
140
+        $shareWith = $share->getSharedWith();
141
+        /*
142 142
 		 * Check if file is not already shared with the remote user
143 143
 		 */
144
-		$alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
145
-		if (!empty($alreadyShared)) {
146
-			$message = 'Sharing %s failed, this item is already shared with %s';
147
-			$message_t = $this->l->t('Sharing %s failed, this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
148
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
149
-			throw new \Exception($message_t);
150
-		}
151
-
152
-		$shareId = $this->createMailShare($share);
153
-		$this->createActivity($share);
154
-		$data = $this->getRawShare($shareId);
155
-		return $this->createShareObject($data);
156
-
157
-	}
158
-
159
-	/**
160
-	 * create activity if a file/folder was shared by mail
161
-	 *
162
-	 * @param IShare $share
163
-	 */
164
-	protected function createActivity(IShare $share) {
165
-
166
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
167
-
168
-		$this->publishActivity(
169
-			Activity::SUBJECT_SHARED_EMAIL_SELF,
170
-			[$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
171
-			$share->getSharedBy(),
172
-			$share->getNode()->getId(),
173
-			$userFolder->getRelativePath($share->getNode()->getPath())
174
-		);
175
-
176
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
177
-			$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
178
-			$fileId = $share->getNode()->getId();
179
-			$nodes = $ownerFolder->getById($fileId);
180
-			$ownerPath = $nodes[0]->getPath();
181
-			$this->publishActivity(
182
-				Activity::SUBJECT_SHARED_EMAIL_BY,
183
-				[$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
184
-				$share->getShareOwner(),
185
-				$fileId,
186
-				$ownerFolder->getRelativePath($ownerPath)
187
-			);
188
-		}
189
-
190
-	}
191
-
192
-	/**
193
-	 * publish activity if a file/folder was shared by mail
194
-	 *
195
-	 * @param $subject
196
-	 * @param $parameters
197
-	 * @param $affectedUser
198
-	 * @param $fileId
199
-	 * @param $filePath
200
-	 */
201
-	protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
202
-		$event = $this->activityManager->generateEvent();
203
-		$event->setApp('sharebymail')
204
-			->setType('shared')
205
-			->setSubject($subject, $parameters)
206
-			->setAffectedUser($affectedUser)
207
-			->setObject('files', $fileId, $filePath);
208
-		$this->activityManager->publish($event);
209
-
210
-	}
211
-
212
-	/**
213
-	 * @param IShare $share
214
-	 * @return int
215
-	 * @throws \Exception
216
-	 */
217
-	protected function createMailShare(IShare $share) {
218
-		$share->setToken($this->generateToken());
219
-		$shareId = $this->addShareToDB(
220
-			$share->getNodeId(),
221
-			$share->getNodeType(),
222
-			$share->getSharedWith(),
223
-			$share->getSharedBy(),
224
-			$share->getShareOwner(),
225
-			$share->getPermissions(),
226
-			$share->getToken()
227
-		);
228
-
229
-		try {
230
-			$link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
231
-				['token' => $share->getToken()]);
232
-			$this->sendMailNotification($share->getNode()->getName(),
233
-				$link,
234
-				$share->getShareOwner(),
235
-				$share->getSharedBy(), $share->getSharedWith());
236
-		} catch (HintException $hintException) {
237
-			$this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
238
-			$this->removeShareFromTable($shareId);
239
-			throw $hintException;
240
-		} catch (\Exception $e) {
241
-			$this->logger->error('Failed to send share by mail: ' . $e->getMessage());
242
-			$this->removeShareFromTable($shareId);
243
-			throw new HintException('Failed to send share by mail',
244
-				$this->l->t('Failed to send share by E-mail'));
245
-		}
246
-
247
-		return $shareId;
248
-
249
-	}
250
-
251
-	protected function sendMailNotification($filename, $link, $owner, $initiator, $shareWith) {
252
-		$ownerUser = $this->userManager->get($owner);
253
-		$initiatorUser = $this->userManager->get($initiator);
254
-		$ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
255
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
256
-		if ($owner === $initiator) {
257
-			$subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
258
-		} else {
259
-			$subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
260
-		}
261
-
262
-		$message = $this->mailer->createMessage();
263
-
264
-		$emailTemplate = $this->mailer->createEMailTemplate();
265
-
266
-		$emailTemplate->addHeader();
267
-		$emailTemplate->addHeading($this->l->t('%s shared »%s« with you', [$ownerDisplayName, $filename]), false);
268
-
269
-		if ($owner === $initiator) {
270
-			$text = $this->l->t('%s shared »%s« with you.', [$ownerDisplayName, $filename]);
271
-		} else {
272
-			$text= $this->l->t('%s shared »%s« with you on behalf of %s.', [$ownerDisplayName, $filename, $initiator]);
273
-		}
274
-
275
-		$emailTemplate->addBodyText(
276
-			$text . ' ' . $this->l->t('Click the button below to open it.'),
277
-			$text
278
-		);
279
-
280
-		$emailTemplate->addBodyButton(
281
-			$this->l->t('Open »%s«', [$filename]),
282
-			$link
283
-		);
284
-		$emailTemplate->addFooter();
285
-
286
-		$message->setTo([$shareWith]);
287
-		$message->setSubject($subject);
288
-		$message->setBody($emailTemplate->renderText(), 'text/plain');
289
-		$message->setHtmlBody($emailTemplate->renderHTML());
290
-		$this->mailer->send($message);
291
-
292
-	}
293
-
294
-	/**
295
-	 * send password to recipient of a mail share
296
-	 *
297
-	 * @param string $filename
298
-	 * @param string $initiator
299
-	 * @param string $shareWith
300
-	 */
301
-	protected function sendPassword($filename, $initiator, $shareWith, $password) {
302
-
303
-		if ($this->settingsManager->sendPasswordByMail() === false) {
304
-			return;
305
-		}
306
-
307
-		$initiatorUser = $this->userManager->get($initiator);
308
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
309
-		$subject = (string)$this->l->t('Password to access »%s« shared to you by %s', [$filename, $initiatorDisplayName]);
310
-
311
-		$message = $this->mailer->createMessage();
312
-
313
-		$emailTemplate = $this->mailer->createEMailTemplate();
314
-
315
-		$emailTemplate->addHeader();
316
-		$emailTemplate->addHeading($this->l->t('Password to access »%s«', [$filename]));
317
-
318
-		$emailTemplate->addBodyText($this->l->t(
319
-			'%s shared »%s« with you. You should have already received a separate mail with a link to access it.',
320
-				[$initiatorDisplayName, $filename]
321
-		));
322
-		$emailTemplate->addBodyText($this->l->t('It is protected with the following password: %s', [$password]));
323
-
324
-		$emailTemplate->addFooter();
325
-
326
-		$message->setTo([$shareWith]);
327
-		$message->setSubject($subject);
328
-		$message->setBody($emailTemplate->renderText(), 'text/plain');
329
-		$message->setHtmlBody($emailTemplate->renderHTML());
330
-		$this->mailer->send($message);
331
-
332
-	}
333
-
334
-
335
-	/**
336
-	 * generate share token
337
-	 *
338
-	 * @return string
339
-	 */
340
-	protected function generateToken() {
341
-		$token = $this->secureRandom->generate(
342
-			15, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
343
-		return $token;
344
-	}
345
-
346
-	/**
347
-	 * Get all children of this share
348
-	 *
349
-	 * @param IShare $parent
350
-	 * @return IShare[]
351
-	 */
352
-	public function getChildren(IShare $parent) {
353
-		$children = [];
354
-
355
-		$qb = $this->dbConnection->getQueryBuilder();
356
-		$qb->select('*')
357
-			->from('share')
358
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
359
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
360
-			->orderBy('id');
361
-
362
-		$cursor = $qb->execute();
363
-		while($data = $cursor->fetch()) {
364
-			$children[] = $this->createShareObject($data);
365
-		}
366
-		$cursor->closeCursor();
367
-
368
-		return $children;
369
-	}
370
-
371
-	/**
372
-	 * add share to the database and return the ID
373
-	 *
374
-	 * @param int $itemSource
375
-	 * @param string $itemType
376
-	 * @param string $shareWith
377
-	 * @param string $sharedBy
378
-	 * @param string $uidOwner
379
-	 * @param int $permissions
380
-	 * @param string $token
381
-	 * @return int
382
-	 */
383
-	protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
384
-		$qb = $this->dbConnection->getQueryBuilder();
385
-		$qb->insert('share')
386
-			->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
387
-			->setValue('item_type', $qb->createNamedParameter($itemType))
388
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
389
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
390
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
391
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
392
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
393
-			->setValue('permissions', $qb->createNamedParameter($permissions))
394
-			->setValue('token', $qb->createNamedParameter($token))
395
-			->setValue('stime', $qb->createNamedParameter(time()));
396
-
397
-		/*
144
+        $alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
145
+        if (!empty($alreadyShared)) {
146
+            $message = 'Sharing %s failed, this item is already shared with %s';
147
+            $message_t = $this->l->t('Sharing %s failed, this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
148
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
149
+            throw new \Exception($message_t);
150
+        }
151
+
152
+        $shareId = $this->createMailShare($share);
153
+        $this->createActivity($share);
154
+        $data = $this->getRawShare($shareId);
155
+        return $this->createShareObject($data);
156
+
157
+    }
158
+
159
+    /**
160
+     * create activity if a file/folder was shared by mail
161
+     *
162
+     * @param IShare $share
163
+     */
164
+    protected function createActivity(IShare $share) {
165
+
166
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
167
+
168
+        $this->publishActivity(
169
+            Activity::SUBJECT_SHARED_EMAIL_SELF,
170
+            [$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
171
+            $share->getSharedBy(),
172
+            $share->getNode()->getId(),
173
+            $userFolder->getRelativePath($share->getNode()->getPath())
174
+        );
175
+
176
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
177
+            $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
178
+            $fileId = $share->getNode()->getId();
179
+            $nodes = $ownerFolder->getById($fileId);
180
+            $ownerPath = $nodes[0]->getPath();
181
+            $this->publishActivity(
182
+                Activity::SUBJECT_SHARED_EMAIL_BY,
183
+                [$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
184
+                $share->getShareOwner(),
185
+                $fileId,
186
+                $ownerFolder->getRelativePath($ownerPath)
187
+            );
188
+        }
189
+
190
+    }
191
+
192
+    /**
193
+     * publish activity if a file/folder was shared by mail
194
+     *
195
+     * @param $subject
196
+     * @param $parameters
197
+     * @param $affectedUser
198
+     * @param $fileId
199
+     * @param $filePath
200
+     */
201
+    protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
202
+        $event = $this->activityManager->generateEvent();
203
+        $event->setApp('sharebymail')
204
+            ->setType('shared')
205
+            ->setSubject($subject, $parameters)
206
+            ->setAffectedUser($affectedUser)
207
+            ->setObject('files', $fileId, $filePath);
208
+        $this->activityManager->publish($event);
209
+
210
+    }
211
+
212
+    /**
213
+     * @param IShare $share
214
+     * @return int
215
+     * @throws \Exception
216
+     */
217
+    protected function createMailShare(IShare $share) {
218
+        $share->setToken($this->generateToken());
219
+        $shareId = $this->addShareToDB(
220
+            $share->getNodeId(),
221
+            $share->getNodeType(),
222
+            $share->getSharedWith(),
223
+            $share->getSharedBy(),
224
+            $share->getShareOwner(),
225
+            $share->getPermissions(),
226
+            $share->getToken()
227
+        );
228
+
229
+        try {
230
+            $link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
231
+                ['token' => $share->getToken()]);
232
+            $this->sendMailNotification($share->getNode()->getName(),
233
+                $link,
234
+                $share->getShareOwner(),
235
+                $share->getSharedBy(), $share->getSharedWith());
236
+        } catch (HintException $hintException) {
237
+            $this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
238
+            $this->removeShareFromTable($shareId);
239
+            throw $hintException;
240
+        } catch (\Exception $e) {
241
+            $this->logger->error('Failed to send share by mail: ' . $e->getMessage());
242
+            $this->removeShareFromTable($shareId);
243
+            throw new HintException('Failed to send share by mail',
244
+                $this->l->t('Failed to send share by E-mail'));
245
+        }
246
+
247
+        return $shareId;
248
+
249
+    }
250
+
251
+    protected function sendMailNotification($filename, $link, $owner, $initiator, $shareWith) {
252
+        $ownerUser = $this->userManager->get($owner);
253
+        $initiatorUser = $this->userManager->get($initiator);
254
+        $ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
255
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
256
+        if ($owner === $initiator) {
257
+            $subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
258
+        } else {
259
+            $subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
260
+        }
261
+
262
+        $message = $this->mailer->createMessage();
263
+
264
+        $emailTemplate = $this->mailer->createEMailTemplate();
265
+
266
+        $emailTemplate->addHeader();
267
+        $emailTemplate->addHeading($this->l->t('%s shared »%s« with you', [$ownerDisplayName, $filename]), false);
268
+
269
+        if ($owner === $initiator) {
270
+            $text = $this->l->t('%s shared »%s« with you.', [$ownerDisplayName, $filename]);
271
+        } else {
272
+            $text= $this->l->t('%s shared »%s« with you on behalf of %s.', [$ownerDisplayName, $filename, $initiator]);
273
+        }
274
+
275
+        $emailTemplate->addBodyText(
276
+            $text . ' ' . $this->l->t('Click the button below to open it.'),
277
+            $text
278
+        );
279
+
280
+        $emailTemplate->addBodyButton(
281
+            $this->l->t('Open »%s«', [$filename]),
282
+            $link
283
+        );
284
+        $emailTemplate->addFooter();
285
+
286
+        $message->setTo([$shareWith]);
287
+        $message->setSubject($subject);
288
+        $message->setBody($emailTemplate->renderText(), 'text/plain');
289
+        $message->setHtmlBody($emailTemplate->renderHTML());
290
+        $this->mailer->send($message);
291
+
292
+    }
293
+
294
+    /**
295
+     * send password to recipient of a mail share
296
+     *
297
+     * @param string $filename
298
+     * @param string $initiator
299
+     * @param string $shareWith
300
+     */
301
+    protected function sendPassword($filename, $initiator, $shareWith, $password) {
302
+
303
+        if ($this->settingsManager->sendPasswordByMail() === false) {
304
+            return;
305
+        }
306
+
307
+        $initiatorUser = $this->userManager->get($initiator);
308
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
309
+        $subject = (string)$this->l->t('Password to access »%s« shared to you by %s', [$filename, $initiatorDisplayName]);
310
+
311
+        $message = $this->mailer->createMessage();
312
+
313
+        $emailTemplate = $this->mailer->createEMailTemplate();
314
+
315
+        $emailTemplate->addHeader();
316
+        $emailTemplate->addHeading($this->l->t('Password to access »%s«', [$filename]));
317
+
318
+        $emailTemplate->addBodyText($this->l->t(
319
+            '%s shared »%s« with you. You should have already received a separate mail with a link to access it.',
320
+                [$initiatorDisplayName, $filename]
321
+        ));
322
+        $emailTemplate->addBodyText($this->l->t('It is protected with the following password: %s', [$password]));
323
+
324
+        $emailTemplate->addFooter();
325
+
326
+        $message->setTo([$shareWith]);
327
+        $message->setSubject($subject);
328
+        $message->setBody($emailTemplate->renderText(), 'text/plain');
329
+        $message->setHtmlBody($emailTemplate->renderHTML());
330
+        $this->mailer->send($message);
331
+
332
+    }
333
+
334
+
335
+    /**
336
+     * generate share token
337
+     *
338
+     * @return string
339
+     */
340
+    protected function generateToken() {
341
+        $token = $this->secureRandom->generate(
342
+            15, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
343
+        return $token;
344
+    }
345
+
346
+    /**
347
+     * Get all children of this share
348
+     *
349
+     * @param IShare $parent
350
+     * @return IShare[]
351
+     */
352
+    public function getChildren(IShare $parent) {
353
+        $children = [];
354
+
355
+        $qb = $this->dbConnection->getQueryBuilder();
356
+        $qb->select('*')
357
+            ->from('share')
358
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
359
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
360
+            ->orderBy('id');
361
+
362
+        $cursor = $qb->execute();
363
+        while($data = $cursor->fetch()) {
364
+            $children[] = $this->createShareObject($data);
365
+        }
366
+        $cursor->closeCursor();
367
+
368
+        return $children;
369
+    }
370
+
371
+    /**
372
+     * add share to the database and return the ID
373
+     *
374
+     * @param int $itemSource
375
+     * @param string $itemType
376
+     * @param string $shareWith
377
+     * @param string $sharedBy
378
+     * @param string $uidOwner
379
+     * @param int $permissions
380
+     * @param string $token
381
+     * @return int
382
+     */
383
+    protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
384
+        $qb = $this->dbConnection->getQueryBuilder();
385
+        $qb->insert('share')
386
+            ->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
387
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
388
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
389
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
390
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
391
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
392
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
393
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
394
+            ->setValue('token', $qb->createNamedParameter($token))
395
+            ->setValue('stime', $qb->createNamedParameter(time()));
396
+
397
+        /*
398 398
 		 * Added to fix https://github.com/owncloud/core/issues/22215
399 399
 		 * Can be removed once we get rid of ajax/share.php
400 400
 		 */
401
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
401
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
402 402
 
403
-		$qb->execute();
404
-		$id = $qb->getLastInsertId();
403
+        $qb->execute();
404
+        $id = $qb->getLastInsertId();
405 405
 
406
-		return (int)$id;
407
-	}
406
+        return (int)$id;
407
+    }
408 408
 
409
-	/**
410
-	 * Update a share
411
-	 *
412
-	 * @param IShare $share
413
-	 * @param string|null $plainTextPassword
414
-	 * @return IShare The share object
415
-	 */
416
-	public function update(IShare $share, $plainTextPassword = null) {
409
+    /**
410
+     * Update a share
411
+     *
412
+     * @param IShare $share
413
+     * @param string|null $plainTextPassword
414
+     * @return IShare The share object
415
+     */
416
+    public function update(IShare $share, $plainTextPassword = null) {
417 417
 
418
-		$originalShare = $this->getShareById($share->getId());
418
+        $originalShare = $this->getShareById($share->getId());
419 419
 
420
-		// a real password was given
421
-		$validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
420
+        // a real password was given
421
+        $validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
422 422
 
423
-		if($validPassword && $originalShare->getPassword() !== $share->getPassword()) {
424
-			$this->sendPassword($share->getNode()->getName(), $share->getSharedBy(), $share->getSharedWith(), $plainTextPassword);
425
-		}
426
-		/*
423
+        if($validPassword && $originalShare->getPassword() !== $share->getPassword()) {
424
+            $this->sendPassword($share->getNode()->getName(), $share->getSharedBy(), $share->getSharedWith(), $plainTextPassword);
425
+        }
426
+        /*
427 427
 		 * We allow updating the permissions and password of mail shares
428 428
 		 */
429
-		$qb = $this->dbConnection->getQueryBuilder();
430
-		$qb->update('share')
431
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
432
-			->set('permissions', $qb->createNamedParameter($share->getPermissions()))
433
-			->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
434
-			->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
435
-			->set('password', $qb->createNamedParameter($share->getPassword()))
436
-			->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
437
-			->execute();
438
-
439
-		return $share;
440
-	}
441
-
442
-	/**
443
-	 * @inheritdoc
444
-	 */
445
-	public function move(IShare $share, $recipient) {
446
-		/**
447
-		 * nothing to do here, mail shares are only outgoing shares
448
-		 */
449
-		return $share;
450
-	}
451
-
452
-	/**
453
-	 * Delete a share (owner unShares the file)
454
-	 *
455
-	 * @param IShare $share
456
-	 */
457
-	public function delete(IShare $share) {
458
-		$this->removeShareFromTable($share->getId());
459
-	}
460
-
461
-	/**
462
-	 * @inheritdoc
463
-	 */
464
-	public function deleteFromSelf(IShare $share, $recipient) {
465
-		// nothing to do here, mail shares are only outgoing shares
466
-		return;
467
-	}
468
-
469
-	/**
470
-	 * @inheritdoc
471
-	 */
472
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
473
-		$qb = $this->dbConnection->getQueryBuilder();
474
-		$qb->select('*')
475
-			->from('share');
476
-
477
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
478
-
479
-		/**
480
-		 * Reshares for this user are shares where they are the owner.
481
-		 */
482
-		if ($reshares === false) {
483
-			//Special case for old shares created via the web UI
484
-			$or1 = $qb->expr()->andX(
485
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
486
-				$qb->expr()->isNull('uid_initiator')
487
-			);
488
-
489
-			$qb->andWhere(
490
-				$qb->expr()->orX(
491
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
492
-					$or1
493
-				)
494
-			);
495
-		} else {
496
-			$qb->andWhere(
497
-				$qb->expr()->orX(
498
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
499
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
500
-				)
501
-			);
502
-		}
503
-
504
-		if ($node !== null) {
505
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
506
-		}
507
-
508
-		if ($limit !== -1) {
509
-			$qb->setMaxResults($limit);
510
-		}
511
-
512
-		$qb->setFirstResult($offset);
513
-		$qb->orderBy('id');
514
-
515
-		$cursor = $qb->execute();
516
-		$shares = [];
517
-		while($data = $cursor->fetch()) {
518
-			$shares[] = $this->createShareObject($data);
519
-		}
520
-		$cursor->closeCursor();
521
-
522
-		return $shares;
523
-	}
524
-
525
-	/**
526
-	 * @inheritdoc
527
-	 */
528
-	public function getShareById($id, $recipientId = null) {
529
-		$qb = $this->dbConnection->getQueryBuilder();
530
-
531
-		$qb->select('*')
532
-			->from('share')
533
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
534
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
535
-
536
-		$cursor = $qb->execute();
537
-		$data = $cursor->fetch();
538
-		$cursor->closeCursor();
539
-
540
-		if ($data === false) {
541
-			throw new ShareNotFound();
542
-		}
543
-
544
-		try {
545
-			$share = $this->createShareObject($data);
546
-		} catch (InvalidShare $e) {
547
-			throw new ShareNotFound();
548
-		}
549
-
550
-		return $share;
551
-	}
552
-
553
-	/**
554
-	 * Get shares for a given path
555
-	 *
556
-	 * @param \OCP\Files\Node $path
557
-	 * @return IShare[]
558
-	 */
559
-	public function getSharesByPath(Node $path) {
560
-		$qb = $this->dbConnection->getQueryBuilder();
561
-
562
-		$cursor = $qb->select('*')
563
-			->from('share')
564
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
565
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
566
-			->execute();
567
-
568
-		$shares = [];
569
-		while($data = $cursor->fetch()) {
570
-			$shares[] = $this->createShareObject($data);
571
-		}
572
-		$cursor->closeCursor();
573
-
574
-		return $shares;
575
-	}
576
-
577
-	/**
578
-	 * @inheritdoc
579
-	 */
580
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
581
-		/** @var IShare[] $shares */
582
-		$shares = [];
583
-
584
-		//Get shares directly with this user
585
-		$qb = $this->dbConnection->getQueryBuilder();
586
-		$qb->select('*')
587
-			->from('share');
588
-
589
-		// Order by id
590
-		$qb->orderBy('id');
591
-
592
-		// Set limit and offset
593
-		if ($limit !== -1) {
594
-			$qb->setMaxResults($limit);
595
-		}
596
-		$qb->setFirstResult($offset);
597
-
598
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
599
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
600
-
601
-		// Filter by node if provided
602
-		if ($node !== null) {
603
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
604
-		}
605
-
606
-		$cursor = $qb->execute();
607
-
608
-		while($data = $cursor->fetch()) {
609
-			$shares[] = $this->createShareObject($data);
610
-		}
611
-		$cursor->closeCursor();
612
-
613
-
614
-		return $shares;
615
-	}
616
-
617
-	/**
618
-	 * Get a share by token
619
-	 *
620
-	 * @param string $token
621
-	 * @return IShare
622
-	 * @throws ShareNotFound
623
-	 */
624
-	public function getShareByToken($token) {
625
-		$qb = $this->dbConnection->getQueryBuilder();
626
-
627
-		$cursor = $qb->select('*')
628
-			->from('share')
629
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
630
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
631
-			->execute();
632
-
633
-		$data = $cursor->fetch();
634
-
635
-		if ($data === false) {
636
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
637
-		}
638
-
639
-		try {
640
-			$share = $this->createShareObject($data);
641
-		} catch (InvalidShare $e) {
642
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
643
-		}
644
-
645
-		return $share;
646
-	}
647
-
648
-	/**
649
-	 * remove share from table
650
-	 *
651
-	 * @param string $shareId
652
-	 */
653
-	protected function removeShareFromTable($shareId) {
654
-		$qb = $this->dbConnection->getQueryBuilder();
655
-		$qb->delete('share')
656
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
657
-		$qb->execute();
658
-	}
659
-
660
-	/**
661
-	 * Create a share object from an database row
662
-	 *
663
-	 * @param array $data
664
-	 * @return IShare
665
-	 * @throws InvalidShare
666
-	 * @throws ShareNotFound
667
-	 */
668
-	protected function createShareObject($data) {
669
-
670
-		$share = new Share($this->rootFolder, $this->userManager);
671
-		$share->setId((int)$data['id'])
672
-			->setShareType((int)$data['share_type'])
673
-			->setPermissions((int)$data['permissions'])
674
-			->setTarget($data['file_target'])
675
-			->setMailSend((bool)$data['mail_send'])
676
-			->setToken($data['token']);
677
-
678
-		$shareTime = new \DateTime();
679
-		$shareTime->setTimestamp((int)$data['stime']);
680
-		$share->setShareTime($shareTime);
681
-		$share->setSharedWith($data['share_with']);
682
-		$share->setPassword($data['password']);
683
-
684
-		if ($data['uid_initiator'] !== null) {
685
-			$share->setShareOwner($data['uid_owner']);
686
-			$share->setSharedBy($data['uid_initiator']);
687
-		} else {
688
-			//OLD SHARE
689
-			$share->setSharedBy($data['uid_owner']);
690
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
691
-
692
-			$owner = $path->getOwner();
693
-			$share->setShareOwner($owner->getUID());
694
-		}
695
-
696
-		if ($data['expiration'] !== null) {
697
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
698
-			if ($expiration !== false) {
699
-				$share->setExpirationDate($expiration);
700
-			}
701
-		}
702
-
703
-		$share->setNodeId((int)$data['file_source']);
704
-		$share->setNodeType($data['item_type']);
705
-
706
-		$share->setProviderId($this->identifier());
707
-
708
-		return $share;
709
-	}
710
-
711
-	/**
712
-	 * Get the node with file $id for $user
713
-	 *
714
-	 * @param string $userId
715
-	 * @param int $id
716
-	 * @return \OCP\Files\File|\OCP\Files\Folder
717
-	 * @throws InvalidShare
718
-	 */
719
-	private function getNode($userId, $id) {
720
-		try {
721
-			$userFolder = $this->rootFolder->getUserFolder($userId);
722
-		} catch (NotFoundException $e) {
723
-			throw new InvalidShare();
724
-		}
725
-
726
-		$nodes = $userFolder->getById($id);
727
-
728
-		if (empty($nodes)) {
729
-			throw new InvalidShare();
730
-		}
731
-
732
-		return $nodes[0];
733
-	}
734
-
735
-	/**
736
-	 * A user is deleted from the system
737
-	 * So clean up the relevant shares.
738
-	 *
739
-	 * @param string $uid
740
-	 * @param int $shareType
741
-	 */
742
-	public function userDeleted($uid, $shareType) {
743
-		$qb = $this->dbConnection->getQueryBuilder();
744
-
745
-		$qb->delete('share')
746
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
747
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
748
-			->execute();
749
-	}
750
-
751
-	/**
752
-	 * This provider does not support group shares
753
-	 *
754
-	 * @param string $gid
755
-	 */
756
-	public function groupDeleted($gid) {
757
-		return;
758
-	}
759
-
760
-	/**
761
-	 * This provider does not support group shares
762
-	 *
763
-	 * @param string $uid
764
-	 * @param string $gid
765
-	 */
766
-	public function userDeletedFromGroup($uid, $gid) {
767
-		return;
768
-	}
769
-
770
-	/**
771
-	 * get database row of a give share
772
-	 *
773
-	 * @param $id
774
-	 * @return array
775
-	 * @throws ShareNotFound
776
-	 */
777
-	protected function getRawShare($id) {
778
-
779
-		// Now fetch the inserted share and create a complete share object
780
-		$qb = $this->dbConnection->getQueryBuilder();
781
-		$qb->select('*')
782
-			->from('share')
783
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
784
-
785
-		$cursor = $qb->execute();
786
-		$data = $cursor->fetch();
787
-		$cursor->closeCursor();
788
-
789
-		if ($data === false) {
790
-			throw new ShareNotFound;
791
-		}
792
-
793
-		return $data;
794
-	}
795
-
796
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
797
-		$qb = $this->dbConnection->getQueryBuilder();
798
-		$qb->select('*')
799
-			->from('share', 's')
800
-			->andWhere($qb->expr()->orX(
801
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
802
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
803
-			))
804
-			->andWhere(
805
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
806
-			);
807
-
808
-		/**
809
-		 * Reshares for this user are shares where they are the owner.
810
-		 */
811
-		if ($reshares === false) {
812
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
813
-		} else {
814
-			$qb->andWhere(
815
-				$qb->expr()->orX(
816
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
817
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
818
-				)
819
-			);
820
-		}
821
-
822
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
823
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
824
-
825
-		$qb->orderBy('id');
826
-
827
-		$cursor = $qb->execute();
828
-		$shares = [];
829
-		while ($data = $cursor->fetch()) {
830
-			$shares[$data['fileid']][] = $this->createShareObject($data);
831
-		}
832
-		$cursor->closeCursor();
833
-
834
-		return $shares;
835
-	}
836
-
837
-	/**
838
-	 * @inheritdoc
839
-	 */
840
-	public function getAccessList($nodes, $currentAccess) {
841
-		$ids = [];
842
-		foreach ($nodes as $node) {
843
-			$ids[] = $node->getId();
844
-		}
845
-
846
-		$qb = $this->dbConnection->getQueryBuilder();
847
-		$qb->select('share_with')
848
-			->from('share')
849
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
850
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
851
-			->andWhere($qb->expr()->orX(
852
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
853
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
854
-			))
855
-			->setMaxResults(1);
856
-		$cursor = $qb->execute();
857
-
858
-		$mail = $cursor->fetch() !== false;
859
-		$cursor->closeCursor();
860
-
861
-		return ['public' => $mail];
862
-	}
429
+        $qb = $this->dbConnection->getQueryBuilder();
430
+        $qb->update('share')
431
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
432
+            ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
433
+            ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
434
+            ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
435
+            ->set('password', $qb->createNamedParameter($share->getPassword()))
436
+            ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
437
+            ->execute();
438
+
439
+        return $share;
440
+    }
441
+
442
+    /**
443
+     * @inheritdoc
444
+     */
445
+    public function move(IShare $share, $recipient) {
446
+        /**
447
+         * nothing to do here, mail shares are only outgoing shares
448
+         */
449
+        return $share;
450
+    }
451
+
452
+    /**
453
+     * Delete a share (owner unShares the file)
454
+     *
455
+     * @param IShare $share
456
+     */
457
+    public function delete(IShare $share) {
458
+        $this->removeShareFromTable($share->getId());
459
+    }
460
+
461
+    /**
462
+     * @inheritdoc
463
+     */
464
+    public function deleteFromSelf(IShare $share, $recipient) {
465
+        // nothing to do here, mail shares are only outgoing shares
466
+        return;
467
+    }
468
+
469
+    /**
470
+     * @inheritdoc
471
+     */
472
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
473
+        $qb = $this->dbConnection->getQueryBuilder();
474
+        $qb->select('*')
475
+            ->from('share');
476
+
477
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
478
+
479
+        /**
480
+         * Reshares for this user are shares where they are the owner.
481
+         */
482
+        if ($reshares === false) {
483
+            //Special case for old shares created via the web UI
484
+            $or1 = $qb->expr()->andX(
485
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
486
+                $qb->expr()->isNull('uid_initiator')
487
+            );
488
+
489
+            $qb->andWhere(
490
+                $qb->expr()->orX(
491
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
492
+                    $or1
493
+                )
494
+            );
495
+        } else {
496
+            $qb->andWhere(
497
+                $qb->expr()->orX(
498
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
499
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
500
+                )
501
+            );
502
+        }
503
+
504
+        if ($node !== null) {
505
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
506
+        }
507
+
508
+        if ($limit !== -1) {
509
+            $qb->setMaxResults($limit);
510
+        }
511
+
512
+        $qb->setFirstResult($offset);
513
+        $qb->orderBy('id');
514
+
515
+        $cursor = $qb->execute();
516
+        $shares = [];
517
+        while($data = $cursor->fetch()) {
518
+            $shares[] = $this->createShareObject($data);
519
+        }
520
+        $cursor->closeCursor();
521
+
522
+        return $shares;
523
+    }
524
+
525
+    /**
526
+     * @inheritdoc
527
+     */
528
+    public function getShareById($id, $recipientId = null) {
529
+        $qb = $this->dbConnection->getQueryBuilder();
530
+
531
+        $qb->select('*')
532
+            ->from('share')
533
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
534
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
535
+
536
+        $cursor = $qb->execute();
537
+        $data = $cursor->fetch();
538
+        $cursor->closeCursor();
539
+
540
+        if ($data === false) {
541
+            throw new ShareNotFound();
542
+        }
543
+
544
+        try {
545
+            $share = $this->createShareObject($data);
546
+        } catch (InvalidShare $e) {
547
+            throw new ShareNotFound();
548
+        }
549
+
550
+        return $share;
551
+    }
552
+
553
+    /**
554
+     * Get shares for a given path
555
+     *
556
+     * @param \OCP\Files\Node $path
557
+     * @return IShare[]
558
+     */
559
+    public function getSharesByPath(Node $path) {
560
+        $qb = $this->dbConnection->getQueryBuilder();
561
+
562
+        $cursor = $qb->select('*')
563
+            ->from('share')
564
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
565
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
566
+            ->execute();
567
+
568
+        $shares = [];
569
+        while($data = $cursor->fetch()) {
570
+            $shares[] = $this->createShareObject($data);
571
+        }
572
+        $cursor->closeCursor();
573
+
574
+        return $shares;
575
+    }
576
+
577
+    /**
578
+     * @inheritdoc
579
+     */
580
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
581
+        /** @var IShare[] $shares */
582
+        $shares = [];
583
+
584
+        //Get shares directly with this user
585
+        $qb = $this->dbConnection->getQueryBuilder();
586
+        $qb->select('*')
587
+            ->from('share');
588
+
589
+        // Order by id
590
+        $qb->orderBy('id');
591
+
592
+        // Set limit and offset
593
+        if ($limit !== -1) {
594
+            $qb->setMaxResults($limit);
595
+        }
596
+        $qb->setFirstResult($offset);
597
+
598
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
599
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
600
+
601
+        // Filter by node if provided
602
+        if ($node !== null) {
603
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
604
+        }
605
+
606
+        $cursor = $qb->execute();
607
+
608
+        while($data = $cursor->fetch()) {
609
+            $shares[] = $this->createShareObject($data);
610
+        }
611
+        $cursor->closeCursor();
612
+
613
+
614
+        return $shares;
615
+    }
616
+
617
+    /**
618
+     * Get a share by token
619
+     *
620
+     * @param string $token
621
+     * @return IShare
622
+     * @throws ShareNotFound
623
+     */
624
+    public function getShareByToken($token) {
625
+        $qb = $this->dbConnection->getQueryBuilder();
626
+
627
+        $cursor = $qb->select('*')
628
+            ->from('share')
629
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
630
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
631
+            ->execute();
632
+
633
+        $data = $cursor->fetch();
634
+
635
+        if ($data === false) {
636
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
637
+        }
638
+
639
+        try {
640
+            $share = $this->createShareObject($data);
641
+        } catch (InvalidShare $e) {
642
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
643
+        }
644
+
645
+        return $share;
646
+    }
647
+
648
+    /**
649
+     * remove share from table
650
+     *
651
+     * @param string $shareId
652
+     */
653
+    protected function removeShareFromTable($shareId) {
654
+        $qb = $this->dbConnection->getQueryBuilder();
655
+        $qb->delete('share')
656
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
657
+        $qb->execute();
658
+    }
659
+
660
+    /**
661
+     * Create a share object from an database row
662
+     *
663
+     * @param array $data
664
+     * @return IShare
665
+     * @throws InvalidShare
666
+     * @throws ShareNotFound
667
+     */
668
+    protected function createShareObject($data) {
669
+
670
+        $share = new Share($this->rootFolder, $this->userManager);
671
+        $share->setId((int)$data['id'])
672
+            ->setShareType((int)$data['share_type'])
673
+            ->setPermissions((int)$data['permissions'])
674
+            ->setTarget($data['file_target'])
675
+            ->setMailSend((bool)$data['mail_send'])
676
+            ->setToken($data['token']);
677
+
678
+        $shareTime = new \DateTime();
679
+        $shareTime->setTimestamp((int)$data['stime']);
680
+        $share->setShareTime($shareTime);
681
+        $share->setSharedWith($data['share_with']);
682
+        $share->setPassword($data['password']);
683
+
684
+        if ($data['uid_initiator'] !== null) {
685
+            $share->setShareOwner($data['uid_owner']);
686
+            $share->setSharedBy($data['uid_initiator']);
687
+        } else {
688
+            //OLD SHARE
689
+            $share->setSharedBy($data['uid_owner']);
690
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
691
+
692
+            $owner = $path->getOwner();
693
+            $share->setShareOwner($owner->getUID());
694
+        }
695
+
696
+        if ($data['expiration'] !== null) {
697
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
698
+            if ($expiration !== false) {
699
+                $share->setExpirationDate($expiration);
700
+            }
701
+        }
702
+
703
+        $share->setNodeId((int)$data['file_source']);
704
+        $share->setNodeType($data['item_type']);
705
+
706
+        $share->setProviderId($this->identifier());
707
+
708
+        return $share;
709
+    }
710
+
711
+    /**
712
+     * Get the node with file $id for $user
713
+     *
714
+     * @param string $userId
715
+     * @param int $id
716
+     * @return \OCP\Files\File|\OCP\Files\Folder
717
+     * @throws InvalidShare
718
+     */
719
+    private function getNode($userId, $id) {
720
+        try {
721
+            $userFolder = $this->rootFolder->getUserFolder($userId);
722
+        } catch (NotFoundException $e) {
723
+            throw new InvalidShare();
724
+        }
725
+
726
+        $nodes = $userFolder->getById($id);
727
+
728
+        if (empty($nodes)) {
729
+            throw new InvalidShare();
730
+        }
731
+
732
+        return $nodes[0];
733
+    }
734
+
735
+    /**
736
+     * A user is deleted from the system
737
+     * So clean up the relevant shares.
738
+     *
739
+     * @param string $uid
740
+     * @param int $shareType
741
+     */
742
+    public function userDeleted($uid, $shareType) {
743
+        $qb = $this->dbConnection->getQueryBuilder();
744
+
745
+        $qb->delete('share')
746
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
747
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
748
+            ->execute();
749
+    }
750
+
751
+    /**
752
+     * This provider does not support group shares
753
+     *
754
+     * @param string $gid
755
+     */
756
+    public function groupDeleted($gid) {
757
+        return;
758
+    }
759
+
760
+    /**
761
+     * This provider does not support group shares
762
+     *
763
+     * @param string $uid
764
+     * @param string $gid
765
+     */
766
+    public function userDeletedFromGroup($uid, $gid) {
767
+        return;
768
+    }
769
+
770
+    /**
771
+     * get database row of a give share
772
+     *
773
+     * @param $id
774
+     * @return array
775
+     * @throws ShareNotFound
776
+     */
777
+    protected function getRawShare($id) {
778
+
779
+        // Now fetch the inserted share and create a complete share object
780
+        $qb = $this->dbConnection->getQueryBuilder();
781
+        $qb->select('*')
782
+            ->from('share')
783
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
784
+
785
+        $cursor = $qb->execute();
786
+        $data = $cursor->fetch();
787
+        $cursor->closeCursor();
788
+
789
+        if ($data === false) {
790
+            throw new ShareNotFound;
791
+        }
792
+
793
+        return $data;
794
+    }
795
+
796
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
797
+        $qb = $this->dbConnection->getQueryBuilder();
798
+        $qb->select('*')
799
+            ->from('share', 's')
800
+            ->andWhere($qb->expr()->orX(
801
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
802
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
803
+            ))
804
+            ->andWhere(
805
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
806
+            );
807
+
808
+        /**
809
+         * Reshares for this user are shares where they are the owner.
810
+         */
811
+        if ($reshares === false) {
812
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
813
+        } else {
814
+            $qb->andWhere(
815
+                $qb->expr()->orX(
816
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
817
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
818
+                )
819
+            );
820
+        }
821
+
822
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
823
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
824
+
825
+        $qb->orderBy('id');
826
+
827
+        $cursor = $qb->execute();
828
+        $shares = [];
829
+        while ($data = $cursor->fetch()) {
830
+            $shares[$data['fileid']][] = $this->createShareObject($data);
831
+        }
832
+        $cursor->closeCursor();
833
+
834
+        return $shares;
835
+    }
836
+
837
+    /**
838
+     * @inheritdoc
839
+     */
840
+    public function getAccessList($nodes, $currentAccess) {
841
+        $ids = [];
842
+        foreach ($nodes as $node) {
843
+            $ids[] = $node->getId();
844
+        }
845
+
846
+        $qb = $this->dbConnection->getQueryBuilder();
847
+        $qb->select('share_with')
848
+            ->from('share')
849
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
850
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
851
+            ->andWhere($qb->expr()->orX(
852
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
853
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
854
+            ))
855
+            ->setMaxResults(1);
856
+        $cursor = $qb->execute();
857
+
858
+        $mail = $cursor->fetch() !== false;
859
+        $cursor->closeCursor();
860
+
861
+        return ['public' => $mail];
862
+    }
863 863
 
864 864
 }
Please login to merge, or discard this patch.