Passed
Push — master ( f0dd71...c56a27 )
by Christoph
11:49 queued 12s
created
lib/private/Search/Result/File.php 1 patch
Indentation   +70 added lines, -70 removed lines patch added patch discarded remove patch
@@ -33,85 +33,85 @@
 block discarded – undo
33 33
  */
34 34
 class File extends \OCP\Search\Result {
35 35
 
36
-	/**
37
-	 * Type name; translated in templates
38
-	 * @var string 
39
-	 */
40
-	public $type = 'file';
36
+    /**
37
+     * Type name; translated in templates
38
+     * @var string 
39
+     */
40
+    public $type = 'file';
41 41
 
42
-	/**
43
-	 * Path to file
44
-	 * @var string
45
-	 */
46
-	public $path;
42
+    /**
43
+     * Path to file
44
+     * @var string
45
+     */
46
+    public $path;
47 47
 
48
-	/**
49
-	 * Size, in bytes
50
-	 * @var int 
51
-	 */
52
-	public $size;
48
+    /**
49
+     * Size, in bytes
50
+     * @var int 
51
+     */
52
+    public $size;
53 53
 
54
-	/**
55
-	 * Date modified, in human readable form
56
-	 * @var string
57
-	 */
58
-	public $modified;
54
+    /**
55
+     * Date modified, in human readable form
56
+     * @var string
57
+     */
58
+    public $modified;
59 59
 
60
-	/**
61
-	 * File mime type
62
-	 * @var string
63
-	 */
64
-	public $mime_type;
60
+    /**
61
+     * File mime type
62
+     * @var string
63
+     */
64
+    public $mime_type;
65 65
 
66
-	/**
67
-	 * File permissions:
68
-	 * 
69
-	 * @var string
70
-	 */
71
-	public $permissions;
66
+    /**
67
+     * File permissions:
68
+     * 
69
+     * @var string
70
+     */
71
+    public $permissions;
72 72
 
73
-	/**
74
-	 * Create a new file search result
75
-	 * @param FileInfo $data file data given by provider
76
-	 */
77
-	public function __construct(FileInfo $data) {
73
+    /**
74
+     * Create a new file search result
75
+     * @param FileInfo $data file data given by provider
76
+     */
77
+    public function __construct(FileInfo $data) {
78 78
 
79
-		$path = $this->getRelativePath($data->getPath());
79
+        $path = $this->getRelativePath($data->getPath());
80 80
 
81
-		$info = pathinfo($path);
82
-		$this->id = $data->getId();
83
-		$this->name = $info['basename'];
84
-		$this->link = \OC::$server->getURLGenerator()->linkToRoute(
85
-			'files.view.index',
86
-			[
87
-				'dir' => $info['dirname'],
88
-				'scrollto' => $info['basename'],
89
-			]
90
-		);
91
-		$this->permissions = $data->getPermissions();
92
-		$this->path = $path;
93
-		$this->size = $data->getSize();
94
-		$this->modified = $data->getMtime();
95
-		$this->mime_type = $data->getMimetype();
96
-	}
81
+        $info = pathinfo($path);
82
+        $this->id = $data->getId();
83
+        $this->name = $info['basename'];
84
+        $this->link = \OC::$server->getURLGenerator()->linkToRoute(
85
+            'files.view.index',
86
+            [
87
+                'dir' => $info['dirname'],
88
+                'scrollto' => $info['basename'],
89
+            ]
90
+        );
91
+        $this->permissions = $data->getPermissions();
92
+        $this->path = $path;
93
+        $this->size = $data->getSize();
94
+        $this->modified = $data->getMtime();
95
+        $this->mime_type = $data->getMimetype();
96
+    }
97 97
 
98
-	/**
99
-	 * @var Folder $userFolderCache
100
-	 */
101
-	static protected $userFolderCache = null;
98
+    /**
99
+     * @var Folder $userFolderCache
100
+     */
101
+    static protected $userFolderCache = null;
102 102
 
103
-	/**
104
-	 * converts a path relative to the users files folder
105
-	 * eg /user/files/foo.txt -> /foo.txt
106
-	 * @param string $path
107
-	 * @return string relative path
108
-	 */
109
-	protected function getRelativePath($path) {
110
-		if (!isset(self::$userFolderCache)) {
111
-			$user = \OC::$server->getUserSession()->getUser()->getUID();
112
-			self::$userFolderCache = \OC::$server->getUserFolder($user);
113
-		}
114
-		return self::$userFolderCache->getRelativePath($path);
115
-	}
103
+    /**
104
+     * converts a path relative to the users files folder
105
+     * eg /user/files/foo.txt -> /foo.txt
106
+     * @param string $path
107
+     * @return string relative path
108
+     */
109
+    protected function getRelativePath($path) {
110
+        if (!isset(self::$userFolderCache)) {
111
+            $user = \OC::$server->getUserSession()->getUser()->getUID();
112
+            self::$userFolderCache = \OC::$server->getUserFolder($user);
113
+        }
114
+        return self::$userFolderCache->getRelativePath($path);
115
+    }
116 116
 
117 117
 }
Please login to merge, or discard this patch.
lib/private/Share20/DefaultShareProvider.php 2 patches
Indentation   +1405 added lines, -1405 removed lines patch added patch discarded remove patch
@@ -62,1445 +62,1445 @@
 block discarded – undo
62 62
  */
63 63
 class DefaultShareProvider implements IShareProvider {
64 64
 
65
-	// Special share type for user modified group shares
66
-	const SHARE_TYPE_USERGROUP = 2;
67
-
68
-	/** @var IDBConnection */
69
-	private $dbConn;
70
-
71
-	/** @var IUserManager */
72
-	private $userManager;
73
-
74
-	/** @var IGroupManager */
75
-	private $groupManager;
76
-
77
-	/** @var IRootFolder */
78
-	private $rootFolder;
79
-
80
-	/** @var IMailer */
81
-	private $mailer;
82
-
83
-	/** @var Defaults */
84
-	private $defaults;
85
-
86
-	/** @var IL10N */
87
-	private $l;
88
-
89
-	/** @var IURLGenerator */
90
-	private $urlGenerator;
91
-
92
-	/**
93
-	 * DefaultShareProvider constructor.
94
-	 *
95
-	 * @param IDBConnection $connection
96
-	 * @param IUserManager $userManager
97
-	 * @param IGroupManager $groupManager
98
-	 * @param IRootFolder $rootFolder
99
-	 * @param IMailer $mailer ;
100
-	 * @param Defaults $defaults
101
-	 * @param IL10N $l
102
-	 * @param IURLGenerator $urlGenerator
103
-	 */
104
-	public function __construct(
105
-			IDBConnection $connection,
106
-			IUserManager $userManager,
107
-			IGroupManager $groupManager,
108
-			IRootFolder $rootFolder,
109
-			IMailer $mailer,
110
-			Defaults $defaults,
111
-			IL10N $l,
112
-			IURLGenerator $urlGenerator) {
113
-		$this->dbConn = $connection;
114
-		$this->userManager = $userManager;
115
-		$this->groupManager = $groupManager;
116
-		$this->rootFolder = $rootFolder;
117
-		$this->mailer = $mailer;
118
-		$this->defaults = $defaults;
119
-		$this->l = $l;
120
-		$this->urlGenerator = $urlGenerator;
121
-	}
122
-
123
-	/**
124
-	 * Return the identifier of this provider.
125
-	 *
126
-	 * @return string Containing only [a-zA-Z0-9]
127
-	 */
128
-	public function identifier() {
129
-		return 'ocinternal';
130
-	}
131
-
132
-	/**
133
-	 * Share a path
134
-	 *
135
-	 * @param \OCP\Share\IShare $share
136
-	 * @return \OCP\Share\IShare The share object
137
-	 * @throws ShareNotFound
138
-	 * @throws \Exception
139
-	 */
140
-	public function create(\OCP\Share\IShare $share) {
141
-		$qb = $this->dbConn->getQueryBuilder();
142
-
143
-		$qb->insert('share');
144
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
145
-
146
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
147
-			//Set the UID of the user we share with
148
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
149
-			$qb->setValue('accepted', $qb->createNamedParameter(IShare::STATUS_PENDING));
150
-
151
-			//If an expiration date is set store it
152
-			if ($share->getExpirationDate() !== null) {
153
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
154
-			}
155
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
156
-			//Set the GID of the group we share with
157
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
158
-
159
-			//If an expiration date is set store it
160
-			if ($share->getExpirationDate() !== null) {
161
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
162
-			}
163
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
164
-			//set label for public link
165
-			$qb->setValue('label', $qb->createNamedParameter($share->getLabel()));
166
-			//Set the token of the share
167
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
168
-
169
-			//If a password is set store it
170
-			if ($share->getPassword() !== null) {
171
-				$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
172
-			}
173
-
174
-			$qb->setValue('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL));
175
-
176
-			//If an expiration date is set store it
177
-			if ($share->getExpirationDate() !== null) {
178
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
179
-			}
180
-
181
-			if (method_exists($share, 'getParent')) {
182
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
183
-			}
184
-		} else {
185
-			throw new \Exception('invalid share type!');
186
-		}
187
-
188
-		// Set what is shares
189
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
190
-		if ($share->getNode() instanceof \OCP\Files\File) {
191
-			$qb->setParameter('itemType', 'file');
192
-		} else {
193
-			$qb->setParameter('itemType', 'folder');
194
-		}
195
-
196
-		// Set the file id
197
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
198
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
199
-
200
-		// set the permissions
201
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
202
-
203
-		// Set who created this share
204
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
205
-
206
-		// Set who is the owner of this file/folder (and this the owner of the share)
207
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
208
-
209
-		// Set the file target
210
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
211
-
212
-		// Set the time this share was created
213
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
214
-
215
-		// insert the data and fetch the id of the share
216
-		$this->dbConn->beginTransaction();
217
-		$qb->execute();
218
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
219
-
220
-		// Now fetch the inserted share and create a complete share object
221
-		$qb = $this->dbConn->getQueryBuilder();
222
-		$qb->select('*')
223
-			->from('share')
224
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
225
-
226
-		$cursor = $qb->execute();
227
-		$data = $cursor->fetch();
228
-		$this->dbConn->commit();
229
-		$cursor->closeCursor();
230
-
231
-		if ($data === false) {
232
-			throw new ShareNotFound();
233
-		}
234
-
235
-		$mailSendValue = $share->getMailSend();
236
-		$data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
237
-
238
-		$share = $this->createShare($data);
239
-		return $share;
240
-	}
241
-
242
-	/**
243
-	 * Update a share
244
-	 *
245
-	 * @param \OCP\Share\IShare $share
246
-	 * @return \OCP\Share\IShare The share object
247
-	 * @throws ShareNotFound
248
-	 * @throws \OCP\Files\InvalidPathException
249
-	 * @throws \OCP\Files\NotFoundException
250
-	 */
251
-	public function update(\OCP\Share\IShare $share) {
252
-
253
-		$originalShare = $this->getShareById($share->getId());
254
-
255
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
256
-			/*
65
+    // Special share type for user modified group shares
66
+    const SHARE_TYPE_USERGROUP = 2;
67
+
68
+    /** @var IDBConnection */
69
+    private $dbConn;
70
+
71
+    /** @var IUserManager */
72
+    private $userManager;
73
+
74
+    /** @var IGroupManager */
75
+    private $groupManager;
76
+
77
+    /** @var IRootFolder */
78
+    private $rootFolder;
79
+
80
+    /** @var IMailer */
81
+    private $mailer;
82
+
83
+    /** @var Defaults */
84
+    private $defaults;
85
+
86
+    /** @var IL10N */
87
+    private $l;
88
+
89
+    /** @var IURLGenerator */
90
+    private $urlGenerator;
91
+
92
+    /**
93
+     * DefaultShareProvider constructor.
94
+     *
95
+     * @param IDBConnection $connection
96
+     * @param IUserManager $userManager
97
+     * @param IGroupManager $groupManager
98
+     * @param IRootFolder $rootFolder
99
+     * @param IMailer $mailer ;
100
+     * @param Defaults $defaults
101
+     * @param IL10N $l
102
+     * @param IURLGenerator $urlGenerator
103
+     */
104
+    public function __construct(
105
+            IDBConnection $connection,
106
+            IUserManager $userManager,
107
+            IGroupManager $groupManager,
108
+            IRootFolder $rootFolder,
109
+            IMailer $mailer,
110
+            Defaults $defaults,
111
+            IL10N $l,
112
+            IURLGenerator $urlGenerator) {
113
+        $this->dbConn = $connection;
114
+        $this->userManager = $userManager;
115
+        $this->groupManager = $groupManager;
116
+        $this->rootFolder = $rootFolder;
117
+        $this->mailer = $mailer;
118
+        $this->defaults = $defaults;
119
+        $this->l = $l;
120
+        $this->urlGenerator = $urlGenerator;
121
+    }
122
+
123
+    /**
124
+     * Return the identifier of this provider.
125
+     *
126
+     * @return string Containing only [a-zA-Z0-9]
127
+     */
128
+    public function identifier() {
129
+        return 'ocinternal';
130
+    }
131
+
132
+    /**
133
+     * Share a path
134
+     *
135
+     * @param \OCP\Share\IShare $share
136
+     * @return \OCP\Share\IShare The share object
137
+     * @throws ShareNotFound
138
+     * @throws \Exception
139
+     */
140
+    public function create(\OCP\Share\IShare $share) {
141
+        $qb = $this->dbConn->getQueryBuilder();
142
+
143
+        $qb->insert('share');
144
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
145
+
146
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
147
+            //Set the UID of the user we share with
148
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
149
+            $qb->setValue('accepted', $qb->createNamedParameter(IShare::STATUS_PENDING));
150
+
151
+            //If an expiration date is set store it
152
+            if ($share->getExpirationDate() !== null) {
153
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
154
+            }
155
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
156
+            //Set the GID of the group we share with
157
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
158
+
159
+            //If an expiration date is set store it
160
+            if ($share->getExpirationDate() !== null) {
161
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
162
+            }
163
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
164
+            //set label for public link
165
+            $qb->setValue('label', $qb->createNamedParameter($share->getLabel()));
166
+            //Set the token of the share
167
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
168
+
169
+            //If a password is set store it
170
+            if ($share->getPassword() !== null) {
171
+                $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
172
+            }
173
+
174
+            $qb->setValue('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL));
175
+
176
+            //If an expiration date is set store it
177
+            if ($share->getExpirationDate() !== null) {
178
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
179
+            }
180
+
181
+            if (method_exists($share, 'getParent')) {
182
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
183
+            }
184
+        } else {
185
+            throw new \Exception('invalid share type!');
186
+        }
187
+
188
+        // Set what is shares
189
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
190
+        if ($share->getNode() instanceof \OCP\Files\File) {
191
+            $qb->setParameter('itemType', 'file');
192
+        } else {
193
+            $qb->setParameter('itemType', 'folder');
194
+        }
195
+
196
+        // Set the file id
197
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
198
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
199
+
200
+        // set the permissions
201
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
202
+
203
+        // Set who created this share
204
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
205
+
206
+        // Set who is the owner of this file/folder (and this the owner of the share)
207
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
208
+
209
+        // Set the file target
210
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
211
+
212
+        // Set the time this share was created
213
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
214
+
215
+        // insert the data and fetch the id of the share
216
+        $this->dbConn->beginTransaction();
217
+        $qb->execute();
218
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
219
+
220
+        // Now fetch the inserted share and create a complete share object
221
+        $qb = $this->dbConn->getQueryBuilder();
222
+        $qb->select('*')
223
+            ->from('share')
224
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
225
+
226
+        $cursor = $qb->execute();
227
+        $data = $cursor->fetch();
228
+        $this->dbConn->commit();
229
+        $cursor->closeCursor();
230
+
231
+        if ($data === false) {
232
+            throw new ShareNotFound();
233
+        }
234
+
235
+        $mailSendValue = $share->getMailSend();
236
+        $data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
237
+
238
+        $share = $this->createShare($data);
239
+        return $share;
240
+    }
241
+
242
+    /**
243
+     * Update a share
244
+     *
245
+     * @param \OCP\Share\IShare $share
246
+     * @return \OCP\Share\IShare The share object
247
+     * @throws ShareNotFound
248
+     * @throws \OCP\Files\InvalidPathException
249
+     * @throws \OCP\Files\NotFoundException
250
+     */
251
+    public function update(\OCP\Share\IShare $share) {
252
+
253
+        $originalShare = $this->getShareById($share->getId());
254
+
255
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
256
+            /*
257 257
 			 * We allow updating the recipient on user shares.
258 258
 			 */
259
-			$qb = $this->dbConn->getQueryBuilder();
260
-			$qb->update('share')
261
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
262
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
263
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
264
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
265
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
266
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
267
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
268
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
269
-				->set('note', $qb->createNamedParameter($share->getNote()))
270
-				->set('accepted', $qb->createNamedParameter($share->getStatus()))
271
-				->execute();
272
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
273
-			$qb = $this->dbConn->getQueryBuilder();
274
-			$qb->update('share')
275
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
276
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
277
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
278
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
279
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
280
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
281
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
282
-				->set('note', $qb->createNamedParameter($share->getNote()))
283
-				->execute();
284
-
285
-			/*
259
+            $qb = $this->dbConn->getQueryBuilder();
260
+            $qb->update('share')
261
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
262
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
263
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
264
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
265
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
266
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
267
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
268
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
269
+                ->set('note', $qb->createNamedParameter($share->getNote()))
270
+                ->set('accepted', $qb->createNamedParameter($share->getStatus()))
271
+                ->execute();
272
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
273
+            $qb = $this->dbConn->getQueryBuilder();
274
+            $qb->update('share')
275
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
276
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
277
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
278
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
279
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
280
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
281
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
282
+                ->set('note', $qb->createNamedParameter($share->getNote()))
283
+                ->execute();
284
+
285
+            /*
286 286
 			 * Update all user defined group shares
287 287
 			 */
288
-			$qb = $this->dbConn->getQueryBuilder();
289
-			$qb->update('share')
290
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
291
-				->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
292
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
293
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
294
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
295
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
296
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
297
-				->set('note', $qb->createNamedParameter($share->getNote()))
298
-				->execute();
299
-
300
-			/*
288
+            $qb = $this->dbConn->getQueryBuilder();
289
+            $qb->update('share')
290
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
291
+                ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
292
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
293
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
294
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
295
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
296
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
297
+                ->set('note', $qb->createNamedParameter($share->getNote()))
298
+                ->execute();
299
+
300
+            /*
301 301
 			 * Now update the permissions for all children that have not set it to 0
302 302
 			 */
303
-			$qb = $this->dbConn->getQueryBuilder();
304
-			$qb->update('share')
305
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
306
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
307
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
308
-				->execute();
309
-
310
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
311
-			$qb = $this->dbConn->getQueryBuilder();
312
-			$qb->update('share')
313
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
314
-				->set('password', $qb->createNamedParameter($share->getPassword()))
315
-				->set('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL))
316
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
317
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
318
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
319
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
320
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
321
-				->set('token', $qb->createNamedParameter($share->getToken()))
322
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
323
-				->set('note', $qb->createNamedParameter($share->getNote()))
324
-				->set('label', $qb->createNamedParameter($share->getLabel()))
325
-				->set('hide_download', $qb->createNamedParameter($share->getHideDownload() ? 1 : 0), IQueryBuilder::PARAM_INT)
326
-				->execute();
327
-		}
328
-
329
-		if ($originalShare->getNote() !== $share->getNote() && $share->getNote() !== '') {
330
-			$this->propagateNote($share);
331
-		}
332
-
333
-
334
-		return $share;
335
-	}
336
-
337
-	/**
338
-	 * Accept a share.
339
-	 *
340
-	 * @param IShare $share
341
-	 * @param string $recipient
342
-	 * @return IShare The share object
343
-	 * @since 9.0.0
344
-	 */
345
-	public function acceptShare(IShare $share, string $recipient): IShare {
346
-		if ($share->getShareType() === IShare::TYPE_GROUP) {
347
-			$group = $this->groupManager->get($share->getSharedWith());
348
-			$user = $this->userManager->get($recipient);
349
-
350
-			if (is_null($group)) {
351
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
352
-			}
353
-
354
-			if (!$group->inGroup($user)) {
355
-				throw new ProviderException('Recipient not in receiving group');
356
-			}
357
-
358
-			// Try to fetch user specific share
359
-			$qb = $this->dbConn->getQueryBuilder();
360
-			$stmt = $qb->select('*')
361
-				->from('share')
362
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
363
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
364
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
365
-				->andWhere($qb->expr()->orX(
366
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
367
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
368
-				))
369
-				->execute();
370
-
371
-			$data = $stmt->fetch();
372
-			$stmt->closeCursor();
373
-
374
-			/*
303
+            $qb = $this->dbConn->getQueryBuilder();
304
+            $qb->update('share')
305
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
306
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
307
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
308
+                ->execute();
309
+
310
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
311
+            $qb = $this->dbConn->getQueryBuilder();
312
+            $qb->update('share')
313
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
314
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
315
+                ->set('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL))
316
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
317
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
318
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
319
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
320
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
321
+                ->set('token', $qb->createNamedParameter($share->getToken()))
322
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
323
+                ->set('note', $qb->createNamedParameter($share->getNote()))
324
+                ->set('label', $qb->createNamedParameter($share->getLabel()))
325
+                ->set('hide_download', $qb->createNamedParameter($share->getHideDownload() ? 1 : 0), IQueryBuilder::PARAM_INT)
326
+                ->execute();
327
+        }
328
+
329
+        if ($originalShare->getNote() !== $share->getNote() && $share->getNote() !== '') {
330
+            $this->propagateNote($share);
331
+        }
332
+
333
+
334
+        return $share;
335
+    }
336
+
337
+    /**
338
+     * Accept a share.
339
+     *
340
+     * @param IShare $share
341
+     * @param string $recipient
342
+     * @return IShare The share object
343
+     * @since 9.0.0
344
+     */
345
+    public function acceptShare(IShare $share, string $recipient): IShare {
346
+        if ($share->getShareType() === IShare::TYPE_GROUP) {
347
+            $group = $this->groupManager->get($share->getSharedWith());
348
+            $user = $this->userManager->get($recipient);
349
+
350
+            if (is_null($group)) {
351
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
352
+            }
353
+
354
+            if (!$group->inGroup($user)) {
355
+                throw new ProviderException('Recipient not in receiving group');
356
+            }
357
+
358
+            // Try to fetch user specific share
359
+            $qb = $this->dbConn->getQueryBuilder();
360
+            $stmt = $qb->select('*')
361
+                ->from('share')
362
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
363
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
364
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
365
+                ->andWhere($qb->expr()->orX(
366
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
367
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
368
+                ))
369
+                ->execute();
370
+
371
+            $data = $stmt->fetch();
372
+            $stmt->closeCursor();
373
+
374
+            /*
375 375
 			 * Check if there already is a user specific group share.
376 376
 			 * If there is update it (if required).
377 377
 			 */
378
-			if ($data === false) {
379
-				$id = $this->createUserSpecificGroupShare($share, $recipient);
380
-			} else {
381
-				$id = $data['id'];
382
-			}
383
-
384
-		} else if ($share->getShareType() === IShare::TYPE_USER) {
385
-			if ($share->getSharedWith() !== $recipient) {
386
-				throw new ProviderException('Recipient does not match');
387
-			}
388
-
389
-			$id = $share->getId();
390
-		} else {
391
-			throw new ProviderException('Invalid shareType');
392
-		}
393
-
394
-		$qb = $this->dbConn->getQueryBuilder();
395
-		$qb->update('share')
396
-			->set('accepted', $qb->createNamedParameter(IShare::STATUS_ACCEPTED))
397
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
398
-			->execute();
399
-
400
-		return $share;
401
-	}
402
-
403
-	/**
404
-	 * Get all children of this share
405
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
406
-	 *
407
-	 * @param \OCP\Share\IShare $parent
408
-	 * @return \OCP\Share\IShare[]
409
-	 */
410
-	public function getChildren(\OCP\Share\IShare $parent) {
411
-		$children = [];
412
-
413
-		$qb = $this->dbConn->getQueryBuilder();
414
-		$qb->select('*')
415
-			->from('share')
416
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
417
-			->andWhere(
418
-				$qb->expr()->in(
419
-					'share_type',
420
-					$qb->createNamedParameter([
421
-						\OCP\Share::SHARE_TYPE_USER,
422
-						\OCP\Share::SHARE_TYPE_GROUP,
423
-						\OCP\Share::SHARE_TYPE_LINK,
424
-					], IQueryBuilder::PARAM_INT_ARRAY)
425
-				)
426
-			)
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
-			->orderBy('id');
432
-
433
-		$cursor = $qb->execute();
434
-		while($data = $cursor->fetch()) {
435
-			$children[] = $this->createShare($data);
436
-		}
437
-		$cursor->closeCursor();
438
-
439
-		return $children;
440
-	}
441
-
442
-	/**
443
-	 * Delete a share
444
-	 *
445
-	 * @param \OCP\Share\IShare $share
446
-	 */
447
-	public function delete(\OCP\Share\IShare $share) {
448
-		$qb = $this->dbConn->getQueryBuilder();
449
-		$qb->delete('share')
450
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
451
-
452
-		/*
378
+            if ($data === false) {
379
+                $id = $this->createUserSpecificGroupShare($share, $recipient);
380
+            } else {
381
+                $id = $data['id'];
382
+            }
383
+
384
+        } else if ($share->getShareType() === IShare::TYPE_USER) {
385
+            if ($share->getSharedWith() !== $recipient) {
386
+                throw new ProviderException('Recipient does not match');
387
+            }
388
+
389
+            $id = $share->getId();
390
+        } else {
391
+            throw new ProviderException('Invalid shareType');
392
+        }
393
+
394
+        $qb = $this->dbConn->getQueryBuilder();
395
+        $qb->update('share')
396
+            ->set('accepted', $qb->createNamedParameter(IShare::STATUS_ACCEPTED))
397
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
398
+            ->execute();
399
+
400
+        return $share;
401
+    }
402
+
403
+    /**
404
+     * Get all children of this share
405
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
406
+     *
407
+     * @param \OCP\Share\IShare $parent
408
+     * @return \OCP\Share\IShare[]
409
+     */
410
+    public function getChildren(\OCP\Share\IShare $parent) {
411
+        $children = [];
412
+
413
+        $qb = $this->dbConn->getQueryBuilder();
414
+        $qb->select('*')
415
+            ->from('share')
416
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
417
+            ->andWhere(
418
+                $qb->expr()->in(
419
+                    'share_type',
420
+                    $qb->createNamedParameter([
421
+                        \OCP\Share::SHARE_TYPE_USER,
422
+                        \OCP\Share::SHARE_TYPE_GROUP,
423
+                        \OCP\Share::SHARE_TYPE_LINK,
424
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
425
+                )
426
+            )
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
+            ->orderBy('id');
432
+
433
+        $cursor = $qb->execute();
434
+        while($data = $cursor->fetch()) {
435
+            $children[] = $this->createShare($data);
436
+        }
437
+        $cursor->closeCursor();
438
+
439
+        return $children;
440
+    }
441
+
442
+    /**
443
+     * Delete a share
444
+     *
445
+     * @param \OCP\Share\IShare $share
446
+     */
447
+    public function delete(\OCP\Share\IShare $share) {
448
+        $qb = $this->dbConn->getQueryBuilder();
449
+        $qb->delete('share')
450
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
451
+
452
+        /*
453 453
 		 * If the share is a group share delete all possible
454 454
 		 * user defined groups shares.
455 455
 		 */
456
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
457
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
458
-		}
459
-
460
-		$qb->execute();
461
-	}
462
-
463
-	/**
464
-	 * Unshare a share from the recipient. If this is a group share
465
-	 * this means we need a special entry in the share db.
466
-	 *
467
-	 * @param IShare $share
468
-	 * @param string $recipient UserId of recipient
469
-	 * @throws BackendError
470
-	 * @throws ProviderException
471
-	 */
472
-	public function deleteFromSelf(IShare $share, $recipient) {
473
-		if ($share->getShareType() === IShare::TYPE_GROUP) {
474
-
475
-			$group = $this->groupManager->get($share->getSharedWith());
476
-			$user = $this->userManager->get($recipient);
477
-
478
-			if (is_null($group)) {
479
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
480
-			}
481
-
482
-			if (!$group->inGroup($user)) {
483
-				throw new ProviderException('Recipient not in receiving group');
484
-			}
485
-
486
-			// Try to fetch user specific share
487
-			$qb = $this->dbConn->getQueryBuilder();
488
-			$stmt = $qb->select('*')
489
-				->from('share')
490
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
491
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
492
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
493
-				->andWhere($qb->expr()->orX(
494
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
495
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
496
-				))
497
-				->execute();
498
-
499
-			$data = $stmt->fetch();
500
-
501
-			/*
456
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
457
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
458
+        }
459
+
460
+        $qb->execute();
461
+    }
462
+
463
+    /**
464
+     * Unshare a share from the recipient. If this is a group share
465
+     * this means we need a special entry in the share db.
466
+     *
467
+     * @param IShare $share
468
+     * @param string $recipient UserId of recipient
469
+     * @throws BackendError
470
+     * @throws ProviderException
471
+     */
472
+    public function deleteFromSelf(IShare $share, $recipient) {
473
+        if ($share->getShareType() === IShare::TYPE_GROUP) {
474
+
475
+            $group = $this->groupManager->get($share->getSharedWith());
476
+            $user = $this->userManager->get($recipient);
477
+
478
+            if (is_null($group)) {
479
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
480
+            }
481
+
482
+            if (!$group->inGroup($user)) {
483
+                throw new ProviderException('Recipient not in receiving group');
484
+            }
485
+
486
+            // Try to fetch user specific share
487
+            $qb = $this->dbConn->getQueryBuilder();
488
+            $stmt = $qb->select('*')
489
+                ->from('share')
490
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
491
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
492
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
493
+                ->andWhere($qb->expr()->orX(
494
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
495
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
496
+                ))
497
+                ->execute();
498
+
499
+            $data = $stmt->fetch();
500
+
501
+            /*
502 502
 			 * Check if there already is a user specific group share.
503 503
 			 * If there is update it (if required).
504 504
 			 */
505
-			if ($data === false) {
506
-				$id = $this->createUserSpecificGroupShare($share, $recipient);
507
-				$permissions = $share->getPermissions();
508
-			} else {
509
-				$permissions = $data['permissions'];
510
-				$id = $data['id'];
511
-			}
512
-
513
-			if ($permissions !== 0) {
514
-				// Update existing usergroup share
515
-				$qb = $this->dbConn->getQueryBuilder();
516
-				$qb->update('share')
517
-					->set('permissions', $qb->createNamedParameter(0))
518
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
519
-					->execute();
520
-			}
521
-
522
-		} else if ($share->getShareType() === IShare::TYPE_USER) {
523
-
524
-			if ($share->getSharedWith() !== $recipient) {
525
-				throw new ProviderException('Recipient does not match');
526
-			}
527
-
528
-			// We can just delete user and link shares
529
-			$this->delete($share);
530
-		} else {
531
-			throw new ProviderException('Invalid shareType');
532
-		}
533
-	}
534
-
535
-	protected function createUserSpecificGroupShare(IShare $share, string $recipient): int {
536
-		$type = $share->getNodeType();
537
-
538
-		$qb = $this->dbConn->getQueryBuilder();
539
-		$qb->insert('share')
540
-			->values([
541
-				'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
542
-				'share_with' => $qb->createNamedParameter($recipient),
543
-				'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
544
-				'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
545
-				'parent' => $qb->createNamedParameter($share->getId()),
546
-				'item_type' => $qb->createNamedParameter($type),
547
-				'item_source' => $qb->createNamedParameter($share->getNodeId()),
548
-				'file_source' => $qb->createNamedParameter($share->getNodeId()),
549
-				'file_target' => $qb->createNamedParameter($share->getTarget()),
550
-				'permissions' => $qb->createNamedParameter($share->getPermissions()),
551
-				'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
552
-			])->execute();
553
-
554
-		return $qb->getLastInsertId();
555
-	}
556
-
557
-	/**
558
-	 * @inheritdoc
559
-	 *
560
-	 * For now this only works for group shares
561
-	 * If this gets implemented for normal shares we have to extend it
562
-	 */
563
-	public function restore(IShare $share, string $recipient): IShare {
564
-		$qb = $this->dbConn->getQueryBuilder();
565
-		$qb->select('permissions')
566
-			->from('share')
567
-			->where(
568
-				$qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))
569
-			);
570
-		$cursor = $qb->execute();
571
-		$data = $cursor->fetch();
572
-		$cursor->closeCursor();
573
-
574
-		$originalPermission = $data['permissions'];
575
-
576
-		$qb = $this->dbConn->getQueryBuilder();
577
-		$qb->update('share')
578
-			->set('permissions', $qb->createNamedParameter($originalPermission))
579
-			->where(
580
-				$qb->expr()->eq('parent', $qb->createNamedParameter($share->getParent()))
581
-			)->andWhere(
582
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
583
-			)->andWhere(
584
-				$qb->expr()->eq('share_with', $qb->createNamedParameter($recipient))
585
-			);
586
-
587
-		$qb->execute();
588
-
589
-		return $this->getShareById($share->getId(), $recipient);
590
-	}
591
-
592
-	/**
593
-	 * @inheritdoc
594
-	 */
595
-	public function move(\OCP\Share\IShare $share, $recipient) {
596
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
597
-			// Just update the target
598
-			$qb = $this->dbConn->getQueryBuilder();
599
-			$qb->update('share')
600
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
601
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
602
-				->execute();
603
-
604
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
605
-
606
-			// Check if there is a usergroup share
607
-			$qb = $this->dbConn->getQueryBuilder();
608
-			$stmt = $qb->select('id')
609
-				->from('share')
610
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
611
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
612
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
613
-				->andWhere($qb->expr()->orX(
614
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
615
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
616
-				))
617
-				->setMaxResults(1)
618
-				->execute();
619
-
620
-			$data = $stmt->fetch();
621
-			$stmt->closeCursor();
622
-
623
-			if ($data === false) {
624
-				// No usergroup share yet. Create one.
625
-				$qb = $this->dbConn->getQueryBuilder();
626
-				$qb->insert('share')
627
-					->values([
628
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
629
-						'share_with' => $qb->createNamedParameter($recipient),
630
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
631
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
632
-						'parent' => $qb->createNamedParameter($share->getId()),
633
-						'item_type' => $qb->createNamedParameter($share->getNodeType()),
634
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
635
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
636
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
637
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
638
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
639
-					])->execute();
640
-			} else {
641
-				// Already a usergroup share. Update it.
642
-				$qb = $this->dbConn->getQueryBuilder();
643
-				$qb->update('share')
644
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
645
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
646
-					->execute();
647
-			}
648
-		}
649
-
650
-		return $share;
651
-	}
652
-
653
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
654
-		$qb = $this->dbConn->getQueryBuilder();
655
-		$qb->select('*')
656
-			->from('share', 's')
657
-			->andWhere($qb->expr()->orX(
658
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
659
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
660
-			));
661
-
662
-		$qb->andWhere($qb->expr()->orX(
663
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
664
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
665
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
666
-		));
667
-
668
-		/**
669
-		 * Reshares for this user are shares where they are the owner.
670
-		 */
671
-		if ($reshares === false) {
672
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
673
-		} else {
674
-			$qb->andWhere(
675
-				$qb->expr()->orX(
676
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
677
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
678
-				)
679
-			);
680
-		}
681
-
682
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
683
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
684
-
685
-		$qb->orderBy('id');
686
-
687
-		$cursor = $qb->execute();
688
-		$shares = [];
689
-		while ($data = $cursor->fetch()) {
690
-			$shares[$data['fileid']][] = $this->createShare($data);
691
-		}
692
-		$cursor->closeCursor();
693
-
694
-		return $shares;
695
-	}
696
-
697
-	/**
698
-	 * @inheritdoc
699
-	 */
700
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
701
-		$qb = $this->dbConn->getQueryBuilder();
702
-		$qb->select('*')
703
-			->from('share')
704
-			->andWhere($qb->expr()->orX(
705
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
706
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
707
-			));
708
-
709
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
710
-
711
-		/**
712
-		 * Reshares for this user are shares where they are the owner.
713
-		 */
714
-		if ($reshares === false) {
715
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
716
-		} else {
717
-			if ($node === null) {
718
-				$qb->andWhere(
719
-					$qb->expr()->orX(
720
-						$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
721
-						$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
722
-					)
723
-				);
724
-			}
725
-		}
726
-
727
-		if ($node !== null) {
728
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
729
-		}
730
-
731
-		if ($limit !== -1) {
732
-			$qb->setMaxResults($limit);
733
-		}
734
-
735
-		$qb->setFirstResult($offset);
736
-		$qb->orderBy('id');
737
-
738
-		$cursor = $qb->execute();
739
-		$shares = [];
740
-		while($data = $cursor->fetch()) {
741
-			$shares[] = $this->createShare($data);
742
-		}
743
-		$cursor->closeCursor();
744
-
745
-		return $shares;
746
-	}
747
-
748
-	/**
749
-	 * @inheritdoc
750
-	 */
751
-	public function getShareById($id, $recipientId = null) {
752
-		$qb = $this->dbConn->getQueryBuilder();
753
-
754
-		$qb->select('*')
755
-			->from('share')
756
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
757
-			->andWhere(
758
-				$qb->expr()->in(
759
-					'share_type',
760
-					$qb->createNamedParameter([
761
-						\OCP\Share::SHARE_TYPE_USER,
762
-						\OCP\Share::SHARE_TYPE_GROUP,
763
-						\OCP\Share::SHARE_TYPE_LINK,
764
-					], IQueryBuilder::PARAM_INT_ARRAY)
765
-				)
766
-			)
767
-			->andWhere($qb->expr()->orX(
768
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
769
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
770
-			));
771
-
772
-		$cursor = $qb->execute();
773
-		$data = $cursor->fetch();
774
-		$cursor->closeCursor();
775
-
776
-		if ($data === false) {
777
-			throw new ShareNotFound();
778
-		}
779
-
780
-		try {
781
-			$share = $this->createShare($data);
782
-		} catch (InvalidShare $e) {
783
-			throw new ShareNotFound();
784
-		}
785
-
786
-		// If the recipient is set for a group share resolve to that user
787
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
788
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
789
-		}
790
-
791
-		return $share;
792
-	}
793
-
794
-	/**
795
-	 * Get shares for a given path
796
-	 *
797
-	 * @param \OCP\Files\Node $path
798
-	 * @return \OCP\Share\IShare[]
799
-	 */
800
-	public function getSharesByPath(Node $path) {
801
-		$qb = $this->dbConn->getQueryBuilder();
802
-
803
-		$cursor = $qb->select('*')
804
-			->from('share')
805
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
806
-			->andWhere(
807
-				$qb->expr()->orX(
808
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
809
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
810
-				)
811
-			)
812
-			->andWhere($qb->expr()->orX(
813
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
814
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
815
-			))
816
-			->execute();
817
-
818
-		$shares = [];
819
-		while($data = $cursor->fetch()) {
820
-			$shares[] = $this->createShare($data);
821
-		}
822
-		$cursor->closeCursor();
823
-
824
-		return $shares;
825
-	}
826
-
827
-	/**
828
-	 * Returns whether the given database result can be interpreted as
829
-	 * a share with accessible file (not trashed, not deleted)
830
-	 */
831
-	private function isAccessibleResult($data) {
832
-		// exclude shares leading to deleted file entries
833
-		if ($data['fileid'] === null) {
834
-			return false;
835
-		}
836
-
837
-		// exclude shares leading to trashbin on home storages
838
-		$pathSections = explode('/', $data['path'], 2);
839
-		// FIXME: would not detect rare md5'd home storage case properly
840
-		if ($pathSections[0] !== 'files'
841
-				&& in_array(explode(':', $data['storage_string_id'], 2)[0], ['home', 'object'])) {
842
-			return false;
843
-		}
844
-		return true;
845
-	}
846
-
847
-	/**
848
-	 * @inheritdoc
849
-	 */
850
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
851
-		/** @var Share[] $shares */
852
-		$shares = [];
853
-
854
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
855
-			//Get shares directly with this user
856
-			$qb = $this->dbConn->getQueryBuilder();
857
-			$qb->select('s.*',
858
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
859
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
860
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
861
-			)
862
-				->selectAlias('st.id', 'storage_string_id')
863
-				->from('share', 's')
864
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
865
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
866
-
867
-			// Order by id
868
-			$qb->orderBy('s.id');
869
-
870
-			// Set limit and offset
871
-			if ($limit !== -1) {
872
-				$qb->setMaxResults($limit);
873
-			}
874
-			$qb->setFirstResult($offset);
875
-
876
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
877
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
878
-				->andWhere($qb->expr()->orX(
879
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
880
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
881
-				));
882
-
883
-			// Filter by node if provided
884
-			if ($node !== null) {
885
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
886
-			}
887
-
888
-			$cursor = $qb->execute();
889
-
890
-			while($data = $cursor->fetch()) {
891
-				if ($this->isAccessibleResult($data)) {
892
-					$shares[] = $this->createShare($data);
893
-				}
894
-			}
895
-			$cursor->closeCursor();
896
-
897
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
898
-			$user = $this->userManager->get($userId);
899
-			$allGroups = $this->groupManager->getUserGroups($user);
900
-
901
-			/** @var Share[] $shares2 */
902
-			$shares2 = [];
903
-
904
-			$start = 0;
905
-			while(true) {
906
-				$groups = array_slice($allGroups, $start, 100);
907
-				$start += 100;
908
-
909
-				if ($groups === []) {
910
-					break;
911
-				}
912
-
913
-				$qb = $this->dbConn->getQueryBuilder();
914
-				$qb->select('s.*',
915
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
916
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
917
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
918
-				)
919
-					->selectAlias('st.id', 'storage_string_id')
920
-					->from('share', 's')
921
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
922
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
923
-					->orderBy('s.id')
924
-					->setFirstResult(0);
925
-
926
-				if ($limit !== -1) {
927
-					$qb->setMaxResults($limit - count($shares));
928
-				}
929
-
930
-				// Filter by node if provided
931
-				if ($node !== null) {
932
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
933
-				}
934
-
935
-
936
-				$groups = array_filter($groups, function ($group) { return $group instanceof IGroup; });
937
-				$groups = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
938
-
939
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
940
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
941
-						$groups,
942
-						IQueryBuilder::PARAM_STR_ARRAY
943
-					)))
944
-					->andWhere($qb->expr()->orX(
945
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
946
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
947
-					));
948
-
949
-				$cursor = $qb->execute();
950
-				while($data = $cursor->fetch()) {
951
-					if ($offset > 0) {
952
-						$offset--;
953
-						continue;
954
-					}
955
-
956
-					if ($this->isAccessibleResult($data)) {
957
-						$shares2[] = $this->createShare($data);
958
-					}
959
-				}
960
-				$cursor->closeCursor();
961
-			}
962
-
963
-			/*
505
+            if ($data === false) {
506
+                $id = $this->createUserSpecificGroupShare($share, $recipient);
507
+                $permissions = $share->getPermissions();
508
+            } else {
509
+                $permissions = $data['permissions'];
510
+                $id = $data['id'];
511
+            }
512
+
513
+            if ($permissions !== 0) {
514
+                // Update existing usergroup share
515
+                $qb = $this->dbConn->getQueryBuilder();
516
+                $qb->update('share')
517
+                    ->set('permissions', $qb->createNamedParameter(0))
518
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
519
+                    ->execute();
520
+            }
521
+
522
+        } else if ($share->getShareType() === IShare::TYPE_USER) {
523
+
524
+            if ($share->getSharedWith() !== $recipient) {
525
+                throw new ProviderException('Recipient does not match');
526
+            }
527
+
528
+            // We can just delete user and link shares
529
+            $this->delete($share);
530
+        } else {
531
+            throw new ProviderException('Invalid shareType');
532
+        }
533
+    }
534
+
535
+    protected function createUserSpecificGroupShare(IShare $share, string $recipient): int {
536
+        $type = $share->getNodeType();
537
+
538
+        $qb = $this->dbConn->getQueryBuilder();
539
+        $qb->insert('share')
540
+            ->values([
541
+                'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
542
+                'share_with' => $qb->createNamedParameter($recipient),
543
+                'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
544
+                'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
545
+                'parent' => $qb->createNamedParameter($share->getId()),
546
+                'item_type' => $qb->createNamedParameter($type),
547
+                'item_source' => $qb->createNamedParameter($share->getNodeId()),
548
+                'file_source' => $qb->createNamedParameter($share->getNodeId()),
549
+                'file_target' => $qb->createNamedParameter($share->getTarget()),
550
+                'permissions' => $qb->createNamedParameter($share->getPermissions()),
551
+                'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
552
+            ])->execute();
553
+
554
+        return $qb->getLastInsertId();
555
+    }
556
+
557
+    /**
558
+     * @inheritdoc
559
+     *
560
+     * For now this only works for group shares
561
+     * If this gets implemented for normal shares we have to extend it
562
+     */
563
+    public function restore(IShare $share, string $recipient): IShare {
564
+        $qb = $this->dbConn->getQueryBuilder();
565
+        $qb->select('permissions')
566
+            ->from('share')
567
+            ->where(
568
+                $qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))
569
+            );
570
+        $cursor = $qb->execute();
571
+        $data = $cursor->fetch();
572
+        $cursor->closeCursor();
573
+
574
+        $originalPermission = $data['permissions'];
575
+
576
+        $qb = $this->dbConn->getQueryBuilder();
577
+        $qb->update('share')
578
+            ->set('permissions', $qb->createNamedParameter($originalPermission))
579
+            ->where(
580
+                $qb->expr()->eq('parent', $qb->createNamedParameter($share->getParent()))
581
+            )->andWhere(
582
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
583
+            )->andWhere(
584
+                $qb->expr()->eq('share_with', $qb->createNamedParameter($recipient))
585
+            );
586
+
587
+        $qb->execute();
588
+
589
+        return $this->getShareById($share->getId(), $recipient);
590
+    }
591
+
592
+    /**
593
+     * @inheritdoc
594
+     */
595
+    public function move(\OCP\Share\IShare $share, $recipient) {
596
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
597
+            // Just update the target
598
+            $qb = $this->dbConn->getQueryBuilder();
599
+            $qb->update('share')
600
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
601
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
602
+                ->execute();
603
+
604
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
605
+
606
+            // Check if there is a usergroup share
607
+            $qb = $this->dbConn->getQueryBuilder();
608
+            $stmt = $qb->select('id')
609
+                ->from('share')
610
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
611
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
612
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
613
+                ->andWhere($qb->expr()->orX(
614
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
615
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
616
+                ))
617
+                ->setMaxResults(1)
618
+                ->execute();
619
+
620
+            $data = $stmt->fetch();
621
+            $stmt->closeCursor();
622
+
623
+            if ($data === false) {
624
+                // No usergroup share yet. Create one.
625
+                $qb = $this->dbConn->getQueryBuilder();
626
+                $qb->insert('share')
627
+                    ->values([
628
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
629
+                        'share_with' => $qb->createNamedParameter($recipient),
630
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
631
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
632
+                        'parent' => $qb->createNamedParameter($share->getId()),
633
+                        'item_type' => $qb->createNamedParameter($share->getNodeType()),
634
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
635
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
636
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
637
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
638
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
639
+                    ])->execute();
640
+            } else {
641
+                // Already a usergroup share. Update it.
642
+                $qb = $this->dbConn->getQueryBuilder();
643
+                $qb->update('share')
644
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
645
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
646
+                    ->execute();
647
+            }
648
+        }
649
+
650
+        return $share;
651
+    }
652
+
653
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
654
+        $qb = $this->dbConn->getQueryBuilder();
655
+        $qb->select('*')
656
+            ->from('share', 's')
657
+            ->andWhere($qb->expr()->orX(
658
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
659
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
660
+            ));
661
+
662
+        $qb->andWhere($qb->expr()->orX(
663
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
664
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
665
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
666
+        ));
667
+
668
+        /**
669
+         * Reshares for this user are shares where they are the owner.
670
+         */
671
+        if ($reshares === false) {
672
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
673
+        } else {
674
+            $qb->andWhere(
675
+                $qb->expr()->orX(
676
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
677
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
678
+                )
679
+            );
680
+        }
681
+
682
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
683
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
684
+
685
+        $qb->orderBy('id');
686
+
687
+        $cursor = $qb->execute();
688
+        $shares = [];
689
+        while ($data = $cursor->fetch()) {
690
+            $shares[$data['fileid']][] = $this->createShare($data);
691
+        }
692
+        $cursor->closeCursor();
693
+
694
+        return $shares;
695
+    }
696
+
697
+    /**
698
+     * @inheritdoc
699
+     */
700
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
701
+        $qb = $this->dbConn->getQueryBuilder();
702
+        $qb->select('*')
703
+            ->from('share')
704
+            ->andWhere($qb->expr()->orX(
705
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
706
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
707
+            ));
708
+
709
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
710
+
711
+        /**
712
+         * Reshares for this user are shares where they are the owner.
713
+         */
714
+        if ($reshares === false) {
715
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
716
+        } else {
717
+            if ($node === null) {
718
+                $qb->andWhere(
719
+                    $qb->expr()->orX(
720
+                        $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
721
+                        $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
722
+                    )
723
+                );
724
+            }
725
+        }
726
+
727
+        if ($node !== null) {
728
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
729
+        }
730
+
731
+        if ($limit !== -1) {
732
+            $qb->setMaxResults($limit);
733
+        }
734
+
735
+        $qb->setFirstResult($offset);
736
+        $qb->orderBy('id');
737
+
738
+        $cursor = $qb->execute();
739
+        $shares = [];
740
+        while($data = $cursor->fetch()) {
741
+            $shares[] = $this->createShare($data);
742
+        }
743
+        $cursor->closeCursor();
744
+
745
+        return $shares;
746
+    }
747
+
748
+    /**
749
+     * @inheritdoc
750
+     */
751
+    public function getShareById($id, $recipientId = null) {
752
+        $qb = $this->dbConn->getQueryBuilder();
753
+
754
+        $qb->select('*')
755
+            ->from('share')
756
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
757
+            ->andWhere(
758
+                $qb->expr()->in(
759
+                    'share_type',
760
+                    $qb->createNamedParameter([
761
+                        \OCP\Share::SHARE_TYPE_USER,
762
+                        \OCP\Share::SHARE_TYPE_GROUP,
763
+                        \OCP\Share::SHARE_TYPE_LINK,
764
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
765
+                )
766
+            )
767
+            ->andWhere($qb->expr()->orX(
768
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
769
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
770
+            ));
771
+
772
+        $cursor = $qb->execute();
773
+        $data = $cursor->fetch();
774
+        $cursor->closeCursor();
775
+
776
+        if ($data === false) {
777
+            throw new ShareNotFound();
778
+        }
779
+
780
+        try {
781
+            $share = $this->createShare($data);
782
+        } catch (InvalidShare $e) {
783
+            throw new ShareNotFound();
784
+        }
785
+
786
+        // If the recipient is set for a group share resolve to that user
787
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
788
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
789
+        }
790
+
791
+        return $share;
792
+    }
793
+
794
+    /**
795
+     * Get shares for a given path
796
+     *
797
+     * @param \OCP\Files\Node $path
798
+     * @return \OCP\Share\IShare[]
799
+     */
800
+    public function getSharesByPath(Node $path) {
801
+        $qb = $this->dbConn->getQueryBuilder();
802
+
803
+        $cursor = $qb->select('*')
804
+            ->from('share')
805
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
806
+            ->andWhere(
807
+                $qb->expr()->orX(
808
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
809
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
810
+                )
811
+            )
812
+            ->andWhere($qb->expr()->orX(
813
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
814
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
815
+            ))
816
+            ->execute();
817
+
818
+        $shares = [];
819
+        while($data = $cursor->fetch()) {
820
+            $shares[] = $this->createShare($data);
821
+        }
822
+        $cursor->closeCursor();
823
+
824
+        return $shares;
825
+    }
826
+
827
+    /**
828
+     * Returns whether the given database result can be interpreted as
829
+     * a share with accessible file (not trashed, not deleted)
830
+     */
831
+    private function isAccessibleResult($data) {
832
+        // exclude shares leading to deleted file entries
833
+        if ($data['fileid'] === null) {
834
+            return false;
835
+        }
836
+
837
+        // exclude shares leading to trashbin on home storages
838
+        $pathSections = explode('/', $data['path'], 2);
839
+        // FIXME: would not detect rare md5'd home storage case properly
840
+        if ($pathSections[0] !== 'files'
841
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], ['home', 'object'])) {
842
+            return false;
843
+        }
844
+        return true;
845
+    }
846
+
847
+    /**
848
+     * @inheritdoc
849
+     */
850
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
851
+        /** @var Share[] $shares */
852
+        $shares = [];
853
+
854
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
855
+            //Get shares directly with this user
856
+            $qb = $this->dbConn->getQueryBuilder();
857
+            $qb->select('s.*',
858
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
859
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
860
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
861
+            )
862
+                ->selectAlias('st.id', 'storage_string_id')
863
+                ->from('share', 's')
864
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
865
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
866
+
867
+            // Order by id
868
+            $qb->orderBy('s.id');
869
+
870
+            // Set limit and offset
871
+            if ($limit !== -1) {
872
+                $qb->setMaxResults($limit);
873
+            }
874
+            $qb->setFirstResult($offset);
875
+
876
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
877
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
878
+                ->andWhere($qb->expr()->orX(
879
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
880
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
881
+                ));
882
+
883
+            // Filter by node if provided
884
+            if ($node !== null) {
885
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
886
+            }
887
+
888
+            $cursor = $qb->execute();
889
+
890
+            while($data = $cursor->fetch()) {
891
+                if ($this->isAccessibleResult($data)) {
892
+                    $shares[] = $this->createShare($data);
893
+                }
894
+            }
895
+            $cursor->closeCursor();
896
+
897
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
898
+            $user = $this->userManager->get($userId);
899
+            $allGroups = $this->groupManager->getUserGroups($user);
900
+
901
+            /** @var Share[] $shares2 */
902
+            $shares2 = [];
903
+
904
+            $start = 0;
905
+            while(true) {
906
+                $groups = array_slice($allGroups, $start, 100);
907
+                $start += 100;
908
+
909
+                if ($groups === []) {
910
+                    break;
911
+                }
912
+
913
+                $qb = $this->dbConn->getQueryBuilder();
914
+                $qb->select('s.*',
915
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
916
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
917
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
918
+                )
919
+                    ->selectAlias('st.id', 'storage_string_id')
920
+                    ->from('share', 's')
921
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
922
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
923
+                    ->orderBy('s.id')
924
+                    ->setFirstResult(0);
925
+
926
+                if ($limit !== -1) {
927
+                    $qb->setMaxResults($limit - count($shares));
928
+                }
929
+
930
+                // Filter by node if provided
931
+                if ($node !== null) {
932
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
933
+                }
934
+
935
+
936
+                $groups = array_filter($groups, function ($group) { return $group instanceof IGroup; });
937
+                $groups = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
938
+
939
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
940
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
941
+                        $groups,
942
+                        IQueryBuilder::PARAM_STR_ARRAY
943
+                    )))
944
+                    ->andWhere($qb->expr()->orX(
945
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
946
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
947
+                    ));
948
+
949
+                $cursor = $qb->execute();
950
+                while($data = $cursor->fetch()) {
951
+                    if ($offset > 0) {
952
+                        $offset--;
953
+                        continue;
954
+                    }
955
+
956
+                    if ($this->isAccessibleResult($data)) {
957
+                        $shares2[] = $this->createShare($data);
958
+                    }
959
+                }
960
+                $cursor->closeCursor();
961
+            }
962
+
963
+            /*
964 964
 			 * Resolve all group shares to user specific shares
965 965
 			 */
966
-			$shares = $this->resolveGroupShares($shares2, $userId);
967
-		} else {
968
-			throw new BackendError('Invalid backend');
969
-		}
970
-
971
-
972
-		return $shares;
973
-	}
974
-
975
-	/**
976
-	 * Get a share by token
977
-	 *
978
-	 * @param string $token
979
-	 * @return \OCP\Share\IShare
980
-	 * @throws ShareNotFound
981
-	 */
982
-	public function getShareByToken($token) {
983
-		$qb = $this->dbConn->getQueryBuilder();
984
-
985
-		$cursor = $qb->select('*')
986
-			->from('share')
987
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
988
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
989
-			->andWhere($qb->expr()->orX(
990
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
991
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
992
-			))
993
-			->execute();
994
-
995
-		$data = $cursor->fetch();
996
-
997
-		if ($data === false) {
998
-			throw new ShareNotFound();
999
-		}
1000
-
1001
-		try {
1002
-			$share = $this->createShare($data);
1003
-		} catch (InvalidShare $e) {
1004
-			throw new ShareNotFound();
1005
-		}
1006
-
1007
-		return $share;
1008
-	}
1009
-
1010
-	/**
1011
-	 * Create a share object from an database row
1012
-	 *
1013
-	 * @param mixed[] $data
1014
-	 * @return \OCP\Share\IShare
1015
-	 * @throws InvalidShare
1016
-	 */
1017
-	private function createShare($data) {
1018
-		$share = new Share($this->rootFolder, $this->userManager);
1019
-		$share->setId((int)$data['id'])
1020
-			->setShareType((int)$data['share_type'])
1021
-			->setPermissions((int)$data['permissions'])
1022
-			->setTarget($data['file_target'])
1023
-			->setNote($data['note'])
1024
-			->setMailSend((bool)$data['mail_send'])
1025
-			->setStatus((int)$data['accepted'])
1026
-			->setLabel($data['label']);
1027
-
1028
-		$shareTime = new \DateTime();
1029
-		$shareTime->setTimestamp((int)$data['stime']);
1030
-		$share->setShareTime($shareTime);
1031
-
1032
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
1033
-			$share->setSharedWith($data['share_with']);
1034
-			$user = $this->userManager->get($data['share_with']);
1035
-			if ($user !== null) {
1036
-				$share->setSharedWithDisplayName($user->getDisplayName());
1037
-			}
1038
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1039
-			$share->setSharedWith($data['share_with']);
1040
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
1041
-			$share->setPassword($data['password']);
1042
-			$share->setSendPasswordByTalk((bool)$data['password_by_talk']);
1043
-			$share->setToken($data['token']);
1044
-		}
1045
-
1046
-		$share->setSharedBy($data['uid_initiator']);
1047
-		$share->setShareOwner($data['uid_owner']);
1048
-
1049
-		$share->setNodeId((int)$data['file_source']);
1050
-		$share->setNodeType($data['item_type']);
1051
-
1052
-		if ($data['expiration'] !== null) {
1053
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
1054
-			$share->setExpirationDate($expiration);
1055
-		}
1056
-
1057
-		if (isset($data['f_permissions'])) {
1058
-			$entryData = $data;
1059
-			$entryData['permissions'] = $entryData['f_permissions'];
1060
-			$entryData['parent'] = $entryData['f_parent'];
1061
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
1062
-				\OC::$server->getMimeTypeLoader()));
1063
-		}
1064
-
1065
-		$share->setProviderId($this->identifier());
1066
-		$share->setHideDownload((int)$data['hide_download'] === 1);
1067
-
1068
-		return $share;
1069
-	}
1070
-
1071
-	/**
1072
-	 * @param Share[] $shares
1073
-	 * @param $userId
1074
-	 * @return Share[] The updates shares if no update is found for a share return the original
1075
-	 */
1076
-	private function resolveGroupShares($shares, $userId) {
1077
-		$result = [];
1078
-
1079
-		$start = 0;
1080
-		while(true) {
1081
-			/** @var Share[] $shareSlice */
1082
-			$shareSlice = array_slice($shares, $start, 100);
1083
-			$start += 100;
1084
-
1085
-			if ($shareSlice === []) {
1086
-				break;
1087
-			}
1088
-
1089
-			/** @var int[] $ids */
1090
-			$ids = [];
1091
-			/** @var Share[] $shareMap */
1092
-			$shareMap = [];
1093
-
1094
-			foreach ($shareSlice as $share) {
1095
-				$ids[] = (int)$share->getId();
1096
-				$shareMap[$share->getId()] = $share;
1097
-			}
1098
-
1099
-			$qb = $this->dbConn->getQueryBuilder();
1100
-
1101
-			$query = $qb->select('*')
1102
-				->from('share')
1103
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1104
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
1105
-				->andWhere($qb->expr()->orX(
1106
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1107
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1108
-				));
1109
-
1110
-			$stmt = $query->execute();
1111
-
1112
-			while($data = $stmt->fetch()) {
1113
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
1114
-				$shareMap[$data['parent']]->setStatus((int)$data['accepted']);
1115
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
1116
-				$shareMap[$data['parent']]->setParent($data['parent']);
1117
-			}
1118
-
1119
-			$stmt->closeCursor();
1120
-
1121
-			foreach ($shareMap as $share) {
1122
-				$result[] = $share;
1123
-			}
1124
-		}
1125
-
1126
-		return $result;
1127
-	}
1128
-
1129
-	/**
1130
-	 * A user is deleted from the system
1131
-	 * So clean up the relevant shares.
1132
-	 *
1133
-	 * @param string $uid
1134
-	 * @param int $shareType
1135
-	 */
1136
-	public function userDeleted($uid, $shareType) {
1137
-		$qb = $this->dbConn->getQueryBuilder();
1138
-
1139
-		$qb->delete('share');
1140
-
1141
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
1142
-			/*
966
+            $shares = $this->resolveGroupShares($shares2, $userId);
967
+        } else {
968
+            throw new BackendError('Invalid backend');
969
+        }
970
+
971
+
972
+        return $shares;
973
+    }
974
+
975
+    /**
976
+     * Get a share by token
977
+     *
978
+     * @param string $token
979
+     * @return \OCP\Share\IShare
980
+     * @throws ShareNotFound
981
+     */
982
+    public function getShareByToken($token) {
983
+        $qb = $this->dbConn->getQueryBuilder();
984
+
985
+        $cursor = $qb->select('*')
986
+            ->from('share')
987
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
988
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
989
+            ->andWhere($qb->expr()->orX(
990
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
991
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
992
+            ))
993
+            ->execute();
994
+
995
+        $data = $cursor->fetch();
996
+
997
+        if ($data === false) {
998
+            throw new ShareNotFound();
999
+        }
1000
+
1001
+        try {
1002
+            $share = $this->createShare($data);
1003
+        } catch (InvalidShare $e) {
1004
+            throw new ShareNotFound();
1005
+        }
1006
+
1007
+        return $share;
1008
+    }
1009
+
1010
+    /**
1011
+     * Create a share object from an database row
1012
+     *
1013
+     * @param mixed[] $data
1014
+     * @return \OCP\Share\IShare
1015
+     * @throws InvalidShare
1016
+     */
1017
+    private function createShare($data) {
1018
+        $share = new Share($this->rootFolder, $this->userManager);
1019
+        $share->setId((int)$data['id'])
1020
+            ->setShareType((int)$data['share_type'])
1021
+            ->setPermissions((int)$data['permissions'])
1022
+            ->setTarget($data['file_target'])
1023
+            ->setNote($data['note'])
1024
+            ->setMailSend((bool)$data['mail_send'])
1025
+            ->setStatus((int)$data['accepted'])
1026
+            ->setLabel($data['label']);
1027
+
1028
+        $shareTime = new \DateTime();
1029
+        $shareTime->setTimestamp((int)$data['stime']);
1030
+        $share->setShareTime($shareTime);
1031
+
1032
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
1033
+            $share->setSharedWith($data['share_with']);
1034
+            $user = $this->userManager->get($data['share_with']);
1035
+            if ($user !== null) {
1036
+                $share->setSharedWithDisplayName($user->getDisplayName());
1037
+            }
1038
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1039
+            $share->setSharedWith($data['share_with']);
1040
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
1041
+            $share->setPassword($data['password']);
1042
+            $share->setSendPasswordByTalk((bool)$data['password_by_talk']);
1043
+            $share->setToken($data['token']);
1044
+        }
1045
+
1046
+        $share->setSharedBy($data['uid_initiator']);
1047
+        $share->setShareOwner($data['uid_owner']);
1048
+
1049
+        $share->setNodeId((int)$data['file_source']);
1050
+        $share->setNodeType($data['item_type']);
1051
+
1052
+        if ($data['expiration'] !== null) {
1053
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
1054
+            $share->setExpirationDate($expiration);
1055
+        }
1056
+
1057
+        if (isset($data['f_permissions'])) {
1058
+            $entryData = $data;
1059
+            $entryData['permissions'] = $entryData['f_permissions'];
1060
+            $entryData['parent'] = $entryData['f_parent'];
1061
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
1062
+                \OC::$server->getMimeTypeLoader()));
1063
+        }
1064
+
1065
+        $share->setProviderId($this->identifier());
1066
+        $share->setHideDownload((int)$data['hide_download'] === 1);
1067
+
1068
+        return $share;
1069
+    }
1070
+
1071
+    /**
1072
+     * @param Share[] $shares
1073
+     * @param $userId
1074
+     * @return Share[] The updates shares if no update is found for a share return the original
1075
+     */
1076
+    private function resolveGroupShares($shares, $userId) {
1077
+        $result = [];
1078
+
1079
+        $start = 0;
1080
+        while(true) {
1081
+            /** @var Share[] $shareSlice */
1082
+            $shareSlice = array_slice($shares, $start, 100);
1083
+            $start += 100;
1084
+
1085
+            if ($shareSlice === []) {
1086
+                break;
1087
+            }
1088
+
1089
+            /** @var int[] $ids */
1090
+            $ids = [];
1091
+            /** @var Share[] $shareMap */
1092
+            $shareMap = [];
1093
+
1094
+            foreach ($shareSlice as $share) {
1095
+                $ids[] = (int)$share->getId();
1096
+                $shareMap[$share->getId()] = $share;
1097
+            }
1098
+
1099
+            $qb = $this->dbConn->getQueryBuilder();
1100
+
1101
+            $query = $qb->select('*')
1102
+                ->from('share')
1103
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1104
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
1105
+                ->andWhere($qb->expr()->orX(
1106
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1107
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1108
+                ));
1109
+
1110
+            $stmt = $query->execute();
1111
+
1112
+            while($data = $stmt->fetch()) {
1113
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
1114
+                $shareMap[$data['parent']]->setStatus((int)$data['accepted']);
1115
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
1116
+                $shareMap[$data['parent']]->setParent($data['parent']);
1117
+            }
1118
+
1119
+            $stmt->closeCursor();
1120
+
1121
+            foreach ($shareMap as $share) {
1122
+                $result[] = $share;
1123
+            }
1124
+        }
1125
+
1126
+        return $result;
1127
+    }
1128
+
1129
+    /**
1130
+     * A user is deleted from the system
1131
+     * So clean up the relevant shares.
1132
+     *
1133
+     * @param string $uid
1134
+     * @param int $shareType
1135
+     */
1136
+    public function userDeleted($uid, $shareType) {
1137
+        $qb = $this->dbConn->getQueryBuilder();
1138
+
1139
+        $qb->delete('share');
1140
+
1141
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
1142
+            /*
1143 1143
 			 * Delete all user shares that are owned by this user
1144 1144
 			 * or that are received by this user
1145 1145
 			 */
1146 1146
 
1147
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
1147
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
1148 1148
 
1149
-			$qb->andWhere(
1150
-				$qb->expr()->orX(
1151
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
1152
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
1153
-				)
1154
-			);
1155
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
1156
-			/*
1149
+            $qb->andWhere(
1150
+                $qb->expr()->orX(
1151
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
1152
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
1153
+                )
1154
+            );
1155
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
1156
+            /*
1157 1157
 			 * Delete all group shares that are owned by this user
1158 1158
 			 * Or special user group shares that are received by this user
1159 1159
 			 */
1160
-			$qb->where(
1161
-				$qb->expr()->andX(
1162
-					$qb->expr()->orX(
1163
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1164
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
1165
-					),
1166
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
1167
-				)
1168
-			);
1169
-
1170
-			$qb->orWhere(
1171
-				$qb->expr()->andX(
1172
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
1173
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
1174
-				)
1175
-			);
1176
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
1177
-			/*
1160
+            $qb->where(
1161
+                $qb->expr()->andX(
1162
+                    $qb->expr()->orX(
1163
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1164
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
1165
+                    ),
1166
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
1167
+                )
1168
+            );
1169
+
1170
+            $qb->orWhere(
1171
+                $qb->expr()->andX(
1172
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
1173
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
1174
+                )
1175
+            );
1176
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
1177
+            /*
1178 1178
 			 * Delete all link shares owned by this user.
1179 1179
 			 * And all link shares initiated by this user (until #22327 is in)
1180 1180
 			 */
1181
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
1182
-
1183
-			$qb->andWhere(
1184
-				$qb->expr()->orX(
1185
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
1186
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
1187
-				)
1188
-			);
1189
-		} else {
1190
-			\OC::$server->getLogger()->logException(new \InvalidArgumentException('Default share provider tried to delete all shares for type: ' . $shareType));
1191
-			return;
1192
-		}
1193
-
1194
-		$qb->execute();
1195
-	}
1196
-
1197
-	/**
1198
-	 * Delete all shares received by this group. As well as any custom group
1199
-	 * shares for group members.
1200
-	 *
1201
-	 * @param string $gid
1202
-	 */
1203
-	public function groupDeleted($gid) {
1204
-		/*
1181
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
1182
+
1183
+            $qb->andWhere(
1184
+                $qb->expr()->orX(
1185
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
1186
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
1187
+                )
1188
+            );
1189
+        } else {
1190
+            \OC::$server->getLogger()->logException(new \InvalidArgumentException('Default share provider tried to delete all shares for type: ' . $shareType));
1191
+            return;
1192
+        }
1193
+
1194
+        $qb->execute();
1195
+    }
1196
+
1197
+    /**
1198
+     * Delete all shares received by this group. As well as any custom group
1199
+     * shares for group members.
1200
+     *
1201
+     * @param string $gid
1202
+     */
1203
+    public function groupDeleted($gid) {
1204
+        /*
1205 1205
 		 * First delete all custom group shares for group members
1206 1206
 		 */
1207
-		$qb = $this->dbConn->getQueryBuilder();
1208
-		$qb->select('id')
1209
-			->from('share')
1210
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1211
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1212
-
1213
-		$cursor = $qb->execute();
1214
-		$ids = [];
1215
-		while($row = $cursor->fetch()) {
1216
-			$ids[] = (int)$row['id'];
1217
-		}
1218
-		$cursor->closeCursor();
1219
-
1220
-		if (!empty($ids)) {
1221
-			$chunks = array_chunk($ids, 100);
1222
-			foreach ($chunks as $chunk) {
1223
-				$qb->delete('share')
1224
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1225
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1226
-				$qb->execute();
1227
-			}
1228
-		}
1229
-
1230
-		/*
1207
+        $qb = $this->dbConn->getQueryBuilder();
1208
+        $qb->select('id')
1209
+            ->from('share')
1210
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1211
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1212
+
1213
+        $cursor = $qb->execute();
1214
+        $ids = [];
1215
+        while($row = $cursor->fetch()) {
1216
+            $ids[] = (int)$row['id'];
1217
+        }
1218
+        $cursor->closeCursor();
1219
+
1220
+        if (!empty($ids)) {
1221
+            $chunks = array_chunk($ids, 100);
1222
+            foreach ($chunks as $chunk) {
1223
+                $qb->delete('share')
1224
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1225
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1226
+                $qb->execute();
1227
+            }
1228
+        }
1229
+
1230
+        /*
1231 1231
 		 * Now delete all the group shares
1232 1232
 		 */
1233
-		$qb = $this->dbConn->getQueryBuilder();
1234
-		$qb->delete('share')
1235
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1236
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1237
-		$qb->execute();
1238
-	}
1239
-
1240
-	/**
1241
-	 * Delete custom group shares to this group for this user
1242
-	 *
1243
-	 * @param string $uid
1244
-	 * @param string $gid
1245
-	 */
1246
-	public function userDeletedFromGroup($uid, $gid) {
1247
-		/*
1233
+        $qb = $this->dbConn->getQueryBuilder();
1234
+        $qb->delete('share')
1235
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1236
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1237
+        $qb->execute();
1238
+    }
1239
+
1240
+    /**
1241
+     * Delete custom group shares to this group for this user
1242
+     *
1243
+     * @param string $uid
1244
+     * @param string $gid
1245
+     */
1246
+    public function userDeletedFromGroup($uid, $gid) {
1247
+        /*
1248 1248
 		 * Get all group shares
1249 1249
 		 */
1250
-		$qb = $this->dbConn->getQueryBuilder();
1251
-		$qb->select('id')
1252
-			->from('share')
1253
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1254
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1255
-
1256
-		$cursor = $qb->execute();
1257
-		$ids = [];
1258
-		while($row = $cursor->fetch()) {
1259
-			$ids[] = (int)$row['id'];
1260
-		}
1261
-		$cursor->closeCursor();
1262
-
1263
-		if (!empty($ids)) {
1264
-			$chunks = array_chunk($ids, 100);
1265
-			foreach ($chunks as $chunk) {
1266
-				/*
1250
+        $qb = $this->dbConn->getQueryBuilder();
1251
+        $qb->select('id')
1252
+            ->from('share')
1253
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1254
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1255
+
1256
+        $cursor = $qb->execute();
1257
+        $ids = [];
1258
+        while($row = $cursor->fetch()) {
1259
+            $ids[] = (int)$row['id'];
1260
+        }
1261
+        $cursor->closeCursor();
1262
+
1263
+        if (!empty($ids)) {
1264
+            $chunks = array_chunk($ids, 100);
1265
+            foreach ($chunks as $chunk) {
1266
+                /*
1267 1267
 				 * Delete all special shares wit this users for the found group shares
1268 1268
 				 */
1269
-				$qb->delete('share')
1270
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1271
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1272
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1273
-				$qb->execute();
1274
-			}
1275
-		}
1276
-	}
1277
-
1278
-	/**
1279
-	 * @inheritdoc
1280
-	 */
1281
-	public function getAccessList($nodes, $currentAccess) {
1282
-		$ids = [];
1283
-		foreach ($nodes as $node) {
1284
-			$ids[] = $node->getId();
1285
-		}
1286
-
1287
-		$qb = $this->dbConn->getQueryBuilder();
1288
-
1289
-		$or = $qb->expr()->orX(
1290
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1291
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1292
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1293
-		);
1294
-
1295
-		if ($currentAccess) {
1296
-			$or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1297
-		}
1298
-
1299
-		$qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1300
-			->from('share')
1301
-			->where(
1302
-				$or
1303
-			)
1304
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1305
-			->andWhere($qb->expr()->orX(
1306
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1307
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1308
-			));
1309
-		$cursor = $qb->execute();
1310
-
1311
-		$users = [];
1312
-		$link = false;
1313
-		while($row = $cursor->fetch()) {
1314
-			$type = (int)$row['share_type'];
1315
-			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1316
-				$uid = $row['share_with'];
1317
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1318
-				$users[$uid][$row['id']] = $row;
1319
-			} else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1320
-				$gid = $row['share_with'];
1321
-				$group = $this->groupManager->get($gid);
1322
-
1323
-				if ($group === null) {
1324
-					continue;
1325
-				}
1326
-
1327
-				$userList = $group->getUsers();
1328
-				foreach ($userList as $user) {
1329
-					$uid = $user->getUID();
1330
-					$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1331
-					$users[$uid][$row['id']] = $row;
1332
-				}
1333
-			} else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1334
-				$link = true;
1335
-			} else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1336
-				$uid = $row['share_with'];
1337
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1338
-				$users[$uid][$row['id']] = $row;
1339
-			}
1340
-		}
1341
-		$cursor->closeCursor();
1342
-
1343
-		if ($currentAccess === true) {
1344
-			$users = array_map([$this, 'filterSharesOfUser'], $users);
1345
-			$users = array_filter($users);
1346
-		} else {
1347
-			$users = array_keys($users);
1348
-		}
1349
-
1350
-		return ['users' => $users, 'public' => $link];
1351
-	}
1352
-
1353
-	/**
1354
-	 * For each user the path with the fewest slashes is returned
1355
-	 * @param array $shares
1356
-	 * @return array
1357
-	 */
1358
-	protected function filterSharesOfUser(array $shares) {
1359
-		// Group shares when the user has a share exception
1360
-		foreach ($shares as $id => $share) {
1361
-			$type = (int) $share['share_type'];
1362
-			$permissions = (int) $share['permissions'];
1363
-
1364
-			if ($type === self::SHARE_TYPE_USERGROUP) {
1365
-				unset($shares[$share['parent']]);
1366
-
1367
-				if ($permissions === 0) {
1368
-					unset($shares[$id]);
1369
-				}
1370
-			}
1371
-		}
1372
-
1373
-		$best = [];
1374
-		$bestDepth = 0;
1375
-		foreach ($shares as $id => $share) {
1376
-			$depth = substr_count($share['file_target'], '/');
1377
-			if (empty($best) || $depth < $bestDepth) {
1378
-				$bestDepth = $depth;
1379
-				$best = [
1380
-					'node_id' => $share['file_source'],
1381
-					'node_path' => $share['file_target'],
1382
-				];
1383
-			}
1384
-		}
1385
-
1386
-		return $best;
1387
-	}
1388
-
1389
-	/**
1390
-	 * propagate notes to the recipients
1391
-	 *
1392
-	 * @param IShare $share
1393
-	 * @throws \OCP\Files\NotFoundException
1394
-	 */
1395
-	private function propagateNote(IShare $share) {
1396
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
1397
-			$user = $this->userManager->get($share->getSharedWith());
1398
-			$this->sendNote([$user], $share);
1399
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1400
-			$group = $this->groupManager->get($share->getSharedWith());
1401
-			$groupMembers = $group->getUsers();
1402
-			$this->sendNote($groupMembers, $share);
1403
-		}
1404
-	}
1405
-
1406
-	/**
1407
-	 * send note by mail
1408
-	 *
1409
-	 * @param array $recipients
1410
-	 * @param IShare $share
1411
-	 * @throws \OCP\Files\NotFoundException
1412
-	 */
1413
-	private function sendNote(array $recipients, IShare $share) {
1414
-
1415
-		$toList = [];
1416
-
1417
-		foreach ($recipients as $recipient) {
1418
-			/** @var IUser $recipient */
1419
-			$email = $recipient->getEMailAddress();
1420
-			if ($email) {
1421
-				$toList[$email] = $recipient->getDisplayName();
1422
-			}
1423
-		}
1424
-
1425
-		if (!empty($toList)) {
1426
-
1427
-			$filename = $share->getNode()->getName();
1428
-			$initiator = $share->getSharedBy();
1429
-			$note = $share->getNote();
1430
-
1431
-			$initiatorUser = $this->userManager->get($initiator);
1432
-			$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
1433
-			$initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
1434
-			$plainHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add:', [$initiatorDisplayName, $filename]);
1435
-			$htmlHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add', [$initiatorDisplayName, $filename]);
1436
-			$message = $this->mailer->createMessage();
1437
-
1438
-			$emailTemplate = $this->mailer->createEMailTemplate('defaultShareProvider.sendNote');
1439
-
1440
-			$emailTemplate->setSubject($this->l->t('»%s« added a note to a file shared with you', [$initiatorDisplayName]));
1441
-			$emailTemplate->addHeader();
1442
-			$emailTemplate->addHeading($htmlHeading, $plainHeading);
1443
-			$emailTemplate->addBodyText(htmlspecialchars($note), $note);
1444
-
1445
-			$link = $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]);
1446
-			$emailTemplate->addBodyButton(
1447
-				$this->l->t('Open »%s«', [$filename]),
1448
-				$link
1449
-			);
1450
-
1451
-
1452
-			// The "From" contains the sharers name
1453
-			$instanceName = $this->defaults->getName();
1454
-			$senderName = $this->l->t(
1455
-				'%1$s via %2$s',
1456
-				[
1457
-					$initiatorDisplayName,
1458
-					$instanceName
1459
-				]
1460
-			);
1461
-			$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
1462
-			if ($initiatorEmailAddress !== null) {
1463
-				$message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
1464
-				$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
1465
-			} else {
1466
-				$emailTemplate->addFooter();
1467
-			}
1468
-
1469
-			if (count($toList) === 1) {
1470
-				$message->setTo($toList);
1471
-			} else {
1472
-				$message->setTo([]);
1473
-				$message->setBcc($toList);
1474
-			}
1475
-			$message->useTemplate($emailTemplate);
1476
-			$this->mailer->send($message);
1477
-		}
1478
-
1479
-	}
1480
-
1481
-	public function getAllShares(): iterable {
1482
-		$qb = $this->dbConn->getQueryBuilder();
1483
-
1484
-		$qb->select('*')
1485
-			->from('share')
1486
-			->where(
1487
-				$qb->expr()->orX(
1488
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_USER)),
1489
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_GROUP)),
1490
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_LINK))
1491
-				)
1492
-			);
1493
-
1494
-		$cursor = $qb->execute();
1495
-		while($data = $cursor->fetch()) {
1496
-			try {
1497
-				$share = $this->createShare($data);
1498
-			} catch (InvalidShare $e) {
1499
-				continue;
1500
-			}
1501
-
1502
-			yield $share;
1503
-		}
1504
-		$cursor->closeCursor();
1505
-	}
1269
+                $qb->delete('share')
1270
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1271
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1272
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1273
+                $qb->execute();
1274
+            }
1275
+        }
1276
+    }
1277
+
1278
+    /**
1279
+     * @inheritdoc
1280
+     */
1281
+    public function getAccessList($nodes, $currentAccess) {
1282
+        $ids = [];
1283
+        foreach ($nodes as $node) {
1284
+            $ids[] = $node->getId();
1285
+        }
1286
+
1287
+        $qb = $this->dbConn->getQueryBuilder();
1288
+
1289
+        $or = $qb->expr()->orX(
1290
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1291
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1292
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1293
+        );
1294
+
1295
+        if ($currentAccess) {
1296
+            $or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1297
+        }
1298
+
1299
+        $qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1300
+            ->from('share')
1301
+            ->where(
1302
+                $or
1303
+            )
1304
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1305
+            ->andWhere($qb->expr()->orX(
1306
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1307
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1308
+            ));
1309
+        $cursor = $qb->execute();
1310
+
1311
+        $users = [];
1312
+        $link = false;
1313
+        while($row = $cursor->fetch()) {
1314
+            $type = (int)$row['share_type'];
1315
+            if ($type === \OCP\Share::SHARE_TYPE_USER) {
1316
+                $uid = $row['share_with'];
1317
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1318
+                $users[$uid][$row['id']] = $row;
1319
+            } else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1320
+                $gid = $row['share_with'];
1321
+                $group = $this->groupManager->get($gid);
1322
+
1323
+                if ($group === null) {
1324
+                    continue;
1325
+                }
1326
+
1327
+                $userList = $group->getUsers();
1328
+                foreach ($userList as $user) {
1329
+                    $uid = $user->getUID();
1330
+                    $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1331
+                    $users[$uid][$row['id']] = $row;
1332
+                }
1333
+            } else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1334
+                $link = true;
1335
+            } else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1336
+                $uid = $row['share_with'];
1337
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1338
+                $users[$uid][$row['id']] = $row;
1339
+            }
1340
+        }
1341
+        $cursor->closeCursor();
1342
+
1343
+        if ($currentAccess === true) {
1344
+            $users = array_map([$this, 'filterSharesOfUser'], $users);
1345
+            $users = array_filter($users);
1346
+        } else {
1347
+            $users = array_keys($users);
1348
+        }
1349
+
1350
+        return ['users' => $users, 'public' => $link];
1351
+    }
1352
+
1353
+    /**
1354
+     * For each user the path with the fewest slashes is returned
1355
+     * @param array $shares
1356
+     * @return array
1357
+     */
1358
+    protected function filterSharesOfUser(array $shares) {
1359
+        // Group shares when the user has a share exception
1360
+        foreach ($shares as $id => $share) {
1361
+            $type = (int) $share['share_type'];
1362
+            $permissions = (int) $share['permissions'];
1363
+
1364
+            if ($type === self::SHARE_TYPE_USERGROUP) {
1365
+                unset($shares[$share['parent']]);
1366
+
1367
+                if ($permissions === 0) {
1368
+                    unset($shares[$id]);
1369
+                }
1370
+            }
1371
+        }
1372
+
1373
+        $best = [];
1374
+        $bestDepth = 0;
1375
+        foreach ($shares as $id => $share) {
1376
+            $depth = substr_count($share['file_target'], '/');
1377
+            if (empty($best) || $depth < $bestDepth) {
1378
+                $bestDepth = $depth;
1379
+                $best = [
1380
+                    'node_id' => $share['file_source'],
1381
+                    'node_path' => $share['file_target'],
1382
+                ];
1383
+            }
1384
+        }
1385
+
1386
+        return $best;
1387
+    }
1388
+
1389
+    /**
1390
+     * propagate notes to the recipients
1391
+     *
1392
+     * @param IShare $share
1393
+     * @throws \OCP\Files\NotFoundException
1394
+     */
1395
+    private function propagateNote(IShare $share) {
1396
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
1397
+            $user = $this->userManager->get($share->getSharedWith());
1398
+            $this->sendNote([$user], $share);
1399
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1400
+            $group = $this->groupManager->get($share->getSharedWith());
1401
+            $groupMembers = $group->getUsers();
1402
+            $this->sendNote($groupMembers, $share);
1403
+        }
1404
+    }
1405
+
1406
+    /**
1407
+     * send note by mail
1408
+     *
1409
+     * @param array $recipients
1410
+     * @param IShare $share
1411
+     * @throws \OCP\Files\NotFoundException
1412
+     */
1413
+    private function sendNote(array $recipients, IShare $share) {
1414
+
1415
+        $toList = [];
1416
+
1417
+        foreach ($recipients as $recipient) {
1418
+            /** @var IUser $recipient */
1419
+            $email = $recipient->getEMailAddress();
1420
+            if ($email) {
1421
+                $toList[$email] = $recipient->getDisplayName();
1422
+            }
1423
+        }
1424
+
1425
+        if (!empty($toList)) {
1426
+
1427
+            $filename = $share->getNode()->getName();
1428
+            $initiator = $share->getSharedBy();
1429
+            $note = $share->getNote();
1430
+
1431
+            $initiatorUser = $this->userManager->get($initiator);
1432
+            $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
1433
+            $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
1434
+            $plainHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add:', [$initiatorDisplayName, $filename]);
1435
+            $htmlHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add', [$initiatorDisplayName, $filename]);
1436
+            $message = $this->mailer->createMessage();
1437
+
1438
+            $emailTemplate = $this->mailer->createEMailTemplate('defaultShareProvider.sendNote');
1439
+
1440
+            $emailTemplate->setSubject($this->l->t('»%s« added a note to a file shared with you', [$initiatorDisplayName]));
1441
+            $emailTemplate->addHeader();
1442
+            $emailTemplate->addHeading($htmlHeading, $plainHeading);
1443
+            $emailTemplate->addBodyText(htmlspecialchars($note), $note);
1444
+
1445
+            $link = $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]);
1446
+            $emailTemplate->addBodyButton(
1447
+                $this->l->t('Open »%s«', [$filename]),
1448
+                $link
1449
+            );
1450
+
1451
+
1452
+            // The "From" contains the sharers name
1453
+            $instanceName = $this->defaults->getName();
1454
+            $senderName = $this->l->t(
1455
+                '%1$s via %2$s',
1456
+                [
1457
+                    $initiatorDisplayName,
1458
+                    $instanceName
1459
+                ]
1460
+            );
1461
+            $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
1462
+            if ($initiatorEmailAddress !== null) {
1463
+                $message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
1464
+                $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
1465
+            } else {
1466
+                $emailTemplate->addFooter();
1467
+            }
1468
+
1469
+            if (count($toList) === 1) {
1470
+                $message->setTo($toList);
1471
+            } else {
1472
+                $message->setTo([]);
1473
+                $message->setBcc($toList);
1474
+            }
1475
+            $message->useTemplate($emailTemplate);
1476
+            $this->mailer->send($message);
1477
+        }
1478
+
1479
+    }
1480
+
1481
+    public function getAllShares(): iterable {
1482
+        $qb = $this->dbConn->getQueryBuilder();
1483
+
1484
+        $qb->select('*')
1485
+            ->from('share')
1486
+            ->where(
1487
+                $qb->expr()->orX(
1488
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_USER)),
1489
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_GROUP)),
1490
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_LINK))
1491
+                )
1492
+            );
1493
+
1494
+        $cursor = $qb->execute();
1495
+        while($data = $cursor->fetch()) {
1496
+            try {
1497
+                $share = $this->createShare($data);
1498
+            } catch (InvalidShare $e) {
1499
+                continue;
1500
+            }
1501
+
1502
+            yield $share;
1503
+        }
1504
+        $cursor->closeCursor();
1505
+    }
1506 1506
 }
Please login to merge, or discard this patch.
Spacing   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
 			$user = $this->userManager->get($recipient);
349 349
 
350 350
 			if (is_null($group)) {
351
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
351
+				throw new ProviderException('Group "'.$share->getSharedWith().'" does not exist');
352 352
 			}
353 353
 
354 354
 			if (!$group->inGroup($user)) {
@@ -431,7 +431,7 @@  discard block
 block discarded – undo
431 431
 			->orderBy('id');
432 432
 
433 433
 		$cursor = $qb->execute();
434
-		while($data = $cursor->fetch()) {
434
+		while ($data = $cursor->fetch()) {
435 435
 			$children[] = $this->createShare($data);
436 436
 		}
437 437
 		$cursor->closeCursor();
@@ -476,7 +476,7 @@  discard block
 block discarded – undo
476 476
 			$user = $this->userManager->get($recipient);
477 477
 
478 478
 			if (is_null($group)) {
479
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
479
+				throw new ProviderException('Group "'.$share->getSharedWith().'" does not exist');
480 480
 			}
481 481
 
482 482
 			if (!$group->inGroup($user)) {
@@ -679,7 +679,7 @@  discard block
 block discarded – undo
679 679
 			);
680 680
 		}
681 681
 
682
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
682
+		$qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
683 683
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
684 684
 
685 685
 		$qb->orderBy('id');
@@ -737,7 +737,7 @@  discard block
 block discarded – undo
737 737
 
738 738
 		$cursor = $qb->execute();
739 739
 		$shares = [];
740
-		while($data = $cursor->fetch()) {
740
+		while ($data = $cursor->fetch()) {
741 741
 			$shares[] = $this->createShare($data);
742 742
 		}
743 743
 		$cursor->closeCursor();
@@ -816,7 +816,7 @@  discard block
 block discarded – undo
816 816
 			->execute();
817 817
 
818 818
 		$shares = [];
819
-		while($data = $cursor->fetch()) {
819
+		while ($data = $cursor->fetch()) {
820 820
 			$shares[] = $this->createShare($data);
821 821
 		}
822 822
 		$cursor->closeCursor();
@@ -887,7 +887,7 @@  discard block
 block discarded – undo
887 887
 
888 888
 			$cursor = $qb->execute();
889 889
 
890
-			while($data = $cursor->fetch()) {
890
+			while ($data = $cursor->fetch()) {
891 891
 				if ($this->isAccessibleResult($data)) {
892 892
 					$shares[] = $this->createShare($data);
893 893
 				}
@@ -902,7 +902,7 @@  discard block
 block discarded – undo
902 902
 			$shares2 = [];
903 903
 
904 904
 			$start = 0;
905
-			while(true) {
905
+			while (true) {
906 906
 				$groups = array_slice($allGroups, $start, 100);
907 907
 				$start += 100;
908 908
 
@@ -933,8 +933,8 @@  discard block
 block discarded – undo
933 933
 				}
934 934
 
935 935
 
936
-				$groups = array_filter($groups, function ($group) { return $group instanceof IGroup; });
937
-				$groups = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
936
+				$groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
937
+				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
938 938
 
939 939
 				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
940 940
 					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
@@ -947,7 +947,7 @@  discard block
 block discarded – undo
947 947
 					));
948 948
 
949 949
 				$cursor = $qb->execute();
950
-				while($data = $cursor->fetch()) {
950
+				while ($data = $cursor->fetch()) {
951 951
 					if ($offset > 0) {
952 952
 						$offset--;
953 953
 						continue;
@@ -1016,17 +1016,17 @@  discard block
 block discarded – undo
1016 1016
 	 */
1017 1017
 	private function createShare($data) {
1018 1018
 		$share = new Share($this->rootFolder, $this->userManager);
1019
-		$share->setId((int)$data['id'])
1020
-			->setShareType((int)$data['share_type'])
1021
-			->setPermissions((int)$data['permissions'])
1019
+		$share->setId((int) $data['id'])
1020
+			->setShareType((int) $data['share_type'])
1021
+			->setPermissions((int) $data['permissions'])
1022 1022
 			->setTarget($data['file_target'])
1023 1023
 			->setNote($data['note'])
1024
-			->setMailSend((bool)$data['mail_send'])
1025
-			->setStatus((int)$data['accepted'])
1024
+			->setMailSend((bool) $data['mail_send'])
1025
+			->setStatus((int) $data['accepted'])
1026 1026
 			->setLabel($data['label']);
1027 1027
 
1028 1028
 		$shareTime = new \DateTime();
1029
-		$shareTime->setTimestamp((int)$data['stime']);
1029
+		$shareTime->setTimestamp((int) $data['stime']);
1030 1030
 		$share->setShareTime($shareTime);
1031 1031
 
1032 1032
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
@@ -1039,14 +1039,14 @@  discard block
 block discarded – undo
1039 1039
 			$share->setSharedWith($data['share_with']);
1040 1040
 		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
1041 1041
 			$share->setPassword($data['password']);
1042
-			$share->setSendPasswordByTalk((bool)$data['password_by_talk']);
1042
+			$share->setSendPasswordByTalk((bool) $data['password_by_talk']);
1043 1043
 			$share->setToken($data['token']);
1044 1044
 		}
1045 1045
 
1046 1046
 		$share->setSharedBy($data['uid_initiator']);
1047 1047
 		$share->setShareOwner($data['uid_owner']);
1048 1048
 
1049
-		$share->setNodeId((int)$data['file_source']);
1049
+		$share->setNodeId((int) $data['file_source']);
1050 1050
 		$share->setNodeType($data['item_type']);
1051 1051
 
1052 1052
 		if ($data['expiration'] !== null) {
@@ -1063,7 +1063,7 @@  discard block
 block discarded – undo
1063 1063
 		}
1064 1064
 
1065 1065
 		$share->setProviderId($this->identifier());
1066
-		$share->setHideDownload((int)$data['hide_download'] === 1);
1066
+		$share->setHideDownload((int) $data['hide_download'] === 1);
1067 1067
 
1068 1068
 		return $share;
1069 1069
 	}
@@ -1077,7 +1077,7 @@  discard block
 block discarded – undo
1077 1077
 		$result = [];
1078 1078
 
1079 1079
 		$start = 0;
1080
-		while(true) {
1080
+		while (true) {
1081 1081
 			/** @var Share[] $shareSlice */
1082 1082
 			$shareSlice = array_slice($shares, $start, 100);
1083 1083
 			$start += 100;
@@ -1092,7 +1092,7 @@  discard block
 block discarded – undo
1092 1092
 			$shareMap = [];
1093 1093
 
1094 1094
 			foreach ($shareSlice as $share) {
1095
-				$ids[] = (int)$share->getId();
1095
+				$ids[] = (int) $share->getId();
1096 1096
 				$shareMap[$share->getId()] = $share;
1097 1097
 			}
1098 1098
 
@@ -1109,9 +1109,9 @@  discard block
 block discarded – undo
1109 1109
 
1110 1110
 			$stmt = $query->execute();
1111 1111
 
1112
-			while($data = $stmt->fetch()) {
1113
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
1114
-				$shareMap[$data['parent']]->setStatus((int)$data['accepted']);
1112
+			while ($data = $stmt->fetch()) {
1113
+				$shareMap[$data['parent']]->setPermissions((int) $data['permissions']);
1114
+				$shareMap[$data['parent']]->setStatus((int) $data['accepted']);
1115 1115
 				$shareMap[$data['parent']]->setTarget($data['file_target']);
1116 1116
 				$shareMap[$data['parent']]->setParent($data['parent']);
1117 1117
 			}
@@ -1187,7 +1187,7 @@  discard block
 block discarded – undo
1187 1187
 				)
1188 1188
 			);
1189 1189
 		} else {
1190
-			\OC::$server->getLogger()->logException(new \InvalidArgumentException('Default share provider tried to delete all shares for type: ' . $shareType));
1190
+			\OC::$server->getLogger()->logException(new \InvalidArgumentException('Default share provider tried to delete all shares for type: '.$shareType));
1191 1191
 			return;
1192 1192
 		}
1193 1193
 
@@ -1212,8 +1212,8 @@  discard block
 block discarded – undo
1212 1212
 
1213 1213
 		$cursor = $qb->execute();
1214 1214
 		$ids = [];
1215
-		while($row = $cursor->fetch()) {
1216
-			$ids[] = (int)$row['id'];
1215
+		while ($row = $cursor->fetch()) {
1216
+			$ids[] = (int) $row['id'];
1217 1217
 		}
1218 1218
 		$cursor->closeCursor();
1219 1219
 
@@ -1255,8 +1255,8 @@  discard block
 block discarded – undo
1255 1255
 
1256 1256
 		$cursor = $qb->execute();
1257 1257
 		$ids = [];
1258
-		while($row = $cursor->fetch()) {
1259
-			$ids[] = (int)$row['id'];
1258
+		while ($row = $cursor->fetch()) {
1259
+			$ids[] = (int) $row['id'];
1260 1260
 		}
1261 1261
 		$cursor->closeCursor();
1262 1262
 
@@ -1310,8 +1310,8 @@  discard block
 block discarded – undo
1310 1310
 
1311 1311
 		$users = [];
1312 1312
 		$link = false;
1313
-		while($row = $cursor->fetch()) {
1314
-			$type = (int)$row['share_type'];
1313
+		while ($row = $cursor->fetch()) {
1314
+			$type = (int) $row['share_type'];
1315 1315
 			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1316 1316
 				$uid = $row['share_with'];
1317 1317
 				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
@@ -1461,7 +1461,7 @@  discard block
 block discarded – undo
1461 1461
 			$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
1462 1462
 			if ($initiatorEmailAddress !== null) {
1463 1463
 				$message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
1464
-				$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
1464
+				$emailTemplate->addFooter($instanceName.' - '.$this->defaults->getSlogan());
1465 1465
 			} else {
1466 1466
 				$emailTemplate->addFooter();
1467 1467
 			}
@@ -1492,7 +1492,7 @@  discard block
 block discarded – undo
1492 1492
 			);
1493 1493
 
1494 1494
 		$cursor = $qb->execute();
1495
-		while($data = $cursor->fetch()) {
1495
+		while ($data = $cursor->fetch()) {
1496 1496
 			try {
1497 1497
 				$share = $this->createShare($data);
1498 1498
 			} catch (InvalidShare $e) {
Please login to merge, or discard this patch.
lib/private/Share20/Manager.php 2 patches
Indentation   +1749 added lines, -1749 removed lines patch added patch discarded remove patch
@@ -77,1776 +77,1776 @@
 block discarded – undo
77 77
  */
78 78
 class Manager implements IManager {
79 79
 
80
-	/** @var IProviderFactory */
81
-	private $factory;
82
-	/** @var ILogger */
83
-	private $logger;
84
-	/** @var IConfig */
85
-	private $config;
86
-	/** @var ISecureRandom */
87
-	private $secureRandom;
88
-	/** @var IHasher */
89
-	private $hasher;
90
-	/** @var IMountManager */
91
-	private $mountManager;
92
-	/** @var IGroupManager */
93
-	private $groupManager;
94
-	/** @var IL10N */
95
-	private $l;
96
-	/** @var IFactory */
97
-	private $l10nFactory;
98
-	/** @var IUserManager */
99
-	private $userManager;
100
-	/** @var IRootFolder */
101
-	private $rootFolder;
102
-	/** @var CappedMemoryCache */
103
-	private $sharingDisabledForUsersCache;
104
-	/** @var EventDispatcherInterface */
105
-	private $legacyDispatcher;
106
-	/** @var LegacyHooks */
107
-	private $legacyHooks;
108
-	/** @var IMailer */
109
-	private $mailer;
110
-	/** @var IURLGenerator */
111
-	private $urlGenerator;
112
-	/** @var \OC_Defaults */
113
-	private $defaults;
114
-	/** @var IEventDispatcher */
115
-	private $dispatcher;
116
-
117
-
118
-	/**
119
-	 * Manager constructor.
120
-	 *
121
-	 * @param ILogger $logger
122
-	 * @param IConfig $config
123
-	 * @param ISecureRandom $secureRandom
124
-	 * @param IHasher $hasher
125
-	 * @param IMountManager $mountManager
126
-	 * @param IGroupManager $groupManager
127
-	 * @param IL10N $l
128
-	 * @param IFactory $l10nFactory
129
-	 * @param IProviderFactory $factory
130
-	 * @param IUserManager $userManager
131
-	 * @param IRootFolder $rootFolder
132
-	 * @param EventDispatcherInterface $eventDispatcher
133
-	 * @param IMailer $mailer
134
-	 * @param IURLGenerator $urlGenerator
135
-	 * @param \OC_Defaults $defaults
136
-	 */
137
-	public function __construct(
138
-			ILogger $logger,
139
-			IConfig $config,
140
-			ISecureRandom $secureRandom,
141
-			IHasher $hasher,
142
-			IMountManager $mountManager,
143
-			IGroupManager $groupManager,
144
-			IL10N $l,
145
-			IFactory $l10nFactory,
146
-			IProviderFactory $factory,
147
-			IUserManager $userManager,
148
-			IRootFolder $rootFolder,
149
-			EventDispatcherInterface $legacyDispatcher,
150
-			IMailer $mailer,
151
-			IURLGenerator $urlGenerator,
152
-			\OC_Defaults $defaults,
153
-			IEventDispatcher $dispatcher
154
-	) {
155
-		$this->logger = $logger;
156
-		$this->config = $config;
157
-		$this->secureRandom = $secureRandom;
158
-		$this->hasher = $hasher;
159
-		$this->mountManager = $mountManager;
160
-		$this->groupManager = $groupManager;
161
-		$this->l = $l;
162
-		$this->l10nFactory = $l10nFactory;
163
-		$this->factory = $factory;
164
-		$this->userManager = $userManager;
165
-		$this->rootFolder = $rootFolder;
166
-		$this->legacyDispatcher = $legacyDispatcher;
167
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
168
-		$this->legacyHooks = new LegacyHooks($this->legacyDispatcher);
169
-		$this->mailer = $mailer;
170
-		$this->urlGenerator = $urlGenerator;
171
-		$this->defaults = $defaults;
172
-		$this->dispatcher = $dispatcher;
173
-	}
174
-
175
-	/**
176
-	 * Convert from a full share id to a tuple (providerId, shareId)
177
-	 *
178
-	 * @param string $id
179
-	 * @return string[]
180
-	 */
181
-	private function splitFullId($id) {
182
-		return explode(':', $id, 2);
183
-	}
184
-
185
-	/**
186
-	 * Verify if a password meets all requirements
187
-	 *
188
-	 * @param string $password
189
-	 * @throws \Exception
190
-	 */
191
-	protected function verifyPassword($password) {
192
-		if ($password === null) {
193
-			// No password is set, check if this is allowed.
194
-			if ($this->shareApiLinkEnforcePassword()) {
195
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
196
-			}
197
-
198
-			return;
199
-		}
200
-
201
-		// Let others verify the password
202
-		try {
203
-			$this->legacyDispatcher->dispatch(new ValidatePasswordPolicyEvent($password));
204
-		} catch (HintException $e) {
205
-			throw new \Exception($e->getHint());
206
-		}
207
-	}
208
-
209
-	/**
210
-	 * Check for generic requirements before creating a share
211
-	 *
212
-	 * @param \OCP\Share\IShare $share
213
-	 * @throws \InvalidArgumentException
214
-	 * @throws GenericShareException
215
-	 *
216
-	 * @suppress PhanUndeclaredClassMethod
217
-	 */
218
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
219
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
220
-			// We expect a valid user as sharedWith for user shares
221
-			if (!$this->userManager->userExists($share->getSharedWith())) {
222
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
223
-			}
224
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
225
-			// We expect a valid group as sharedWith for group shares
226
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
227
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
228
-			}
229
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
230
-			if ($share->getSharedWith() !== null) {
231
-				throw new \InvalidArgumentException('SharedWith should be empty');
232
-			}
233
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
234
-			if ($share->getSharedWith() === null) {
235
-				throw new \InvalidArgumentException('SharedWith should not be empty');
236
-			}
237
-		}  else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
238
-			if ($share->getSharedWith() === null) {
239
-				throw new \InvalidArgumentException('SharedWith should not be empty');
240
-			}
241
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
242
-			if ($share->getSharedWith() === null) {
243
-				throw new \InvalidArgumentException('SharedWith should not be empty');
244
-			}
245
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
246
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
247
-			if ($circle === null) {
248
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
249
-			}
250
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_ROOM) {
251
-		} else {
252
-			// We can't handle other types yet
253
-			throw new \InvalidArgumentException('unknown share type');
254
-		}
255
-
256
-		// Verify the initiator of the share is set
257
-		if ($share->getSharedBy() === null) {
258
-			throw new \InvalidArgumentException('SharedBy should be set');
259
-		}
260
-
261
-		// Cannot share with yourself
262
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
263
-			$share->getSharedWith() === $share->getSharedBy()) {
264
-			throw new \InvalidArgumentException('Can’t share with yourself');
265
-		}
266
-
267
-		// The path should be set
268
-		if ($share->getNode() === null) {
269
-			throw new \InvalidArgumentException('Path should be set');
270
-		}
271
-
272
-		// And it should be a file or a folder
273
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
274
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
275
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
276
-		}
277
-
278
-		// And you can't share your rootfolder
279
-		if ($this->userManager->userExists($share->getSharedBy())) {
280
-			$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
281
-			$userFolderPath = $userFolder->getPath();
282
-		} else {
283
-			$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
284
-			$userFolderPath = $userFolder->getPath();
285
-		}
286
-		if ($userFolderPath === $share->getNode()->getPath()) {
287
-			throw new \InvalidArgumentException('You can’t share your root folder');
288
-		}
289
-
290
-		// Check if we actually have share permissions
291
-		if (!$share->getNode()->isShareable()) {
292
-			$path = $userFolder->getRelativePath($share->getNode()->getPath());
293
-			$message_t = $this->l->t('You are not allowed to share %s', [$path]);
294
-			throw new GenericShareException($message_t, $message_t, 404);
295
-		}
296
-
297
-		// Permissions should be set
298
-		if ($share->getPermissions() === null) {
299
-			throw new \InvalidArgumentException('A share requires permissions');
300
-		}
301
-
302
-		$isFederatedShare = $share->getNode()->getStorage()->instanceOfStorage('\OCA\Files_Sharing\External\Storage');
303
-		$permissions = 0;
304
-		$mount = $share->getNode()->getMountPoint();
305
-		if (!$isFederatedShare && $share->getNode()->getOwner()->getUID() !== $share->getSharedBy()) {
306
-			// When it's a reshare use the parent share permissions as maximum
307
-			$userMountPointId = $mount->getStorageRootId();
308
-			$userMountPoints = $userFolder->getById($userMountPointId);
309
-			$userMountPoint = array_shift($userMountPoints);
310
-
311
-			/* Check if this is an incoming share */
312
-			$incomingShares = $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_USER, $userMountPoint, -1, 0);
313
-			$incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_GROUP, $userMountPoint, -1, 0));
314
-			$incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_CIRCLE, $userMountPoint, -1, 0));
315
-			$incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_ROOM, $userMountPoint, -1, 0));
316
-
317
-			/** @var \OCP\Share\IShare[] $incomingShares */
318
-			if (!empty($incomingShares)) {
319
-				foreach ($incomingShares as $incomingShare) {
320
-					$permissions |= $incomingShare->getPermissions();
321
-				}
322
-			}
323
-		} else {
324
-			/*
80
+    /** @var IProviderFactory */
81
+    private $factory;
82
+    /** @var ILogger */
83
+    private $logger;
84
+    /** @var IConfig */
85
+    private $config;
86
+    /** @var ISecureRandom */
87
+    private $secureRandom;
88
+    /** @var IHasher */
89
+    private $hasher;
90
+    /** @var IMountManager */
91
+    private $mountManager;
92
+    /** @var IGroupManager */
93
+    private $groupManager;
94
+    /** @var IL10N */
95
+    private $l;
96
+    /** @var IFactory */
97
+    private $l10nFactory;
98
+    /** @var IUserManager */
99
+    private $userManager;
100
+    /** @var IRootFolder */
101
+    private $rootFolder;
102
+    /** @var CappedMemoryCache */
103
+    private $sharingDisabledForUsersCache;
104
+    /** @var EventDispatcherInterface */
105
+    private $legacyDispatcher;
106
+    /** @var LegacyHooks */
107
+    private $legacyHooks;
108
+    /** @var IMailer */
109
+    private $mailer;
110
+    /** @var IURLGenerator */
111
+    private $urlGenerator;
112
+    /** @var \OC_Defaults */
113
+    private $defaults;
114
+    /** @var IEventDispatcher */
115
+    private $dispatcher;
116
+
117
+
118
+    /**
119
+     * Manager constructor.
120
+     *
121
+     * @param ILogger $logger
122
+     * @param IConfig $config
123
+     * @param ISecureRandom $secureRandom
124
+     * @param IHasher $hasher
125
+     * @param IMountManager $mountManager
126
+     * @param IGroupManager $groupManager
127
+     * @param IL10N $l
128
+     * @param IFactory $l10nFactory
129
+     * @param IProviderFactory $factory
130
+     * @param IUserManager $userManager
131
+     * @param IRootFolder $rootFolder
132
+     * @param EventDispatcherInterface $eventDispatcher
133
+     * @param IMailer $mailer
134
+     * @param IURLGenerator $urlGenerator
135
+     * @param \OC_Defaults $defaults
136
+     */
137
+    public function __construct(
138
+            ILogger $logger,
139
+            IConfig $config,
140
+            ISecureRandom $secureRandom,
141
+            IHasher $hasher,
142
+            IMountManager $mountManager,
143
+            IGroupManager $groupManager,
144
+            IL10N $l,
145
+            IFactory $l10nFactory,
146
+            IProviderFactory $factory,
147
+            IUserManager $userManager,
148
+            IRootFolder $rootFolder,
149
+            EventDispatcherInterface $legacyDispatcher,
150
+            IMailer $mailer,
151
+            IURLGenerator $urlGenerator,
152
+            \OC_Defaults $defaults,
153
+            IEventDispatcher $dispatcher
154
+    ) {
155
+        $this->logger = $logger;
156
+        $this->config = $config;
157
+        $this->secureRandom = $secureRandom;
158
+        $this->hasher = $hasher;
159
+        $this->mountManager = $mountManager;
160
+        $this->groupManager = $groupManager;
161
+        $this->l = $l;
162
+        $this->l10nFactory = $l10nFactory;
163
+        $this->factory = $factory;
164
+        $this->userManager = $userManager;
165
+        $this->rootFolder = $rootFolder;
166
+        $this->legacyDispatcher = $legacyDispatcher;
167
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
168
+        $this->legacyHooks = new LegacyHooks($this->legacyDispatcher);
169
+        $this->mailer = $mailer;
170
+        $this->urlGenerator = $urlGenerator;
171
+        $this->defaults = $defaults;
172
+        $this->dispatcher = $dispatcher;
173
+    }
174
+
175
+    /**
176
+     * Convert from a full share id to a tuple (providerId, shareId)
177
+     *
178
+     * @param string $id
179
+     * @return string[]
180
+     */
181
+    private function splitFullId($id) {
182
+        return explode(':', $id, 2);
183
+    }
184
+
185
+    /**
186
+     * Verify if a password meets all requirements
187
+     *
188
+     * @param string $password
189
+     * @throws \Exception
190
+     */
191
+    protected function verifyPassword($password) {
192
+        if ($password === null) {
193
+            // No password is set, check if this is allowed.
194
+            if ($this->shareApiLinkEnforcePassword()) {
195
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
196
+            }
197
+
198
+            return;
199
+        }
200
+
201
+        // Let others verify the password
202
+        try {
203
+            $this->legacyDispatcher->dispatch(new ValidatePasswordPolicyEvent($password));
204
+        } catch (HintException $e) {
205
+            throw new \Exception($e->getHint());
206
+        }
207
+    }
208
+
209
+    /**
210
+     * Check for generic requirements before creating a share
211
+     *
212
+     * @param \OCP\Share\IShare $share
213
+     * @throws \InvalidArgumentException
214
+     * @throws GenericShareException
215
+     *
216
+     * @suppress PhanUndeclaredClassMethod
217
+     */
218
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
219
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
220
+            // We expect a valid user as sharedWith for user shares
221
+            if (!$this->userManager->userExists($share->getSharedWith())) {
222
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
223
+            }
224
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
225
+            // We expect a valid group as sharedWith for group shares
226
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
227
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
228
+            }
229
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
230
+            if ($share->getSharedWith() !== null) {
231
+                throw new \InvalidArgumentException('SharedWith should be empty');
232
+            }
233
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
234
+            if ($share->getSharedWith() === null) {
235
+                throw new \InvalidArgumentException('SharedWith should not be empty');
236
+            }
237
+        }  else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
238
+            if ($share->getSharedWith() === null) {
239
+                throw new \InvalidArgumentException('SharedWith should not be empty');
240
+            }
241
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
242
+            if ($share->getSharedWith() === null) {
243
+                throw new \InvalidArgumentException('SharedWith should not be empty');
244
+            }
245
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
246
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
247
+            if ($circle === null) {
248
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
249
+            }
250
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_ROOM) {
251
+        } else {
252
+            // We can't handle other types yet
253
+            throw new \InvalidArgumentException('unknown share type');
254
+        }
255
+
256
+        // Verify the initiator of the share is set
257
+        if ($share->getSharedBy() === null) {
258
+            throw new \InvalidArgumentException('SharedBy should be set');
259
+        }
260
+
261
+        // Cannot share with yourself
262
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
263
+            $share->getSharedWith() === $share->getSharedBy()) {
264
+            throw new \InvalidArgumentException('Can’t share with yourself');
265
+        }
266
+
267
+        // The path should be set
268
+        if ($share->getNode() === null) {
269
+            throw new \InvalidArgumentException('Path should be set');
270
+        }
271
+
272
+        // And it should be a file or a folder
273
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
274
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
275
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
276
+        }
277
+
278
+        // And you can't share your rootfolder
279
+        if ($this->userManager->userExists($share->getSharedBy())) {
280
+            $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
281
+            $userFolderPath = $userFolder->getPath();
282
+        } else {
283
+            $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
284
+            $userFolderPath = $userFolder->getPath();
285
+        }
286
+        if ($userFolderPath === $share->getNode()->getPath()) {
287
+            throw new \InvalidArgumentException('You can’t share your root folder');
288
+        }
289
+
290
+        // Check if we actually have share permissions
291
+        if (!$share->getNode()->isShareable()) {
292
+            $path = $userFolder->getRelativePath($share->getNode()->getPath());
293
+            $message_t = $this->l->t('You are not allowed to share %s', [$path]);
294
+            throw new GenericShareException($message_t, $message_t, 404);
295
+        }
296
+
297
+        // Permissions should be set
298
+        if ($share->getPermissions() === null) {
299
+            throw new \InvalidArgumentException('A share requires permissions');
300
+        }
301
+
302
+        $isFederatedShare = $share->getNode()->getStorage()->instanceOfStorage('\OCA\Files_Sharing\External\Storage');
303
+        $permissions = 0;
304
+        $mount = $share->getNode()->getMountPoint();
305
+        if (!$isFederatedShare && $share->getNode()->getOwner()->getUID() !== $share->getSharedBy()) {
306
+            // When it's a reshare use the parent share permissions as maximum
307
+            $userMountPointId = $mount->getStorageRootId();
308
+            $userMountPoints = $userFolder->getById($userMountPointId);
309
+            $userMountPoint = array_shift($userMountPoints);
310
+
311
+            /* Check if this is an incoming share */
312
+            $incomingShares = $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_USER, $userMountPoint, -1, 0);
313
+            $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_GROUP, $userMountPoint, -1, 0));
314
+            $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_CIRCLE, $userMountPoint, -1, 0));
315
+            $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_ROOM, $userMountPoint, -1, 0));
316
+
317
+            /** @var \OCP\Share\IShare[] $incomingShares */
318
+            if (!empty($incomingShares)) {
319
+                foreach ($incomingShares as $incomingShare) {
320
+                    $permissions |= $incomingShare->getPermissions();
321
+                }
322
+            }
323
+        } else {
324
+            /*
325 325
 			 * Quick fix for #23536
326 326
 			 * Non moveable mount points do not have update and delete permissions
327 327
 			 * while we 'most likely' do have that on the storage.
328 328
 			 */
329
-			$permissions = $share->getNode()->getPermissions();
330
-			if (!($mount instanceof MoveableMount)) {
331
-				$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
332
-			}
333
-		}
334
-
335
-		// Check that we do not share with more permissions than we have
336
-		if ($share->getPermissions() & ~$permissions) {
337
-			$path = $userFolder->getRelativePath($share->getNode()->getPath());
338
-			$message_t = $this->l->t('Can’t increase permissions of %s', [$path]);
339
-			throw new GenericShareException($message_t, $message_t, 404);
340
-		}
341
-
342
-
343
-		// Check that read permissions are always set
344
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
345
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
346
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
347
-		if (!$noReadPermissionRequired &&
348
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
349
-			throw new \InvalidArgumentException('Shares need at least read permissions');
350
-		}
351
-
352
-		if ($share->getNode() instanceof \OCP\Files\File) {
353
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
354
-				$message_t = $this->l->t('Files can’t be shared with delete permissions');
355
-				throw new GenericShareException($message_t);
356
-			}
357
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
358
-				$message_t = $this->l->t('Files can’t be shared with create permissions');
359
-				throw new GenericShareException($message_t);
360
-			}
361
-		}
362
-	}
363
-
364
-	/**
365
-	 * Validate if the expiration date fits the system settings
366
-	 *
367
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
368
-	 * @return \OCP\Share\IShare The modified share object
369
-	 * @throws GenericShareException
370
-	 * @throws \InvalidArgumentException
371
-	 * @throws \Exception
372
-	 */
373
-	protected function validateExpirationDateInternal(\OCP\Share\IShare $share) {
374
-		$expirationDate = $share->getExpirationDate();
375
-
376
-		if ($expirationDate !== null) {
377
-			//Make sure the expiration date is a date
378
-			$expirationDate->setTime(0, 0, 0);
379
-
380
-			$date = new \DateTime();
381
-			$date->setTime(0, 0, 0);
382
-			if ($date >= $expirationDate) {
383
-				$message = $this->l->t('Expiration date is in the past');
384
-				throw new GenericShareException($message, $message, 404);
385
-			}
386
-		}
387
-
388
-		// If expiredate is empty set a default one if there is a default
389
-		$fullId = null;
390
-		try {
391
-			$fullId = $share->getFullId();
392
-		} catch (\UnexpectedValueException $e) {
393
-			// This is a new share
394
-		}
395
-
396
-		if ($fullId === null && $expirationDate === null && $this->shareApiInternalDefaultExpireDate()) {
397
-			$expirationDate = new \DateTime();
398
-			$expirationDate->setTime(0,0,0);
399
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiInternalDefaultExpireDays().'D'));
400
-		}
401
-
402
-		// If we enforce the expiration date check that is does not exceed
403
-		if ($this->shareApiInternalDefaultExpireDateEnforced()) {
404
-			if ($expirationDate === null) {
405
-				throw new \InvalidArgumentException('Expiration date is enforced');
406
-			}
407
-
408
-			$date = new \DateTime();
409
-			$date->setTime(0, 0, 0);
410
-			$date->add(new \DateInterval('P' . $this->shareApiInternalDefaultExpireDays() . 'D'));
411
-			if ($date < $expirationDate) {
412
-				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiInternalDefaultExpireDays()]);
413
-				throw new GenericShareException($message, $message, 404);
414
-			}
415
-		}
416
-
417
-		$accepted = true;
418
-		$message = '';
419
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
420
-			'expirationDate' => &$expirationDate,
421
-			'accepted' => &$accepted,
422
-			'message' => &$message,
423
-			'passwordSet' => $share->getPassword() !== null,
424
-		]);
425
-
426
-		if (!$accepted) {
427
-			throw new \Exception($message);
428
-		}
429
-
430
-		$share->setExpirationDate($expirationDate);
431
-
432
-		return $share;
433
-	}
434
-
435
-	/**
436
-	 * Validate if the expiration date fits the system settings
437
-	 *
438
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
439
-	 * @return \OCP\Share\IShare The modified share object
440
-	 * @throws GenericShareException
441
-	 * @throws \InvalidArgumentException
442
-	 * @throws \Exception
443
-	 */
444
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
445
-
446
-		$expirationDate = $share->getExpirationDate();
447
-
448
-		if ($expirationDate !== null) {
449
-			//Make sure the expiration date is a date
450
-			$expirationDate->setTime(0, 0, 0);
451
-
452
-			$date = new \DateTime();
453
-			$date->setTime(0, 0, 0);
454
-			if ($date >= $expirationDate) {
455
-				$message = $this->l->t('Expiration date is in the past');
456
-				throw new GenericShareException($message, $message, 404);
457
-			}
458
-		}
459
-
460
-		// If expiredate is empty set a default one if there is a default
461
-		$fullId = null;
462
-		try {
463
-			$fullId = $share->getFullId();
464
-		} catch (\UnexpectedValueException $e) {
465
-			// This is a new share
466
-		}
467
-
468
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
469
-			$expirationDate = new \DateTime();
470
-			$expirationDate->setTime(0,0,0);
471
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
472
-		}
473
-
474
-		// If we enforce the expiration date check that is does not exceed
475
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
476
-			if ($expirationDate === null) {
477
-				throw new \InvalidArgumentException('Expiration date is enforced');
478
-			}
479
-
480
-			$date = new \DateTime();
481
-			$date->setTime(0, 0, 0);
482
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
483
-			if ($date < $expirationDate) {
484
-				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
485
-				throw new GenericShareException($message, $message, 404);
486
-			}
487
-		}
488
-
489
-		$accepted = true;
490
-		$message = '';
491
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
492
-			'expirationDate' => &$expirationDate,
493
-			'accepted' => &$accepted,
494
-			'message' => &$message,
495
-			'passwordSet' => $share->getPassword() !== null,
496
-		]);
497
-
498
-		if (!$accepted) {
499
-			throw new \Exception($message);
500
-		}
501
-
502
-		$share->setExpirationDate($expirationDate);
503
-
504
-		return $share;
505
-	}
506
-
507
-	/**
508
-	 * Check for pre share requirements for user shares
509
-	 *
510
-	 * @param \OCP\Share\IShare $share
511
-	 * @throws \Exception
512
-	 */
513
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
514
-		// Check if we can share with group members only
515
-		if ($this->shareWithGroupMembersOnly()) {
516
-			$sharedBy = $this->userManager->get($share->getSharedBy());
517
-			$sharedWith = $this->userManager->get($share->getSharedWith());
518
-			// Verify we can share with this user
519
-			$groups = array_intersect(
520
-					$this->groupManager->getUserGroupIds($sharedBy),
521
-					$this->groupManager->getUserGroupIds($sharedWith)
522
-			);
523
-			if (empty($groups)) {
524
-				throw new \Exception('Sharing is only allowed with group members');
525
-			}
526
-		}
527
-
528
-		/*
329
+            $permissions = $share->getNode()->getPermissions();
330
+            if (!($mount instanceof MoveableMount)) {
331
+                $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
332
+            }
333
+        }
334
+
335
+        // Check that we do not share with more permissions than we have
336
+        if ($share->getPermissions() & ~$permissions) {
337
+            $path = $userFolder->getRelativePath($share->getNode()->getPath());
338
+            $message_t = $this->l->t('Can’t increase permissions of %s', [$path]);
339
+            throw new GenericShareException($message_t, $message_t, 404);
340
+        }
341
+
342
+
343
+        // Check that read permissions are always set
344
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
345
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
346
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
347
+        if (!$noReadPermissionRequired &&
348
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
349
+            throw new \InvalidArgumentException('Shares need at least read permissions');
350
+        }
351
+
352
+        if ($share->getNode() instanceof \OCP\Files\File) {
353
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
354
+                $message_t = $this->l->t('Files can’t be shared with delete permissions');
355
+                throw new GenericShareException($message_t);
356
+            }
357
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
358
+                $message_t = $this->l->t('Files can’t be shared with create permissions');
359
+                throw new GenericShareException($message_t);
360
+            }
361
+        }
362
+    }
363
+
364
+    /**
365
+     * Validate if the expiration date fits the system settings
366
+     *
367
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
368
+     * @return \OCP\Share\IShare The modified share object
369
+     * @throws GenericShareException
370
+     * @throws \InvalidArgumentException
371
+     * @throws \Exception
372
+     */
373
+    protected function validateExpirationDateInternal(\OCP\Share\IShare $share) {
374
+        $expirationDate = $share->getExpirationDate();
375
+
376
+        if ($expirationDate !== null) {
377
+            //Make sure the expiration date is a date
378
+            $expirationDate->setTime(0, 0, 0);
379
+
380
+            $date = new \DateTime();
381
+            $date->setTime(0, 0, 0);
382
+            if ($date >= $expirationDate) {
383
+                $message = $this->l->t('Expiration date is in the past');
384
+                throw new GenericShareException($message, $message, 404);
385
+            }
386
+        }
387
+
388
+        // If expiredate is empty set a default one if there is a default
389
+        $fullId = null;
390
+        try {
391
+            $fullId = $share->getFullId();
392
+        } catch (\UnexpectedValueException $e) {
393
+            // This is a new share
394
+        }
395
+
396
+        if ($fullId === null && $expirationDate === null && $this->shareApiInternalDefaultExpireDate()) {
397
+            $expirationDate = new \DateTime();
398
+            $expirationDate->setTime(0,0,0);
399
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiInternalDefaultExpireDays().'D'));
400
+        }
401
+
402
+        // If we enforce the expiration date check that is does not exceed
403
+        if ($this->shareApiInternalDefaultExpireDateEnforced()) {
404
+            if ($expirationDate === null) {
405
+                throw new \InvalidArgumentException('Expiration date is enforced');
406
+            }
407
+
408
+            $date = new \DateTime();
409
+            $date->setTime(0, 0, 0);
410
+            $date->add(new \DateInterval('P' . $this->shareApiInternalDefaultExpireDays() . 'D'));
411
+            if ($date < $expirationDate) {
412
+                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiInternalDefaultExpireDays()]);
413
+                throw new GenericShareException($message, $message, 404);
414
+            }
415
+        }
416
+
417
+        $accepted = true;
418
+        $message = '';
419
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
420
+            'expirationDate' => &$expirationDate,
421
+            'accepted' => &$accepted,
422
+            'message' => &$message,
423
+            'passwordSet' => $share->getPassword() !== null,
424
+        ]);
425
+
426
+        if (!$accepted) {
427
+            throw new \Exception($message);
428
+        }
429
+
430
+        $share->setExpirationDate($expirationDate);
431
+
432
+        return $share;
433
+    }
434
+
435
+    /**
436
+     * Validate if the expiration date fits the system settings
437
+     *
438
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
439
+     * @return \OCP\Share\IShare The modified share object
440
+     * @throws GenericShareException
441
+     * @throws \InvalidArgumentException
442
+     * @throws \Exception
443
+     */
444
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
445
+
446
+        $expirationDate = $share->getExpirationDate();
447
+
448
+        if ($expirationDate !== null) {
449
+            //Make sure the expiration date is a date
450
+            $expirationDate->setTime(0, 0, 0);
451
+
452
+            $date = new \DateTime();
453
+            $date->setTime(0, 0, 0);
454
+            if ($date >= $expirationDate) {
455
+                $message = $this->l->t('Expiration date is in the past');
456
+                throw new GenericShareException($message, $message, 404);
457
+            }
458
+        }
459
+
460
+        // If expiredate is empty set a default one if there is a default
461
+        $fullId = null;
462
+        try {
463
+            $fullId = $share->getFullId();
464
+        } catch (\UnexpectedValueException $e) {
465
+            // This is a new share
466
+        }
467
+
468
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
469
+            $expirationDate = new \DateTime();
470
+            $expirationDate->setTime(0,0,0);
471
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
472
+        }
473
+
474
+        // If we enforce the expiration date check that is does not exceed
475
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
476
+            if ($expirationDate === null) {
477
+                throw new \InvalidArgumentException('Expiration date is enforced');
478
+            }
479
+
480
+            $date = new \DateTime();
481
+            $date->setTime(0, 0, 0);
482
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
483
+            if ($date < $expirationDate) {
484
+                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
485
+                throw new GenericShareException($message, $message, 404);
486
+            }
487
+        }
488
+
489
+        $accepted = true;
490
+        $message = '';
491
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
492
+            'expirationDate' => &$expirationDate,
493
+            'accepted' => &$accepted,
494
+            'message' => &$message,
495
+            'passwordSet' => $share->getPassword() !== null,
496
+        ]);
497
+
498
+        if (!$accepted) {
499
+            throw new \Exception($message);
500
+        }
501
+
502
+        $share->setExpirationDate($expirationDate);
503
+
504
+        return $share;
505
+    }
506
+
507
+    /**
508
+     * Check for pre share requirements for user shares
509
+     *
510
+     * @param \OCP\Share\IShare $share
511
+     * @throws \Exception
512
+     */
513
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
514
+        // Check if we can share with group members only
515
+        if ($this->shareWithGroupMembersOnly()) {
516
+            $sharedBy = $this->userManager->get($share->getSharedBy());
517
+            $sharedWith = $this->userManager->get($share->getSharedWith());
518
+            // Verify we can share with this user
519
+            $groups = array_intersect(
520
+                    $this->groupManager->getUserGroupIds($sharedBy),
521
+                    $this->groupManager->getUserGroupIds($sharedWith)
522
+            );
523
+            if (empty($groups)) {
524
+                throw new \Exception('Sharing is only allowed with group members');
525
+            }
526
+        }
527
+
528
+        /*
529 529
 		 * TODO: Could be costly, fix
530 530
 		 *
531 531
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
532 532
 		 */
533
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
534
-		$existingShares = $provider->getSharesByPath($share->getNode());
535
-		foreach($existingShares as $existingShare) {
536
-			// Ignore if it is the same share
537
-			try {
538
-				if ($existingShare->getFullId() === $share->getFullId()) {
539
-					continue;
540
-				}
541
-			} catch (\UnexpectedValueException $e) {
542
-				//Shares are not identical
543
-			}
544
-
545
-			// Identical share already existst
546
-			if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
547
-				throw new \Exception('Path is already shared with this user');
548
-			}
549
-
550
-			// The share is already shared with this user via a group share
551
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
552
-				$group = $this->groupManager->get($existingShare->getSharedWith());
553
-				if (!is_null($group)) {
554
-					$user = $this->userManager->get($share->getSharedWith());
555
-
556
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
557
-						throw new \Exception('Path is already shared with this user');
558
-					}
559
-				}
560
-			}
561
-		}
562
-	}
563
-
564
-	/**
565
-	 * Check for pre share requirements for group shares
566
-	 *
567
-	 * @param \OCP\Share\IShare $share
568
-	 * @throws \Exception
569
-	 */
570
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
571
-		// Verify group shares are allowed
572
-		if (!$this->allowGroupSharing()) {
573
-			throw new \Exception('Group sharing is now allowed');
574
-		}
575
-
576
-		// Verify if the user can share with this group
577
-		if ($this->shareWithGroupMembersOnly()) {
578
-			$sharedBy = $this->userManager->get($share->getSharedBy());
579
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
580
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
581
-				throw new \Exception('Sharing is only allowed within your own groups');
582
-			}
583
-		}
584
-
585
-		/*
533
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
534
+        $existingShares = $provider->getSharesByPath($share->getNode());
535
+        foreach($existingShares as $existingShare) {
536
+            // Ignore if it is the same share
537
+            try {
538
+                if ($existingShare->getFullId() === $share->getFullId()) {
539
+                    continue;
540
+                }
541
+            } catch (\UnexpectedValueException $e) {
542
+                //Shares are not identical
543
+            }
544
+
545
+            // Identical share already existst
546
+            if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
547
+                throw new \Exception('Path is already shared with this user');
548
+            }
549
+
550
+            // The share is already shared with this user via a group share
551
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
552
+                $group = $this->groupManager->get($existingShare->getSharedWith());
553
+                if (!is_null($group)) {
554
+                    $user = $this->userManager->get($share->getSharedWith());
555
+
556
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
557
+                        throw new \Exception('Path is already shared with this user');
558
+                    }
559
+                }
560
+            }
561
+        }
562
+    }
563
+
564
+    /**
565
+     * Check for pre share requirements for group shares
566
+     *
567
+     * @param \OCP\Share\IShare $share
568
+     * @throws \Exception
569
+     */
570
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
571
+        // Verify group shares are allowed
572
+        if (!$this->allowGroupSharing()) {
573
+            throw new \Exception('Group sharing is now allowed');
574
+        }
575
+
576
+        // Verify if the user can share with this group
577
+        if ($this->shareWithGroupMembersOnly()) {
578
+            $sharedBy = $this->userManager->get($share->getSharedBy());
579
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
580
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
581
+                throw new \Exception('Sharing is only allowed within your own groups');
582
+            }
583
+        }
584
+
585
+        /*
586 586
 		 * TODO: Could be costly, fix
587 587
 		 *
588 588
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
589 589
 		 */
590
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
591
-		$existingShares = $provider->getSharesByPath($share->getNode());
592
-		foreach($existingShares as $existingShare) {
593
-			try {
594
-				if ($existingShare->getFullId() === $share->getFullId()) {
595
-					continue;
596
-				}
597
-			} catch (\UnexpectedValueException $e) {
598
-				//It is a new share so just continue
599
-			}
600
-
601
-			if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
602
-				throw new \Exception('Path is already shared with this group');
603
-			}
604
-		}
605
-	}
606
-
607
-	/**
608
-	 * Check for pre share requirements for link shares
609
-	 *
610
-	 * @param \OCP\Share\IShare $share
611
-	 * @throws \Exception
612
-	 */
613
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
614
-		// Are link shares allowed?
615
-		if (!$this->shareApiAllowLinks()) {
616
-			throw new \Exception('Link sharing is not allowed');
617
-		}
618
-
619
-		// Link shares by definition can't have share permissions
620
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
621
-			throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
622
-		}
623
-
624
-		// Check if public upload is allowed
625
-		if (!$this->shareApiLinkAllowPublicUpload() &&
626
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
627
-			throw new \InvalidArgumentException('Public upload is not allowed');
628
-		}
629
-	}
630
-
631
-	/**
632
-	 * To make sure we don't get invisible link shares we set the parent
633
-	 * of a link if it is a reshare. This is a quick word around
634
-	 * until we can properly display multiple link shares in the UI
635
-	 *
636
-	 * See: https://github.com/owncloud/core/issues/22295
637
-	 *
638
-	 * FIXME: Remove once multiple link shares can be properly displayed
639
-	 *
640
-	 * @param \OCP\Share\IShare $share
641
-	 */
642
-	protected function setLinkParent(\OCP\Share\IShare $share) {
643
-
644
-		// No sense in checking if the method is not there.
645
-		if (method_exists($share, 'setParent')) {
646
-			$storage = $share->getNode()->getStorage();
647
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
648
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
649
-				$share->setParent($storage->getShareId());
650
-			}
651
-		}
652
-	}
653
-
654
-	/**
655
-	 * @param File|Folder $path
656
-	 */
657
-	protected function pathCreateChecks($path) {
658
-		// Make sure that we do not share a path that contains a shared mountpoint
659
-		if ($path instanceof \OCP\Files\Folder) {
660
-			$mounts = $this->mountManager->findIn($path->getPath());
661
-			foreach($mounts as $mount) {
662
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
663
-					throw new \InvalidArgumentException('Path contains files shared with you');
664
-				}
665
-			}
666
-		}
667
-	}
668
-
669
-	/**
670
-	 * Check if the user that is sharing can actually share
671
-	 *
672
-	 * @param \OCP\Share\IShare $share
673
-	 * @throws \Exception
674
-	 */
675
-	protected function canShare(\OCP\Share\IShare $share) {
676
-		if (!$this->shareApiEnabled()) {
677
-			throw new \Exception('Sharing is disabled');
678
-		}
679
-
680
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
681
-			throw new \Exception('Sharing is disabled for you');
682
-		}
683
-	}
684
-
685
-	/**
686
-	 * Share a path
687
-	 *
688
-	 * @param \OCP\Share\IShare $share
689
-	 * @return Share The share object
690
-	 * @throws \Exception
691
-	 *
692
-	 * TODO: handle link share permissions or check them
693
-	 */
694
-	public function createShare(\OCP\Share\IShare $share) {
695
-		$this->canShare($share);
696
-
697
-		$this->generalCreateChecks($share);
698
-
699
-		// Verify if there are any issues with the path
700
-		$this->pathCreateChecks($share->getNode());
701
-
702
-		/*
590
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
591
+        $existingShares = $provider->getSharesByPath($share->getNode());
592
+        foreach($existingShares as $existingShare) {
593
+            try {
594
+                if ($existingShare->getFullId() === $share->getFullId()) {
595
+                    continue;
596
+                }
597
+            } catch (\UnexpectedValueException $e) {
598
+                //It is a new share so just continue
599
+            }
600
+
601
+            if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
602
+                throw new \Exception('Path is already shared with this group');
603
+            }
604
+        }
605
+    }
606
+
607
+    /**
608
+     * Check for pre share requirements for link shares
609
+     *
610
+     * @param \OCP\Share\IShare $share
611
+     * @throws \Exception
612
+     */
613
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
614
+        // Are link shares allowed?
615
+        if (!$this->shareApiAllowLinks()) {
616
+            throw new \Exception('Link sharing is not allowed');
617
+        }
618
+
619
+        // Link shares by definition can't have share permissions
620
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
621
+            throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
622
+        }
623
+
624
+        // Check if public upload is allowed
625
+        if (!$this->shareApiLinkAllowPublicUpload() &&
626
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
627
+            throw new \InvalidArgumentException('Public upload is not allowed');
628
+        }
629
+    }
630
+
631
+    /**
632
+     * To make sure we don't get invisible link shares we set the parent
633
+     * of a link if it is a reshare. This is a quick word around
634
+     * until we can properly display multiple link shares in the UI
635
+     *
636
+     * See: https://github.com/owncloud/core/issues/22295
637
+     *
638
+     * FIXME: Remove once multiple link shares can be properly displayed
639
+     *
640
+     * @param \OCP\Share\IShare $share
641
+     */
642
+    protected function setLinkParent(\OCP\Share\IShare $share) {
643
+
644
+        // No sense in checking if the method is not there.
645
+        if (method_exists($share, 'setParent')) {
646
+            $storage = $share->getNode()->getStorage();
647
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
648
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
649
+                $share->setParent($storage->getShareId());
650
+            }
651
+        }
652
+    }
653
+
654
+    /**
655
+     * @param File|Folder $path
656
+     */
657
+    protected function pathCreateChecks($path) {
658
+        // Make sure that we do not share a path that contains a shared mountpoint
659
+        if ($path instanceof \OCP\Files\Folder) {
660
+            $mounts = $this->mountManager->findIn($path->getPath());
661
+            foreach($mounts as $mount) {
662
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
663
+                    throw new \InvalidArgumentException('Path contains files shared with you');
664
+                }
665
+            }
666
+        }
667
+    }
668
+
669
+    /**
670
+     * Check if the user that is sharing can actually share
671
+     *
672
+     * @param \OCP\Share\IShare $share
673
+     * @throws \Exception
674
+     */
675
+    protected function canShare(\OCP\Share\IShare $share) {
676
+        if (!$this->shareApiEnabled()) {
677
+            throw new \Exception('Sharing is disabled');
678
+        }
679
+
680
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
681
+            throw new \Exception('Sharing is disabled for you');
682
+        }
683
+    }
684
+
685
+    /**
686
+     * Share a path
687
+     *
688
+     * @param \OCP\Share\IShare $share
689
+     * @return Share The share object
690
+     * @throws \Exception
691
+     *
692
+     * TODO: handle link share permissions or check them
693
+     */
694
+    public function createShare(\OCP\Share\IShare $share) {
695
+        $this->canShare($share);
696
+
697
+        $this->generalCreateChecks($share);
698
+
699
+        // Verify if there are any issues with the path
700
+        $this->pathCreateChecks($share->getNode());
701
+
702
+        /*
703 703
 		 * On creation of a share the owner is always the owner of the path
704 704
 		 * Except for mounted federated shares.
705 705
 		 */
706
-		$storage = $share->getNode()->getStorage();
707
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
708
-			$parent = $share->getNode()->getParent();
709
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
710
-				$parent = $parent->getParent();
711
-			}
712
-			$share->setShareOwner($parent->getOwner()->getUID());
713
-		} else {
714
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
715
-		}
716
-
717
-		//Verify share type
718
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
719
-			$this->userCreateChecks($share);
720
-
721
-			//Verify the expiration date
722
-			$share = $this->validateExpirationDateInternal($share);
723
-
724
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
725
-			$this->groupCreateChecks($share);
726
-
727
-			//Verify the expiration date
728
-			$share = $this->validateExpirationDateInternal($share);
729
-
730
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
731
-			$this->linkCreateChecks($share);
732
-			$this->setLinkParent($share);
733
-
734
-			/*
706
+        $storage = $share->getNode()->getStorage();
707
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
708
+            $parent = $share->getNode()->getParent();
709
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
710
+                $parent = $parent->getParent();
711
+            }
712
+            $share->setShareOwner($parent->getOwner()->getUID());
713
+        } else {
714
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
715
+        }
716
+
717
+        //Verify share type
718
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
719
+            $this->userCreateChecks($share);
720
+
721
+            //Verify the expiration date
722
+            $share = $this->validateExpirationDateInternal($share);
723
+
724
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
725
+            $this->groupCreateChecks($share);
726
+
727
+            //Verify the expiration date
728
+            $share = $this->validateExpirationDateInternal($share);
729
+
730
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
731
+            $this->linkCreateChecks($share);
732
+            $this->setLinkParent($share);
733
+
734
+            /*
735 735
 			 * For now ignore a set token.
736 736
 			 */
737
-			$share->setToken(
738
-				$this->secureRandom->generate(
739
-					\OC\Share\Constants::TOKEN_LENGTH,
740
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
741
-				)
742
-			);
743
-
744
-			//Verify the expiration date
745
-			$share = $this->validateExpirationDate($share);
746
-
747
-			//Verify the password
748
-			$this->verifyPassword($share->getPassword());
749
-
750
-			// If a password is set. Hash it!
751
-			if ($share->getPassword() !== null) {
752
-				$share->setPassword($this->hasher->hash($share->getPassword()));
753
-			}
754
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
755
-			$share->setToken(
756
-				$this->secureRandom->generate(
757
-					\OC\Share\Constants::TOKEN_LENGTH,
758
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
759
-				)
760
-			);
761
-		}
762
-
763
-		// Cannot share with the owner
764
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
765
-			$share->getSharedWith() === $share->getShareOwner()) {
766
-			throw new \InvalidArgumentException('Can’t share with the share owner');
767
-		}
768
-
769
-		// Generate the target
770
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
771
-		$target = \OC\Files\Filesystem::normalizePath($target);
772
-		$share->setTarget($target);
773
-
774
-		// Pre share event
775
-		$event = new GenericEvent($share);
776
-		$this->legacyDispatcher->dispatch('OCP\Share::preShare', $event);
777
-		if ($event->isPropagationStopped() && $event->hasArgument('error')) {
778
-			throw new \Exception($event->getArgument('error'));
779
-		}
780
-
781
-		$oldShare = $share;
782
-		$provider = $this->factory->getProviderForType($share->getShareType());
783
-		$share = $provider->create($share);
784
-		//reuse the node we already have
785
-		$share->setNode($oldShare->getNode());
786
-
787
-		// Reset the target if it is null for the new share
788
-		if ($share->getTarget() === '') {
789
-			$share->setTarget($target);
790
-		}
791
-
792
-		// Post share event
793
-		$event = new GenericEvent($share);
794
-		$this->legacyDispatcher->dispatch('OCP\Share::postShare', $event);
795
-
796
-		$this->dispatcher->dispatchTyped(new Share\Events\ShareCreatedEvent($share));
797
-
798
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
799
-			$mailSend = $share->getMailSend();
800
-			if($mailSend === true) {
801
-				$user = $this->userManager->get($share->getSharedWith());
802
-				if ($user !== null) {
803
-					$emailAddress = $user->getEMailAddress();
804
-					if ($emailAddress !== null && $emailAddress !== '') {
805
-						$userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
806
-						$l = $this->l10nFactory->get('lib', $userLang);
807
-						$this->sendMailNotification(
808
-							$l,
809
-							$share->getNode()->getName(),
810
-							$this->urlGenerator->linkToRouteAbsolute('files_sharing.Accept.accept', ['shareId' => $share->getFullId()]),
811
-							$share->getSharedBy(),
812
-							$emailAddress,
813
-							$share->getExpirationDate()
814
-						);
815
-						$this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
816
-					} else {
817
-						$this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
818
-					}
819
-				} else {
820
-					$this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
821
-				}
822
-			} else {
823
-				$this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']);
824
-			}
825
-		}
826
-
827
-		return $share;
828
-	}
829
-
830
-	/**
831
-	 * Send mail notifications
832
-	 *
833
-	 * This method will catch and log mail transmission errors
834
-	 *
835
-	 * @param IL10N $l Language of the recipient
836
-	 * @param string $filename file/folder name
837
-	 * @param string $link link to the file/folder
838
-	 * @param string $initiator user ID of share sender
839
-	 * @param string $shareWith email address of share receiver
840
-	 * @param \DateTime|null $expiration
841
-	 */
842
-	protected function sendMailNotification(IL10N $l,
843
-											$filename,
844
-											$link,
845
-											$initiator,
846
-											$shareWith,
847
-											\DateTime $expiration = null) {
848
-		$initiatorUser = $this->userManager->get($initiator);
849
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
850
-
851
-		$message = $this->mailer->createMessage();
852
-
853
-		$emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
854
-			'filename' => $filename,
855
-			'link' => $link,
856
-			'initiator' => $initiatorDisplayName,
857
-			'expiration' => $expiration,
858
-			'shareWith' => $shareWith,
859
-		]);
860
-
861
-		$emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]));
862
-		$emailTemplate->addHeader();
863
-		$emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
864
-		$text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
865
-
866
-		$emailTemplate->addBodyText(
867
-			htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
868
-			$text
869
-		);
870
-		$emailTemplate->addBodyButton(
871
-			$l->t('Open »%s«', [$filename]),
872
-			$link
873
-		);
874
-
875
-		$message->setTo([$shareWith]);
876
-
877
-		// The "From" contains the sharers name
878
-		$instanceName = $this->defaults->getName();
879
-		$senderName = $l->t(
880
-			'%1$s via %2$s',
881
-			[
882
-				$initiatorDisplayName,
883
-				$instanceName
884
-			]
885
-		);
886
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
887
-
888
-		// The "Reply-To" is set to the sharer if an mail address is configured
889
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
890
-		$initiatorEmail = $initiatorUser->getEMailAddress();
891
-		if($initiatorEmail !== null) {
892
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
893
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
894
-		} else {
895
-			$emailTemplate->addFooter();
896
-		}
897
-
898
-		$message->useTemplate($emailTemplate);
899
-		try {
900
-			$failedRecipients = $this->mailer->send($message);
901
-			if(!empty($failedRecipients)) {
902
-				$this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
903
-				return;
904
-			}
905
-		} catch (\Exception $e) {
906
-			$this->logger->logException($e, ['message' => 'Share notification mail could not be sent']);
907
-		}
908
-	}
909
-
910
-	/**
911
-	 * Update a share
912
-	 *
913
-	 * @param \OCP\Share\IShare $share
914
-	 * @return \OCP\Share\IShare The share object
915
-	 * @throws \InvalidArgumentException
916
-	 */
917
-	public function updateShare(\OCP\Share\IShare $share) {
918
-		$expirationDateUpdated = false;
919
-
920
-		$this->canShare($share);
921
-
922
-		try {
923
-			$originalShare = $this->getShareById($share->getFullId());
924
-		} catch (\UnexpectedValueException $e) {
925
-			throw new \InvalidArgumentException('Share does not have a full id');
926
-		}
927
-
928
-		// We can't change the share type!
929
-		if ($share->getShareType() !== $originalShare->getShareType()) {
930
-			throw new \InvalidArgumentException('Can’t change share type');
931
-		}
932
-
933
-		// We can only change the recipient on user shares
934
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
935
-			$share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
936
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
937
-		}
938
-
939
-		// Cannot share with the owner
940
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
941
-			$share->getSharedWith() === $share->getShareOwner()) {
942
-			throw new \InvalidArgumentException('Can’t share with the share owner');
943
-		}
944
-
945
-		$this->generalCreateChecks($share);
946
-
947
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
948
-			$this->userCreateChecks($share);
949
-
950
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
951
-				//Verify the expiration date
952
-				$this->validateExpirationDate($share);
953
-				$expirationDateUpdated = true;
954
-			}
955
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
956
-			$this->groupCreateChecks($share);
957
-
958
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
959
-				//Verify the expiration date
960
-				$this->validateExpirationDate($share);
961
-				$expirationDateUpdated = true;
962
-			}
963
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
964
-			$this->linkCreateChecks($share);
965
-
966
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
967
-
968
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
969
-				//Verify the expiration date
970
-				$this->validateExpirationDate($share);
971
-				$expirationDateUpdated = true;
972
-			}
973
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
974
-			// The new password is not set again if it is the same as the old
975
-			// one, unless when switching from sending by Talk to sending by
976
-			// mail.
977
-			$plainTextPassword = $share->getPassword();
978
-			if (!empty($plainTextPassword) && !$this->updateSharePasswordIfNeeded($share, $originalShare) &&
979
-					!($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk())) {
980
-				$plainTextPassword = null;
981
-			}
982
-			if (empty($plainTextPassword) && !$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) {
983
-				// If the same password was already sent by mail the recipient
984
-				// would already have access to the share without having to call
985
-				// the sharer to verify her identity
986
-				throw new \InvalidArgumentException('Can’t enable sending the password by Talk without setting a new password');
987
-			}
988
-		}
989
-
990
-		$this->pathCreateChecks($share->getNode());
991
-
992
-		// Now update the share!
993
-		$provider = $this->factory->getProviderForType($share->getShareType());
994
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
995
-			$share = $provider->update($share, $plainTextPassword);
996
-		} else {
997
-			$share = $provider->update($share);
998
-		}
999
-
1000
-		if ($expirationDateUpdated === true) {
1001
-			\OC_Hook::emit(Share::class, 'post_set_expiration_date', [
1002
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1003
-				'itemSource' => $share->getNode()->getId(),
1004
-				'date' => $share->getExpirationDate(),
1005
-				'uidOwner' => $share->getSharedBy(),
1006
-			]);
1007
-		}
1008
-
1009
-		if ($share->getPassword() !== $originalShare->getPassword()) {
1010
-			\OC_Hook::emit(Share::class, 'post_update_password', [
1011
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1012
-				'itemSource' => $share->getNode()->getId(),
1013
-				'uidOwner' => $share->getSharedBy(),
1014
-				'token' => $share->getToken(),
1015
-				'disabled' => is_null($share->getPassword()),
1016
-			]);
1017
-		}
1018
-
1019
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
1020
-			if ($this->userManager->userExists($share->getShareOwner())) {
1021
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
1022
-			} else {
1023
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
1024
-			}
1025
-			\OC_Hook::emit(Share::class, 'post_update_permissions', [
1026
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1027
-				'itemSource' => $share->getNode()->getId(),
1028
-				'shareType' => $share->getShareType(),
1029
-				'shareWith' => $share->getSharedWith(),
1030
-				'uidOwner' => $share->getSharedBy(),
1031
-				'permissions' => $share->getPermissions(),
1032
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
1033
-			]);
1034
-		}
1035
-
1036
-		return $share;
1037
-	}
1038
-
1039
-	/**
1040
-	 * Accept a share.
1041
-	 *
1042
-	 * @param IShare $share
1043
-	 * @param string $recipientId
1044
-	 * @return IShare The share object
1045
-	 * @throws \InvalidArgumentException
1046
-	 * @since 9.0.0
1047
-	 */
1048
-	public function acceptShare(IShare $share, string $recipientId): IShare {
1049
-		[$providerId, ] = $this->splitFullId($share->getFullId());
1050
-		$provider = $this->factory->getProvider($providerId);
1051
-
1052
-		if (!method_exists($provider, 'acceptShare')) {
1053
-			// TODO FIX ME
1054
-			throw new \InvalidArgumentException('Share provider does not support accepting');
1055
-		}
1056
-		$provider->acceptShare($share, $recipientId);
1057
-		$event = new GenericEvent($share);
1058
-		$this->legacyDispatcher->dispatch('OCP\Share::postAcceptShare', $event);
1059
-
1060
-		return $share;
1061
-	}
1062
-
1063
-	/**
1064
-	 * Updates the password of the given share if it is not the same as the
1065
-	 * password of the original share.
1066
-	 *
1067
-	 * @param \OCP\Share\IShare $share the share to update its password.
1068
-	 * @param \OCP\Share\IShare $originalShare the original share to compare its
1069
-	 *        password with.
1070
-	 * @return boolean whether the password was updated or not.
1071
-	 */
1072
-	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
1073
-		// Password updated.
1074
-		if ($share->getPassword() !== $originalShare->getPassword()) {
1075
-			//Verify the password
1076
-			$this->verifyPassword($share->getPassword());
1077
-
1078
-			// If a password is set. Hash it!
1079
-			if ($share->getPassword() !== null) {
1080
-				$share->setPassword($this->hasher->hash($share->getPassword()));
1081
-
1082
-				return true;
1083
-			}
1084
-		}
1085
-
1086
-		return false;
1087
-	}
1088
-
1089
-	/**
1090
-	 * Delete all the children of this share
1091
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
1092
-	 *
1093
-	 * @param \OCP\Share\IShare $share
1094
-	 * @return \OCP\Share\IShare[] List of deleted shares
1095
-	 */
1096
-	protected function deleteChildren(\OCP\Share\IShare $share) {
1097
-		$deletedShares = [];
1098
-
1099
-		$provider = $this->factory->getProviderForType($share->getShareType());
1100
-
1101
-		foreach ($provider->getChildren($share) as $child) {
1102
-			$deletedChildren = $this->deleteChildren($child);
1103
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
1104
-
1105
-			$provider->delete($child);
1106
-			$deletedShares[] = $child;
1107
-		}
1108
-
1109
-		return $deletedShares;
1110
-	}
1111
-
1112
-	/**
1113
-	 * Delete a share
1114
-	 *
1115
-	 * @param \OCP\Share\IShare $share
1116
-	 * @throws ShareNotFound
1117
-	 * @throws \InvalidArgumentException
1118
-	 */
1119
-	public function deleteShare(\OCP\Share\IShare $share) {
1120
-
1121
-		try {
1122
-			$share->getFullId();
1123
-		} catch (\UnexpectedValueException $e) {
1124
-			throw new \InvalidArgumentException('Share does not have a full id');
1125
-		}
1126
-
1127
-		$event = new GenericEvent($share);
1128
-		$this->legacyDispatcher->dispatch('OCP\Share::preUnshare', $event);
1129
-
1130
-		// Get all children and delete them as well
1131
-		$deletedShares = $this->deleteChildren($share);
1132
-
1133
-		// Do the actual delete
1134
-		$provider = $this->factory->getProviderForType($share->getShareType());
1135
-		$provider->delete($share);
1136
-
1137
-		// All the deleted shares caused by this delete
1138
-		$deletedShares[] = $share;
1139
-
1140
-		// Emit post hook
1141
-		$event->setArgument('deletedShares', $deletedShares);
1142
-		$this->legacyDispatcher->dispatch('OCP\Share::postUnshare', $event);
1143
-	}
1144
-
1145
-
1146
-	/**
1147
-	 * Unshare a file as the recipient.
1148
-	 * This can be different from a regular delete for example when one of
1149
-	 * the users in a groups deletes that share. But the provider should
1150
-	 * handle this.
1151
-	 *
1152
-	 * @param \OCP\Share\IShare $share
1153
-	 * @param string $recipientId
1154
-	 */
1155
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
1156
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1157
-		$provider = $this->factory->getProvider($providerId);
1158
-
1159
-		$provider->deleteFromSelf($share, $recipientId);
1160
-		$event = new GenericEvent($share);
1161
-		$this->legacyDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
1162
-	}
1163
-
1164
-	public function restoreShare(IShare $share, string $recipientId): IShare {
1165
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1166
-		$provider = $this->factory->getProvider($providerId);
1167
-
1168
-		return $provider->restore($share, $recipientId);
1169
-	}
1170
-
1171
-	/**
1172
-	 * @inheritdoc
1173
-	 */
1174
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
1175
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
1176
-			throw new \InvalidArgumentException('Can’t change target of link share');
1177
-		}
1178
-
1179
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
1180
-			throw new \InvalidArgumentException('Invalid recipient');
1181
-		}
1182
-
1183
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1184
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
1185
-			if (is_null($sharedWith)) {
1186
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1187
-			}
1188
-			$recipient = $this->userManager->get($recipientId);
1189
-			if (!$sharedWith->inGroup($recipient)) {
1190
-				throw new \InvalidArgumentException('Invalid recipient');
1191
-			}
1192
-		}
1193
-
1194
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1195
-		$provider = $this->factory->getProvider($providerId);
1196
-
1197
-		$provider->move($share, $recipientId);
1198
-	}
1199
-
1200
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1201
-		$providers = $this->factory->getAllProviders();
1202
-
1203
-		return array_reduce($providers, function ($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1204
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1205
-			foreach ($newShares as $fid => $data) {
1206
-				if (!isset($shares[$fid])) {
1207
-					$shares[$fid] = [];
1208
-				}
1209
-
1210
-				$shares[$fid] = array_merge($shares[$fid], $data);
1211
-			}
1212
-			return $shares;
1213
-		}, []);
1214
-	}
1215
-
1216
-	/**
1217
-	 * @inheritdoc
1218
-	 */
1219
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1220
-		if ($path !== null &&
1221
-				!($path instanceof \OCP\Files\File) &&
1222
-				!($path instanceof \OCP\Files\Folder)) {
1223
-			throw new \InvalidArgumentException('invalid path');
1224
-		}
1225
-
1226
-		try {
1227
-			$provider = $this->factory->getProviderForType($shareType);
1228
-		} catch (ProviderException $e) {
1229
-			return [];
1230
-		}
1231
-
1232
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1233
-
1234
-		/*
737
+            $share->setToken(
738
+                $this->secureRandom->generate(
739
+                    \OC\Share\Constants::TOKEN_LENGTH,
740
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
741
+                )
742
+            );
743
+
744
+            //Verify the expiration date
745
+            $share = $this->validateExpirationDate($share);
746
+
747
+            //Verify the password
748
+            $this->verifyPassword($share->getPassword());
749
+
750
+            // If a password is set. Hash it!
751
+            if ($share->getPassword() !== null) {
752
+                $share->setPassword($this->hasher->hash($share->getPassword()));
753
+            }
754
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
755
+            $share->setToken(
756
+                $this->secureRandom->generate(
757
+                    \OC\Share\Constants::TOKEN_LENGTH,
758
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
759
+                )
760
+            );
761
+        }
762
+
763
+        // Cannot share with the owner
764
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
765
+            $share->getSharedWith() === $share->getShareOwner()) {
766
+            throw new \InvalidArgumentException('Can’t share with the share owner');
767
+        }
768
+
769
+        // Generate the target
770
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
771
+        $target = \OC\Files\Filesystem::normalizePath($target);
772
+        $share->setTarget($target);
773
+
774
+        // Pre share event
775
+        $event = new GenericEvent($share);
776
+        $this->legacyDispatcher->dispatch('OCP\Share::preShare', $event);
777
+        if ($event->isPropagationStopped() && $event->hasArgument('error')) {
778
+            throw new \Exception($event->getArgument('error'));
779
+        }
780
+
781
+        $oldShare = $share;
782
+        $provider = $this->factory->getProviderForType($share->getShareType());
783
+        $share = $provider->create($share);
784
+        //reuse the node we already have
785
+        $share->setNode($oldShare->getNode());
786
+
787
+        // Reset the target if it is null for the new share
788
+        if ($share->getTarget() === '') {
789
+            $share->setTarget($target);
790
+        }
791
+
792
+        // Post share event
793
+        $event = new GenericEvent($share);
794
+        $this->legacyDispatcher->dispatch('OCP\Share::postShare', $event);
795
+
796
+        $this->dispatcher->dispatchTyped(new Share\Events\ShareCreatedEvent($share));
797
+
798
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
799
+            $mailSend = $share->getMailSend();
800
+            if($mailSend === true) {
801
+                $user = $this->userManager->get($share->getSharedWith());
802
+                if ($user !== null) {
803
+                    $emailAddress = $user->getEMailAddress();
804
+                    if ($emailAddress !== null && $emailAddress !== '') {
805
+                        $userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
806
+                        $l = $this->l10nFactory->get('lib', $userLang);
807
+                        $this->sendMailNotification(
808
+                            $l,
809
+                            $share->getNode()->getName(),
810
+                            $this->urlGenerator->linkToRouteAbsolute('files_sharing.Accept.accept', ['shareId' => $share->getFullId()]),
811
+                            $share->getSharedBy(),
812
+                            $emailAddress,
813
+                            $share->getExpirationDate()
814
+                        );
815
+                        $this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
816
+                    } else {
817
+                        $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
818
+                    }
819
+                } else {
820
+                    $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
821
+                }
822
+            } else {
823
+                $this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']);
824
+            }
825
+        }
826
+
827
+        return $share;
828
+    }
829
+
830
+    /**
831
+     * Send mail notifications
832
+     *
833
+     * This method will catch and log mail transmission errors
834
+     *
835
+     * @param IL10N $l Language of the recipient
836
+     * @param string $filename file/folder name
837
+     * @param string $link link to the file/folder
838
+     * @param string $initiator user ID of share sender
839
+     * @param string $shareWith email address of share receiver
840
+     * @param \DateTime|null $expiration
841
+     */
842
+    protected function sendMailNotification(IL10N $l,
843
+                                            $filename,
844
+                                            $link,
845
+                                            $initiator,
846
+                                            $shareWith,
847
+                                            \DateTime $expiration = null) {
848
+        $initiatorUser = $this->userManager->get($initiator);
849
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
850
+
851
+        $message = $this->mailer->createMessage();
852
+
853
+        $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
854
+            'filename' => $filename,
855
+            'link' => $link,
856
+            'initiator' => $initiatorDisplayName,
857
+            'expiration' => $expiration,
858
+            'shareWith' => $shareWith,
859
+        ]);
860
+
861
+        $emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]));
862
+        $emailTemplate->addHeader();
863
+        $emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
864
+        $text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
865
+
866
+        $emailTemplate->addBodyText(
867
+            htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
868
+            $text
869
+        );
870
+        $emailTemplate->addBodyButton(
871
+            $l->t('Open »%s«', [$filename]),
872
+            $link
873
+        );
874
+
875
+        $message->setTo([$shareWith]);
876
+
877
+        // The "From" contains the sharers name
878
+        $instanceName = $this->defaults->getName();
879
+        $senderName = $l->t(
880
+            '%1$s via %2$s',
881
+            [
882
+                $initiatorDisplayName,
883
+                $instanceName
884
+            ]
885
+        );
886
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
887
+
888
+        // The "Reply-To" is set to the sharer if an mail address is configured
889
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
890
+        $initiatorEmail = $initiatorUser->getEMailAddress();
891
+        if($initiatorEmail !== null) {
892
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
893
+            $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
894
+        } else {
895
+            $emailTemplate->addFooter();
896
+        }
897
+
898
+        $message->useTemplate($emailTemplate);
899
+        try {
900
+            $failedRecipients = $this->mailer->send($message);
901
+            if(!empty($failedRecipients)) {
902
+                $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
903
+                return;
904
+            }
905
+        } catch (\Exception $e) {
906
+            $this->logger->logException($e, ['message' => 'Share notification mail could not be sent']);
907
+        }
908
+    }
909
+
910
+    /**
911
+     * Update a share
912
+     *
913
+     * @param \OCP\Share\IShare $share
914
+     * @return \OCP\Share\IShare The share object
915
+     * @throws \InvalidArgumentException
916
+     */
917
+    public function updateShare(\OCP\Share\IShare $share) {
918
+        $expirationDateUpdated = false;
919
+
920
+        $this->canShare($share);
921
+
922
+        try {
923
+            $originalShare = $this->getShareById($share->getFullId());
924
+        } catch (\UnexpectedValueException $e) {
925
+            throw new \InvalidArgumentException('Share does not have a full id');
926
+        }
927
+
928
+        // We can't change the share type!
929
+        if ($share->getShareType() !== $originalShare->getShareType()) {
930
+            throw new \InvalidArgumentException('Can’t change share type');
931
+        }
932
+
933
+        // We can only change the recipient on user shares
934
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
935
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
936
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
937
+        }
938
+
939
+        // Cannot share with the owner
940
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
941
+            $share->getSharedWith() === $share->getShareOwner()) {
942
+            throw new \InvalidArgumentException('Can’t share with the share owner');
943
+        }
944
+
945
+        $this->generalCreateChecks($share);
946
+
947
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
948
+            $this->userCreateChecks($share);
949
+
950
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
951
+                //Verify the expiration date
952
+                $this->validateExpirationDate($share);
953
+                $expirationDateUpdated = true;
954
+            }
955
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
956
+            $this->groupCreateChecks($share);
957
+
958
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
959
+                //Verify the expiration date
960
+                $this->validateExpirationDate($share);
961
+                $expirationDateUpdated = true;
962
+            }
963
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
964
+            $this->linkCreateChecks($share);
965
+
966
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
967
+
968
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
969
+                //Verify the expiration date
970
+                $this->validateExpirationDate($share);
971
+                $expirationDateUpdated = true;
972
+            }
973
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
974
+            // The new password is not set again if it is the same as the old
975
+            // one, unless when switching from sending by Talk to sending by
976
+            // mail.
977
+            $plainTextPassword = $share->getPassword();
978
+            if (!empty($plainTextPassword) && !$this->updateSharePasswordIfNeeded($share, $originalShare) &&
979
+                    !($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk())) {
980
+                $plainTextPassword = null;
981
+            }
982
+            if (empty($plainTextPassword) && !$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) {
983
+                // If the same password was already sent by mail the recipient
984
+                // would already have access to the share without having to call
985
+                // the sharer to verify her identity
986
+                throw new \InvalidArgumentException('Can’t enable sending the password by Talk without setting a new password');
987
+            }
988
+        }
989
+
990
+        $this->pathCreateChecks($share->getNode());
991
+
992
+        // Now update the share!
993
+        $provider = $this->factory->getProviderForType($share->getShareType());
994
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
995
+            $share = $provider->update($share, $plainTextPassword);
996
+        } else {
997
+            $share = $provider->update($share);
998
+        }
999
+
1000
+        if ($expirationDateUpdated === true) {
1001
+            \OC_Hook::emit(Share::class, 'post_set_expiration_date', [
1002
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1003
+                'itemSource' => $share->getNode()->getId(),
1004
+                'date' => $share->getExpirationDate(),
1005
+                'uidOwner' => $share->getSharedBy(),
1006
+            ]);
1007
+        }
1008
+
1009
+        if ($share->getPassword() !== $originalShare->getPassword()) {
1010
+            \OC_Hook::emit(Share::class, 'post_update_password', [
1011
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1012
+                'itemSource' => $share->getNode()->getId(),
1013
+                'uidOwner' => $share->getSharedBy(),
1014
+                'token' => $share->getToken(),
1015
+                'disabled' => is_null($share->getPassword()),
1016
+            ]);
1017
+        }
1018
+
1019
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
1020
+            if ($this->userManager->userExists($share->getShareOwner())) {
1021
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
1022
+            } else {
1023
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
1024
+            }
1025
+            \OC_Hook::emit(Share::class, 'post_update_permissions', [
1026
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1027
+                'itemSource' => $share->getNode()->getId(),
1028
+                'shareType' => $share->getShareType(),
1029
+                'shareWith' => $share->getSharedWith(),
1030
+                'uidOwner' => $share->getSharedBy(),
1031
+                'permissions' => $share->getPermissions(),
1032
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
1033
+            ]);
1034
+        }
1035
+
1036
+        return $share;
1037
+    }
1038
+
1039
+    /**
1040
+     * Accept a share.
1041
+     *
1042
+     * @param IShare $share
1043
+     * @param string $recipientId
1044
+     * @return IShare The share object
1045
+     * @throws \InvalidArgumentException
1046
+     * @since 9.0.0
1047
+     */
1048
+    public function acceptShare(IShare $share, string $recipientId): IShare {
1049
+        [$providerId, ] = $this->splitFullId($share->getFullId());
1050
+        $provider = $this->factory->getProvider($providerId);
1051
+
1052
+        if (!method_exists($provider, 'acceptShare')) {
1053
+            // TODO FIX ME
1054
+            throw new \InvalidArgumentException('Share provider does not support accepting');
1055
+        }
1056
+        $provider->acceptShare($share, $recipientId);
1057
+        $event = new GenericEvent($share);
1058
+        $this->legacyDispatcher->dispatch('OCP\Share::postAcceptShare', $event);
1059
+
1060
+        return $share;
1061
+    }
1062
+
1063
+    /**
1064
+     * Updates the password of the given share if it is not the same as the
1065
+     * password of the original share.
1066
+     *
1067
+     * @param \OCP\Share\IShare $share the share to update its password.
1068
+     * @param \OCP\Share\IShare $originalShare the original share to compare its
1069
+     *        password with.
1070
+     * @return boolean whether the password was updated or not.
1071
+     */
1072
+    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
1073
+        // Password updated.
1074
+        if ($share->getPassword() !== $originalShare->getPassword()) {
1075
+            //Verify the password
1076
+            $this->verifyPassword($share->getPassword());
1077
+
1078
+            // If a password is set. Hash it!
1079
+            if ($share->getPassword() !== null) {
1080
+                $share->setPassword($this->hasher->hash($share->getPassword()));
1081
+
1082
+                return true;
1083
+            }
1084
+        }
1085
+
1086
+        return false;
1087
+    }
1088
+
1089
+    /**
1090
+     * Delete all the children of this share
1091
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
1092
+     *
1093
+     * @param \OCP\Share\IShare $share
1094
+     * @return \OCP\Share\IShare[] List of deleted shares
1095
+     */
1096
+    protected function deleteChildren(\OCP\Share\IShare $share) {
1097
+        $deletedShares = [];
1098
+
1099
+        $provider = $this->factory->getProviderForType($share->getShareType());
1100
+
1101
+        foreach ($provider->getChildren($share) as $child) {
1102
+            $deletedChildren = $this->deleteChildren($child);
1103
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
1104
+
1105
+            $provider->delete($child);
1106
+            $deletedShares[] = $child;
1107
+        }
1108
+
1109
+        return $deletedShares;
1110
+    }
1111
+
1112
+    /**
1113
+     * Delete a share
1114
+     *
1115
+     * @param \OCP\Share\IShare $share
1116
+     * @throws ShareNotFound
1117
+     * @throws \InvalidArgumentException
1118
+     */
1119
+    public function deleteShare(\OCP\Share\IShare $share) {
1120
+
1121
+        try {
1122
+            $share->getFullId();
1123
+        } catch (\UnexpectedValueException $e) {
1124
+            throw new \InvalidArgumentException('Share does not have a full id');
1125
+        }
1126
+
1127
+        $event = new GenericEvent($share);
1128
+        $this->legacyDispatcher->dispatch('OCP\Share::preUnshare', $event);
1129
+
1130
+        // Get all children and delete them as well
1131
+        $deletedShares = $this->deleteChildren($share);
1132
+
1133
+        // Do the actual delete
1134
+        $provider = $this->factory->getProviderForType($share->getShareType());
1135
+        $provider->delete($share);
1136
+
1137
+        // All the deleted shares caused by this delete
1138
+        $deletedShares[] = $share;
1139
+
1140
+        // Emit post hook
1141
+        $event->setArgument('deletedShares', $deletedShares);
1142
+        $this->legacyDispatcher->dispatch('OCP\Share::postUnshare', $event);
1143
+    }
1144
+
1145
+
1146
+    /**
1147
+     * Unshare a file as the recipient.
1148
+     * This can be different from a regular delete for example when one of
1149
+     * the users in a groups deletes that share. But the provider should
1150
+     * handle this.
1151
+     *
1152
+     * @param \OCP\Share\IShare $share
1153
+     * @param string $recipientId
1154
+     */
1155
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
1156
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1157
+        $provider = $this->factory->getProvider($providerId);
1158
+
1159
+        $provider->deleteFromSelf($share, $recipientId);
1160
+        $event = new GenericEvent($share);
1161
+        $this->legacyDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
1162
+    }
1163
+
1164
+    public function restoreShare(IShare $share, string $recipientId): IShare {
1165
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1166
+        $provider = $this->factory->getProvider($providerId);
1167
+
1168
+        return $provider->restore($share, $recipientId);
1169
+    }
1170
+
1171
+    /**
1172
+     * @inheritdoc
1173
+     */
1174
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
1175
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
1176
+            throw new \InvalidArgumentException('Can’t change target of link share');
1177
+        }
1178
+
1179
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
1180
+            throw new \InvalidArgumentException('Invalid recipient');
1181
+        }
1182
+
1183
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1184
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
1185
+            if (is_null($sharedWith)) {
1186
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1187
+            }
1188
+            $recipient = $this->userManager->get($recipientId);
1189
+            if (!$sharedWith->inGroup($recipient)) {
1190
+                throw new \InvalidArgumentException('Invalid recipient');
1191
+            }
1192
+        }
1193
+
1194
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1195
+        $provider = $this->factory->getProvider($providerId);
1196
+
1197
+        $provider->move($share, $recipientId);
1198
+    }
1199
+
1200
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1201
+        $providers = $this->factory->getAllProviders();
1202
+
1203
+        return array_reduce($providers, function ($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1204
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1205
+            foreach ($newShares as $fid => $data) {
1206
+                if (!isset($shares[$fid])) {
1207
+                    $shares[$fid] = [];
1208
+                }
1209
+
1210
+                $shares[$fid] = array_merge($shares[$fid], $data);
1211
+            }
1212
+            return $shares;
1213
+        }, []);
1214
+    }
1215
+
1216
+    /**
1217
+     * @inheritdoc
1218
+     */
1219
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1220
+        if ($path !== null &&
1221
+                !($path instanceof \OCP\Files\File) &&
1222
+                !($path instanceof \OCP\Files\Folder)) {
1223
+            throw new \InvalidArgumentException('invalid path');
1224
+        }
1225
+
1226
+        try {
1227
+            $provider = $this->factory->getProviderForType($shareType);
1228
+        } catch (ProviderException $e) {
1229
+            return [];
1230
+        }
1231
+
1232
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1233
+
1234
+        /*
1235 1235
 		 * Work around so we don't return expired shares but still follow
1236 1236
 		 * proper pagination.
1237 1237
 		 */
1238 1238
 
1239
-		$shares2 = [];
1240
-
1241
-		while(true) {
1242
-			$added = 0;
1243
-			foreach ($shares as $share) {
1244
-
1245
-				try {
1246
-					$this->checkExpireDate($share);
1247
-				} catch (ShareNotFound $e) {
1248
-					//Ignore since this basically means the share is deleted
1249
-					continue;
1250
-				}
1251
-
1252
-				$added++;
1253
-				$shares2[] = $share;
1254
-
1255
-				if (count($shares2) === $limit) {
1256
-					break;
1257
-				}
1258
-			}
1259
-
1260
-			// If we did not fetch more shares than the limit then there are no more shares
1261
-			if (count($shares) < $limit) {
1262
-				break;
1263
-			}
1264
-
1265
-			if (count($shares2) === $limit) {
1266
-				break;
1267
-			}
1268
-
1269
-			// If there was no limit on the select we are done
1270
-			if ($limit === -1) {
1271
-				break;
1272
-			}
1273
-
1274
-			$offset += $added;
1275
-
1276
-			// Fetch again $limit shares
1277
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1278
-
1279
-			// No more shares means we are done
1280
-			if (empty($shares)) {
1281
-				break;
1282
-			}
1283
-		}
1284
-
1285
-		$shares = $shares2;
1286
-
1287
-		return $shares;
1288
-	}
1289
-
1290
-	/**
1291
-	 * @inheritdoc
1292
-	 */
1293
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1294
-		try {
1295
-			$provider = $this->factory->getProviderForType($shareType);
1296
-		} catch (ProviderException $e) {
1297
-			return [];
1298
-		}
1299
-
1300
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1301
-
1302
-		// remove all shares which are already expired
1303
-		foreach ($shares as $key => $share) {
1304
-			try {
1305
-				$this->checkExpireDate($share);
1306
-			} catch (ShareNotFound $e) {
1307
-				unset($shares[$key]);
1308
-			}
1309
-		}
1310
-
1311
-		return $shares;
1312
-	}
1313
-
1314
-	/**
1315
-	 * @inheritdoc
1316
-	 */
1317
-	public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1318
-		$shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
1319
-
1320
-		// Only get deleted shares
1321
-		$shares = array_filter($shares, function (IShare $share) {
1322
-			return $share->getPermissions() === 0;
1323
-		});
1324
-
1325
-		// Only get shares where the owner still exists
1326
-		$shares = array_filter($shares, function (IShare $share) {
1327
-			return $this->userManager->userExists($share->getShareOwner());
1328
-		});
1329
-
1330
-		return $shares;
1331
-	}
1332
-
1333
-	/**
1334
-	 * @inheritdoc
1335
-	 */
1336
-	public function getShareById($id, $recipient = null) {
1337
-		if ($id === null) {
1338
-			throw new ShareNotFound();
1339
-		}
1340
-
1341
-		list($providerId, $id) = $this->splitFullId($id);
1342
-
1343
-		try {
1344
-			$provider = $this->factory->getProvider($providerId);
1345
-		} catch (ProviderException $e) {
1346
-			throw new ShareNotFound();
1347
-		}
1348
-
1349
-		$share = $provider->getShareById($id, $recipient);
1350
-
1351
-		$this->checkExpireDate($share);
1352
-
1353
-		return $share;
1354
-	}
1355
-
1356
-	/**
1357
-	 * Get all the shares for a given path
1358
-	 *
1359
-	 * @param \OCP\Files\Node $path
1360
-	 * @param int $page
1361
-	 * @param int $perPage
1362
-	 *
1363
-	 * @return Share[]
1364
-	 */
1365
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1366
-		return [];
1367
-	}
1368
-
1369
-	/**
1370
-	 * Get the share by token possible with password
1371
-	 *
1372
-	 * @param string $token
1373
-	 * @return Share
1374
-	 *
1375
-	 * @throws ShareNotFound
1376
-	 */
1377
-	public function getShareByToken($token) {
1378
-		// tokens can't be valid local user names
1379
-		if ($this->userManager->userExists($token)) {
1380
-			throw new ShareNotFound();
1381
-		}
1382
-		$share = null;
1383
-		try {
1384
-			if($this->shareApiAllowLinks()) {
1385
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1386
-				$share = $provider->getShareByToken($token);
1387
-			}
1388
-		} catch (ProviderException $e) {
1389
-		} catch (ShareNotFound $e) {
1390
-		}
1391
-
1392
-
1393
-		// If it is not a link share try to fetch a federated share by token
1394
-		if ($share === null) {
1395
-			try {
1396
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1397
-				$share = $provider->getShareByToken($token);
1398
-			} catch (ProviderException $e) {
1399
-			} catch (ShareNotFound $e) {
1400
-			}
1401
-		}
1402
-
1403
-		// If it is not a link share try to fetch a mail share by token
1404
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1405
-			try {
1406
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1407
-				$share = $provider->getShareByToken($token);
1408
-			} catch (ProviderException $e) {
1409
-			} catch (ShareNotFound $e) {
1410
-			}
1411
-		}
1412
-
1413
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1414
-			try {
1415
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1416
-				$share = $provider->getShareByToken($token);
1417
-			} catch (ProviderException $e) {
1418
-			} catch (ShareNotFound $e) {
1419
-			}
1420
-		}
1421
-
1422
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_ROOM)) {
1423
-			try {
1424
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_ROOM);
1425
-				$share = $provider->getShareByToken($token);
1426
-			} catch (ProviderException $e) {
1427
-			} catch (ShareNotFound $e) {
1428
-			}
1429
-		}
1430
-
1431
-		if ($share === null) {
1432
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1433
-		}
1434
-
1435
-		$this->checkExpireDate($share);
1436
-
1437
-		/*
1239
+        $shares2 = [];
1240
+
1241
+        while(true) {
1242
+            $added = 0;
1243
+            foreach ($shares as $share) {
1244
+
1245
+                try {
1246
+                    $this->checkExpireDate($share);
1247
+                } catch (ShareNotFound $e) {
1248
+                    //Ignore since this basically means the share is deleted
1249
+                    continue;
1250
+                }
1251
+
1252
+                $added++;
1253
+                $shares2[] = $share;
1254
+
1255
+                if (count($shares2) === $limit) {
1256
+                    break;
1257
+                }
1258
+            }
1259
+
1260
+            // If we did not fetch more shares than the limit then there are no more shares
1261
+            if (count($shares) < $limit) {
1262
+                break;
1263
+            }
1264
+
1265
+            if (count($shares2) === $limit) {
1266
+                break;
1267
+            }
1268
+
1269
+            // If there was no limit on the select we are done
1270
+            if ($limit === -1) {
1271
+                break;
1272
+            }
1273
+
1274
+            $offset += $added;
1275
+
1276
+            // Fetch again $limit shares
1277
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1278
+
1279
+            // No more shares means we are done
1280
+            if (empty($shares)) {
1281
+                break;
1282
+            }
1283
+        }
1284
+
1285
+        $shares = $shares2;
1286
+
1287
+        return $shares;
1288
+    }
1289
+
1290
+    /**
1291
+     * @inheritdoc
1292
+     */
1293
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1294
+        try {
1295
+            $provider = $this->factory->getProviderForType($shareType);
1296
+        } catch (ProviderException $e) {
1297
+            return [];
1298
+        }
1299
+
1300
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1301
+
1302
+        // remove all shares which are already expired
1303
+        foreach ($shares as $key => $share) {
1304
+            try {
1305
+                $this->checkExpireDate($share);
1306
+            } catch (ShareNotFound $e) {
1307
+                unset($shares[$key]);
1308
+            }
1309
+        }
1310
+
1311
+        return $shares;
1312
+    }
1313
+
1314
+    /**
1315
+     * @inheritdoc
1316
+     */
1317
+    public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1318
+        $shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
1319
+
1320
+        // Only get deleted shares
1321
+        $shares = array_filter($shares, function (IShare $share) {
1322
+            return $share->getPermissions() === 0;
1323
+        });
1324
+
1325
+        // Only get shares where the owner still exists
1326
+        $shares = array_filter($shares, function (IShare $share) {
1327
+            return $this->userManager->userExists($share->getShareOwner());
1328
+        });
1329
+
1330
+        return $shares;
1331
+    }
1332
+
1333
+    /**
1334
+     * @inheritdoc
1335
+     */
1336
+    public function getShareById($id, $recipient = null) {
1337
+        if ($id === null) {
1338
+            throw new ShareNotFound();
1339
+        }
1340
+
1341
+        list($providerId, $id) = $this->splitFullId($id);
1342
+
1343
+        try {
1344
+            $provider = $this->factory->getProvider($providerId);
1345
+        } catch (ProviderException $e) {
1346
+            throw new ShareNotFound();
1347
+        }
1348
+
1349
+        $share = $provider->getShareById($id, $recipient);
1350
+
1351
+        $this->checkExpireDate($share);
1352
+
1353
+        return $share;
1354
+    }
1355
+
1356
+    /**
1357
+     * Get all the shares for a given path
1358
+     *
1359
+     * @param \OCP\Files\Node $path
1360
+     * @param int $page
1361
+     * @param int $perPage
1362
+     *
1363
+     * @return Share[]
1364
+     */
1365
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1366
+        return [];
1367
+    }
1368
+
1369
+    /**
1370
+     * Get the share by token possible with password
1371
+     *
1372
+     * @param string $token
1373
+     * @return Share
1374
+     *
1375
+     * @throws ShareNotFound
1376
+     */
1377
+    public function getShareByToken($token) {
1378
+        // tokens can't be valid local user names
1379
+        if ($this->userManager->userExists($token)) {
1380
+            throw new ShareNotFound();
1381
+        }
1382
+        $share = null;
1383
+        try {
1384
+            if($this->shareApiAllowLinks()) {
1385
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1386
+                $share = $provider->getShareByToken($token);
1387
+            }
1388
+        } catch (ProviderException $e) {
1389
+        } catch (ShareNotFound $e) {
1390
+        }
1391
+
1392
+
1393
+        // If it is not a link share try to fetch a federated share by token
1394
+        if ($share === null) {
1395
+            try {
1396
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1397
+                $share = $provider->getShareByToken($token);
1398
+            } catch (ProviderException $e) {
1399
+            } catch (ShareNotFound $e) {
1400
+            }
1401
+        }
1402
+
1403
+        // If it is not a link share try to fetch a mail share by token
1404
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1405
+            try {
1406
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1407
+                $share = $provider->getShareByToken($token);
1408
+            } catch (ProviderException $e) {
1409
+            } catch (ShareNotFound $e) {
1410
+            }
1411
+        }
1412
+
1413
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1414
+            try {
1415
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1416
+                $share = $provider->getShareByToken($token);
1417
+            } catch (ProviderException $e) {
1418
+            } catch (ShareNotFound $e) {
1419
+            }
1420
+        }
1421
+
1422
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_ROOM)) {
1423
+            try {
1424
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_ROOM);
1425
+                $share = $provider->getShareByToken($token);
1426
+            } catch (ProviderException $e) {
1427
+            } catch (ShareNotFound $e) {
1428
+            }
1429
+        }
1430
+
1431
+        if ($share === null) {
1432
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1433
+        }
1434
+
1435
+        $this->checkExpireDate($share);
1436
+
1437
+        /*
1438 1438
 		 * Reduce the permissions for link shares if public upload is not enabled
1439 1439
 		 */
1440
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1441
-			!$this->shareApiLinkAllowPublicUpload()) {
1442
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1443
-		}
1444
-
1445
-		return $share;
1446
-	}
1447
-
1448
-	protected function checkExpireDate($share) {
1449
-		if ($share->isExpired()) {
1450
-			$this->deleteShare($share);
1451
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1452
-		}
1453
-
1454
-	}
1455
-
1456
-	/**
1457
-	 * Verify the password of a public share
1458
-	 *
1459
-	 * @param \OCP\Share\IShare $share
1460
-	 * @param string $password
1461
-	 * @return bool
1462
-	 */
1463
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1464
-		$passwordProtected = $share->getShareType() !== IShare::TYPE_LINK
1465
-							 || $share->getShareType() !== IShare::TYPE_EMAIL
1466
-							 || $share->getShareType() !== IShare::TYPE_CIRCLE;
1467
-		if (!$passwordProtected) {
1468
-			//TODO maybe exception?
1469
-			return false;
1470
-		}
1471
-
1472
-		if ($password === null || $share->getPassword() === null) {
1473
-			return false;
1474
-		}
1475
-
1476
-		$newHash = '';
1477
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1478
-			return false;
1479
-		}
1480
-
1481
-		if (!empty($newHash)) {
1482
-			$share->setPassword($newHash);
1483
-			$provider = $this->factory->getProviderForType($share->getShareType());
1484
-			$provider->update($share);
1485
-		}
1486
-
1487
-		return true;
1488
-	}
1489
-
1490
-	/**
1491
-	 * @inheritdoc
1492
-	 */
1493
-	public function userDeleted($uid) {
1494
-		$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];
1495
-
1496
-		foreach ($types as $type) {
1497
-			try {
1498
-				$provider = $this->factory->getProviderForType($type);
1499
-			} catch (ProviderException $e) {
1500
-				continue;
1501
-			}
1502
-			$provider->userDeleted($uid, $type);
1503
-		}
1504
-	}
1505
-
1506
-	/**
1507
-	 * @inheritdoc
1508
-	 */
1509
-	public function groupDeleted($gid) {
1510
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1511
-		$provider->groupDeleted($gid);
1512
-	}
1513
-
1514
-	/**
1515
-	 * @inheritdoc
1516
-	 */
1517
-	public function userDeletedFromGroup($uid, $gid) {
1518
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1519
-		$provider->userDeletedFromGroup($uid, $gid);
1520
-	}
1521
-
1522
-	/**
1523
-	 * Get access list to a path. This means
1524
-	 * all the users that can access a given path.
1525
-	 *
1526
-	 * Consider:
1527
-	 * -root
1528
-	 * |-folder1 (23)
1529
-	 *  |-folder2 (32)
1530
-	 *   |-fileA (42)
1531
-	 *
1532
-	 * fileA is shared with user1 and user1@server1
1533
-	 * folder2 is shared with group2 (user4 is a member of group2)
1534
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1535
-	 *
1536
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1537
-	 * [
1538
-	 *  users  => [
1539
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1540
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1541
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1542
-	 *  ],
1543
-	 *  remote => [
1544
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1545
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1546
-	 *  ],
1547
-	 *  public => bool
1548
-	 *  mail => bool
1549
-	 * ]
1550
-	 *
1551
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1552
-	 * [
1553
-	 *  users  => ['user1', 'user2', 'user4'],
1554
-	 *  remote => bool,
1555
-	 *  public => bool
1556
-	 *  mail => bool
1557
-	 * ]
1558
-	 *
1559
-	 * This is required for encryption/activity
1560
-	 *
1561
-	 * @param \OCP\Files\Node $path
1562
-	 * @param bool $recursive Should we check all parent folders as well
1563
-	 * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1564
-	 * @return array
1565
-	 */
1566
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1567
-		$owner = $path->getOwner();
1568
-
1569
-		if ($owner === null) {
1570
-			return [];
1571
-		}
1572
-
1573
-		$owner = $owner->getUID();
1574
-
1575
-		if ($currentAccess) {
1576
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1577
-		} else {
1578
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1579
-		}
1580
-		if (!$this->userManager->userExists($owner)) {
1581
-			return $al;
1582
-		}
1583
-
1584
-		//Get node for the owner and correct the owner in case of external storages
1585
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1586
-		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1587
-			$nodes = $userFolder->getById($path->getId());
1588
-			$path = array_shift($nodes);
1589
-			if ($path->getOwner() === null) {
1590
-				return [];
1591
-			}
1592
-			$owner = $path->getOwner()->getUID();
1593
-		}
1594
-
1595
-		$providers = $this->factory->getAllProviders();
1596
-
1597
-		/** @var Node[] $nodes */
1598
-		$nodes = [];
1599
-
1600
-
1601
-		if ($currentAccess) {
1602
-			$ownerPath = $path->getPath();
1603
-			$ownerPath = explode('/', $ownerPath, 4);
1604
-			if (count($ownerPath) < 4) {
1605
-				$ownerPath = '';
1606
-			} else {
1607
-				$ownerPath = $ownerPath[3];
1608
-			}
1609
-			$al['users'][$owner] = [
1610
-				'node_id' => $path->getId(),
1611
-				'node_path' => '/' . $ownerPath,
1612
-			];
1613
-		} else {
1614
-			$al['users'][] = $owner;
1615
-		}
1616
-
1617
-		// Collect all the shares
1618
-		while ($path->getPath() !== $userFolder->getPath()) {
1619
-			$nodes[] = $path;
1620
-			if (!$recursive) {
1621
-				break;
1622
-			}
1623
-			$path = $path->getParent();
1624
-		}
1625
-
1626
-		foreach ($providers as $provider) {
1627
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1628
-
1629
-			foreach ($tmp as $k => $v) {
1630
-				if (isset($al[$k])) {
1631
-					if (is_array($al[$k])) {
1632
-						if ($currentAccess) {
1633
-							$al[$k] += $v;
1634
-						} else {
1635
-							$al[$k] = array_merge($al[$k], $v);
1636
-							$al[$k] = array_unique($al[$k]);
1637
-							$al[$k] = array_values($al[$k]);
1638
-						}
1639
-					} else {
1640
-						$al[$k] = $al[$k] || $v;
1641
-					}
1642
-				} else {
1643
-					$al[$k] = $v;
1644
-				}
1645
-			}
1646
-		}
1647
-
1648
-		return $al;
1649
-	}
1650
-
1651
-	/**
1652
-	 * Create a new share
1653
-	 * @return \OCP\Share\IShare
1654
-	 */
1655
-	public function newShare() {
1656
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1657
-	}
1658
-
1659
-	/**
1660
-	 * Is the share API enabled
1661
-	 *
1662
-	 * @return bool
1663
-	 */
1664
-	public function shareApiEnabled() {
1665
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1666
-	}
1667
-
1668
-	/**
1669
-	 * Is public link sharing enabled
1670
-	 *
1671
-	 * @return bool
1672
-	 */
1673
-	public function shareApiAllowLinks() {
1674
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1675
-	}
1676
-
1677
-	/**
1678
-	 * Is password on public link requires
1679
-	 *
1680
-	 * @return bool
1681
-	 */
1682
-	public function shareApiLinkEnforcePassword() {
1683
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1684
-	}
1685
-
1686
-	/**
1687
-	 * Is default link expire date enabled
1688
-	 *
1689
-	 * @return bool
1690
-	 */
1691
-	public function shareApiLinkDefaultExpireDate() {
1692
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1693
-	}
1694
-
1695
-	/**
1696
-	 * Is default link expire date enforced
1697
-	 *`
1698
-	 * @return bool
1699
-	 */
1700
-	public function shareApiLinkDefaultExpireDateEnforced() {
1701
-		return $this->shareApiLinkDefaultExpireDate() &&
1702
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1703
-	}
1704
-
1705
-
1706
-	/**
1707
-	 * Number of default link expire days
1708
-	 * @return int
1709
-	 */
1710
-	public function shareApiLinkDefaultExpireDays() {
1711
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1712
-	}
1713
-
1714
-	/**
1715
-	 * Is default internal expire date enabled
1716
-	 *
1717
-	 * @return bool
1718
-	 */
1719
-	public function shareApiInternalDefaultExpireDate(): bool {
1720
-		return $this->config->getAppValue('core', 'shareapi_default_internal_expire_date', 'no') === 'yes';
1721
-	}
1722
-
1723
-	/**
1724
-	 * Is default expire date enforced
1725
-	 *`
1726
-	 * @return bool
1727
-	 */
1728
-	public function shareApiInternalDefaultExpireDateEnforced(): bool {
1729
-		return $this->shareApiInternalDefaultExpireDate() &&
1730
-			$this->config->getAppValue('core', 'shareapi_enforce_internal_expire_date', 'no') === 'yes';
1731
-	}
1732
-
1733
-
1734
-	/**
1735
-	 * Number of default expire days
1736
-	 * @return int
1737
-	 */
1738
-	public function shareApiInternalDefaultExpireDays(): int {
1739
-		return (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
1740
-	}
1741
-
1742
-	/**
1743
-	 * Allow public upload on link shares
1744
-	 *
1745
-	 * @return bool
1746
-	 */
1747
-	public function shareApiLinkAllowPublicUpload() {
1748
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1749
-	}
1750
-
1751
-	/**
1752
-	 * check if user can only share with group members
1753
-	 * @return bool
1754
-	 */
1755
-	public function shareWithGroupMembersOnly() {
1756
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1757
-	}
1758
-
1759
-	/**
1760
-	 * Check if users can share with groups
1761
-	 * @return bool
1762
-	 */
1763
-	public function allowGroupSharing() {
1764
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1765
-	}
1766
-
1767
-	public function allowEnumeration(): bool {
1768
-		return $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
1769
-	}
1770
-
1771
-	public function limitEnumerationToGroups(): bool {
1772
-		return $this->allowEnumeration() &&
1773
-			$this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
1774
-	}
1775
-
1776
-	/**
1777
-	 * Copied from \OC_Util::isSharingDisabledForUser
1778
-	 *
1779
-	 * TODO: Deprecate fuction from OC_Util
1780
-	 *
1781
-	 * @param string $userId
1782
-	 * @return bool
1783
-	 */
1784
-	public function sharingDisabledForUser($userId) {
1785
-		if ($userId === null) {
1786
-			return false;
1787
-		}
1788
-
1789
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1790
-			return $this->sharingDisabledForUsersCache[$userId];
1791
-		}
1792
-
1793
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1794
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1795
-			$excludedGroups = json_decode($groupsList);
1796
-			if (is_null($excludedGroups)) {
1797
-				$excludedGroups = explode(',', $groupsList);
1798
-				$newValue = json_encode($excludedGroups);
1799
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1800
-			}
1801
-			$user = $this->userManager->get($userId);
1802
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1803
-			if (!empty($usersGroups)) {
1804
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1805
-				// if the user is only in groups which are disabled for sharing then
1806
-				// sharing is also disabled for the user
1807
-				if (empty($remainingGroups)) {
1808
-					$this->sharingDisabledForUsersCache[$userId] = true;
1809
-					return true;
1810
-				}
1811
-			}
1812
-		}
1813
-
1814
-		$this->sharingDisabledForUsersCache[$userId] = false;
1815
-		return false;
1816
-	}
1817
-
1818
-	/**
1819
-	 * @inheritdoc
1820
-	 */
1821
-	public function outgoingServer2ServerSharesAllowed() {
1822
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1823
-	}
1824
-
1825
-	/**
1826
-	 * @inheritdoc
1827
-	 */
1828
-	public function outgoingServer2ServerGroupSharesAllowed() {
1829
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
1830
-	}
1831
-
1832
-	/**
1833
-	 * @inheritdoc
1834
-	 */
1835
-	public function shareProviderExists($shareType) {
1836
-		try {
1837
-			$this->factory->getProviderForType($shareType);
1838
-		} catch (ProviderException $e) {
1839
-			return false;
1840
-		}
1841
-
1842
-		return true;
1843
-	}
1844
-
1845
-	public function getAllShares(): iterable {
1846
-		$providers = $this->factory->getAllProviders();
1847
-
1848
-		foreach ($providers as $provider) {
1849
-			yield from $provider->getAllShares();
1850
-		}
1851
-	}
1440
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1441
+            !$this->shareApiLinkAllowPublicUpload()) {
1442
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1443
+        }
1444
+
1445
+        return $share;
1446
+    }
1447
+
1448
+    protected function checkExpireDate($share) {
1449
+        if ($share->isExpired()) {
1450
+            $this->deleteShare($share);
1451
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1452
+        }
1453
+
1454
+    }
1455
+
1456
+    /**
1457
+     * Verify the password of a public share
1458
+     *
1459
+     * @param \OCP\Share\IShare $share
1460
+     * @param string $password
1461
+     * @return bool
1462
+     */
1463
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1464
+        $passwordProtected = $share->getShareType() !== IShare::TYPE_LINK
1465
+                             || $share->getShareType() !== IShare::TYPE_EMAIL
1466
+                             || $share->getShareType() !== IShare::TYPE_CIRCLE;
1467
+        if (!$passwordProtected) {
1468
+            //TODO maybe exception?
1469
+            return false;
1470
+        }
1471
+
1472
+        if ($password === null || $share->getPassword() === null) {
1473
+            return false;
1474
+        }
1475
+
1476
+        $newHash = '';
1477
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1478
+            return false;
1479
+        }
1480
+
1481
+        if (!empty($newHash)) {
1482
+            $share->setPassword($newHash);
1483
+            $provider = $this->factory->getProviderForType($share->getShareType());
1484
+            $provider->update($share);
1485
+        }
1486
+
1487
+        return true;
1488
+    }
1489
+
1490
+    /**
1491
+     * @inheritdoc
1492
+     */
1493
+    public function userDeleted($uid) {
1494
+        $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];
1495
+
1496
+        foreach ($types as $type) {
1497
+            try {
1498
+                $provider = $this->factory->getProviderForType($type);
1499
+            } catch (ProviderException $e) {
1500
+                continue;
1501
+            }
1502
+            $provider->userDeleted($uid, $type);
1503
+        }
1504
+    }
1505
+
1506
+    /**
1507
+     * @inheritdoc
1508
+     */
1509
+    public function groupDeleted($gid) {
1510
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1511
+        $provider->groupDeleted($gid);
1512
+    }
1513
+
1514
+    /**
1515
+     * @inheritdoc
1516
+     */
1517
+    public function userDeletedFromGroup($uid, $gid) {
1518
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1519
+        $provider->userDeletedFromGroup($uid, $gid);
1520
+    }
1521
+
1522
+    /**
1523
+     * Get access list to a path. This means
1524
+     * all the users that can access a given path.
1525
+     *
1526
+     * Consider:
1527
+     * -root
1528
+     * |-folder1 (23)
1529
+     *  |-folder2 (32)
1530
+     *   |-fileA (42)
1531
+     *
1532
+     * fileA is shared with user1 and user1@server1
1533
+     * folder2 is shared with group2 (user4 is a member of group2)
1534
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1535
+     *
1536
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1537
+     * [
1538
+     *  users  => [
1539
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1540
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1541
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1542
+     *  ],
1543
+     *  remote => [
1544
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1545
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1546
+     *  ],
1547
+     *  public => bool
1548
+     *  mail => bool
1549
+     * ]
1550
+     *
1551
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1552
+     * [
1553
+     *  users  => ['user1', 'user2', 'user4'],
1554
+     *  remote => bool,
1555
+     *  public => bool
1556
+     *  mail => bool
1557
+     * ]
1558
+     *
1559
+     * This is required for encryption/activity
1560
+     *
1561
+     * @param \OCP\Files\Node $path
1562
+     * @param bool $recursive Should we check all parent folders as well
1563
+     * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1564
+     * @return array
1565
+     */
1566
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1567
+        $owner = $path->getOwner();
1568
+
1569
+        if ($owner === null) {
1570
+            return [];
1571
+        }
1572
+
1573
+        $owner = $owner->getUID();
1574
+
1575
+        if ($currentAccess) {
1576
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1577
+        } else {
1578
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1579
+        }
1580
+        if (!$this->userManager->userExists($owner)) {
1581
+            return $al;
1582
+        }
1583
+
1584
+        //Get node for the owner and correct the owner in case of external storages
1585
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1586
+        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1587
+            $nodes = $userFolder->getById($path->getId());
1588
+            $path = array_shift($nodes);
1589
+            if ($path->getOwner() === null) {
1590
+                return [];
1591
+            }
1592
+            $owner = $path->getOwner()->getUID();
1593
+        }
1594
+
1595
+        $providers = $this->factory->getAllProviders();
1596
+
1597
+        /** @var Node[] $nodes */
1598
+        $nodes = [];
1599
+
1600
+
1601
+        if ($currentAccess) {
1602
+            $ownerPath = $path->getPath();
1603
+            $ownerPath = explode('/', $ownerPath, 4);
1604
+            if (count($ownerPath) < 4) {
1605
+                $ownerPath = '';
1606
+            } else {
1607
+                $ownerPath = $ownerPath[3];
1608
+            }
1609
+            $al['users'][$owner] = [
1610
+                'node_id' => $path->getId(),
1611
+                'node_path' => '/' . $ownerPath,
1612
+            ];
1613
+        } else {
1614
+            $al['users'][] = $owner;
1615
+        }
1616
+
1617
+        // Collect all the shares
1618
+        while ($path->getPath() !== $userFolder->getPath()) {
1619
+            $nodes[] = $path;
1620
+            if (!$recursive) {
1621
+                break;
1622
+            }
1623
+            $path = $path->getParent();
1624
+        }
1625
+
1626
+        foreach ($providers as $provider) {
1627
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1628
+
1629
+            foreach ($tmp as $k => $v) {
1630
+                if (isset($al[$k])) {
1631
+                    if (is_array($al[$k])) {
1632
+                        if ($currentAccess) {
1633
+                            $al[$k] += $v;
1634
+                        } else {
1635
+                            $al[$k] = array_merge($al[$k], $v);
1636
+                            $al[$k] = array_unique($al[$k]);
1637
+                            $al[$k] = array_values($al[$k]);
1638
+                        }
1639
+                    } else {
1640
+                        $al[$k] = $al[$k] || $v;
1641
+                    }
1642
+                } else {
1643
+                    $al[$k] = $v;
1644
+                }
1645
+            }
1646
+        }
1647
+
1648
+        return $al;
1649
+    }
1650
+
1651
+    /**
1652
+     * Create a new share
1653
+     * @return \OCP\Share\IShare
1654
+     */
1655
+    public function newShare() {
1656
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1657
+    }
1658
+
1659
+    /**
1660
+     * Is the share API enabled
1661
+     *
1662
+     * @return bool
1663
+     */
1664
+    public function shareApiEnabled() {
1665
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1666
+    }
1667
+
1668
+    /**
1669
+     * Is public link sharing enabled
1670
+     *
1671
+     * @return bool
1672
+     */
1673
+    public function shareApiAllowLinks() {
1674
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1675
+    }
1676
+
1677
+    /**
1678
+     * Is password on public link requires
1679
+     *
1680
+     * @return bool
1681
+     */
1682
+    public function shareApiLinkEnforcePassword() {
1683
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1684
+    }
1685
+
1686
+    /**
1687
+     * Is default link expire date enabled
1688
+     *
1689
+     * @return bool
1690
+     */
1691
+    public function shareApiLinkDefaultExpireDate() {
1692
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1693
+    }
1694
+
1695
+    /**
1696
+     * Is default link expire date enforced
1697
+     *`
1698
+     * @return bool
1699
+     */
1700
+    public function shareApiLinkDefaultExpireDateEnforced() {
1701
+        return $this->shareApiLinkDefaultExpireDate() &&
1702
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1703
+    }
1704
+
1705
+
1706
+    /**
1707
+     * Number of default link expire days
1708
+     * @return int
1709
+     */
1710
+    public function shareApiLinkDefaultExpireDays() {
1711
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1712
+    }
1713
+
1714
+    /**
1715
+     * Is default internal expire date enabled
1716
+     *
1717
+     * @return bool
1718
+     */
1719
+    public function shareApiInternalDefaultExpireDate(): bool {
1720
+        return $this->config->getAppValue('core', 'shareapi_default_internal_expire_date', 'no') === 'yes';
1721
+    }
1722
+
1723
+    /**
1724
+     * Is default expire date enforced
1725
+     *`
1726
+     * @return bool
1727
+     */
1728
+    public function shareApiInternalDefaultExpireDateEnforced(): bool {
1729
+        return $this->shareApiInternalDefaultExpireDate() &&
1730
+            $this->config->getAppValue('core', 'shareapi_enforce_internal_expire_date', 'no') === 'yes';
1731
+    }
1732
+
1733
+
1734
+    /**
1735
+     * Number of default expire days
1736
+     * @return int
1737
+     */
1738
+    public function shareApiInternalDefaultExpireDays(): int {
1739
+        return (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
1740
+    }
1741
+
1742
+    /**
1743
+     * Allow public upload on link shares
1744
+     *
1745
+     * @return bool
1746
+     */
1747
+    public function shareApiLinkAllowPublicUpload() {
1748
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1749
+    }
1750
+
1751
+    /**
1752
+     * check if user can only share with group members
1753
+     * @return bool
1754
+     */
1755
+    public function shareWithGroupMembersOnly() {
1756
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1757
+    }
1758
+
1759
+    /**
1760
+     * Check if users can share with groups
1761
+     * @return bool
1762
+     */
1763
+    public function allowGroupSharing() {
1764
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1765
+    }
1766
+
1767
+    public function allowEnumeration(): bool {
1768
+        return $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
1769
+    }
1770
+
1771
+    public function limitEnumerationToGroups(): bool {
1772
+        return $this->allowEnumeration() &&
1773
+            $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
1774
+    }
1775
+
1776
+    /**
1777
+     * Copied from \OC_Util::isSharingDisabledForUser
1778
+     *
1779
+     * TODO: Deprecate fuction from OC_Util
1780
+     *
1781
+     * @param string $userId
1782
+     * @return bool
1783
+     */
1784
+    public function sharingDisabledForUser($userId) {
1785
+        if ($userId === null) {
1786
+            return false;
1787
+        }
1788
+
1789
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1790
+            return $this->sharingDisabledForUsersCache[$userId];
1791
+        }
1792
+
1793
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1794
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1795
+            $excludedGroups = json_decode($groupsList);
1796
+            if (is_null($excludedGroups)) {
1797
+                $excludedGroups = explode(',', $groupsList);
1798
+                $newValue = json_encode($excludedGroups);
1799
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1800
+            }
1801
+            $user = $this->userManager->get($userId);
1802
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1803
+            if (!empty($usersGroups)) {
1804
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1805
+                // if the user is only in groups which are disabled for sharing then
1806
+                // sharing is also disabled for the user
1807
+                if (empty($remainingGroups)) {
1808
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1809
+                    return true;
1810
+                }
1811
+            }
1812
+        }
1813
+
1814
+        $this->sharingDisabledForUsersCache[$userId] = false;
1815
+        return false;
1816
+    }
1817
+
1818
+    /**
1819
+     * @inheritdoc
1820
+     */
1821
+    public function outgoingServer2ServerSharesAllowed() {
1822
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1823
+    }
1824
+
1825
+    /**
1826
+     * @inheritdoc
1827
+     */
1828
+    public function outgoingServer2ServerGroupSharesAllowed() {
1829
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
1830
+    }
1831
+
1832
+    /**
1833
+     * @inheritdoc
1834
+     */
1835
+    public function shareProviderExists($shareType) {
1836
+        try {
1837
+            $this->factory->getProviderForType($shareType);
1838
+        } catch (ProviderException $e) {
1839
+            return false;
1840
+        }
1841
+
1842
+        return true;
1843
+    }
1844
+
1845
+    public function getAllShares(): iterable {
1846
+        $providers = $this->factory->getAllProviders();
1847
+
1848
+        foreach ($providers as $provider) {
1849
+            yield from $provider->getAllShares();
1850
+        }
1851
+    }
1852 1852
 }
Please login to merge, or discard this patch.
Spacing   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
 			if ($share->getSharedWith() === null) {
235 235
 				throw new \InvalidArgumentException('SharedWith should not be empty');
236 236
 			}
237
-		}  else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
237
+		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
238 238
 			if ($share->getSharedWith() === null) {
239 239
 				throw new \InvalidArgumentException('SharedWith should not be empty');
240 240
 			}
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
 
396 396
 		if ($fullId === null && $expirationDate === null && $this->shareApiInternalDefaultExpireDate()) {
397 397
 			$expirationDate = new \DateTime();
398
-			$expirationDate->setTime(0,0,0);
398
+			$expirationDate->setTime(0, 0, 0);
399 399
 			$expirationDate->add(new \DateInterval('P'.$this->shareApiInternalDefaultExpireDays().'D'));
400 400
 		}
401 401
 
@@ -407,7 +407,7 @@  discard block
 block discarded – undo
407 407
 
408 408
 			$date = new \DateTime();
409 409
 			$date->setTime(0, 0, 0);
410
-			$date->add(new \DateInterval('P' . $this->shareApiInternalDefaultExpireDays() . 'D'));
410
+			$date->add(new \DateInterval('P'.$this->shareApiInternalDefaultExpireDays().'D'));
411 411
 			if ($date < $expirationDate) {
412 412
 				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiInternalDefaultExpireDays()]);
413 413
 				throw new GenericShareException($message, $message, 404);
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
 
468 468
 		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
469 469
 			$expirationDate = new \DateTime();
470
-			$expirationDate->setTime(0,0,0);
470
+			$expirationDate->setTime(0, 0, 0);
471 471
 			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
472 472
 		}
473 473
 
@@ -479,7 +479,7 @@  discard block
 block discarded – undo
479 479
 
480 480
 			$date = new \DateTime();
481 481
 			$date->setTime(0, 0, 0);
482
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
482
+			$date->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
483 483
 			if ($date < $expirationDate) {
484 484
 				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
485 485
 				throw new GenericShareException($message, $message, 404);
@@ -532,7 +532,7 @@  discard block
 block discarded – undo
532 532
 		 */
533 533
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
534 534
 		$existingShares = $provider->getSharesByPath($share->getNode());
535
-		foreach($existingShares as $existingShare) {
535
+		foreach ($existingShares as $existingShare) {
536 536
 			// Ignore if it is the same share
537 537
 			try {
538 538
 				if ($existingShare->getFullId() === $share->getFullId()) {
@@ -589,7 +589,7 @@  discard block
 block discarded – undo
589 589
 		 */
590 590
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
591 591
 		$existingShares = $provider->getSharesByPath($share->getNode());
592
-		foreach($existingShares as $existingShare) {
592
+		foreach ($existingShares as $existingShare) {
593 593
 			try {
594 594
 				if ($existingShare->getFullId() === $share->getFullId()) {
595 595
 					continue;
@@ -658,7 +658,7 @@  discard block
 block discarded – undo
658 658
 		// Make sure that we do not share a path that contains a shared mountpoint
659 659
 		if ($path instanceof \OCP\Files\Folder) {
660 660
 			$mounts = $this->mountManager->findIn($path->getPath());
661
-			foreach($mounts as $mount) {
661
+			foreach ($mounts as $mount) {
662 662
 				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
663 663
 					throw new \InvalidArgumentException('Path contains files shared with you');
664 664
 				}
@@ -706,7 +706,7 @@  discard block
 block discarded – undo
706 706
 		$storage = $share->getNode()->getStorage();
707 707
 		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
708 708
 			$parent = $share->getNode()->getParent();
709
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
709
+			while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
710 710
 				$parent = $parent->getParent();
711 711
 			}
712 712
 			$share->setShareOwner($parent->getOwner()->getUID());
@@ -767,7 +767,7 @@  discard block
 block discarded – undo
767 767
 		}
768 768
 
769 769
 		// Generate the target
770
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
770
+		$target = $this->config->getSystemValue('share_folder', '/').'/'.$share->getNode()->getName();
771 771
 		$target = \OC\Files\Filesystem::normalizePath($target);
772 772
 		$share->setTarget($target);
773 773
 
@@ -797,7 +797,7 @@  discard block
 block discarded – undo
797 797
 
798 798
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
799 799
 			$mailSend = $share->getMailSend();
800
-			if($mailSend === true) {
800
+			if ($mailSend === true) {
801 801
 				$user = $this->userManager->get($share->getSharedWith());
802 802
 				if ($user !== null) {
803 803
 					$emailAddress = $user->getEMailAddress();
@@ -812,12 +812,12 @@  discard block
 block discarded – undo
812 812
 							$emailAddress,
813 813
 							$share->getExpirationDate()
814 814
 						);
815
-						$this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
815
+						$this->logger->debug('Sent share notification to '.$emailAddress.' for share with ID '.$share->getId(), ['app' => 'share']);
816 816
 					} else {
817
-						$this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
817
+						$this->logger->debug('Share notification not sent to '.$share->getSharedWith().' because email address is not set.', ['app' => 'share']);
818 818
 					}
819 819
 				} else {
820
-					$this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
820
+					$this->logger->debug('Share notification not sent to '.$share->getSharedWith().' because user could not be found.', ['app' => 'share']);
821 821
 				}
822 822
 			} else {
823 823
 				$this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']);
@@ -864,7 +864,7 @@  discard block
 block discarded – undo
864 864
 		$text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
865 865
 
866 866
 		$emailTemplate->addBodyText(
867
-			htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
867
+			htmlspecialchars($text.' '.$l->t('Click the button below to open it.')),
868 868
 			$text
869 869
 		);
870 870
 		$emailTemplate->addBodyButton(
@@ -888,9 +888,9 @@  discard block
 block discarded – undo
888 888
 		// The "Reply-To" is set to the sharer if an mail address is configured
889 889
 		// also the default footer contains a "Do not reply" which needs to be adjusted.
890 890
 		$initiatorEmail = $initiatorUser->getEMailAddress();
891
-		if($initiatorEmail !== null) {
891
+		if ($initiatorEmail !== null) {
892 892
 			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
893
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
893
+			$emailTemplate->addFooter($instanceName.($this->defaults->getSlogan() !== '' ? ' - '.$this->defaults->getSlogan() : ''));
894 894
 		} else {
895 895
 			$emailTemplate->addFooter();
896 896
 		}
@@ -898,8 +898,8 @@  discard block
 block discarded – undo
898 898
 		$message->useTemplate($emailTemplate);
899 899
 		try {
900 900
 			$failedRecipients = $this->mailer->send($message);
901
-			if(!empty($failedRecipients)) {
902
-				$this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
901
+			if (!empty($failedRecipients)) {
902
+				$this->logger->error('Share notification mail could not be sent to: '.implode(', ', $failedRecipients));
903 903
 				return;
904 904
 			}
905 905
 		} catch (\Exception $e) {
@@ -1153,7 +1153,7 @@  discard block
 block discarded – undo
1153 1153
 	 * @param string $recipientId
1154 1154
 	 */
1155 1155
 	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
1156
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1156
+		list($providerId,) = $this->splitFullId($share->getFullId());
1157 1157
 		$provider = $this->factory->getProvider($providerId);
1158 1158
 
1159 1159
 		$provider->deleteFromSelf($share, $recipientId);
@@ -1162,7 +1162,7 @@  discard block
 block discarded – undo
1162 1162
 	}
1163 1163
 
1164 1164
 	public function restoreShare(IShare $share, string $recipientId): IShare {
1165
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1165
+		list($providerId,) = $this->splitFullId($share->getFullId());
1166 1166
 		$provider = $this->factory->getProvider($providerId);
1167 1167
 
1168 1168
 		return $provider->restore($share, $recipientId);
@@ -1183,7 +1183,7 @@  discard block
 block discarded – undo
1183 1183
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1184 1184
 			$sharedWith = $this->groupManager->get($share->getSharedWith());
1185 1185
 			if (is_null($sharedWith)) {
1186
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1186
+				throw new \InvalidArgumentException('Group "'.$share->getSharedWith().'" does not exist');
1187 1187
 			}
1188 1188
 			$recipient = $this->userManager->get($recipientId);
1189 1189
 			if (!$sharedWith->inGroup($recipient)) {
@@ -1191,7 +1191,7 @@  discard block
 block discarded – undo
1191 1191
 			}
1192 1192
 		}
1193 1193
 
1194
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1194
+		list($providerId,) = $this->splitFullId($share->getFullId());
1195 1195
 		$provider = $this->factory->getProvider($providerId);
1196 1196
 
1197 1197
 		$provider->move($share, $recipientId);
@@ -1200,7 +1200,7 @@  discard block
 block discarded – undo
1200 1200
 	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1201 1201
 		$providers = $this->factory->getAllProviders();
1202 1202
 
1203
-		return array_reduce($providers, function ($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1203
+		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1204 1204
 			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1205 1205
 			foreach ($newShares as $fid => $data) {
1206 1206
 				if (!isset($shares[$fid])) {
@@ -1238,7 +1238,7 @@  discard block
 block discarded – undo
1238 1238
 
1239 1239
 		$shares2 = [];
1240 1240
 
1241
-		while(true) {
1241
+		while (true) {
1242 1242
 			$added = 0;
1243 1243
 			foreach ($shares as $share) {
1244 1244
 
@@ -1318,12 +1318,12 @@  discard block
 block discarded – undo
1318 1318
 		$shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
1319 1319
 
1320 1320
 		// Only get deleted shares
1321
-		$shares = array_filter($shares, function (IShare $share) {
1321
+		$shares = array_filter($shares, function(IShare $share) {
1322 1322
 			return $share->getPermissions() === 0;
1323 1323
 		});
1324 1324
 
1325 1325
 		// Only get shares where the owner still exists
1326
-		$shares = array_filter($shares, function (IShare $share) {
1326
+		$shares = array_filter($shares, function(IShare $share) {
1327 1327
 			return $this->userManager->userExists($share->getShareOwner());
1328 1328
 		});
1329 1329
 
@@ -1362,7 +1362,7 @@  discard block
 block discarded – undo
1362 1362
 	 *
1363 1363
 	 * @return Share[]
1364 1364
 	 */
1365
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1365
+	public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) {
1366 1366
 		return [];
1367 1367
 	}
1368 1368
 
@@ -1381,7 +1381,7 @@  discard block
 block discarded – undo
1381 1381
 		}
1382 1382
 		$share = null;
1383 1383
 		try {
1384
-			if($this->shareApiAllowLinks()) {
1384
+			if ($this->shareApiAllowLinks()) {
1385 1385
 				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1386 1386
 				$share = $provider->getShareByToken($token);
1387 1387
 			}
@@ -1608,7 +1608,7 @@  discard block
 block discarded – undo
1608 1608
 			}
1609 1609
 			$al['users'][$owner] = [
1610 1610
 				'node_id' => $path->getId(),
1611
-				'node_path' => '/' . $ownerPath,
1611
+				'node_path' => '/'.$ownerPath,
1612 1612
 			];
1613 1613
 		} else {
1614 1614
 			$al['users'][] = $owner;
@@ -1708,7 +1708,7 @@  discard block
 block discarded – undo
1708 1708
 	 * @return int
1709 1709
 	 */
1710 1710
 	public function shareApiLinkDefaultExpireDays() {
1711
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1711
+		return (int) $this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1712 1712
 	}
1713 1713
 
1714 1714
 	/**
@@ -1736,7 +1736,7 @@  discard block
 block discarded – undo
1736 1736
 	 * @return int
1737 1737
 	 */
1738 1738
 	public function shareApiInternalDefaultExpireDays(): int {
1739
-		return (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
1739
+		return (int) $this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
1740 1740
 	}
1741 1741
 
1742 1742
 	/**
Please login to merge, or discard this patch.
lib/private/User/Backend.php 2 patches
Indentation   +120 added lines, -120 removed lines patch added patch discarded remove patch
@@ -31,136 +31,136 @@
 block discarded – undo
31 31
  * capabilities.
32 32
  */
33 33
 abstract class Backend implements UserInterface {
34
-	/**
35
-	 * error code for functions not provided by the user backend
36
-	 */
37
-	const NOT_IMPLEMENTED = -501;
34
+    /**
35
+     * error code for functions not provided by the user backend
36
+     */
37
+    const NOT_IMPLEMENTED = -501;
38 38
 
39
-	/**
40
-	 * actions that user backends can define
41
-	 */
42
-	const CREATE_USER		= 1;			// 1 << 0
43
-	const SET_PASSWORD		= 16;			// 1 << 4
44
-	const CHECK_PASSWORD	= 256;			// 1 << 8
45
-	const GET_HOME			= 4096;			// 1 << 12
46
-	const GET_DISPLAYNAME	= 65536;		// 1 << 16
47
-	const SET_DISPLAYNAME	= 1048576;		// 1 << 20
48
-	const PROVIDE_AVATAR	= 16777216;		// 1 << 24
49
-	const COUNT_USERS		= 268435456;	// 1 << 28
39
+    /**
40
+     * actions that user backends can define
41
+     */
42
+    const CREATE_USER		= 1;			// 1 << 0
43
+    const SET_PASSWORD		= 16;			// 1 << 4
44
+    const CHECK_PASSWORD	= 256;			// 1 << 8
45
+    const GET_HOME			= 4096;			// 1 << 12
46
+    const GET_DISPLAYNAME	= 65536;		// 1 << 16
47
+    const SET_DISPLAYNAME	= 1048576;		// 1 << 20
48
+    const PROVIDE_AVATAR	= 16777216;		// 1 << 24
49
+    const COUNT_USERS		= 268435456;	// 1 << 28
50 50
 
51
-	protected $possibleActions = [
52
-		self::CREATE_USER => 'createUser',
53
-		self::SET_PASSWORD => 'setPassword',
54
-		self::CHECK_PASSWORD => 'checkPassword',
55
-		self::GET_HOME => 'getHome',
56
-		self::GET_DISPLAYNAME => 'getDisplayName',
57
-		self::SET_DISPLAYNAME => 'setDisplayName',
58
-		self::PROVIDE_AVATAR => 'canChangeAvatar',
59
-		self::COUNT_USERS => 'countUsers',
60
-	];
51
+    protected $possibleActions = [
52
+        self::CREATE_USER => 'createUser',
53
+        self::SET_PASSWORD => 'setPassword',
54
+        self::CHECK_PASSWORD => 'checkPassword',
55
+        self::GET_HOME => 'getHome',
56
+        self::GET_DISPLAYNAME => 'getDisplayName',
57
+        self::SET_DISPLAYNAME => 'setDisplayName',
58
+        self::PROVIDE_AVATAR => 'canChangeAvatar',
59
+        self::COUNT_USERS => 'countUsers',
60
+    ];
61 61
 
62
-	/**
63
-	 * Get all supported actions
64
-	 * @return int bitwise-or'ed actions
65
-	 *
66
-	 * Returns the supported actions as int to be
67
-	 * compared with self::CREATE_USER etc.
68
-	 */
69
-	public function getSupportedActions() {
70
-		$actions = 0;
71
-		foreach($this->possibleActions AS $action => $methodName) {
72
-			if(method_exists($this, $methodName)) {
73
-				$actions |= $action;
74
-			}
75
-		}
62
+    /**
63
+     * Get all supported actions
64
+     * @return int bitwise-or'ed actions
65
+     *
66
+     * Returns the supported actions as int to be
67
+     * compared with self::CREATE_USER etc.
68
+     */
69
+    public function getSupportedActions() {
70
+        $actions = 0;
71
+        foreach($this->possibleActions AS $action => $methodName) {
72
+            if(method_exists($this, $methodName)) {
73
+                $actions |= $action;
74
+            }
75
+        }
76 76
 
77
-		return $actions;
78
-	}
77
+        return $actions;
78
+    }
79 79
 
80
-	/**
81
-	 * Check if backend implements actions
82
-	 * @param int $actions bitwise-or'ed actions
83
-	 * @return boolean
84
-	 *
85
-	 * Returns the supported actions as int to be
86
-	 * compared with self::CREATE_USER etc.
87
-	 */
88
-	public function implementsActions($actions) {
89
-		return (bool)($this->getSupportedActions() & $actions);
90
-	}
80
+    /**
81
+     * Check if backend implements actions
82
+     * @param int $actions bitwise-or'ed actions
83
+     * @return boolean
84
+     *
85
+     * Returns the supported actions as int to be
86
+     * compared with self::CREATE_USER etc.
87
+     */
88
+    public function implementsActions($actions) {
89
+        return (bool)($this->getSupportedActions() & $actions);
90
+    }
91 91
 
92
-	/**
93
-	 * delete a user
94
-	 * @param string $uid The username of the user to delete
95
-	 * @return bool
96
-	 *
97
-	 * Deletes a user
98
-	 */
99
-	public function deleteUser($uid) {
100
-		return false;
101
-	}
92
+    /**
93
+     * delete a user
94
+     * @param string $uid The username of the user to delete
95
+     * @return bool
96
+     *
97
+     * Deletes a user
98
+     */
99
+    public function deleteUser($uid) {
100
+        return false;
101
+    }
102 102
 
103
-	/**
104
-	 * Get a list of all users
105
-	 *
106
-	 * @param string $search
107
-	 * @param null|int $limit
108
-	 * @param null|int $offset
109
-	 * @return string[] an array of all uids
110
-	 */
111
-	public function getUsers($search = '', $limit = null, $offset = null) {
112
-		return [];
113
-	}
103
+    /**
104
+     * Get a list of all users
105
+     *
106
+     * @param string $search
107
+     * @param null|int $limit
108
+     * @param null|int $offset
109
+     * @return string[] an array of all uids
110
+     */
111
+    public function getUsers($search = '', $limit = null, $offset = null) {
112
+        return [];
113
+    }
114 114
 
115
-	/**
116
-	 * check if a user exists
117
-	 * @param string $uid the username
118
-	 * @return boolean
119
-	 */
120
-	public function userExists($uid) {
121
-		return false;
122
-	}
115
+    /**
116
+     * check if a user exists
117
+     * @param string $uid the username
118
+     * @return boolean
119
+     */
120
+    public function userExists($uid) {
121
+        return false;
122
+    }
123 123
 
124
-	/**
125
-	 * get the user's home directory
126
-	 * @param string $uid the username
127
-	 * @return boolean
128
-	 */
129
-	public function getHome($uid) {
130
-		return false;
131
-	}
124
+    /**
125
+     * get the user's home directory
126
+     * @param string $uid the username
127
+     * @return boolean
128
+     */
129
+    public function getHome($uid) {
130
+        return false;
131
+    }
132 132
 
133
-	/**
134
-	 * get display name of the user
135
-	 * @param string $uid user ID of the user
136
-	 * @return string display name
137
-	 */
138
-	public function getDisplayName($uid) {
139
-		return $uid;
140
-	}
133
+    /**
134
+     * get display name of the user
135
+     * @param string $uid user ID of the user
136
+     * @return string display name
137
+     */
138
+    public function getDisplayName($uid) {
139
+        return $uid;
140
+    }
141 141
 
142
-	/**
143
-	 * Get a list of all display names and user ids.
144
-	 *
145
-	 * @param string $search
146
-	 * @param string|null $limit
147
-	 * @param string|null $offset
148
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
149
-	 */
150
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
151
-		$displayNames = [];
152
-		$users = $this->getUsers($search, $limit, $offset);
153
-		foreach ( $users as $user) {
154
-			$displayNames[$user] = $user;
155
-		}
156
-		return $displayNames;
157
-	}
142
+    /**
143
+     * Get a list of all display names and user ids.
144
+     *
145
+     * @param string $search
146
+     * @param string|null $limit
147
+     * @param string|null $offset
148
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
149
+     */
150
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
151
+        $displayNames = [];
152
+        $users = $this->getUsers($search, $limit, $offset);
153
+        foreach ( $users as $user) {
154
+            $displayNames[$user] = $user;
155
+        }
156
+        return $displayNames;
157
+    }
158 158
 
159
-	/**
160
-	 * Check if a user list is available or not
161
-	 * @return boolean if users can be listed or not
162
-	 */
163
-	public function hasUserListings() {
164
-		return false;
165
-	}
159
+    /**
160
+     * Check if a user list is available or not
161
+     * @return boolean if users can be listed or not
162
+     */
163
+    public function hasUserListings() {
164
+        return false;
165
+    }
166 166
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -39,14 +39,14 @@  discard block
 block discarded – undo
39 39
 	/**
40 40
 	 * actions that user backends can define
41 41
 	 */
42
-	const CREATE_USER		= 1;			// 1 << 0
43
-	const SET_PASSWORD		= 16;			// 1 << 4
44
-	const CHECK_PASSWORD	= 256;			// 1 << 8
45
-	const GET_HOME			= 4096;			// 1 << 12
46
-	const GET_DISPLAYNAME	= 65536;		// 1 << 16
47
-	const SET_DISPLAYNAME	= 1048576;		// 1 << 20
48
-	const PROVIDE_AVATAR	= 16777216;		// 1 << 24
49
-	const COUNT_USERS		= 268435456;	// 1 << 28
42
+	const CREATE_USER = 1; // 1 << 0
43
+	const SET_PASSWORD = 16; // 1 << 4
44
+	const CHECK_PASSWORD = 256; // 1 << 8
45
+	const GET_HOME = 4096; // 1 << 12
46
+	const GET_DISPLAYNAME	= 65536; // 1 << 16
47
+	const SET_DISPLAYNAME	= 1048576; // 1 << 20
48
+	const PROVIDE_AVATAR = 16777216; // 1 << 24
49
+	const COUNT_USERS = 268435456; // 1 << 28
50 50
 
51 51
 	protected $possibleActions = [
52 52
 		self::CREATE_USER => 'createUser',
@@ -68,8 +68,8 @@  discard block
 block discarded – undo
68 68
 	 */
69 69
 	public function getSupportedActions() {
70 70
 		$actions = 0;
71
-		foreach($this->possibleActions AS $action => $methodName) {
72
-			if(method_exists($this, $methodName)) {
71
+		foreach ($this->possibleActions AS $action => $methodName) {
72
+			if (method_exists($this, $methodName)) {
73 73
 				$actions |= $action;
74 74
 			}
75 75
 		}
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 	 * compared with self::CREATE_USER etc.
87 87
 	 */
88 88
 	public function implementsActions($actions) {
89
-		return (bool)($this->getSupportedActions() & $actions);
89
+		return (bool) ($this->getSupportedActions() & $actions);
90 90
 	}
91 91
 
92 92
 	/**
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 	public function getDisplayNames($search = '', $limit = null, $offset = null) {
151 151
 		$displayNames = [];
152 152
 		$users = $this->getUsers($search, $limit, $offset);
153
-		foreach ( $users as $user) {
153
+		foreach ($users as $user) {
154 154
 			$displayNames[$user] = $user;
155 155
 		}
156 156
 		return $displayNames;
Please login to merge, or discard this patch.
lib/private/User/Manager.php 2 patches
Indentation   +578 added lines, -578 removed lines patch added patch discarded remove patch
@@ -66,582 +66,582 @@
 block discarded – undo
66 66
  * @package OC\User
67 67
  */
68 68
 class Manager extends PublicEmitter implements IUserManager {
69
-	/**
70
-	 * @var \OCP\UserInterface[] $backends
71
-	 */
72
-	private $backends = [];
73
-
74
-	/**
75
-	 * @var \OC\User\User[] $cachedUsers
76
-	 */
77
-	private $cachedUsers = [];
78
-
79
-	/** @var IConfig */
80
-	private $config;
81
-
82
-	/** @var EventDispatcherInterface */
83
-	private $dispatcher;
84
-
85
-	/** @var IEventDispatcher */
86
-	private $eventDispatcher;
87
-
88
-	public function __construct(IConfig $config,
89
-								EventDispatcherInterface $oldDispatcher,
90
-								IEventDispatcher $eventDispatcher) {
91
-		$this->config = $config;
92
-		$this->dispatcher = $oldDispatcher;
93
-		$cachedUsers = &$this->cachedUsers;
94
-		$this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
95
-			/** @var \OC\User\User $user */
96
-			unset($cachedUsers[$user->getUID()]);
97
-		});
98
-		$this->eventDispatcher = $eventDispatcher;
99
-	}
100
-
101
-	/**
102
-	 * Get the active backends
103
-	 * @return \OCP\UserInterface[]
104
-	 */
105
-	public function getBackends() {
106
-		return $this->backends;
107
-	}
108
-
109
-	/**
110
-	 * register a user backend
111
-	 *
112
-	 * @param \OCP\UserInterface $backend
113
-	 */
114
-	public function registerBackend($backend) {
115
-		$this->backends[] = $backend;
116
-	}
117
-
118
-	/**
119
-	 * remove a user backend
120
-	 *
121
-	 * @param \OCP\UserInterface $backend
122
-	 */
123
-	public function removeBackend($backend) {
124
-		$this->cachedUsers = [];
125
-		if (($i = array_search($backend, $this->backends)) !== false) {
126
-			unset($this->backends[$i]);
127
-		}
128
-	}
129
-
130
-	/**
131
-	 * remove all user backends
132
-	 */
133
-	public function clearBackends() {
134
-		$this->cachedUsers = [];
135
-		$this->backends = [];
136
-	}
137
-
138
-	/**
139
-	 * get a user by user id
140
-	 *
141
-	 * @param string $uid
142
-	 * @return \OC\User\User|null Either the user or null if the specified user does not exist
143
-	 */
144
-	public function get($uid) {
145
-		if (is_null($uid) || $uid === '' || $uid === false) {
146
-			return null;
147
-		}
148
-		if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
149
-			return $this->cachedUsers[$uid];
150
-		}
151
-		foreach ($this->backends as $backend) {
152
-			if ($backend->userExists($uid)) {
153
-				return $this->getUserObject($uid, $backend);
154
-			}
155
-		}
156
-		return null;
157
-	}
158
-
159
-	/**
160
-	 * get or construct the user object
161
-	 *
162
-	 * @param string $uid
163
-	 * @param \OCP\UserInterface $backend
164
-	 * @param bool $cacheUser If false the newly created user object will not be cached
165
-	 * @return \OC\User\User
166
-	 */
167
-	protected function getUserObject($uid, $backend, $cacheUser = true) {
168
-		if ($backend instanceof IGetRealUIDBackend) {
169
-			$uid = $backend->getRealUID($uid);
170
-		}
171
-
172
-		if (isset($this->cachedUsers[$uid])) {
173
-			return $this->cachedUsers[$uid];
174
-		}
175
-
176
-		$user = new User($uid, $backend, $this->dispatcher, $this, $this->config);
177
-		if ($cacheUser) {
178
-			$this->cachedUsers[$uid] = $user;
179
-		}
180
-		return $user;
181
-	}
182
-
183
-	/**
184
-	 * check if a user exists
185
-	 *
186
-	 * @param string $uid
187
-	 * @return bool
188
-	 */
189
-	public function userExists($uid) {
190
-		$user = $this->get($uid);
191
-		return ($user !== null);
192
-	}
193
-
194
-	/**
195
-	 * Check if the password is valid for the user
196
-	 *
197
-	 * @param string $loginName
198
-	 * @param string $password
199
-	 * @return mixed the User object on success, false otherwise
200
-	 */
201
-	public function checkPassword($loginName, $password) {
202
-		$result = $this->checkPasswordNoLogging($loginName, $password);
203
-
204
-		if ($result === false) {
205
-			\OC::$server->getLogger()->warning('Login failed: \''. $loginName .'\' (Remote IP: \''. \OC::$server->getRequest()->getRemoteAddress(). '\')', ['app' => 'core']);
206
-		}
207
-
208
-		return $result;
209
-	}
210
-
211
-	/**
212
-	 * Check if the password is valid for the user
213
-	 *
214
-	 * @internal
215
-	 * @param string $loginName
216
-	 * @param string $password
217
-	 * @return IUser|false the User object on success, false otherwise
218
-	 */
219
-	public function checkPasswordNoLogging($loginName, $password) {
220
-		$loginName = str_replace("\0", '', $loginName);
221
-		$password = str_replace("\0", '', $password);
222
-
223
-		foreach ($this->backends as $backend) {
224
-			if ($backend->implementsActions(Backend::CHECK_PASSWORD)) {
225
-				$uid = $backend->checkPassword($loginName, $password);
226
-				if ($uid !== false) {
227
-					return $this->getUserObject($uid, $backend);
228
-				}
229
-			}
230
-		}
231
-
232
-		return false;
233
-	}
234
-
235
-	/**
236
-	 * search by user id
237
-	 *
238
-	 * @param string $pattern
239
-	 * @param int $limit
240
-	 * @param int $offset
241
-	 * @return \OC\User\User[]
242
-	 */
243
-	public function search($pattern, $limit = null, $offset = null) {
244
-		$users = [];
245
-		foreach ($this->backends as $backend) {
246
-			$backendUsers = $backend->getUsers($pattern, $limit, $offset);
247
-			if (is_array($backendUsers)) {
248
-				foreach ($backendUsers as $uid) {
249
-					$users[$uid] = $this->getUserObject($uid, $backend);
250
-				}
251
-			}
252
-		}
253
-
254
-		uasort($users, function ($a, $b) {
255
-			/**
256
-			 * @var \OC\User\User $a
257
-			 * @var \OC\User\User $b
258
-			 */
259
-			return strcasecmp($a->getUID(), $b->getUID());
260
-		});
261
-		return $users;
262
-	}
263
-
264
-	/**
265
-	 * search by displayName
266
-	 *
267
-	 * @param string $pattern
268
-	 * @param int $limit
269
-	 * @param int $offset
270
-	 * @return \OC\User\User[]
271
-	 */
272
-	public function searchDisplayName($pattern, $limit = null, $offset = null) {
273
-		$users = [];
274
-		foreach ($this->backends as $backend) {
275
-			$backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
276
-			if (is_array($backendUsers)) {
277
-				foreach ($backendUsers as $uid => $displayName) {
278
-					$users[] = $this->getUserObject($uid, $backend);
279
-				}
280
-			}
281
-		}
282
-
283
-		usort($users, function ($a, $b) {
284
-			/**
285
-			 * @var \OC\User\User $a
286
-			 * @var \OC\User\User $b
287
-			 */
288
-			return strcasecmp($a->getDisplayName(), $b->getDisplayName());
289
-		});
290
-		return $users;
291
-	}
292
-
293
-	/**
294
-	 * @param string $uid
295
-	 * @param string $password
296
-	 * @throws \InvalidArgumentException
297
-	 * @return bool|IUser the created user or false
298
-	 */
299
-	public function createUser($uid, $password) {
300
-		$localBackends = [];
301
-		foreach ($this->backends as $backend) {
302
-			if ($backend instanceof Database) {
303
-				// First check if there is another user backend
304
-				$localBackends[] = $backend;
305
-				continue;
306
-			}
307
-
308
-			if ($backend->implementsActions(Backend::CREATE_USER)) {
309
-				return $this->createUserFromBackend($uid, $password, $backend);
310
-			}
311
-		}
312
-
313
-		foreach ($localBackends as $backend) {
314
-			if ($backend->implementsActions(Backend::CREATE_USER)) {
315
-				return $this->createUserFromBackend($uid, $password, $backend);
316
-			}
317
-		}
318
-
319
-		return false;
320
-	}
321
-
322
-	/**
323
-	 * @param string $uid
324
-	 * @param string $password
325
-	 * @param UserInterface $backend
326
-	 * @return IUser|null
327
-	 * @throws \InvalidArgumentException
328
-	 */
329
-	public function createUserFromBackend($uid, $password, UserInterface $backend) {
330
-		$l = \OC::$server->getL10N('lib');
331
-
332
-		// Check the name for bad characters
333
-		// Allowed are: "a-z", "A-Z", "0-9" and "_.@-'"
334
-		if (preg_match('/[^a-zA-Z0-9 _.@\-\']/', $uid)) {
335
-			throw new \InvalidArgumentException($l->t('Only the following characters are allowed in a username:'
336
-				. ' "a-z", "A-Z", "0-9", and "_.@-\'"'));
337
-		}
338
-
339
-		// No empty username
340
-		if (trim($uid) === '') {
341
-			throw new \InvalidArgumentException($l->t('A valid username must be provided'));
342
-		}
343
-
344
-		// No whitespace at the beginning or at the end
345
-		if (trim($uid) !== $uid) {
346
-			throw new \InvalidArgumentException($l->t('Username contains whitespace at the beginning or at the end'));
347
-		}
348
-
349
-		// Username only consists of 1 or 2 dots (directory traversal)
350
-		if ($uid === '.' || $uid === '..') {
351
-			throw new \InvalidArgumentException($l->t('Username must not consist of dots only'));
352
-		}
353
-
354
-		if (!$this->verifyUid($uid)) {
355
-			throw new \InvalidArgumentException($l->t('Username is invalid because files already exist for this user'));
356
-		}
357
-
358
-		// No empty password
359
-		if (trim($password) === '') {
360
-			throw new \InvalidArgumentException($l->t('A valid password must be provided'));
361
-		}
362
-
363
-		// Check if user already exists
364
-		if ($this->userExists($uid)) {
365
-			throw new \InvalidArgumentException($l->t('The username is already being used'));
366
-		}
367
-
368
-		$this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
369
-		$this->eventDispatcher->dispatchTyped(new CreateUserEvent($uid, $password));
370
-		$state = $backend->createUser($uid, $password);
371
-		if($state === false) {
372
-			throw new \InvalidArgumentException($l->t('Could not create user'));
373
-		}
374
-		$user = $this->getUserObject($uid, $backend);
375
-		if ($user instanceof IUser) {
376
-			$this->emit('\OC\User', 'postCreateUser', [$user, $password]);
377
-			$this->eventDispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
378
-		}
379
-		return $user;
380
-	}
381
-
382
-	/**
383
-	 * returns how many users per backend exist (if supported by backend)
384
-	 *
385
-	 * @param boolean $hasLoggedIn when true only users that have a lastLogin
386
-	 *                entry in the preferences table will be affected
387
-	 * @return array|int an array of backend class as key and count number as value
388
-	 *                if $hasLoggedIn is true only an int is returned
389
-	 */
390
-	public function countUsers($hasLoggedIn = false) {
391
-		if ($hasLoggedIn) {
392
-			return $this->countSeenUsers();
393
-		}
394
-		$userCountStatistics = [];
395
-		foreach ($this->backends as $backend) {
396
-			if ($backend->implementsActions(Backend::COUNT_USERS)) {
397
-				$backendUsers = $backend->countUsers();
398
-				if($backendUsers !== false) {
399
-					if($backend instanceof IUserBackend) {
400
-						$name = $backend->getBackendName();
401
-					} else {
402
-						$name = get_class($backend);
403
-					}
404
-					if(isset($userCountStatistics[$name])) {
405
-						$userCountStatistics[$name] += $backendUsers;
406
-					} else {
407
-						$userCountStatistics[$name] = $backendUsers;
408
-					}
409
-				}
410
-			}
411
-		}
412
-		return $userCountStatistics;
413
-	}
414
-
415
-	/**
416
-	 * returns how many users per backend exist in the requested groups (if supported by backend)
417
-	 *
418
-	 * @param IGroup[] $groups an array of gid to search in
419
-	 * @return array|int an array of backend class as key and count number as value
420
-	 *                if $hasLoggedIn is true only an int is returned
421
-	 */
422
-	public function countUsersOfGroups(array $groups) {
423
-		$users = [];
424
-		foreach($groups as $group) {
425
-			$usersIds = array_map(function ($user) {
426
-				return $user->getUID();
427
-			}, $group->getUsers());
428
-			$users = array_merge($users, $usersIds);
429
-		}
430
-		return count(array_unique($users));
431
-	}
432
-
433
-	/**
434
-	 * The callback is executed for each user on each backend.
435
-	 * If the callback returns false no further users will be retrieved.
436
-	 *
437
-	 * @param \Closure $callback
438
-	 * @param string $search
439
-	 * @param boolean $onlySeen when true only users that have a lastLogin entry
440
-	 *                in the preferences table will be affected
441
-	 * @since 9.0.0
442
-	 */
443
-	public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) {
444
-		if ($onlySeen) {
445
-			$this->callForSeenUsers($callback);
446
-		} else {
447
-			foreach ($this->getBackends() as $backend) {
448
-				$limit = 500;
449
-				$offset = 0;
450
-				do {
451
-					$users = $backend->getUsers($search, $limit, $offset);
452
-					foreach ($users as $uid) {
453
-						if (!$backend->userExists($uid)) {
454
-							continue;
455
-						}
456
-						$user = $this->getUserObject($uid, $backend, false);
457
-						$return = $callback($user);
458
-						if ($return === false) {
459
-							break;
460
-						}
461
-					}
462
-					$offset += $limit;
463
-				} while (count($users) >= $limit);
464
-			}
465
-		}
466
-	}
467
-
468
-	/**
469
-	 * returns how many users are disabled
470
-	 *
471
-	 * @return int
472
-	 * @since 12.0.0
473
-	 */
474
-	public function countDisabledUsers(): int {
475
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
476
-		$queryBuilder->select($queryBuilder->func()->count('*'))
477
-			->from('preferences')
478
-			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
479
-			->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
480
-			->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR));
481
-
482
-
483
-		$result = $queryBuilder->execute();
484
-		$count = $result->fetchColumn();
485
-		$result->closeCursor();
486
-
487
-		if ($count !== false) {
488
-			$count = (int)$count;
489
-		} else {
490
-			$count = 0;
491
-		}
492
-
493
-		return $count;
494
-	}
495
-
496
-	/**
497
-	 * returns how many users are disabled in the requested groups
498
-	 *
499
-	 * @param array $groups groupids to search
500
-	 * @return int
501
-	 * @since 14.0.0
502
-	 */
503
-	public function countDisabledUsersOfGroups(array $groups): int {
504
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
505
-		$queryBuilder->select($queryBuilder->createFunction('COUNT(DISTINCT ' . $queryBuilder->getColumnName('uid') . ')'))
506
-			->from('preferences', 'p')
507
-			->innerJoin('p', 'group_user', 'g', $queryBuilder->expr()->eq('p.userid', 'g.uid'))
508
-			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
509
-			->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
510
-			->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
511
-			->andWhere($queryBuilder->expr()->in('gid', $queryBuilder->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)));
512
-
513
-		$result = $queryBuilder->execute();
514
-		$count = $result->fetchColumn();
515
-		$result->closeCursor();
516
-
517
-		if ($count !== false) {
518
-			$count = (int)$count;
519
-		} else {
520
-			$count = 0;
521
-		}
522
-
523
-		return $count;
524
-	}
525
-
526
-	/**
527
-	 * returns how many users have logged in once
528
-	 *
529
-	 * @return int
530
-	 * @since 11.0.0
531
-	 */
532
-	public function countSeenUsers() {
533
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
534
-		$queryBuilder->select($queryBuilder->func()->count('*'))
535
-			->from('preferences')
536
-			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login')))
537
-			->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin')))
538
-			->andWhere($queryBuilder->expr()->isNotNull('configvalue'));
539
-
540
-		$query = $queryBuilder->execute();
541
-
542
-		$result = (int)$query->fetchColumn();
543
-		$query->closeCursor();
544
-
545
-		return $result;
546
-	}
547
-
548
-	/**
549
-	 * @param \Closure $callback
550
-	 * @since 11.0.0
551
-	 */
552
-	public function callForSeenUsers(\Closure $callback) {
553
-		$limit = 1000;
554
-		$offset = 0;
555
-		do {
556
-			$userIds = $this->getSeenUserIds($limit, $offset);
557
-			$offset += $limit;
558
-			foreach ($userIds as $userId) {
559
-				foreach ($this->backends as $backend) {
560
-					if ($backend->userExists($userId)) {
561
-						$user = $this->getUserObject($userId, $backend, false);
562
-						$return = $callback($user);
563
-						if ($return === false) {
564
-							return;
565
-						}
566
-						break;
567
-					}
568
-				}
569
-			}
570
-		} while (count($userIds) >= $limit);
571
-	}
572
-
573
-	/**
574
-	 * Getting all userIds that have a listLogin value requires checking the
575
-	 * value in php because on oracle you cannot use a clob in a where clause,
576
-	 * preventing us from doing a not null or length(value) > 0 check.
577
-	 *
578
-	 * @param int $limit
579
-	 * @param int $offset
580
-	 * @return string[] with user ids
581
-	 */
582
-	private function getSeenUserIds($limit = null, $offset = null) {
583
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
584
-		$queryBuilder->select(['userid'])
585
-			->from('preferences')
586
-			->where($queryBuilder->expr()->eq(
587
-				'appid', $queryBuilder->createNamedParameter('login'))
588
-			)
589
-			->andWhere($queryBuilder->expr()->eq(
590
-				'configkey', $queryBuilder->createNamedParameter('lastLogin'))
591
-			)
592
-			->andWhere($queryBuilder->expr()->isNotNull('configvalue')
593
-			);
594
-
595
-		if ($limit !== null) {
596
-			$queryBuilder->setMaxResults($limit);
597
-		}
598
-		if ($offset !== null) {
599
-			$queryBuilder->setFirstResult($offset);
600
-		}
601
-		$query = $queryBuilder->execute();
602
-		$result = [];
603
-
604
-		while ($row = $query->fetch()) {
605
-			$result[] = $row['userid'];
606
-		}
607
-
608
-		$query->closeCursor();
609
-
610
-		return $result;
611
-	}
612
-
613
-	/**
614
-	 * @param string $email
615
-	 * @return IUser[]
616
-	 * @since 9.1.0
617
-	 */
618
-	public function getByEmail($email) {
619
-		$userIds = $this->config->getUsersForUserValueCaseInsensitive('settings', 'email', $email);
620
-
621
-		$users = array_map(function ($uid) {
622
-			return $this->get($uid);
623
-		}, $userIds);
624
-
625
-		return array_values(array_filter($users, function ($u) {
626
-			return ($u instanceof IUser);
627
-		}));
628
-	}
629
-
630
-	private function verifyUid(string $uid): bool {
631
-		$appdata = 'appdata_' . $this->config->getSystemValueString('instanceid');
632
-
633
-		if (\in_array($uid, [
634
-			'.htaccess',
635
-			'files_external',
636
-			'.ocdata',
637
-			'owncloud.log',
638
-			'nextcloud.log',
639
-			$appdata], true)) {
640
-			return false;
641
-		}
642
-
643
-		$dataDirectory = $this->config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data');
644
-
645
-		return !file_exists(rtrim($dataDirectory, '/') . '/' . $uid);
646
-	}
69
+    /**
70
+     * @var \OCP\UserInterface[] $backends
71
+     */
72
+    private $backends = [];
73
+
74
+    /**
75
+     * @var \OC\User\User[] $cachedUsers
76
+     */
77
+    private $cachedUsers = [];
78
+
79
+    /** @var IConfig */
80
+    private $config;
81
+
82
+    /** @var EventDispatcherInterface */
83
+    private $dispatcher;
84
+
85
+    /** @var IEventDispatcher */
86
+    private $eventDispatcher;
87
+
88
+    public function __construct(IConfig $config,
89
+                                EventDispatcherInterface $oldDispatcher,
90
+                                IEventDispatcher $eventDispatcher) {
91
+        $this->config = $config;
92
+        $this->dispatcher = $oldDispatcher;
93
+        $cachedUsers = &$this->cachedUsers;
94
+        $this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
95
+            /** @var \OC\User\User $user */
96
+            unset($cachedUsers[$user->getUID()]);
97
+        });
98
+        $this->eventDispatcher = $eventDispatcher;
99
+    }
100
+
101
+    /**
102
+     * Get the active backends
103
+     * @return \OCP\UserInterface[]
104
+     */
105
+    public function getBackends() {
106
+        return $this->backends;
107
+    }
108
+
109
+    /**
110
+     * register a user backend
111
+     *
112
+     * @param \OCP\UserInterface $backend
113
+     */
114
+    public function registerBackend($backend) {
115
+        $this->backends[] = $backend;
116
+    }
117
+
118
+    /**
119
+     * remove a user backend
120
+     *
121
+     * @param \OCP\UserInterface $backend
122
+     */
123
+    public function removeBackend($backend) {
124
+        $this->cachedUsers = [];
125
+        if (($i = array_search($backend, $this->backends)) !== false) {
126
+            unset($this->backends[$i]);
127
+        }
128
+    }
129
+
130
+    /**
131
+     * remove all user backends
132
+     */
133
+    public function clearBackends() {
134
+        $this->cachedUsers = [];
135
+        $this->backends = [];
136
+    }
137
+
138
+    /**
139
+     * get a user by user id
140
+     *
141
+     * @param string $uid
142
+     * @return \OC\User\User|null Either the user or null if the specified user does not exist
143
+     */
144
+    public function get($uid) {
145
+        if (is_null($uid) || $uid === '' || $uid === false) {
146
+            return null;
147
+        }
148
+        if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
149
+            return $this->cachedUsers[$uid];
150
+        }
151
+        foreach ($this->backends as $backend) {
152
+            if ($backend->userExists($uid)) {
153
+                return $this->getUserObject($uid, $backend);
154
+            }
155
+        }
156
+        return null;
157
+    }
158
+
159
+    /**
160
+     * get or construct the user object
161
+     *
162
+     * @param string $uid
163
+     * @param \OCP\UserInterface $backend
164
+     * @param bool $cacheUser If false the newly created user object will not be cached
165
+     * @return \OC\User\User
166
+     */
167
+    protected function getUserObject($uid, $backend, $cacheUser = true) {
168
+        if ($backend instanceof IGetRealUIDBackend) {
169
+            $uid = $backend->getRealUID($uid);
170
+        }
171
+
172
+        if (isset($this->cachedUsers[$uid])) {
173
+            return $this->cachedUsers[$uid];
174
+        }
175
+
176
+        $user = new User($uid, $backend, $this->dispatcher, $this, $this->config);
177
+        if ($cacheUser) {
178
+            $this->cachedUsers[$uid] = $user;
179
+        }
180
+        return $user;
181
+    }
182
+
183
+    /**
184
+     * check if a user exists
185
+     *
186
+     * @param string $uid
187
+     * @return bool
188
+     */
189
+    public function userExists($uid) {
190
+        $user = $this->get($uid);
191
+        return ($user !== null);
192
+    }
193
+
194
+    /**
195
+     * Check if the password is valid for the user
196
+     *
197
+     * @param string $loginName
198
+     * @param string $password
199
+     * @return mixed the User object on success, false otherwise
200
+     */
201
+    public function checkPassword($loginName, $password) {
202
+        $result = $this->checkPasswordNoLogging($loginName, $password);
203
+
204
+        if ($result === false) {
205
+            \OC::$server->getLogger()->warning('Login failed: \''. $loginName .'\' (Remote IP: \''. \OC::$server->getRequest()->getRemoteAddress(). '\')', ['app' => 'core']);
206
+        }
207
+
208
+        return $result;
209
+    }
210
+
211
+    /**
212
+     * Check if the password is valid for the user
213
+     *
214
+     * @internal
215
+     * @param string $loginName
216
+     * @param string $password
217
+     * @return IUser|false the User object on success, false otherwise
218
+     */
219
+    public function checkPasswordNoLogging($loginName, $password) {
220
+        $loginName = str_replace("\0", '', $loginName);
221
+        $password = str_replace("\0", '', $password);
222
+
223
+        foreach ($this->backends as $backend) {
224
+            if ($backend->implementsActions(Backend::CHECK_PASSWORD)) {
225
+                $uid = $backend->checkPassword($loginName, $password);
226
+                if ($uid !== false) {
227
+                    return $this->getUserObject($uid, $backend);
228
+                }
229
+            }
230
+        }
231
+
232
+        return false;
233
+    }
234
+
235
+    /**
236
+     * search by user id
237
+     *
238
+     * @param string $pattern
239
+     * @param int $limit
240
+     * @param int $offset
241
+     * @return \OC\User\User[]
242
+     */
243
+    public function search($pattern, $limit = null, $offset = null) {
244
+        $users = [];
245
+        foreach ($this->backends as $backend) {
246
+            $backendUsers = $backend->getUsers($pattern, $limit, $offset);
247
+            if (is_array($backendUsers)) {
248
+                foreach ($backendUsers as $uid) {
249
+                    $users[$uid] = $this->getUserObject($uid, $backend);
250
+                }
251
+            }
252
+        }
253
+
254
+        uasort($users, function ($a, $b) {
255
+            /**
256
+             * @var \OC\User\User $a
257
+             * @var \OC\User\User $b
258
+             */
259
+            return strcasecmp($a->getUID(), $b->getUID());
260
+        });
261
+        return $users;
262
+    }
263
+
264
+    /**
265
+     * search by displayName
266
+     *
267
+     * @param string $pattern
268
+     * @param int $limit
269
+     * @param int $offset
270
+     * @return \OC\User\User[]
271
+     */
272
+    public function searchDisplayName($pattern, $limit = null, $offset = null) {
273
+        $users = [];
274
+        foreach ($this->backends as $backend) {
275
+            $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
276
+            if (is_array($backendUsers)) {
277
+                foreach ($backendUsers as $uid => $displayName) {
278
+                    $users[] = $this->getUserObject($uid, $backend);
279
+                }
280
+            }
281
+        }
282
+
283
+        usort($users, function ($a, $b) {
284
+            /**
285
+             * @var \OC\User\User $a
286
+             * @var \OC\User\User $b
287
+             */
288
+            return strcasecmp($a->getDisplayName(), $b->getDisplayName());
289
+        });
290
+        return $users;
291
+    }
292
+
293
+    /**
294
+     * @param string $uid
295
+     * @param string $password
296
+     * @throws \InvalidArgumentException
297
+     * @return bool|IUser the created user or false
298
+     */
299
+    public function createUser($uid, $password) {
300
+        $localBackends = [];
301
+        foreach ($this->backends as $backend) {
302
+            if ($backend instanceof Database) {
303
+                // First check if there is another user backend
304
+                $localBackends[] = $backend;
305
+                continue;
306
+            }
307
+
308
+            if ($backend->implementsActions(Backend::CREATE_USER)) {
309
+                return $this->createUserFromBackend($uid, $password, $backend);
310
+            }
311
+        }
312
+
313
+        foreach ($localBackends as $backend) {
314
+            if ($backend->implementsActions(Backend::CREATE_USER)) {
315
+                return $this->createUserFromBackend($uid, $password, $backend);
316
+            }
317
+        }
318
+
319
+        return false;
320
+    }
321
+
322
+    /**
323
+     * @param string $uid
324
+     * @param string $password
325
+     * @param UserInterface $backend
326
+     * @return IUser|null
327
+     * @throws \InvalidArgumentException
328
+     */
329
+    public function createUserFromBackend($uid, $password, UserInterface $backend) {
330
+        $l = \OC::$server->getL10N('lib');
331
+
332
+        // Check the name for bad characters
333
+        // Allowed are: "a-z", "A-Z", "0-9" and "_.@-'"
334
+        if (preg_match('/[^a-zA-Z0-9 _.@\-\']/', $uid)) {
335
+            throw new \InvalidArgumentException($l->t('Only the following characters are allowed in a username:'
336
+                . ' "a-z", "A-Z", "0-9", and "_.@-\'"'));
337
+        }
338
+
339
+        // No empty username
340
+        if (trim($uid) === '') {
341
+            throw new \InvalidArgumentException($l->t('A valid username must be provided'));
342
+        }
343
+
344
+        // No whitespace at the beginning or at the end
345
+        if (trim($uid) !== $uid) {
346
+            throw new \InvalidArgumentException($l->t('Username contains whitespace at the beginning or at the end'));
347
+        }
348
+
349
+        // Username only consists of 1 or 2 dots (directory traversal)
350
+        if ($uid === '.' || $uid === '..') {
351
+            throw new \InvalidArgumentException($l->t('Username must not consist of dots only'));
352
+        }
353
+
354
+        if (!$this->verifyUid($uid)) {
355
+            throw new \InvalidArgumentException($l->t('Username is invalid because files already exist for this user'));
356
+        }
357
+
358
+        // No empty password
359
+        if (trim($password) === '') {
360
+            throw new \InvalidArgumentException($l->t('A valid password must be provided'));
361
+        }
362
+
363
+        // Check if user already exists
364
+        if ($this->userExists($uid)) {
365
+            throw new \InvalidArgumentException($l->t('The username is already being used'));
366
+        }
367
+
368
+        $this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
369
+        $this->eventDispatcher->dispatchTyped(new CreateUserEvent($uid, $password));
370
+        $state = $backend->createUser($uid, $password);
371
+        if($state === false) {
372
+            throw new \InvalidArgumentException($l->t('Could not create user'));
373
+        }
374
+        $user = $this->getUserObject($uid, $backend);
375
+        if ($user instanceof IUser) {
376
+            $this->emit('\OC\User', 'postCreateUser', [$user, $password]);
377
+            $this->eventDispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
378
+        }
379
+        return $user;
380
+    }
381
+
382
+    /**
383
+     * returns how many users per backend exist (if supported by backend)
384
+     *
385
+     * @param boolean $hasLoggedIn when true only users that have a lastLogin
386
+     *                entry in the preferences table will be affected
387
+     * @return array|int an array of backend class as key and count number as value
388
+     *                if $hasLoggedIn is true only an int is returned
389
+     */
390
+    public function countUsers($hasLoggedIn = false) {
391
+        if ($hasLoggedIn) {
392
+            return $this->countSeenUsers();
393
+        }
394
+        $userCountStatistics = [];
395
+        foreach ($this->backends as $backend) {
396
+            if ($backend->implementsActions(Backend::COUNT_USERS)) {
397
+                $backendUsers = $backend->countUsers();
398
+                if($backendUsers !== false) {
399
+                    if($backend instanceof IUserBackend) {
400
+                        $name = $backend->getBackendName();
401
+                    } else {
402
+                        $name = get_class($backend);
403
+                    }
404
+                    if(isset($userCountStatistics[$name])) {
405
+                        $userCountStatistics[$name] += $backendUsers;
406
+                    } else {
407
+                        $userCountStatistics[$name] = $backendUsers;
408
+                    }
409
+                }
410
+            }
411
+        }
412
+        return $userCountStatistics;
413
+    }
414
+
415
+    /**
416
+     * returns how many users per backend exist in the requested groups (if supported by backend)
417
+     *
418
+     * @param IGroup[] $groups an array of gid to search in
419
+     * @return array|int an array of backend class as key and count number as value
420
+     *                if $hasLoggedIn is true only an int is returned
421
+     */
422
+    public function countUsersOfGroups(array $groups) {
423
+        $users = [];
424
+        foreach($groups as $group) {
425
+            $usersIds = array_map(function ($user) {
426
+                return $user->getUID();
427
+            }, $group->getUsers());
428
+            $users = array_merge($users, $usersIds);
429
+        }
430
+        return count(array_unique($users));
431
+    }
432
+
433
+    /**
434
+     * The callback is executed for each user on each backend.
435
+     * If the callback returns false no further users will be retrieved.
436
+     *
437
+     * @param \Closure $callback
438
+     * @param string $search
439
+     * @param boolean $onlySeen when true only users that have a lastLogin entry
440
+     *                in the preferences table will be affected
441
+     * @since 9.0.0
442
+     */
443
+    public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) {
444
+        if ($onlySeen) {
445
+            $this->callForSeenUsers($callback);
446
+        } else {
447
+            foreach ($this->getBackends() as $backend) {
448
+                $limit = 500;
449
+                $offset = 0;
450
+                do {
451
+                    $users = $backend->getUsers($search, $limit, $offset);
452
+                    foreach ($users as $uid) {
453
+                        if (!$backend->userExists($uid)) {
454
+                            continue;
455
+                        }
456
+                        $user = $this->getUserObject($uid, $backend, false);
457
+                        $return = $callback($user);
458
+                        if ($return === false) {
459
+                            break;
460
+                        }
461
+                    }
462
+                    $offset += $limit;
463
+                } while (count($users) >= $limit);
464
+            }
465
+        }
466
+    }
467
+
468
+    /**
469
+     * returns how many users are disabled
470
+     *
471
+     * @return int
472
+     * @since 12.0.0
473
+     */
474
+    public function countDisabledUsers(): int {
475
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
476
+        $queryBuilder->select($queryBuilder->func()->count('*'))
477
+            ->from('preferences')
478
+            ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
479
+            ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
480
+            ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR));
481
+
482
+
483
+        $result = $queryBuilder->execute();
484
+        $count = $result->fetchColumn();
485
+        $result->closeCursor();
486
+
487
+        if ($count !== false) {
488
+            $count = (int)$count;
489
+        } else {
490
+            $count = 0;
491
+        }
492
+
493
+        return $count;
494
+    }
495
+
496
+    /**
497
+     * returns how many users are disabled in the requested groups
498
+     *
499
+     * @param array $groups groupids to search
500
+     * @return int
501
+     * @since 14.0.0
502
+     */
503
+    public function countDisabledUsersOfGroups(array $groups): int {
504
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
505
+        $queryBuilder->select($queryBuilder->createFunction('COUNT(DISTINCT ' . $queryBuilder->getColumnName('uid') . ')'))
506
+            ->from('preferences', 'p')
507
+            ->innerJoin('p', 'group_user', 'g', $queryBuilder->expr()->eq('p.userid', 'g.uid'))
508
+            ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
509
+            ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
510
+            ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
511
+            ->andWhere($queryBuilder->expr()->in('gid', $queryBuilder->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)));
512
+
513
+        $result = $queryBuilder->execute();
514
+        $count = $result->fetchColumn();
515
+        $result->closeCursor();
516
+
517
+        if ($count !== false) {
518
+            $count = (int)$count;
519
+        } else {
520
+            $count = 0;
521
+        }
522
+
523
+        return $count;
524
+    }
525
+
526
+    /**
527
+     * returns how many users have logged in once
528
+     *
529
+     * @return int
530
+     * @since 11.0.0
531
+     */
532
+    public function countSeenUsers() {
533
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
534
+        $queryBuilder->select($queryBuilder->func()->count('*'))
535
+            ->from('preferences')
536
+            ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login')))
537
+            ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin')))
538
+            ->andWhere($queryBuilder->expr()->isNotNull('configvalue'));
539
+
540
+        $query = $queryBuilder->execute();
541
+
542
+        $result = (int)$query->fetchColumn();
543
+        $query->closeCursor();
544
+
545
+        return $result;
546
+    }
547
+
548
+    /**
549
+     * @param \Closure $callback
550
+     * @since 11.0.0
551
+     */
552
+    public function callForSeenUsers(\Closure $callback) {
553
+        $limit = 1000;
554
+        $offset = 0;
555
+        do {
556
+            $userIds = $this->getSeenUserIds($limit, $offset);
557
+            $offset += $limit;
558
+            foreach ($userIds as $userId) {
559
+                foreach ($this->backends as $backend) {
560
+                    if ($backend->userExists($userId)) {
561
+                        $user = $this->getUserObject($userId, $backend, false);
562
+                        $return = $callback($user);
563
+                        if ($return === false) {
564
+                            return;
565
+                        }
566
+                        break;
567
+                    }
568
+                }
569
+            }
570
+        } while (count($userIds) >= $limit);
571
+    }
572
+
573
+    /**
574
+     * Getting all userIds that have a listLogin value requires checking the
575
+     * value in php because on oracle you cannot use a clob in a where clause,
576
+     * preventing us from doing a not null or length(value) > 0 check.
577
+     *
578
+     * @param int $limit
579
+     * @param int $offset
580
+     * @return string[] with user ids
581
+     */
582
+    private function getSeenUserIds($limit = null, $offset = null) {
583
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
584
+        $queryBuilder->select(['userid'])
585
+            ->from('preferences')
586
+            ->where($queryBuilder->expr()->eq(
587
+                'appid', $queryBuilder->createNamedParameter('login'))
588
+            )
589
+            ->andWhere($queryBuilder->expr()->eq(
590
+                'configkey', $queryBuilder->createNamedParameter('lastLogin'))
591
+            )
592
+            ->andWhere($queryBuilder->expr()->isNotNull('configvalue')
593
+            );
594
+
595
+        if ($limit !== null) {
596
+            $queryBuilder->setMaxResults($limit);
597
+        }
598
+        if ($offset !== null) {
599
+            $queryBuilder->setFirstResult($offset);
600
+        }
601
+        $query = $queryBuilder->execute();
602
+        $result = [];
603
+
604
+        while ($row = $query->fetch()) {
605
+            $result[] = $row['userid'];
606
+        }
607
+
608
+        $query->closeCursor();
609
+
610
+        return $result;
611
+    }
612
+
613
+    /**
614
+     * @param string $email
615
+     * @return IUser[]
616
+     * @since 9.1.0
617
+     */
618
+    public function getByEmail($email) {
619
+        $userIds = $this->config->getUsersForUserValueCaseInsensitive('settings', 'email', $email);
620
+
621
+        $users = array_map(function ($uid) {
622
+            return $this->get($uid);
623
+        }, $userIds);
624
+
625
+        return array_values(array_filter($users, function ($u) {
626
+            return ($u instanceof IUser);
627
+        }));
628
+    }
629
+
630
+    private function verifyUid(string $uid): bool {
631
+        $appdata = 'appdata_' . $this->config->getSystemValueString('instanceid');
632
+
633
+        if (\in_array($uid, [
634
+            '.htaccess',
635
+            'files_external',
636
+            '.ocdata',
637
+            'owncloud.log',
638
+            'nextcloud.log',
639
+            $appdata], true)) {
640
+            return false;
641
+        }
642
+
643
+        $dataDirectory = $this->config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data');
644
+
645
+        return !file_exists(rtrim($dataDirectory, '/') . '/' . $uid);
646
+    }
647 647
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 		$this->config = $config;
92 92
 		$this->dispatcher = $oldDispatcher;
93 93
 		$cachedUsers = &$this->cachedUsers;
94
-		$this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
94
+		$this->listen('\OC\User', 'postDelete', function($user) use (&$cachedUsers) {
95 95
 			/** @var \OC\User\User $user */
96 96
 			unset($cachedUsers[$user->getUID()]);
97 97
 		});
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 		$result = $this->checkPasswordNoLogging($loginName, $password);
203 203
 
204 204
 		if ($result === false) {
205
-			\OC::$server->getLogger()->warning('Login failed: \''. $loginName .'\' (Remote IP: \''. \OC::$server->getRequest()->getRemoteAddress(). '\')', ['app' => 'core']);
205
+			\OC::$server->getLogger()->warning('Login failed: \''.$loginName.'\' (Remote IP: \''.\OC::$server->getRequest()->getRemoteAddress().'\')', ['app' => 'core']);
206 206
 		}
207 207
 
208 208
 		return $result;
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
 			}
252 252
 		}
253 253
 
254
-		uasort($users, function ($a, $b) {
254
+		uasort($users, function($a, $b) {
255 255
 			/**
256 256
 			 * @var \OC\User\User $a
257 257
 			 * @var \OC\User\User $b
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
 			}
281 281
 		}
282 282
 
283
-		usort($users, function ($a, $b) {
283
+		usort($users, function($a, $b) {
284 284
 			/**
285 285
 			 * @var \OC\User\User $a
286 286
 			 * @var \OC\User\User $b
@@ -368,7 +368,7 @@  discard block
 block discarded – undo
368 368
 		$this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
369 369
 		$this->eventDispatcher->dispatchTyped(new CreateUserEvent($uid, $password));
370 370
 		$state = $backend->createUser($uid, $password);
371
-		if($state === false) {
371
+		if ($state === false) {
372 372
 			throw new \InvalidArgumentException($l->t('Could not create user'));
373 373
 		}
374 374
 		$user = $this->getUserObject($uid, $backend);
@@ -395,13 +395,13 @@  discard block
 block discarded – undo
395 395
 		foreach ($this->backends as $backend) {
396 396
 			if ($backend->implementsActions(Backend::COUNT_USERS)) {
397 397
 				$backendUsers = $backend->countUsers();
398
-				if($backendUsers !== false) {
399
-					if($backend instanceof IUserBackend) {
398
+				if ($backendUsers !== false) {
399
+					if ($backend instanceof IUserBackend) {
400 400
 						$name = $backend->getBackendName();
401 401
 					} else {
402 402
 						$name = get_class($backend);
403 403
 					}
404
-					if(isset($userCountStatistics[$name])) {
404
+					if (isset($userCountStatistics[$name])) {
405 405
 						$userCountStatistics[$name] += $backendUsers;
406 406
 					} else {
407 407
 						$userCountStatistics[$name] = $backendUsers;
@@ -421,8 +421,8 @@  discard block
 block discarded – undo
421 421
 	 */
422 422
 	public function countUsersOfGroups(array $groups) {
423 423
 		$users = [];
424
-		foreach($groups as $group) {
425
-			$usersIds = array_map(function ($user) {
424
+		foreach ($groups as $group) {
425
+			$usersIds = array_map(function($user) {
426 426
 				return $user->getUID();
427 427
 			}, $group->getUsers());
428 428
 			$users = array_merge($users, $usersIds);
@@ -485,7 +485,7 @@  discard block
 block discarded – undo
485 485
 		$result->closeCursor();
486 486
 
487 487
 		if ($count !== false) {
488
-			$count = (int)$count;
488
+			$count = (int) $count;
489 489
 		} else {
490 490
 			$count = 0;
491 491
 		}
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
 	 */
503 503
 	public function countDisabledUsersOfGroups(array $groups): int {
504 504
 		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
505
-		$queryBuilder->select($queryBuilder->createFunction('COUNT(DISTINCT ' . $queryBuilder->getColumnName('uid') . ')'))
505
+		$queryBuilder->select($queryBuilder->createFunction('COUNT(DISTINCT '.$queryBuilder->getColumnName('uid').')'))
506 506
 			->from('preferences', 'p')
507 507
 			->innerJoin('p', 'group_user', 'g', $queryBuilder->expr()->eq('p.userid', 'g.uid'))
508 508
 			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
 		$result->closeCursor();
516 516
 
517 517
 		if ($count !== false) {
518
-			$count = (int)$count;
518
+			$count = (int) $count;
519 519
 		} else {
520 520
 			$count = 0;
521 521
 		}
@@ -539,7 +539,7 @@  discard block
 block discarded – undo
539 539
 
540 540
 		$query = $queryBuilder->execute();
541 541
 
542
-		$result = (int)$query->fetchColumn();
542
+		$result = (int) $query->fetchColumn();
543 543
 		$query->closeCursor();
544 544
 
545 545
 		return $result;
@@ -618,17 +618,17 @@  discard block
 block discarded – undo
618 618
 	public function getByEmail($email) {
619 619
 		$userIds = $this->config->getUsersForUserValueCaseInsensitive('settings', 'email', $email);
620 620
 
621
-		$users = array_map(function ($uid) {
621
+		$users = array_map(function($uid) {
622 622
 			return $this->get($uid);
623 623
 		}, $userIds);
624 624
 
625
-		return array_values(array_filter($users, function ($u) {
625
+		return array_values(array_filter($users, function($u) {
626 626
 			return ($u instanceof IUser);
627 627
 		}));
628 628
 	}
629 629
 
630 630
 	private function verifyUid(string $uid): bool {
631
-		$appdata = 'appdata_' . $this->config->getSystemValueString('instanceid');
631
+		$appdata = 'appdata_'.$this->config->getSystemValueString('instanceid');
632 632
 
633 633
 		if (\in_array($uid, [
634 634
 			'.htaccess',
@@ -640,8 +640,8 @@  discard block
 block discarded – undo
640 640
 			return false;
641 641
 		}
642 642
 
643
-		$dataDirectory = $this->config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data');
643
+		$dataDirectory = $this->config->getSystemValueString('datadirectory', \OC::$SERVERROOT.'/data');
644 644
 
645
-		return !file_exists(rtrim($dataDirectory, '/') . '/' . $uid);
645
+		return !file_exists(rtrim($dataDirectory, '/').'/'.$uid);
646 646
 	}
647 647
 }
Please login to merge, or discard this patch.
lib/private/Share/Share.php 2 patches
Indentation   +1496 added lines, -1496 removed lines patch added patch discarded remove patch
@@ -49,1500 +49,1500 @@
 block discarded – undo
49 49
  */
50 50
 class Share extends Constants {
51 51
 
52
-	/** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
53
-	 * Construct permissions for share() and setPermissions with Or (|) e.g.
54
-	 * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
55
-	 *
56
-	 * Check if permission is granted with And (&) e.g. Check if delete is
57
-	 * granted: if ($permissions & PERMISSION_DELETE)
58
-	 *
59
-	 * Remove permissions with And (&) and Not (~) e.g. Remove the update
60
-	 * permission: $permissions &= ~PERMISSION_UPDATE
61
-	 *
62
-	 * Apps are required to handle permissions on their own, this class only
63
-	 * stores and manages the permissions of shares
64
-	 * @see lib/public/constants.php
65
-	 */
66
-
67
-	/**
68
-	 * Register a sharing backend class that implements OCP\Share_Backend for an item type
69
-	 * @param string $itemType Item type
70
-	 * @param string $class Backend class
71
-	 * @param string $collectionOf (optional) Depends on item type
72
-	 * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
73
-	 * @return boolean true if backend is registered or false if error
74
-	 */
75
-	public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
76
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') {
77
-			if (!isset(self::$backendTypes[$itemType])) {
78
-				self::$backendTypes[$itemType] = [
79
-					'class' => $class,
80
-					'collectionOf' => $collectionOf,
81
-					'supportedFileExtensions' => $supportedFileExtensions
82
-				];
83
-				return true;
84
-			}
85
-			\OCP\Util::writeLog('OCP\Share',
86
-				'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
87
-				.' is already registered for '.$itemType,
88
-				ILogger::WARN);
89
-		}
90
-		return false;
91
-	}
92
-
93
-	/**
94
-	 * Get the items of item type shared with the current user
95
-	 * @param string $itemType
96
-	 * @param int $format (optional) Format type must be defined by the backend
97
-	 * @param mixed $parameters (optional)
98
-	 * @param int $limit Number of items to return (optional) Returns all by default
99
-	 * @param boolean $includeCollections (optional)
100
-	 * @return mixed Return depends on format
101
-	 * @deprecated TESTS ONLY - this methods is only used by tests
102
-	 * called like this:
103
-	 * \OC\Share\Share::getItemsSharedWith('folder'); (apps/files_sharing/tests/UpdaterTest.php)
104
-	 */
105
-	public static function getItemsSharedWith() {
106
-		return self::getItems('folder', null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, self::FORMAT_NONE,
107
-			null, -1, false);
108
-	}
109
-
110
-	/**
111
-	 * Get the items of item type shared with a user
112
-	 * @param string $itemType
113
-	 * @param string $user id for which user we want the shares
114
-	 * @param int $format (optional) Format type must be defined by the backend
115
-	 * @param mixed $parameters (optional)
116
-	 * @param int $limit Number of items to return (optional) Returns all by default
117
-	 * @param boolean $includeCollections (optional)
118
-	 * @return mixed Return depends on format
119
-	 */
120
-	public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
121
-												  $parameters = null, $limit = -1, $includeCollections = false) {
122
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
123
-			$parameters, $limit, $includeCollections);
124
-	}
125
-
126
-	/**
127
-	 * Get the item of item type shared with a given user by source
128
-	 * @param string $itemType
129
-	 * @param string $itemSource
130
-	 * @param string $user User to whom the item was shared
131
-	 * @param string $owner Owner of the share
132
-	 * @param int $shareType only look for a specific share type
133
-	 * @return array Return list of items with file_target, permissions and expiration
134
-	 */
135
-	public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
136
-		$shares = [];
137
-		$fileDependent = false;
138
-
139
-		$where = 'WHERE';
140
-		$fileDependentWhere = '';
141
-		if ($itemType === 'file' || $itemType === 'folder') {
142
-			$fileDependent = true;
143
-			$column = 'file_source';
144
-			$fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
145
-			$fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
146
-		} else {
147
-			$column = 'item_source';
148
-		}
149
-
150
-		$select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
151
-
152
-		$where .= ' `' . $column . '` = ? AND `item_type` = ? ';
153
-		$arguments = [$itemSource, $itemType];
154
-		// for link shares $user === null
155
-		if ($user !== null) {
156
-			$where .= ' AND `share_with` = ? ';
157
-			$arguments[] = $user;
158
-		}
159
-
160
-		if ($shareType !== null) {
161
-			$where .= ' AND `share_type` = ? ';
162
-			$arguments[] = $shareType;
163
-		}
164
-
165
-		if ($owner !== null) {
166
-			$where .= ' AND `uid_owner` = ? ';
167
-			$arguments[] = $owner;
168
-		}
169
-
170
-		$query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
171
-
172
-		$result = \OC_DB::executeAudited($query, $arguments);
173
-
174
-		while ($row = $result->fetchRow()) {
175
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
176
-				continue;
177
-			}
178
-			if ($fileDependent && (int)$row['file_parent'] === -1) {
179
-				// if it is a mount point we need to get the path from the mount manager
180
-				$mountManager = \OC\Files\Filesystem::getMountManager();
181
-				$mountPoint = $mountManager->findByStorageId($row['storage_id']);
182
-				if (!empty($mountPoint)) {
183
-					$path = $mountPoint[0]->getMountPoint();
184
-					$path = trim($path, '/');
185
-					$path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
186
-					$row['path'] = $path;
187
-				} else {
188
-					\OC::$server->getLogger()->warning(
189
-						'Could not resolve mount point for ' . $row['storage_id'],
190
-						['app' => 'OCP\Share']
191
-					);
192
-				}
193
-			}
194
-			$shares[] = $row;
195
-		}
196
-
197
-		//if didn't found a result than let's look for a group share.
198
-		if(empty($shares) && $user !== null) {
199
-			$userObject = \OC::$server->getUserManager()->get($user);
200
-			$groups = [];
201
-			if ($userObject) {
202
-				$groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
203
-			}
204
-
205
-			if (!empty($groups)) {
206
-				$where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
207
-				$arguments = [$itemSource, $itemType, $groups];
208
-				$types = [null, null, IQueryBuilder::PARAM_STR_ARRAY];
209
-
210
-				if ($owner !== null) {
211
-					$where .= ' AND `uid_owner` = ?';
212
-					$arguments[] = $owner;
213
-					$types[] = null;
214
-				}
215
-
216
-				// TODO: inject connection, hopefully one day in the future when this
217
-				// class isn't static anymore...
218
-				$conn = \OC::$server->getDatabaseConnection();
219
-				$result = $conn->executeQuery(
220
-					'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
221
-					$arguments,
222
-					$types
223
-				);
224
-
225
-				while ($row = $result->fetch()) {
226
-					$shares[] = $row;
227
-				}
228
-			}
229
-		}
230
-
231
-		return $shares;
232
-
233
-	}
234
-
235
-	/**
236
-	 * Get the item of item type shared with the current user by source
237
-	 * @param string $itemType
238
-	 * @param string $itemSource
239
-	 * @param int $format (optional) Format type must be defined by the backend
240
-	 * @param mixed $parameters
241
-	 * @param boolean $includeCollections
242
-	 * @param string $shareWith (optional) define against which user should be checked, default: current user
243
-	 * @return array
244
-	 */
245
-	public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
246
-													 $parameters = null, $includeCollections = false, $shareWith = null) {
247
-		$shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
248
-		return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
249
-			$parameters, 1, $includeCollections, true);
250
-	}
251
-
252
-	/**
253
-	 * Get the shared item of item type owned by the current user
254
-	 * @param string $itemType
255
-	 * @param string $itemSource
256
-	 * @param int $format (optional) Format type must be defined by the backend
257
-	 * @param mixed $parameters
258
-	 * @param boolean $includeCollections
259
-	 * @return mixed Return depends on format
260
-	 */
261
-	public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
262
-										 $parameters = null, $includeCollections = false) {
263
-		return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
264
-			$parameters, -1, $includeCollections);
265
-	}
266
-
267
-	/**
268
-	 * Share an item with a user, group, or via private link
269
-	 * @param string $itemType
270
-	 * @param string $itemSource
271
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
272
-	 * @param string $shareWith User or group the item is being shared with
273
-	 * @param int $permissions CRUDS
274
-	 * @param string $itemSourceName
275
-	 * @param \DateTime|null $expirationDate
276
-	 * @return boolean|string Returns true on success or false on failure, Returns token on success for links
277
-	 * @throws \OC\HintException when the share type is remote and the shareWith is invalid
278
-	 * @throws \Exception
279
-	 * @since 5.0.0 - parameter $itemSourceName was added in 6.0.0, parameter $expirationDate was added in 7.0.0, parameter $passwordChanged added in 9.0.0
280
-	 * @deprecated 14.0.0 TESTS ONLY - this methods is as of 2018-06 only used by tests
281
-	 * called like this:
282
-	 * \OC\Share\Share::shareItem('test', 1, \OCP\Share::SHARE_TYPE_USER, $otherUserId, \OCP\Constants::PERMISSION_READ);
283
-	 */
284
-	public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions) {
285
-		$backend = self::getBackend($itemType);
286
-
287
-		if ($backend->isShareTypeAllowed($shareType) === false) {
288
-			$message = 'Sharing failed, because the backend does not allow shares from type %i';
289
-			throw new \Exception(sprintf($message, $shareType));
290
-		}
291
-
292
-		$uidOwner = \OC_User::getUser();
293
-
294
-		// Verify share type and sharing conditions are met
295
-		if ($shareType === self::SHARE_TYPE_USER) {
296
-			if ($shareWith == $uidOwner) {
297
-				$message = 'Sharing failed, because you can not share with yourself';
298
-				throw new \Exception($message);
299
-			}
300
-			if (!\OC::$server->getUserManager()->userExists($shareWith)) {
301
-				$message = 'Sharing failed, because the user %s does not exist';
302
-				throw new \Exception(sprintf($message, $shareWith));
303
-			}
304
-			// Check if the item source is already shared with the user, either from the same owner or a different user
305
-			if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
306
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
307
-				// Only allow the same share to occur again if it is the same
308
-				// owner and is not a user share, this use case is for increasing
309
-				// permissions for a specific user
310
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
311
-					$message = 'Sharing failed, because this item is already shared with %s';
312
-					throw new \Exception(sprintf($message, $shareWith));
313
-				}
314
-			}
315
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
316
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
317
-				// Only allow the same share to occur again if it is the same
318
-				// owner and is not a user share, this use case is for increasing
319
-				// permissions for a specific user
320
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
321
-					$message = 'Sharing failed, because this item is already shared with user %s';
322
-					throw new \Exception(sprintf($message, $shareWith));
323
-				}
324
-			}
325
-		}
326
-
327
-		// Put the item into the database
328
-		$result = self::put('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions);
329
-
330
-		return $result ? true : false;
331
-	}
332
-
333
-	/**
334
-	 * Unshare an item from a user, group, or delete a private link
335
-	 * @param string $itemType
336
-	 * @param string $itemSource
337
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
338
-	 * @param string $shareWith User or group the item is being shared with
339
-	 * @param string $owner owner of the share, if null the current user is used
340
-	 * @return boolean true on success or false on failure
341
-	 */
342
-	public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
343
-
344
-		// check if it is a valid itemType
345
-		self::getBackend($itemType);
346
-
347
-		$items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
348
-
349
-		$toDelete = [];
350
-		$newParent = null;
351
-		$currentUser = $owner ? $owner : \OC_User::getUser();
352
-		foreach ($items as $item) {
353
-			// delete the item with the expected share_type and owner
354
-			if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
355
-				$toDelete = $item;
356
-				// if there is more then one result we don't have to delete the children
357
-				// but update their parent. For group shares the new parent should always be
358
-				// the original group share and not the db entry with the unique name
359
-			} else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
360
-				$newParent = $item['parent'];
361
-			} else {
362
-				$newParent = $item['id'];
363
-			}
364
-		}
365
-
366
-		if (!empty($toDelete)) {
367
-			self::unshareItem($toDelete, $newParent);
368
-			return true;
369
-		}
370
-		return false;
371
-	}
372
-
373
-	/**
374
-	 * Checks whether a share has expired, calls unshareItem() if yes.
375
-	 * @param array $item Share data (usually database row)
376
-	 * @return boolean True if item was expired, false otherwise.
377
-	 */
378
-	protected static function expireItem(array $item) {
379
-
380
-		$result = false;
381
-
382
-		// only use default expiration date for link shares
383
-		if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
384
-
385
-			// calculate expiration date
386
-			if (!empty($item['expiration'])) {
387
-				$userDefinedExpire = new \DateTime($item['expiration']);
388
-				$expires = $userDefinedExpire->getTimestamp();
389
-			} else {
390
-				$expires = null;
391
-			}
392
-
393
-
394
-			// get default expiration settings
395
-			$defaultSettings = Helper::getDefaultExpireSetting();
396
-			$expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
397
-
398
-
399
-			if (is_int($expires)) {
400
-				$now = time();
401
-				if ($now > $expires) {
402
-					self::unshareItem($item);
403
-					$result = true;
404
-				}
405
-			}
406
-		}
407
-		return $result;
408
-	}
409
-
410
-	/**
411
-	 * Unshares a share given a share data array
412
-	 * @param array $item Share data (usually database row)
413
-	 * @param int $newParent parent ID
414
-	 * @return null
415
-	 */
416
-	protected static function unshareItem(array $item, $newParent = null) {
417
-
418
-		$shareType = (int)$item['share_type'];
419
-		$shareWith = null;
420
-		if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
421
-			$shareWith = $item['share_with'];
422
-		}
423
-
424
-		// Pass all the vars we have for now, they may be useful
425
-		$hookParams = [
426
-			'id'            => $item['id'],
427
-			'itemType'      => $item['item_type'],
428
-			'itemSource'    => $item['item_source'],
429
-			'shareType'     => $shareType,
430
-			'shareWith'     => $shareWith,
431
-			'itemParent'    => $item['parent'],
432
-			'uidOwner'      => $item['uid_owner'],
433
-		];
434
-		if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
435
-			$hookParams['fileSource'] = $item['file_source'];
436
-			$hookParams['fileTarget'] = $item['file_target'];
437
-		}
438
-
439
-		\OC_Hook::emit(\OCP\Share::class, 'pre_unshare', $hookParams);
440
-		$deletedShares = Helper::delete($item['id'], false, null, $newParent);
441
-		$deletedShares[] = $hookParams;
442
-		$hookParams['deletedShares'] = $deletedShares;
443
-		\OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
444
-		if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
445
-			list(, $remote) = Helper::splitUserRemote($item['share_with']);
446
-			self::sendRemoteUnshare($remote, $item['id'], $item['token']);
447
-		}
448
-	}
449
-
450
-	/**
451
-	 * Get the backend class for the specified item type
452
-	 * @param string $itemType
453
-	 * @throws \Exception
454
-	 * @return \OCP\Share_Backend
455
-	 */
456
-	public static function getBackend($itemType) {
457
-		$l = \OC::$server->getL10N('lib');
458
-		if (isset(self::$backends[$itemType])) {
459
-			return self::$backends[$itemType];
460
-		} else if (isset(self::$backendTypes[$itemType]['class'])) {
461
-			$class = self::$backendTypes[$itemType]['class'];
462
-			if (class_exists($class)) {
463
-				self::$backends[$itemType] = new $class;
464
-				if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
465
-					$message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
466
-					$message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', [$class]);
467
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
468
-					throw new \Exception($message_t);
469
-				}
470
-				return self::$backends[$itemType];
471
-			} else {
472
-				$message = 'Sharing backend %s not found';
473
-				$message_t = $l->t('Sharing backend %s not found', [$class]);
474
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
475
-				throw new \Exception($message_t);
476
-			}
477
-		}
478
-		$message = 'Sharing backend for %s not found';
479
-		$message_t = $l->t('Sharing backend for %s not found', [$itemType]);
480
-		\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), ILogger::ERROR);
481
-		throw new \Exception($message_t);
482
-	}
483
-
484
-	/**
485
-	 * Check if resharing is allowed
486
-	 * @return boolean true if allowed or false
487
-	 *
488
-	 * Resharing is allowed by default if not configured
489
-	 */
490
-	public static function isResharingAllowed() {
491
-		if (!isset(self::$isResharingAllowed)) {
492
-			if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
493
-				self::$isResharingAllowed = true;
494
-			} else {
495
-				self::$isResharingAllowed = false;
496
-			}
497
-		}
498
-		return self::$isResharingAllowed;
499
-	}
500
-
501
-	/**
502
-	 * Get a list of collection item types for the specified item type
503
-	 * @param string $itemType
504
-	 * @return array
505
-	 */
506
-	private static function getCollectionItemTypes($itemType) {
507
-		$collectionTypes = [$itemType];
508
-		foreach (self::$backendTypes as $type => $backend) {
509
-			if (in_array($backend['collectionOf'], $collectionTypes)) {
510
-				$collectionTypes[] = $type;
511
-			}
512
-		}
513
-		// TODO Add option for collections to be collection of themselves, only 'folder' does it now...
514
-		if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
515
-			unset($collectionTypes[0]);
516
-		}
517
-		// Return array if collections were found or the item type is a
518
-		// collection itself - collections can be inside collections
519
-		if (count($collectionTypes) > 0) {
520
-			return $collectionTypes;
521
-		}
522
-		return false;
523
-	}
524
-
525
-	/**
526
-	 * Get the owners of items shared with a user.
527
-	 *
528
-	 * @param string $user The user the items are shared with.
529
-	 * @param string $type The type of the items shared with the user.
530
-	 * @param boolean $includeCollections Include collection item types (optional)
531
-	 * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
532
-	 * @return array
533
-	 * @deprecated TESTS ONLY - this methods is only used by tests
534
-	 * called like this:
535
-	 * \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true)
536
-	 */
537
-	public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
538
-		// First, we find out if $type is part of a collection (and if that collection is part of
539
-		// another one and so on).
540
-		$collectionTypes = [];
541
-		if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
542
-			$collectionTypes[] = $type;
543
-		}
544
-
545
-		// Of these collection types, along with our original $type, we make a
546
-		// list of the ones for which a sharing backend has been registered.
547
-		// FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
548
-		// with its $includeCollections parameter set to true. Unfortunately, this fails currently.
549
-		$allMaybeSharedItems = [];
550
-		foreach ($collectionTypes as $collectionType) {
551
-			if (isset(self::$backends[$collectionType])) {
552
-				$allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
553
-					$collectionType,
554
-					$user,
555
-					self::FORMAT_NONE
556
-				);
557
-			}
558
-		}
559
-
560
-		$owners = [];
561
-		if ($includeOwner) {
562
-			$owners[] = $user;
563
-		}
564
-
565
-		// We take a look at all shared items of the given $type (or of the collections it is part of)
566
-		// and find out their owners. Then, we gather the tags for the original $type from all owners,
567
-		// and return them as elements of a list that look like "Tag (owner)".
568
-		foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
569
-			foreach ($maybeSharedItems as $sharedItem) {
570
-				if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
571
-					$owners[] = $sharedItem['uid_owner'];
572
-				}
573
-			}
574
-		}
575
-
576
-		return $owners;
577
-	}
578
-
579
-	/**
580
-	 * Get shared items from the database
581
-	 * @param string $itemType
582
-	 * @param string $item Item source or target (optional)
583
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
584
-	 * @param string $shareWith User or group the item is being shared with
585
-	 * @param string $uidOwner User that is the owner of shared items (optional)
586
-	 * @param int $format Format to convert items to with formatItems() (optional)
587
-	 * @param mixed $parameters to pass to formatItems() (optional)
588
-	 * @param int $limit Number of items to return, -1 to return all matches (optional)
589
-	 * @param boolean $includeCollections Include collection item types (optional)
590
-	 * @param boolean $itemShareWithBySource (optional)
591
-	 * @param boolean $checkExpireDate
592
-	 * @return array
593
-	 *
594
-	 * See public functions getItem(s)... for parameter usage
595
-	 *
596
-	 */
597
-	public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
598
-									$uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
599
-									$includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
600
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') {
601
-			return [];
602
-		}
603
-		$backend = self::getBackend($itemType);
604
-		$collectionTypes = false;
605
-		// Get filesystem root to add it to the file target and remove from the
606
-		// file source, match file_source with the file cache
607
-		if ($itemType == 'file' || $itemType == 'folder') {
608
-			if(!is_null($uidOwner)) {
609
-				$root = \OC\Files\Filesystem::getRoot();
610
-			} else {
611
-				$root = '';
612
-			}
613
-			$where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
614
-			if (!isset($item)) {
615
-				$where .= ' AND `file_target` IS NOT NULL ';
616
-			}
617
-			$where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
618
-			$fileDependent = true;
619
-			$queryArgs = [];
620
-		} else {
621
-			$fileDependent = false;
622
-			$root = '';
623
-			$collectionTypes = self::getCollectionItemTypes($itemType);
624
-			if ($includeCollections && !isset($item) && $collectionTypes) {
625
-				// If includeCollections is true, find collections of this item type, e.g. a music album contains songs
626
-				if (!in_array($itemType, $collectionTypes)) {
627
-					$itemTypes = array_merge([$itemType], $collectionTypes);
628
-				} else {
629
-					$itemTypes = $collectionTypes;
630
-				}
631
-				$placeholders = implode(',', array_fill(0, count($itemTypes), '?'));
632
-				$where = ' WHERE `item_type` IN ('.$placeholders.'))';
633
-				$queryArgs = $itemTypes;
634
-			} else {
635
-				$where = ' WHERE `item_type` = ?';
636
-				$queryArgs = [$itemType];
637
-			}
638
-		}
639
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
640
-			$where .= ' AND `share_type` != ?';
641
-			$queryArgs[] = self::SHARE_TYPE_LINK;
642
-		}
643
-		if (isset($shareType)) {
644
-			// Include all user and group items
645
-			if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
646
-				$where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
647
-				$queryArgs[] = self::SHARE_TYPE_USER;
648
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
649
-				$queryArgs[] = $shareWith;
650
-
651
-				$user = \OC::$server->getUserManager()->get($shareWith);
652
-				$groups = [];
653
-				if ($user) {
654
-					$groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
655
-				}
656
-				if (!empty($groups)) {
657
-					$placeholders = implode(',', array_fill(0, count($groups), '?'));
658
-					$where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
659
-					$queryArgs[] = self::SHARE_TYPE_GROUP;
660
-					$queryArgs = array_merge($queryArgs, $groups);
661
-				}
662
-				$where .= ')';
663
-				// Don't include own group shares
664
-				$where .= ' AND `uid_owner` != ?';
665
-				$queryArgs[] = $shareWith;
666
-			} else {
667
-				$where .= ' AND `share_type` = ?';
668
-				$queryArgs[] = $shareType;
669
-				if (isset($shareWith)) {
670
-					$where .= ' AND `share_with` = ?';
671
-					$queryArgs[] = $shareWith;
672
-				}
673
-			}
674
-		}
675
-		if (isset($uidOwner)) {
676
-			$where .= ' AND `uid_owner` = ?';
677
-			$queryArgs[] = $uidOwner;
678
-			if (!isset($shareType)) {
679
-				// Prevent unique user targets for group shares from being selected
680
-				$where .= ' AND `share_type` != ?';
681
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
682
-			}
683
-			if ($fileDependent) {
684
-				$column = 'file_source';
685
-			} else {
686
-				$column = 'item_source';
687
-			}
688
-		} else {
689
-			if ($fileDependent) {
690
-				$column = 'file_target';
691
-			} else {
692
-				$column = 'item_target';
693
-			}
694
-		}
695
-		if (isset($item)) {
696
-			$collectionTypes = self::getCollectionItemTypes($itemType);
697
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
698
-				$where .= ' AND (';
699
-			} else {
700
-				$where .= ' AND';
701
-			}
702
-			// If looking for own shared items, check item_source else check item_target
703
-			if (isset($uidOwner) || $itemShareWithBySource) {
704
-				// If item type is a file, file source needs to be checked in case the item was converted
705
-				if ($fileDependent) {
706
-					$where .= ' `file_source` = ?';
707
-					$column = 'file_source';
708
-				} else {
709
-					$where .= ' `item_source` = ?';
710
-					$column = 'item_source';
711
-				}
712
-			} else {
713
-				if ($fileDependent) {
714
-					$where .= ' `file_target` = ?';
715
-					$item = \OC\Files\Filesystem::normalizePath($item);
716
-				} else {
717
-					$where .= ' `item_target` = ?';
718
-				}
719
-			}
720
-			$queryArgs[] = $item;
721
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
722
-				$placeholders = implode(',', array_fill(0, count($collectionTypes), '?'));
723
-				$where .= ' OR `item_type` IN ('.$placeholders.'))';
724
-				$queryArgs = array_merge($queryArgs, $collectionTypes);
725
-			}
726
-		}
727
-
728
-		if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
729
-			// Make sure the unique user target is returned if it exists,
730
-			// unique targets should follow the group share in the database
731
-			// If the limit is not 1, the filtering can be done later
732
-			$where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
733
-		} else {
734
-			$where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
735
-		}
736
-
737
-		if ($limit != -1 && !$includeCollections) {
738
-			// The limit must be at least 3, because filtering needs to be done
739
-			if ($limit < 3) {
740
-				$queryLimit = 3;
741
-			} else {
742
-				$queryLimit = $limit;
743
-			}
744
-		} else {
745
-			$queryLimit = null;
746
-		}
747
-		$select = self::createSelectStatement($format, $fileDependent, $uidOwner);
748
-		$root = strlen($root);
749
-		$query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
750
-		$result = $query->execute($queryArgs);
751
-		if ($result === false) {
752
-			\OCP\Util::writeLog('OCP\Share',
753
-				\OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
754
-				ILogger::ERROR);
755
-		}
756
-		$items = [];
757
-		$targets = [];
758
-		$switchedItems = [];
759
-		$mounts = [];
760
-		while ($row = $result->fetchRow()) {
761
-			self::transformDBResults($row);
762
-			// Filter out duplicate group shares for users with unique targets
763
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
764
-				continue;
765
-			}
766
-			if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
767
-				$row['share_type'] = self::SHARE_TYPE_GROUP;
768
-				$row['unique_name'] = true; // remember that we use a unique name for this user
769
-				$row['share_with'] = $items[$row['parent']]['share_with'];
770
-				// if the group share was unshared from the user we keep the permission, otherwise
771
-				// we take the permission from the parent because this is always the up-to-date
772
-				// permission for the group share
773
-				if ($row['permissions'] > 0) {
774
-					$row['permissions'] = $items[$row['parent']]['permissions'];
775
-				}
776
-				// Remove the parent group share
777
-				unset($items[$row['parent']]);
778
-				if ($row['permissions'] == 0) {
779
-					continue;
780
-				}
781
-			} else if (!isset($uidOwner)) {
782
-				// Check if the same target already exists
783
-				if (isset($targets[$row['id']])) {
784
-					// Check if the same owner shared with the user twice
785
-					// through a group and user share - this is allowed
786
-					$id = $targets[$row['id']];
787
-					if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
788
-						// Switch to group share type to ensure resharing conditions aren't bypassed
789
-						if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
790
-							$items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
791
-							$items[$id]['share_with'] = $row['share_with'];
792
-						}
793
-						// Switch ids if sharing permission is granted on only
794
-						// one share to ensure correct parent is used if resharing
795
-						if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
796
-							&& (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
797
-							$items[$row['id']] = $items[$id];
798
-							$switchedItems[$id] = $row['id'];
799
-							unset($items[$id]);
800
-							$id = $row['id'];
801
-						}
802
-						$items[$id]['permissions'] |= (int)$row['permissions'];
803
-
804
-					}
805
-					continue;
806
-				} elseif (!empty($row['parent'])) {
807
-					$targets[$row['parent']] = $row['id'];
808
-				}
809
-			}
810
-			// Remove root from file source paths if retrieving own shared items
811
-			if (isset($uidOwner) && isset($row['path'])) {
812
-				if (isset($row['parent'])) {
813
-					$query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
814
-					$parentResult = $query->execute([$row['parent']]);
815
-					if ($result === false) {
816
-						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
817
-							\OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
818
-							ILogger::ERROR);
819
-					} else {
820
-						$parentRow = $parentResult->fetchRow();
821
-						$tmpPath = $parentRow['file_target'];
822
-						// find the right position where the row path continues from the target path
823
-						$pos = strrpos($row['path'], $parentRow['file_target']);
824
-						$subPath = substr($row['path'], $pos);
825
-						$splitPath = explode('/', $subPath);
826
-						foreach (array_slice($splitPath, 2) as $pathPart) {
827
-							$tmpPath = $tmpPath . '/' . $pathPart;
828
-						}
829
-						$row['path'] = $tmpPath;
830
-					}
831
-				} else {
832
-					if (!isset($mounts[$row['storage']])) {
833
-						$mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
834
-						if (is_array($mountPoints) && !empty($mountPoints)) {
835
-							$mounts[$row['storage']] = current($mountPoints);
836
-						}
837
-					}
838
-					if (!empty($mounts[$row['storage']])) {
839
-						$path = $mounts[$row['storage']]->getMountPoint().$row['path'];
840
-						$relPath = substr($path, $root); // path relative to data/user
841
-						$row['path'] = rtrim($relPath, '/');
842
-					}
843
-				}
844
-			}
845
-
846
-			if($checkExpireDate) {
847
-				if (self::expireItem($row)) {
848
-					continue;
849
-				}
850
-			}
851
-			// Check if resharing is allowed, if not remove share permission
852
-			if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
853
-				$row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
854
-			}
855
-			// Add display names to result
856
-			$row['share_with_displayname'] = $row['share_with'];
857
-			if ( isset($row['share_with']) && $row['share_with'] != '' &&
858
-				$row['share_type'] === self::SHARE_TYPE_USER) {
859
-				$shareWithUser = \OC::$server->getUserManager()->get($row['share_with']);
860
-				$row['share_with_displayname'] = $shareWithUser === null ? $row['share_with'] : $shareWithUser->getDisplayName();
861
-			} else if(isset($row['share_with']) && $row['share_with'] != '' &&
862
-				$row['share_type'] === self::SHARE_TYPE_REMOTE) {
863
-				$addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
864
-				foreach ($addressBookEntries as $entry) {
865
-					foreach ($entry['CLOUD'] as $cloudID) {
866
-						if ($cloudID === $row['share_with']) {
867
-							$row['share_with_displayname'] = $entry['FN'];
868
-						}
869
-					}
870
-				}
871
-			}
872
-			if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
873
-				$ownerUser = \OC::$server->getUserManager()->get($row['uid_owner']);
874
-				$row['displayname_owner'] = $ownerUser === null ? $row['uid_owner'] : $ownerUser->getDisplayName();
875
-			}
876
-
877
-			if ($row['permissions'] > 0) {
878
-				$items[$row['id']] = $row;
879
-			}
880
-
881
-		}
882
-
883
-		// group items if we are looking for items shared with the current user
884
-		if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
885
-			$items = self::groupItems($items, $itemType);
886
-		}
887
-
888
-		if (!empty($items)) {
889
-			$collectionItems = [];
890
-			foreach ($items as &$row) {
891
-				// Return only the item instead of a 2-dimensional array
892
-				if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
893
-					if ($format == self::FORMAT_NONE) {
894
-						return $row;
895
-					} else {
896
-						break;
897
-					}
898
-				}
899
-				// Check if this is a collection of the requested item type
900
-				if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
901
-					if (($collectionBackend = self::getBackend($row['item_type']))
902
-						&& $collectionBackend instanceof \OCP\Share_Backend_Collection) {
903
-						// Collections can be inside collections, check if the item is a collection
904
-						if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
905
-							$collectionItems[] = $row;
906
-						} else {
907
-							$collection = [];
908
-							$collection['item_type'] = $row['item_type'];
909
-							if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
910
-								$collection['path'] = basename($row['path']);
911
-							}
912
-							$row['collection'] = $collection;
913
-							// Fetch all of the children sources
914
-							$children = $collectionBackend->getChildren($row[$column]);
915
-							foreach ($children as $child) {
916
-								$childItem = $row;
917
-								$childItem['item_type'] = $itemType;
918
-								if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
919
-									$childItem['item_source'] = $child['source'];
920
-									$childItem['item_target'] = $child['target'];
921
-								}
922
-								if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
923
-									if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
924
-										$childItem['file_source'] = $child['source'];
925
-									} else { // TODO is this really needed if we already know that we use the file backend?
926
-										$meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
927
-										$childItem['file_source'] = $meta['fileid'];
928
-									}
929
-									$childItem['file_target'] =
930
-										\OC\Files\Filesystem::normalizePath($child['file_path']);
931
-								}
932
-								if (isset($item)) {
933
-									if ($childItem[$column] == $item) {
934
-										// Return only the item instead of a 2-dimensional array
935
-										if ($limit == 1) {
936
-											if ($format == self::FORMAT_NONE) {
937
-												return $childItem;
938
-											} else {
939
-												// Unset the items array and break out of both loops
940
-												$items = [];
941
-												$items[] = $childItem;
942
-												break 2;
943
-											}
944
-										} else {
945
-											$collectionItems[] = $childItem;
946
-										}
947
-									}
948
-								} else {
949
-									$collectionItems[] = $childItem;
950
-								}
951
-							}
952
-						}
953
-					}
954
-					// Remove collection item
955
-					$toRemove = $row['id'];
956
-					if (array_key_exists($toRemove, $switchedItems)) {
957
-						$toRemove = $switchedItems[$toRemove];
958
-					}
959
-					unset($items[$toRemove]);
960
-				} elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
961
-					// FIXME: Thats a dirty hack to improve file sharing performance,
962
-					// see github issue #10588 for more details
963
-					// Need to find a solution which works for all back-ends
964
-					$collectionBackend = self::getBackend($row['item_type']);
965
-					$sharedParents = $collectionBackend->getParents($row['item_source']);
966
-					foreach ($sharedParents as $parent) {
967
-						$collectionItems[] = $parent;
968
-					}
969
-				}
970
-			}
971
-			if (!empty($collectionItems)) {
972
-				$collectionItems = array_unique($collectionItems, SORT_REGULAR);
973
-				$items = array_merge($items, $collectionItems);
974
-			}
975
-
976
-			// filter out invalid items, these can appear when subshare entries exist
977
-			// for a group in which the requested user isn't a member any more
978
-			$items = array_filter($items, function ($item) {
979
-				return $item['share_type'] !== self::$shareTypeGroupUserUnique;
980
-			});
981
-
982
-			return self::formatResult($items, $column, $backend, $format, $parameters);
983
-		} elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
984
-			// FIXME: Thats a dirty hack to improve file sharing performance,
985
-			// see github issue #10588 for more details
986
-			// Need to find a solution which works for all back-ends
987
-			$collectionItems = [];
988
-			$collectionBackend = self::getBackend('folder');
989
-			$sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
990
-			foreach ($sharedParents as $parent) {
991
-				$collectionItems[] = $parent;
992
-			}
993
-			if ($limit === 1) {
994
-				return reset($collectionItems);
995
-			}
996
-			return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
997
-		}
998
-
999
-		return [];
1000
-	}
1001
-
1002
-	/**
1003
-	 * group items with link to the same source
1004
-	 *
1005
-	 * @param array $items
1006
-	 * @param string $itemType
1007
-	 * @return array of grouped items
1008
-	 */
1009
-	protected static function groupItems($items, $itemType) {
1010
-
1011
-		$fileSharing = $itemType === 'file' || $itemType === 'folder';
1012
-
1013
-		$result = [];
1014
-
1015
-		foreach ($items as $item) {
1016
-			$grouped = false;
1017
-			foreach ($result as $key => $r) {
1018
-				// for file/folder shares we need to compare file_source, otherwise we compare item_source
1019
-				// only group shares if they already point to the same target, otherwise the file where shared
1020
-				// before grouping of shares was added. In this case we don't group them toi avoid confusions
1021
-				if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1022
-					(!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
1023
-					// add the first item to the list of grouped shares
1024
-					if (!isset($result[$key]['grouped'])) {
1025
-						$result[$key]['grouped'][] = $result[$key];
1026
-					}
1027
-					$result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
1028
-					$result[$key]['grouped'][] = $item;
1029
-					$grouped = true;
1030
-					break;
1031
-				}
1032
-			}
1033
-
1034
-			if (!$grouped) {
1035
-				$result[] = $item;
1036
-			}
1037
-
1038
-		}
1039
-
1040
-		return $result;
1041
-	}
1042
-
1043
-	/**
1044
-	 * Put shared item into the database
1045
-	 * @param string $itemType Item type
1046
-	 * @param string $itemSource Item source
1047
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1048
-	 * @param string $shareWith User or group the item is being shared with
1049
-	 * @param string $uidOwner User that is the owner of shared item
1050
-	 * @param int $permissions CRUDS permissions
1051
-	 * @throws \Exception
1052
-	 * @return mixed id of the new share or false
1053
-	 * @deprecated TESTS ONLY - this methods is only used by tests
1054
-	 * called like this:
1055
-	 * self::put('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions);
1056
-	 */
1057
-	private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1058
-								$permissions) {
1059
-
1060
-		$queriesToExecute = [];
1061
-		$suggestedItemTarget = null;
1062
-		$groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
1063
-		$groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1064
-
1065
-		$result = self::checkReshare('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions, null, null);
1066
-		if(!empty($result)) {
1067
-			$parent = $result['parent'];
1068
-			$itemSource = $result['itemSource'];
1069
-			$fileSource = $result['fileSource'];
1070
-			$suggestedItemTarget = $result['suggestedItemTarget'];
1071
-			$suggestedFileTarget = $result['suggestedFileTarget'];
1072
-			$filePath = $result['filePath'];
1073
-		}
1074
-
1075
-		$isGroupShare = false;
1076
-			$users = [$shareWith];
1077
-			$itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1078
-				$suggestedItemTarget);
1079
-
1080
-		$run = true;
1081
-		$error = '';
1082
-		$preHookData = [
1083
-			'itemType' => $itemType,
1084
-			'itemSource' => $itemSource,
1085
-			'shareType' => $shareType,
1086
-			'uidOwner' => $uidOwner,
1087
-			'permissions' => $permissions,
1088
-			'fileSource' => $fileSource,
1089
-			'expiration' => null,
1090
-			'token' => null,
1091
-			'run' => &$run,
1092
-			'error' => &$error
1093
-		];
1094
-
1095
-		$preHookData['itemTarget'] = $itemTarget;
1096
-		$preHookData['shareWith'] = $shareWith;
1097
-
1098
-		\OC_Hook::emit(\OCP\Share::class, 'pre_shared', $preHookData);
1099
-
1100
-		if ($run === false) {
1101
-			throw new \Exception($error);
1102
-		}
1103
-
1104
-		foreach ($users as $user) {
1105
-			$sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
1106
-			$sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
1107
-
1108
-			$userShareType = $shareType;
1109
-
1110
-			if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
1111
-				$fileTarget = $sourceExists['file_target'];
1112
-				$itemTarget = $sourceExists['item_target'];
1113
-
1114
-			} elseif(!$sourceExists)  {
1115
-
1116
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1117
-					$uidOwner, $suggestedItemTarget, $parent);
1118
-				if (isset($fileSource)) {
1119
-						$fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
1120
-							$user, $uidOwner, $suggestedFileTarget, $parent);
1121
-				} else {
1122
-					$fileTarget = null;
1123
-				}
1124
-
1125
-			} else {
1126
-
1127
-				// group share which doesn't exists until now, check if we need a unique target for this user
1128
-
1129
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
1130
-					$uidOwner, $suggestedItemTarget, $parent);
1131
-
1132
-				// do we also need a file target
1133
-				if (isset($fileSource)) {
1134
-					$fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
1135
-						$uidOwner, $suggestedFileTarget, $parent);
1136
-				} else {
1137
-					$fileTarget = null;
1138
-				}
1139
-
1140
-				if (($itemTarget === $groupItemTarget) &&
1141
-					(!isset($fileSource) || $fileTarget === $groupFileTarget)) {
1142
-					continue;
1143
-				}
1144
-			}
1145
-
1146
-			$queriesToExecute[] = [
1147
-				'itemType'			=> $itemType,
1148
-				'itemSource'		=> $itemSource,
1149
-				'itemTarget'		=> $itemTarget,
1150
-				'shareType'			=> $userShareType,
1151
-				'shareWith'			=> $user,
1152
-				'uidOwner'			=> $uidOwner,
1153
-				'permissions'		=> $permissions,
1154
-				'shareTime'			=> time(),
1155
-				'fileSource'		=> $fileSource,
1156
-				'fileTarget'		=> $fileTarget,
1157
-				'token'				=> null,
1158
-				'parent'			=> $parent,
1159
-				'expiration'		=> null,
1160
-			];
1161
-
1162
-		}
1163
-
1164
-		$id = false;
1165
-
1166
-		foreach ($queriesToExecute as $shareQuery) {
1167
-			$shareQuery['parent'] = $parent;
1168
-			$id = self::insertShare($shareQuery);
1169
-		}
1170
-
1171
-		$postHookData = [
1172
-			'itemType' => $itemType,
1173
-			'itemSource' => $itemSource,
1174
-			'parent' => $parent,
1175
-			'shareType' => $shareType,
1176
-			'uidOwner' => $uidOwner,
1177
-			'permissions' => $permissions,
1178
-			'fileSource' => $fileSource,
1179
-			'id' => $parent,
1180
-			'token' => null,
1181
-			'expirationDate' => null,
1182
-		];
1183
-
1184
-		$postHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith;
1185
-		$postHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget;
1186
-		$postHookData['fileTarget'] = $isGroupShare ? $groupFileTarget : $fileTarget;
1187
-
1188
-		\OC_Hook::emit(\OCP\Share::class, 'post_shared', $postHookData);
1189
-
1190
-
1191
-		return $id ? $id : false;
1192
-	}
1193
-
1194
-	/**
1195
-	 * @param string $itemType
1196
-	 * @param string $itemSource
1197
-	 * @param int $shareType
1198
-	 * @param string $shareWith
1199
-	 * @param string $uidOwner
1200
-	 * @param int $permissions
1201
-	 * @param string|null $itemSourceName
1202
-	 * @param null|\DateTime $expirationDate
1203
-	 * @deprecated TESTS ONLY - this methods is only used by tests
1204
-	 * called like this:
1205
-	 * self::checkReshare('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions, null, null);
1206
-	 */
1207
-	private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
1208
-		$backend = self::getBackend($itemType);
1209
-
1210
-		$result = [];
1211
-
1212
-		$column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
1213
-
1214
-		$checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
1215
-		if ($checkReshare) {
1216
-			// Check if attempting to share back to owner
1217
-			if ($checkReshare['uid_owner'] == $shareWith) {
1218
-				$message = 'Sharing %1$s failed, because the user %2$s is the original sharer';
1219
-				throw new \Exception(sprintf($message, $itemSourceName, $shareWith));
1220
-			}
1221
-		}
1222
-
1223
-		if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1224
-			// Check if share permissions is granted
1225
-			if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1226
-				if (~(int)$checkReshare['permissions'] & $permissions) {
1227
-					$message = 'Sharing %1$s failed, because the permissions exceed permissions granted to %2$s';
1228
-					throw new \Exception(sprintf($message, $itemSourceName, $uidOwner));
1229
-				} else {
1230
-					// TODO Don't check if inside folder
1231
-					$result['parent'] = $checkReshare['id'];
1232
-
1233
-					$result['expirationDate'] = $expirationDate;
1234
-					// $checkReshare['expiration'] could be null and then is always less than any value
1235
-					if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1236
-						$result['expirationDate'] = $checkReshare['expiration'];
1237
-					}
1238
-
1239
-					// only suggest the same name as new target if it is a reshare of the
1240
-					// same file/folder and not the reshare of a child
1241
-					if ($checkReshare[$column] === $itemSource) {
1242
-						$result['filePath'] = $checkReshare['file_target'];
1243
-						$result['itemSource'] = $checkReshare['item_source'];
1244
-						$result['fileSource'] = $checkReshare['file_source'];
1245
-						$result['suggestedItemTarget'] = $checkReshare['item_target'];
1246
-						$result['suggestedFileTarget'] = $checkReshare['file_target'];
1247
-					} else {
1248
-						$result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
1249
-						$result['suggestedItemTarget'] = null;
1250
-						$result['suggestedFileTarget'] = null;
1251
-						$result['itemSource'] = $itemSource;
1252
-						$result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
1253
-					}
1254
-				}
1255
-			} else {
1256
-				$message = 'Sharing %s failed, because resharing is not allowed';
1257
-				throw new \Exception(sprintf($message, $itemSourceName));
1258
-			}
1259
-		} else {
1260
-			$result['parent'] = null;
1261
-			$result['suggestedItemTarget'] = null;
1262
-			$result['suggestedFileTarget'] = null;
1263
-			$result['itemSource'] = $itemSource;
1264
-			$result['expirationDate'] = $expirationDate;
1265
-			if (!$backend->isValidSource($itemSource, $uidOwner)) {
1266
-				$message = 'Sharing %1$s failed, because the sharing backend for '
1267
-					.'%2$s could not find its source';
1268
-				throw new \Exception(sprintf($message, $itemSource, $itemType));
1269
-			}
1270
-			if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1271
-				$result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
1272
-					$meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
1273
-					$result['fileSource'] = $meta['fileid'];
1274
-				if ($result['fileSource'] == -1) {
1275
-					$message = 'Sharing %s failed, because the file could not be found in the file cache';
1276
-					throw new \Exception(sprintf($message, $itemSource));
1277
-				}
1278
-			} else {
1279
-				$result['filePath'] = null;
1280
-				$result['fileSource'] = null;
1281
-			}
1282
-		}
1283
-
1284
-		return $result;
1285
-	}
1286
-
1287
-	/**
1288
-	 *
1289
-	 * @param array $shareData
1290
-	 * @return mixed false in case of a failure or the id of the new share
1291
-	 */
1292
-	private static function insertShare(array $shareData) {
1293
-
1294
-		$query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
1295
-			.' `item_type`, `item_source`, `item_target`, `share_type`,'
1296
-			.' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
1297
-			.' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
1298
-		$query->bindValue(1, $shareData['itemType']);
1299
-		$query->bindValue(2, $shareData['itemSource']);
1300
-		$query->bindValue(3, $shareData['itemTarget']);
1301
-		$query->bindValue(4, $shareData['shareType']);
1302
-		$query->bindValue(5, $shareData['shareWith']);
1303
-		$query->bindValue(6, $shareData['uidOwner']);
1304
-		$query->bindValue(7, $shareData['permissions']);
1305
-		$query->bindValue(8, $shareData['shareTime']);
1306
-		$query->bindValue(9, $shareData['fileSource']);
1307
-		$query->bindValue(10, $shareData['fileTarget']);
1308
-		$query->bindValue(11, $shareData['token']);
1309
-		$query->bindValue(12, $shareData['parent']);
1310
-		$query->bindValue(13, $shareData['expiration'], 'datetime');
1311
-		$result = $query->execute();
1312
-
1313
-		$id = false;
1314
-		if ($result) {
1315
-			$id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1316
-		}
1317
-
1318
-		return $id;
1319
-
1320
-	}
1321
-
1322
-	/**
1323
-	 * construct select statement
1324
-	 * @param int $format
1325
-	 * @param boolean $fileDependent ist it a file/folder share or a generla share
1326
-	 * @param string $uidOwner
1327
-	 * @return string select statement
1328
-	 */
1329
-	private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
1330
-		$select = '*';
1331
-		if ($format == self::FORMAT_STATUSES) {
1332
-			if ($fileDependent) {
1333
-				$select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
1334
-					. '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
1335
-					. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1336
-					. '`uid_initiator`';
1337
-			} else {
1338
-				$select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
1339
-			}
1340
-		} else {
1341
-			if (isset($uidOwner)) {
1342
-				if ($fileDependent) {
1343
-					$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
1344
-						. ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
1345
-						. ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
1346
-						. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1347
-				} else {
1348
-					$select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
1349
-						. ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
1350
-				}
1351
-			} else {
1352
-				if ($fileDependent) {
1353
-					if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
1354
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
1355
-							. '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
1356
-							. '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1357
-							. '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
1358
-					} else {
1359
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
1360
-							. '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
1361
-							. '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
1362
-							. '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
1363
-							. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1364
-					}
1365
-				}
1366
-			}
1367
-		}
1368
-		return $select;
1369
-	}
1370
-
1371
-
1372
-	/**
1373
-	 * transform db results
1374
-	 * @param array $row result
1375
-	 */
1376
-	private static function transformDBResults(&$row) {
1377
-		if (isset($row['id'])) {
1378
-			$row['id'] = (int) $row['id'];
1379
-		}
1380
-		if (isset($row['share_type'])) {
1381
-			$row['share_type'] = (int) $row['share_type'];
1382
-		}
1383
-		if (isset($row['parent'])) {
1384
-			$row['parent'] = (int) $row['parent'];
1385
-		}
1386
-		if (isset($row['file_parent'])) {
1387
-			$row['file_parent'] = (int) $row['file_parent'];
1388
-		}
1389
-		if (isset($row['file_source'])) {
1390
-			$row['file_source'] = (int) $row['file_source'];
1391
-		}
1392
-		if (isset($row['permissions'])) {
1393
-			$row['permissions'] = (int) $row['permissions'];
1394
-		}
1395
-		if (isset($row['storage'])) {
1396
-			$row['storage'] = (int) $row['storage'];
1397
-		}
1398
-		if (isset($row['stime'])) {
1399
-			$row['stime'] = (int) $row['stime'];
1400
-		}
1401
-		if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
1402
-			// discard expiration date for non-link shares, which might have been
1403
-			// set by ancient bugs
1404
-			$row['expiration'] = null;
1405
-		}
1406
-	}
1407
-
1408
-	/**
1409
-	 * format result
1410
-	 * @param array $items result
1411
-	 * @param string $column is it a file share or a general share ('file_target' or 'item_target')
1412
-	 * @param \OCP\Share_Backend $backend sharing backend
1413
-	 * @param int $format
1414
-	 * @param array $parameters additional format parameters
1415
-	 * @return array format result
1416
-	 */
1417
-	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
1418
-		if ($format === self::FORMAT_NONE) {
1419
-			return $items;
1420
-		} else if ($format === self::FORMAT_STATUSES) {
1421
-			$statuses = [];
1422
-			foreach ($items as $item) {
1423
-				if ($item['share_type'] === self::SHARE_TYPE_LINK) {
1424
-					if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
1425
-						continue;
1426
-					}
1427
-					$statuses[$item[$column]]['link'] = true;
1428
-				} else if (!isset($statuses[$item[$column]])) {
1429
-					$statuses[$item[$column]]['link'] = false;
1430
-				}
1431
-				if (!empty($item['file_target'])) {
1432
-					$statuses[$item[$column]]['path'] = $item['path'];
1433
-				}
1434
-			}
1435
-			return $statuses;
1436
-		} else {
1437
-			return $backend->formatItems($items, $format, $parameters);
1438
-		}
1439
-	}
1440
-
1441
-	/**
1442
-	 * remove protocol from URL
1443
-	 *
1444
-	 * @param string $url
1445
-	 * @return string
1446
-	 */
1447
-	public static function removeProtocolFromUrl($url) {
1448
-		if (strpos($url, 'https://') === 0) {
1449
-			return substr($url, strlen('https://'));
1450
-		} else if (strpos($url, 'http://') === 0) {
1451
-			return substr($url, strlen('http://'));
1452
-		}
1453
-
1454
-		return $url;
1455
-	}
1456
-
1457
-	/**
1458
-	 * try http post first with https and then with http as a fallback
1459
-	 *
1460
-	 * @param string $remoteDomain
1461
-	 * @param string $urlSuffix
1462
-	 * @param array $fields post parameters
1463
-	 * @return array
1464
-	 */
1465
-	private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
1466
-		$protocol = 'https://';
1467
-		$result = [
1468
-			'success' => false,
1469
-			'result' => '',
1470
-		];
1471
-		$try = 0;
1472
-		$discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
1473
-		while ($result['success'] === false && $try < 2) {
1474
-			$federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
1475
-			$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
1476
-			$client = \OC::$server->getHTTPClientService()->newClient();
1477
-
1478
-			try {
1479
-				$response = $client->post(
1480
-					$protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
1481
-					[
1482
-						'body' => $fields,
1483
-						'connect_timeout' => 10,
1484
-					]
1485
-				);
1486
-
1487
-				$result = ['success' => true, 'result' => $response->getBody()];
1488
-			} catch (\Exception $e) {
1489
-				$result = ['success' => false, 'result' => $e->getMessage()];
1490
-			}
1491
-
1492
-			$try++;
1493
-			$protocol = 'http://';
1494
-		}
1495
-
1496
-		return $result;
1497
-	}
1498
-
1499
-	/**
1500
-	 * send server-to-server unshare to remote server
1501
-	 *
1502
-	 * @param string $remote url
1503
-	 * @param int $id share id
1504
-	 * @param string $token
1505
-	 * @return bool
1506
-	 */
1507
-	private static function sendRemoteUnshare($remote, $id, $token) {
1508
-		$url = rtrim($remote, '/');
1509
-		$fields = ['token' => $token, 'format' => 'json'];
1510
-		$url = self::removeProtocolFromUrl($url);
1511
-		$result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
1512
-		$status = json_decode($result['result'], true);
1513
-
1514
-		return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
1515
-	}
1516
-
1517
-	/**
1518
-	 * @return int
1519
-	 */
1520
-	public static function getExpireInterval() {
1521
-		return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1522
-	}
1523
-
1524
-	/**
1525
-	 * Checks whether the given path is reachable for the given owner
1526
-	 *
1527
-	 * @param string $path path relative to files
1528
-	 * @param string $ownerStorageId storage id of the owner
1529
-	 *
1530
-	 * @return boolean true if file is reachable, false otherwise
1531
-	 */
1532
-	private static function isFileReachable($path, $ownerStorageId) {
1533
-		// if outside the home storage, file is always considered reachable
1534
-		if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
1535
-			substr($ownerStorageId, 0, 13) === 'object::user:'
1536
-		)) {
1537
-			return true;
1538
-		}
1539
-
1540
-		// if inside the home storage, the file has to be under "/files/"
1541
-		$path = ltrim($path, '/');
1542
-		if (substr($path, 0, 6) === 'files/') {
1543
-			return true;
1544
-		}
1545
-
1546
-		return false;
1547
-	}
52
+    /** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
53
+     * Construct permissions for share() and setPermissions with Or (|) e.g.
54
+     * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
55
+     *
56
+     * Check if permission is granted with And (&) e.g. Check if delete is
57
+     * granted: if ($permissions & PERMISSION_DELETE)
58
+     *
59
+     * Remove permissions with And (&) and Not (~) e.g. Remove the update
60
+     * permission: $permissions &= ~PERMISSION_UPDATE
61
+     *
62
+     * Apps are required to handle permissions on their own, this class only
63
+     * stores and manages the permissions of shares
64
+     * @see lib/public/constants.php
65
+     */
66
+
67
+    /**
68
+     * Register a sharing backend class that implements OCP\Share_Backend for an item type
69
+     * @param string $itemType Item type
70
+     * @param string $class Backend class
71
+     * @param string $collectionOf (optional) Depends on item type
72
+     * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
73
+     * @return boolean true if backend is registered or false if error
74
+     */
75
+    public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
76
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') {
77
+            if (!isset(self::$backendTypes[$itemType])) {
78
+                self::$backendTypes[$itemType] = [
79
+                    'class' => $class,
80
+                    'collectionOf' => $collectionOf,
81
+                    'supportedFileExtensions' => $supportedFileExtensions
82
+                ];
83
+                return true;
84
+            }
85
+            \OCP\Util::writeLog('OCP\Share',
86
+                'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
87
+                .' is already registered for '.$itemType,
88
+                ILogger::WARN);
89
+        }
90
+        return false;
91
+    }
92
+
93
+    /**
94
+     * Get the items of item type shared with the current user
95
+     * @param string $itemType
96
+     * @param int $format (optional) Format type must be defined by the backend
97
+     * @param mixed $parameters (optional)
98
+     * @param int $limit Number of items to return (optional) Returns all by default
99
+     * @param boolean $includeCollections (optional)
100
+     * @return mixed Return depends on format
101
+     * @deprecated TESTS ONLY - this methods is only used by tests
102
+     * called like this:
103
+     * \OC\Share\Share::getItemsSharedWith('folder'); (apps/files_sharing/tests/UpdaterTest.php)
104
+     */
105
+    public static function getItemsSharedWith() {
106
+        return self::getItems('folder', null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, self::FORMAT_NONE,
107
+            null, -1, false);
108
+    }
109
+
110
+    /**
111
+     * Get the items of item type shared with a user
112
+     * @param string $itemType
113
+     * @param string $user id for which user we want the shares
114
+     * @param int $format (optional) Format type must be defined by the backend
115
+     * @param mixed $parameters (optional)
116
+     * @param int $limit Number of items to return (optional) Returns all by default
117
+     * @param boolean $includeCollections (optional)
118
+     * @return mixed Return depends on format
119
+     */
120
+    public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
121
+                                                    $parameters = null, $limit = -1, $includeCollections = false) {
122
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
123
+            $parameters, $limit, $includeCollections);
124
+    }
125
+
126
+    /**
127
+     * Get the item of item type shared with a given user by source
128
+     * @param string $itemType
129
+     * @param string $itemSource
130
+     * @param string $user User to whom the item was shared
131
+     * @param string $owner Owner of the share
132
+     * @param int $shareType only look for a specific share type
133
+     * @return array Return list of items with file_target, permissions and expiration
134
+     */
135
+    public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
136
+        $shares = [];
137
+        $fileDependent = false;
138
+
139
+        $where = 'WHERE';
140
+        $fileDependentWhere = '';
141
+        if ($itemType === 'file' || $itemType === 'folder') {
142
+            $fileDependent = true;
143
+            $column = 'file_source';
144
+            $fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
145
+            $fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
146
+        } else {
147
+            $column = 'item_source';
148
+        }
149
+
150
+        $select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
151
+
152
+        $where .= ' `' . $column . '` = ? AND `item_type` = ? ';
153
+        $arguments = [$itemSource, $itemType];
154
+        // for link shares $user === null
155
+        if ($user !== null) {
156
+            $where .= ' AND `share_with` = ? ';
157
+            $arguments[] = $user;
158
+        }
159
+
160
+        if ($shareType !== null) {
161
+            $where .= ' AND `share_type` = ? ';
162
+            $arguments[] = $shareType;
163
+        }
164
+
165
+        if ($owner !== null) {
166
+            $where .= ' AND `uid_owner` = ? ';
167
+            $arguments[] = $owner;
168
+        }
169
+
170
+        $query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
171
+
172
+        $result = \OC_DB::executeAudited($query, $arguments);
173
+
174
+        while ($row = $result->fetchRow()) {
175
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
176
+                continue;
177
+            }
178
+            if ($fileDependent && (int)$row['file_parent'] === -1) {
179
+                // if it is a mount point we need to get the path from the mount manager
180
+                $mountManager = \OC\Files\Filesystem::getMountManager();
181
+                $mountPoint = $mountManager->findByStorageId($row['storage_id']);
182
+                if (!empty($mountPoint)) {
183
+                    $path = $mountPoint[0]->getMountPoint();
184
+                    $path = trim($path, '/');
185
+                    $path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
186
+                    $row['path'] = $path;
187
+                } else {
188
+                    \OC::$server->getLogger()->warning(
189
+                        'Could not resolve mount point for ' . $row['storage_id'],
190
+                        ['app' => 'OCP\Share']
191
+                    );
192
+                }
193
+            }
194
+            $shares[] = $row;
195
+        }
196
+
197
+        //if didn't found a result than let's look for a group share.
198
+        if(empty($shares) && $user !== null) {
199
+            $userObject = \OC::$server->getUserManager()->get($user);
200
+            $groups = [];
201
+            if ($userObject) {
202
+                $groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
203
+            }
204
+
205
+            if (!empty($groups)) {
206
+                $where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
207
+                $arguments = [$itemSource, $itemType, $groups];
208
+                $types = [null, null, IQueryBuilder::PARAM_STR_ARRAY];
209
+
210
+                if ($owner !== null) {
211
+                    $where .= ' AND `uid_owner` = ?';
212
+                    $arguments[] = $owner;
213
+                    $types[] = null;
214
+                }
215
+
216
+                // TODO: inject connection, hopefully one day in the future when this
217
+                // class isn't static anymore...
218
+                $conn = \OC::$server->getDatabaseConnection();
219
+                $result = $conn->executeQuery(
220
+                    'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
221
+                    $arguments,
222
+                    $types
223
+                );
224
+
225
+                while ($row = $result->fetch()) {
226
+                    $shares[] = $row;
227
+                }
228
+            }
229
+        }
230
+
231
+        return $shares;
232
+
233
+    }
234
+
235
+    /**
236
+     * Get the item of item type shared with the current user by source
237
+     * @param string $itemType
238
+     * @param string $itemSource
239
+     * @param int $format (optional) Format type must be defined by the backend
240
+     * @param mixed $parameters
241
+     * @param boolean $includeCollections
242
+     * @param string $shareWith (optional) define against which user should be checked, default: current user
243
+     * @return array
244
+     */
245
+    public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
246
+                                                        $parameters = null, $includeCollections = false, $shareWith = null) {
247
+        $shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
248
+        return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
249
+            $parameters, 1, $includeCollections, true);
250
+    }
251
+
252
+    /**
253
+     * Get the shared item of item type owned by the current user
254
+     * @param string $itemType
255
+     * @param string $itemSource
256
+     * @param int $format (optional) Format type must be defined by the backend
257
+     * @param mixed $parameters
258
+     * @param boolean $includeCollections
259
+     * @return mixed Return depends on format
260
+     */
261
+    public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
262
+                                            $parameters = null, $includeCollections = false) {
263
+        return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
264
+            $parameters, -1, $includeCollections);
265
+    }
266
+
267
+    /**
268
+     * Share an item with a user, group, or via private link
269
+     * @param string $itemType
270
+     * @param string $itemSource
271
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
272
+     * @param string $shareWith User or group the item is being shared with
273
+     * @param int $permissions CRUDS
274
+     * @param string $itemSourceName
275
+     * @param \DateTime|null $expirationDate
276
+     * @return boolean|string Returns true on success or false on failure, Returns token on success for links
277
+     * @throws \OC\HintException when the share type is remote and the shareWith is invalid
278
+     * @throws \Exception
279
+     * @since 5.0.0 - parameter $itemSourceName was added in 6.0.0, parameter $expirationDate was added in 7.0.0, parameter $passwordChanged added in 9.0.0
280
+     * @deprecated 14.0.0 TESTS ONLY - this methods is as of 2018-06 only used by tests
281
+     * called like this:
282
+     * \OC\Share\Share::shareItem('test', 1, \OCP\Share::SHARE_TYPE_USER, $otherUserId, \OCP\Constants::PERMISSION_READ);
283
+     */
284
+    public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions) {
285
+        $backend = self::getBackend($itemType);
286
+
287
+        if ($backend->isShareTypeAllowed($shareType) === false) {
288
+            $message = 'Sharing failed, because the backend does not allow shares from type %i';
289
+            throw new \Exception(sprintf($message, $shareType));
290
+        }
291
+
292
+        $uidOwner = \OC_User::getUser();
293
+
294
+        // Verify share type and sharing conditions are met
295
+        if ($shareType === self::SHARE_TYPE_USER) {
296
+            if ($shareWith == $uidOwner) {
297
+                $message = 'Sharing failed, because you can not share with yourself';
298
+                throw new \Exception($message);
299
+            }
300
+            if (!\OC::$server->getUserManager()->userExists($shareWith)) {
301
+                $message = 'Sharing failed, because the user %s does not exist';
302
+                throw new \Exception(sprintf($message, $shareWith));
303
+            }
304
+            // Check if the item source is already shared with the user, either from the same owner or a different user
305
+            if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
306
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
307
+                // Only allow the same share to occur again if it is the same
308
+                // owner and is not a user share, this use case is for increasing
309
+                // permissions for a specific user
310
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
311
+                    $message = 'Sharing failed, because this item is already shared with %s';
312
+                    throw new \Exception(sprintf($message, $shareWith));
313
+                }
314
+            }
315
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
316
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
317
+                // Only allow the same share to occur again if it is the same
318
+                // owner and is not a user share, this use case is for increasing
319
+                // permissions for a specific user
320
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
321
+                    $message = 'Sharing failed, because this item is already shared with user %s';
322
+                    throw new \Exception(sprintf($message, $shareWith));
323
+                }
324
+            }
325
+        }
326
+
327
+        // Put the item into the database
328
+        $result = self::put('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions);
329
+
330
+        return $result ? true : false;
331
+    }
332
+
333
+    /**
334
+     * Unshare an item from a user, group, or delete a private link
335
+     * @param string $itemType
336
+     * @param string $itemSource
337
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
338
+     * @param string $shareWith User or group the item is being shared with
339
+     * @param string $owner owner of the share, if null the current user is used
340
+     * @return boolean true on success or false on failure
341
+     */
342
+    public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
343
+
344
+        // check if it is a valid itemType
345
+        self::getBackend($itemType);
346
+
347
+        $items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
348
+
349
+        $toDelete = [];
350
+        $newParent = null;
351
+        $currentUser = $owner ? $owner : \OC_User::getUser();
352
+        foreach ($items as $item) {
353
+            // delete the item with the expected share_type and owner
354
+            if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
355
+                $toDelete = $item;
356
+                // if there is more then one result we don't have to delete the children
357
+                // but update their parent. For group shares the new parent should always be
358
+                // the original group share and not the db entry with the unique name
359
+            } else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
360
+                $newParent = $item['parent'];
361
+            } else {
362
+                $newParent = $item['id'];
363
+            }
364
+        }
365
+
366
+        if (!empty($toDelete)) {
367
+            self::unshareItem($toDelete, $newParent);
368
+            return true;
369
+        }
370
+        return false;
371
+    }
372
+
373
+    /**
374
+     * Checks whether a share has expired, calls unshareItem() if yes.
375
+     * @param array $item Share data (usually database row)
376
+     * @return boolean True if item was expired, false otherwise.
377
+     */
378
+    protected static function expireItem(array $item) {
379
+
380
+        $result = false;
381
+
382
+        // only use default expiration date for link shares
383
+        if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
384
+
385
+            // calculate expiration date
386
+            if (!empty($item['expiration'])) {
387
+                $userDefinedExpire = new \DateTime($item['expiration']);
388
+                $expires = $userDefinedExpire->getTimestamp();
389
+            } else {
390
+                $expires = null;
391
+            }
392
+
393
+
394
+            // get default expiration settings
395
+            $defaultSettings = Helper::getDefaultExpireSetting();
396
+            $expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
397
+
398
+
399
+            if (is_int($expires)) {
400
+                $now = time();
401
+                if ($now > $expires) {
402
+                    self::unshareItem($item);
403
+                    $result = true;
404
+                }
405
+            }
406
+        }
407
+        return $result;
408
+    }
409
+
410
+    /**
411
+     * Unshares a share given a share data array
412
+     * @param array $item Share data (usually database row)
413
+     * @param int $newParent parent ID
414
+     * @return null
415
+     */
416
+    protected static function unshareItem(array $item, $newParent = null) {
417
+
418
+        $shareType = (int)$item['share_type'];
419
+        $shareWith = null;
420
+        if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
421
+            $shareWith = $item['share_with'];
422
+        }
423
+
424
+        // Pass all the vars we have for now, they may be useful
425
+        $hookParams = [
426
+            'id'            => $item['id'],
427
+            'itemType'      => $item['item_type'],
428
+            'itemSource'    => $item['item_source'],
429
+            'shareType'     => $shareType,
430
+            'shareWith'     => $shareWith,
431
+            'itemParent'    => $item['parent'],
432
+            'uidOwner'      => $item['uid_owner'],
433
+        ];
434
+        if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
435
+            $hookParams['fileSource'] = $item['file_source'];
436
+            $hookParams['fileTarget'] = $item['file_target'];
437
+        }
438
+
439
+        \OC_Hook::emit(\OCP\Share::class, 'pre_unshare', $hookParams);
440
+        $deletedShares = Helper::delete($item['id'], false, null, $newParent);
441
+        $deletedShares[] = $hookParams;
442
+        $hookParams['deletedShares'] = $deletedShares;
443
+        \OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
444
+        if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
445
+            list(, $remote) = Helper::splitUserRemote($item['share_with']);
446
+            self::sendRemoteUnshare($remote, $item['id'], $item['token']);
447
+        }
448
+    }
449
+
450
+    /**
451
+     * Get the backend class for the specified item type
452
+     * @param string $itemType
453
+     * @throws \Exception
454
+     * @return \OCP\Share_Backend
455
+     */
456
+    public static function getBackend($itemType) {
457
+        $l = \OC::$server->getL10N('lib');
458
+        if (isset(self::$backends[$itemType])) {
459
+            return self::$backends[$itemType];
460
+        } else if (isset(self::$backendTypes[$itemType]['class'])) {
461
+            $class = self::$backendTypes[$itemType]['class'];
462
+            if (class_exists($class)) {
463
+                self::$backends[$itemType] = new $class;
464
+                if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
465
+                    $message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
466
+                    $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', [$class]);
467
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
468
+                    throw new \Exception($message_t);
469
+                }
470
+                return self::$backends[$itemType];
471
+            } else {
472
+                $message = 'Sharing backend %s not found';
473
+                $message_t = $l->t('Sharing backend %s not found', [$class]);
474
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
475
+                throw new \Exception($message_t);
476
+            }
477
+        }
478
+        $message = 'Sharing backend for %s not found';
479
+        $message_t = $l->t('Sharing backend for %s not found', [$itemType]);
480
+        \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), ILogger::ERROR);
481
+        throw new \Exception($message_t);
482
+    }
483
+
484
+    /**
485
+     * Check if resharing is allowed
486
+     * @return boolean true if allowed or false
487
+     *
488
+     * Resharing is allowed by default if not configured
489
+     */
490
+    public static function isResharingAllowed() {
491
+        if (!isset(self::$isResharingAllowed)) {
492
+            if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
493
+                self::$isResharingAllowed = true;
494
+            } else {
495
+                self::$isResharingAllowed = false;
496
+            }
497
+        }
498
+        return self::$isResharingAllowed;
499
+    }
500
+
501
+    /**
502
+     * Get a list of collection item types for the specified item type
503
+     * @param string $itemType
504
+     * @return array
505
+     */
506
+    private static function getCollectionItemTypes($itemType) {
507
+        $collectionTypes = [$itemType];
508
+        foreach (self::$backendTypes as $type => $backend) {
509
+            if (in_array($backend['collectionOf'], $collectionTypes)) {
510
+                $collectionTypes[] = $type;
511
+            }
512
+        }
513
+        // TODO Add option for collections to be collection of themselves, only 'folder' does it now...
514
+        if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
515
+            unset($collectionTypes[0]);
516
+        }
517
+        // Return array if collections were found or the item type is a
518
+        // collection itself - collections can be inside collections
519
+        if (count($collectionTypes) > 0) {
520
+            return $collectionTypes;
521
+        }
522
+        return false;
523
+    }
524
+
525
+    /**
526
+     * Get the owners of items shared with a user.
527
+     *
528
+     * @param string $user The user the items are shared with.
529
+     * @param string $type The type of the items shared with the user.
530
+     * @param boolean $includeCollections Include collection item types (optional)
531
+     * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
532
+     * @return array
533
+     * @deprecated TESTS ONLY - this methods is only used by tests
534
+     * called like this:
535
+     * \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true)
536
+     */
537
+    public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
538
+        // First, we find out if $type is part of a collection (and if that collection is part of
539
+        // another one and so on).
540
+        $collectionTypes = [];
541
+        if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
542
+            $collectionTypes[] = $type;
543
+        }
544
+
545
+        // Of these collection types, along with our original $type, we make a
546
+        // list of the ones for which a sharing backend has been registered.
547
+        // FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
548
+        // with its $includeCollections parameter set to true. Unfortunately, this fails currently.
549
+        $allMaybeSharedItems = [];
550
+        foreach ($collectionTypes as $collectionType) {
551
+            if (isset(self::$backends[$collectionType])) {
552
+                $allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
553
+                    $collectionType,
554
+                    $user,
555
+                    self::FORMAT_NONE
556
+                );
557
+            }
558
+        }
559
+
560
+        $owners = [];
561
+        if ($includeOwner) {
562
+            $owners[] = $user;
563
+        }
564
+
565
+        // We take a look at all shared items of the given $type (or of the collections it is part of)
566
+        // and find out their owners. Then, we gather the tags for the original $type from all owners,
567
+        // and return them as elements of a list that look like "Tag (owner)".
568
+        foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
569
+            foreach ($maybeSharedItems as $sharedItem) {
570
+                if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
571
+                    $owners[] = $sharedItem['uid_owner'];
572
+                }
573
+            }
574
+        }
575
+
576
+        return $owners;
577
+    }
578
+
579
+    /**
580
+     * Get shared items from the database
581
+     * @param string $itemType
582
+     * @param string $item Item source or target (optional)
583
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
584
+     * @param string $shareWith User or group the item is being shared with
585
+     * @param string $uidOwner User that is the owner of shared items (optional)
586
+     * @param int $format Format to convert items to with formatItems() (optional)
587
+     * @param mixed $parameters to pass to formatItems() (optional)
588
+     * @param int $limit Number of items to return, -1 to return all matches (optional)
589
+     * @param boolean $includeCollections Include collection item types (optional)
590
+     * @param boolean $itemShareWithBySource (optional)
591
+     * @param boolean $checkExpireDate
592
+     * @return array
593
+     *
594
+     * See public functions getItem(s)... for parameter usage
595
+     *
596
+     */
597
+    public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
598
+                                    $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
599
+                                    $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
600
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') {
601
+            return [];
602
+        }
603
+        $backend = self::getBackend($itemType);
604
+        $collectionTypes = false;
605
+        // Get filesystem root to add it to the file target and remove from the
606
+        // file source, match file_source with the file cache
607
+        if ($itemType == 'file' || $itemType == 'folder') {
608
+            if(!is_null($uidOwner)) {
609
+                $root = \OC\Files\Filesystem::getRoot();
610
+            } else {
611
+                $root = '';
612
+            }
613
+            $where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
614
+            if (!isset($item)) {
615
+                $where .= ' AND `file_target` IS NOT NULL ';
616
+            }
617
+            $where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
618
+            $fileDependent = true;
619
+            $queryArgs = [];
620
+        } else {
621
+            $fileDependent = false;
622
+            $root = '';
623
+            $collectionTypes = self::getCollectionItemTypes($itemType);
624
+            if ($includeCollections && !isset($item) && $collectionTypes) {
625
+                // If includeCollections is true, find collections of this item type, e.g. a music album contains songs
626
+                if (!in_array($itemType, $collectionTypes)) {
627
+                    $itemTypes = array_merge([$itemType], $collectionTypes);
628
+                } else {
629
+                    $itemTypes = $collectionTypes;
630
+                }
631
+                $placeholders = implode(',', array_fill(0, count($itemTypes), '?'));
632
+                $where = ' WHERE `item_type` IN ('.$placeholders.'))';
633
+                $queryArgs = $itemTypes;
634
+            } else {
635
+                $where = ' WHERE `item_type` = ?';
636
+                $queryArgs = [$itemType];
637
+            }
638
+        }
639
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
640
+            $where .= ' AND `share_type` != ?';
641
+            $queryArgs[] = self::SHARE_TYPE_LINK;
642
+        }
643
+        if (isset($shareType)) {
644
+            // Include all user and group items
645
+            if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
646
+                $where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
647
+                $queryArgs[] = self::SHARE_TYPE_USER;
648
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
649
+                $queryArgs[] = $shareWith;
650
+
651
+                $user = \OC::$server->getUserManager()->get($shareWith);
652
+                $groups = [];
653
+                if ($user) {
654
+                    $groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
655
+                }
656
+                if (!empty($groups)) {
657
+                    $placeholders = implode(',', array_fill(0, count($groups), '?'));
658
+                    $where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
659
+                    $queryArgs[] = self::SHARE_TYPE_GROUP;
660
+                    $queryArgs = array_merge($queryArgs, $groups);
661
+                }
662
+                $where .= ')';
663
+                // Don't include own group shares
664
+                $where .= ' AND `uid_owner` != ?';
665
+                $queryArgs[] = $shareWith;
666
+            } else {
667
+                $where .= ' AND `share_type` = ?';
668
+                $queryArgs[] = $shareType;
669
+                if (isset($shareWith)) {
670
+                    $where .= ' AND `share_with` = ?';
671
+                    $queryArgs[] = $shareWith;
672
+                }
673
+            }
674
+        }
675
+        if (isset($uidOwner)) {
676
+            $where .= ' AND `uid_owner` = ?';
677
+            $queryArgs[] = $uidOwner;
678
+            if (!isset($shareType)) {
679
+                // Prevent unique user targets for group shares from being selected
680
+                $where .= ' AND `share_type` != ?';
681
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
682
+            }
683
+            if ($fileDependent) {
684
+                $column = 'file_source';
685
+            } else {
686
+                $column = 'item_source';
687
+            }
688
+        } else {
689
+            if ($fileDependent) {
690
+                $column = 'file_target';
691
+            } else {
692
+                $column = 'item_target';
693
+            }
694
+        }
695
+        if (isset($item)) {
696
+            $collectionTypes = self::getCollectionItemTypes($itemType);
697
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
698
+                $where .= ' AND (';
699
+            } else {
700
+                $where .= ' AND';
701
+            }
702
+            // If looking for own shared items, check item_source else check item_target
703
+            if (isset($uidOwner) || $itemShareWithBySource) {
704
+                // If item type is a file, file source needs to be checked in case the item was converted
705
+                if ($fileDependent) {
706
+                    $where .= ' `file_source` = ?';
707
+                    $column = 'file_source';
708
+                } else {
709
+                    $where .= ' `item_source` = ?';
710
+                    $column = 'item_source';
711
+                }
712
+            } else {
713
+                if ($fileDependent) {
714
+                    $where .= ' `file_target` = ?';
715
+                    $item = \OC\Files\Filesystem::normalizePath($item);
716
+                } else {
717
+                    $where .= ' `item_target` = ?';
718
+                }
719
+            }
720
+            $queryArgs[] = $item;
721
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
722
+                $placeholders = implode(',', array_fill(0, count($collectionTypes), '?'));
723
+                $where .= ' OR `item_type` IN ('.$placeholders.'))';
724
+                $queryArgs = array_merge($queryArgs, $collectionTypes);
725
+            }
726
+        }
727
+
728
+        if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
729
+            // Make sure the unique user target is returned if it exists,
730
+            // unique targets should follow the group share in the database
731
+            // If the limit is not 1, the filtering can be done later
732
+            $where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
733
+        } else {
734
+            $where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
735
+        }
736
+
737
+        if ($limit != -1 && !$includeCollections) {
738
+            // The limit must be at least 3, because filtering needs to be done
739
+            if ($limit < 3) {
740
+                $queryLimit = 3;
741
+            } else {
742
+                $queryLimit = $limit;
743
+            }
744
+        } else {
745
+            $queryLimit = null;
746
+        }
747
+        $select = self::createSelectStatement($format, $fileDependent, $uidOwner);
748
+        $root = strlen($root);
749
+        $query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
750
+        $result = $query->execute($queryArgs);
751
+        if ($result === false) {
752
+            \OCP\Util::writeLog('OCP\Share',
753
+                \OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
754
+                ILogger::ERROR);
755
+        }
756
+        $items = [];
757
+        $targets = [];
758
+        $switchedItems = [];
759
+        $mounts = [];
760
+        while ($row = $result->fetchRow()) {
761
+            self::transformDBResults($row);
762
+            // Filter out duplicate group shares for users with unique targets
763
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
764
+                continue;
765
+            }
766
+            if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
767
+                $row['share_type'] = self::SHARE_TYPE_GROUP;
768
+                $row['unique_name'] = true; // remember that we use a unique name for this user
769
+                $row['share_with'] = $items[$row['parent']]['share_with'];
770
+                // if the group share was unshared from the user we keep the permission, otherwise
771
+                // we take the permission from the parent because this is always the up-to-date
772
+                // permission for the group share
773
+                if ($row['permissions'] > 0) {
774
+                    $row['permissions'] = $items[$row['parent']]['permissions'];
775
+                }
776
+                // Remove the parent group share
777
+                unset($items[$row['parent']]);
778
+                if ($row['permissions'] == 0) {
779
+                    continue;
780
+                }
781
+            } else if (!isset($uidOwner)) {
782
+                // Check if the same target already exists
783
+                if (isset($targets[$row['id']])) {
784
+                    // Check if the same owner shared with the user twice
785
+                    // through a group and user share - this is allowed
786
+                    $id = $targets[$row['id']];
787
+                    if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
788
+                        // Switch to group share type to ensure resharing conditions aren't bypassed
789
+                        if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
790
+                            $items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
791
+                            $items[$id]['share_with'] = $row['share_with'];
792
+                        }
793
+                        // Switch ids if sharing permission is granted on only
794
+                        // one share to ensure correct parent is used if resharing
795
+                        if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
796
+                            && (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
797
+                            $items[$row['id']] = $items[$id];
798
+                            $switchedItems[$id] = $row['id'];
799
+                            unset($items[$id]);
800
+                            $id = $row['id'];
801
+                        }
802
+                        $items[$id]['permissions'] |= (int)$row['permissions'];
803
+
804
+                    }
805
+                    continue;
806
+                } elseif (!empty($row['parent'])) {
807
+                    $targets[$row['parent']] = $row['id'];
808
+                }
809
+            }
810
+            // Remove root from file source paths if retrieving own shared items
811
+            if (isset($uidOwner) && isset($row['path'])) {
812
+                if (isset($row['parent'])) {
813
+                    $query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
814
+                    $parentResult = $query->execute([$row['parent']]);
815
+                    if ($result === false) {
816
+                        \OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
817
+                            \OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
818
+                            ILogger::ERROR);
819
+                    } else {
820
+                        $parentRow = $parentResult->fetchRow();
821
+                        $tmpPath = $parentRow['file_target'];
822
+                        // find the right position where the row path continues from the target path
823
+                        $pos = strrpos($row['path'], $parentRow['file_target']);
824
+                        $subPath = substr($row['path'], $pos);
825
+                        $splitPath = explode('/', $subPath);
826
+                        foreach (array_slice($splitPath, 2) as $pathPart) {
827
+                            $tmpPath = $tmpPath . '/' . $pathPart;
828
+                        }
829
+                        $row['path'] = $tmpPath;
830
+                    }
831
+                } else {
832
+                    if (!isset($mounts[$row['storage']])) {
833
+                        $mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
834
+                        if (is_array($mountPoints) && !empty($mountPoints)) {
835
+                            $mounts[$row['storage']] = current($mountPoints);
836
+                        }
837
+                    }
838
+                    if (!empty($mounts[$row['storage']])) {
839
+                        $path = $mounts[$row['storage']]->getMountPoint().$row['path'];
840
+                        $relPath = substr($path, $root); // path relative to data/user
841
+                        $row['path'] = rtrim($relPath, '/');
842
+                    }
843
+                }
844
+            }
845
+
846
+            if($checkExpireDate) {
847
+                if (self::expireItem($row)) {
848
+                    continue;
849
+                }
850
+            }
851
+            // Check if resharing is allowed, if not remove share permission
852
+            if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
853
+                $row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
854
+            }
855
+            // Add display names to result
856
+            $row['share_with_displayname'] = $row['share_with'];
857
+            if ( isset($row['share_with']) && $row['share_with'] != '' &&
858
+                $row['share_type'] === self::SHARE_TYPE_USER) {
859
+                $shareWithUser = \OC::$server->getUserManager()->get($row['share_with']);
860
+                $row['share_with_displayname'] = $shareWithUser === null ? $row['share_with'] : $shareWithUser->getDisplayName();
861
+            } else if(isset($row['share_with']) && $row['share_with'] != '' &&
862
+                $row['share_type'] === self::SHARE_TYPE_REMOTE) {
863
+                $addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
864
+                foreach ($addressBookEntries as $entry) {
865
+                    foreach ($entry['CLOUD'] as $cloudID) {
866
+                        if ($cloudID === $row['share_with']) {
867
+                            $row['share_with_displayname'] = $entry['FN'];
868
+                        }
869
+                    }
870
+                }
871
+            }
872
+            if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
873
+                $ownerUser = \OC::$server->getUserManager()->get($row['uid_owner']);
874
+                $row['displayname_owner'] = $ownerUser === null ? $row['uid_owner'] : $ownerUser->getDisplayName();
875
+            }
876
+
877
+            if ($row['permissions'] > 0) {
878
+                $items[$row['id']] = $row;
879
+            }
880
+
881
+        }
882
+
883
+        // group items if we are looking for items shared with the current user
884
+        if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
885
+            $items = self::groupItems($items, $itemType);
886
+        }
887
+
888
+        if (!empty($items)) {
889
+            $collectionItems = [];
890
+            foreach ($items as &$row) {
891
+                // Return only the item instead of a 2-dimensional array
892
+                if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
893
+                    if ($format == self::FORMAT_NONE) {
894
+                        return $row;
895
+                    } else {
896
+                        break;
897
+                    }
898
+                }
899
+                // Check if this is a collection of the requested item type
900
+                if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
901
+                    if (($collectionBackend = self::getBackend($row['item_type']))
902
+                        && $collectionBackend instanceof \OCP\Share_Backend_Collection) {
903
+                        // Collections can be inside collections, check if the item is a collection
904
+                        if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
905
+                            $collectionItems[] = $row;
906
+                        } else {
907
+                            $collection = [];
908
+                            $collection['item_type'] = $row['item_type'];
909
+                            if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
910
+                                $collection['path'] = basename($row['path']);
911
+                            }
912
+                            $row['collection'] = $collection;
913
+                            // Fetch all of the children sources
914
+                            $children = $collectionBackend->getChildren($row[$column]);
915
+                            foreach ($children as $child) {
916
+                                $childItem = $row;
917
+                                $childItem['item_type'] = $itemType;
918
+                                if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
919
+                                    $childItem['item_source'] = $child['source'];
920
+                                    $childItem['item_target'] = $child['target'];
921
+                                }
922
+                                if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
923
+                                    if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
924
+                                        $childItem['file_source'] = $child['source'];
925
+                                    } else { // TODO is this really needed if we already know that we use the file backend?
926
+                                        $meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
927
+                                        $childItem['file_source'] = $meta['fileid'];
928
+                                    }
929
+                                    $childItem['file_target'] =
930
+                                        \OC\Files\Filesystem::normalizePath($child['file_path']);
931
+                                }
932
+                                if (isset($item)) {
933
+                                    if ($childItem[$column] == $item) {
934
+                                        // Return only the item instead of a 2-dimensional array
935
+                                        if ($limit == 1) {
936
+                                            if ($format == self::FORMAT_NONE) {
937
+                                                return $childItem;
938
+                                            } else {
939
+                                                // Unset the items array and break out of both loops
940
+                                                $items = [];
941
+                                                $items[] = $childItem;
942
+                                                break 2;
943
+                                            }
944
+                                        } else {
945
+                                            $collectionItems[] = $childItem;
946
+                                        }
947
+                                    }
948
+                                } else {
949
+                                    $collectionItems[] = $childItem;
950
+                                }
951
+                            }
952
+                        }
953
+                    }
954
+                    // Remove collection item
955
+                    $toRemove = $row['id'];
956
+                    if (array_key_exists($toRemove, $switchedItems)) {
957
+                        $toRemove = $switchedItems[$toRemove];
958
+                    }
959
+                    unset($items[$toRemove]);
960
+                } elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
961
+                    // FIXME: Thats a dirty hack to improve file sharing performance,
962
+                    // see github issue #10588 for more details
963
+                    // Need to find a solution which works for all back-ends
964
+                    $collectionBackend = self::getBackend($row['item_type']);
965
+                    $sharedParents = $collectionBackend->getParents($row['item_source']);
966
+                    foreach ($sharedParents as $parent) {
967
+                        $collectionItems[] = $parent;
968
+                    }
969
+                }
970
+            }
971
+            if (!empty($collectionItems)) {
972
+                $collectionItems = array_unique($collectionItems, SORT_REGULAR);
973
+                $items = array_merge($items, $collectionItems);
974
+            }
975
+
976
+            // filter out invalid items, these can appear when subshare entries exist
977
+            // for a group in which the requested user isn't a member any more
978
+            $items = array_filter($items, function ($item) {
979
+                return $item['share_type'] !== self::$shareTypeGroupUserUnique;
980
+            });
981
+
982
+            return self::formatResult($items, $column, $backend, $format, $parameters);
983
+        } elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
984
+            // FIXME: Thats a dirty hack to improve file sharing performance,
985
+            // see github issue #10588 for more details
986
+            // Need to find a solution which works for all back-ends
987
+            $collectionItems = [];
988
+            $collectionBackend = self::getBackend('folder');
989
+            $sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
990
+            foreach ($sharedParents as $parent) {
991
+                $collectionItems[] = $parent;
992
+            }
993
+            if ($limit === 1) {
994
+                return reset($collectionItems);
995
+            }
996
+            return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
997
+        }
998
+
999
+        return [];
1000
+    }
1001
+
1002
+    /**
1003
+     * group items with link to the same source
1004
+     *
1005
+     * @param array $items
1006
+     * @param string $itemType
1007
+     * @return array of grouped items
1008
+     */
1009
+    protected static function groupItems($items, $itemType) {
1010
+
1011
+        $fileSharing = $itemType === 'file' || $itemType === 'folder';
1012
+
1013
+        $result = [];
1014
+
1015
+        foreach ($items as $item) {
1016
+            $grouped = false;
1017
+            foreach ($result as $key => $r) {
1018
+                // for file/folder shares we need to compare file_source, otherwise we compare item_source
1019
+                // only group shares if they already point to the same target, otherwise the file where shared
1020
+                // before grouping of shares was added. In this case we don't group them toi avoid confusions
1021
+                if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1022
+                    (!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
1023
+                    // add the first item to the list of grouped shares
1024
+                    if (!isset($result[$key]['grouped'])) {
1025
+                        $result[$key]['grouped'][] = $result[$key];
1026
+                    }
1027
+                    $result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
1028
+                    $result[$key]['grouped'][] = $item;
1029
+                    $grouped = true;
1030
+                    break;
1031
+                }
1032
+            }
1033
+
1034
+            if (!$grouped) {
1035
+                $result[] = $item;
1036
+            }
1037
+
1038
+        }
1039
+
1040
+        return $result;
1041
+    }
1042
+
1043
+    /**
1044
+     * Put shared item into the database
1045
+     * @param string $itemType Item type
1046
+     * @param string $itemSource Item source
1047
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1048
+     * @param string $shareWith User or group the item is being shared with
1049
+     * @param string $uidOwner User that is the owner of shared item
1050
+     * @param int $permissions CRUDS permissions
1051
+     * @throws \Exception
1052
+     * @return mixed id of the new share or false
1053
+     * @deprecated TESTS ONLY - this methods is only used by tests
1054
+     * called like this:
1055
+     * self::put('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions);
1056
+     */
1057
+    private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1058
+                                $permissions) {
1059
+
1060
+        $queriesToExecute = [];
1061
+        $suggestedItemTarget = null;
1062
+        $groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
1063
+        $groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1064
+
1065
+        $result = self::checkReshare('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions, null, null);
1066
+        if(!empty($result)) {
1067
+            $parent = $result['parent'];
1068
+            $itemSource = $result['itemSource'];
1069
+            $fileSource = $result['fileSource'];
1070
+            $suggestedItemTarget = $result['suggestedItemTarget'];
1071
+            $suggestedFileTarget = $result['suggestedFileTarget'];
1072
+            $filePath = $result['filePath'];
1073
+        }
1074
+
1075
+        $isGroupShare = false;
1076
+            $users = [$shareWith];
1077
+            $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1078
+                $suggestedItemTarget);
1079
+
1080
+        $run = true;
1081
+        $error = '';
1082
+        $preHookData = [
1083
+            'itemType' => $itemType,
1084
+            'itemSource' => $itemSource,
1085
+            'shareType' => $shareType,
1086
+            'uidOwner' => $uidOwner,
1087
+            'permissions' => $permissions,
1088
+            'fileSource' => $fileSource,
1089
+            'expiration' => null,
1090
+            'token' => null,
1091
+            'run' => &$run,
1092
+            'error' => &$error
1093
+        ];
1094
+
1095
+        $preHookData['itemTarget'] = $itemTarget;
1096
+        $preHookData['shareWith'] = $shareWith;
1097
+
1098
+        \OC_Hook::emit(\OCP\Share::class, 'pre_shared', $preHookData);
1099
+
1100
+        if ($run === false) {
1101
+            throw new \Exception($error);
1102
+        }
1103
+
1104
+        foreach ($users as $user) {
1105
+            $sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
1106
+            $sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
1107
+
1108
+            $userShareType = $shareType;
1109
+
1110
+            if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
1111
+                $fileTarget = $sourceExists['file_target'];
1112
+                $itemTarget = $sourceExists['item_target'];
1113
+
1114
+            } elseif(!$sourceExists)  {
1115
+
1116
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1117
+                    $uidOwner, $suggestedItemTarget, $parent);
1118
+                if (isset($fileSource)) {
1119
+                        $fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
1120
+                            $user, $uidOwner, $suggestedFileTarget, $parent);
1121
+                } else {
1122
+                    $fileTarget = null;
1123
+                }
1124
+
1125
+            } else {
1126
+
1127
+                // group share which doesn't exists until now, check if we need a unique target for this user
1128
+
1129
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
1130
+                    $uidOwner, $suggestedItemTarget, $parent);
1131
+
1132
+                // do we also need a file target
1133
+                if (isset($fileSource)) {
1134
+                    $fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
1135
+                        $uidOwner, $suggestedFileTarget, $parent);
1136
+                } else {
1137
+                    $fileTarget = null;
1138
+                }
1139
+
1140
+                if (($itemTarget === $groupItemTarget) &&
1141
+                    (!isset($fileSource) || $fileTarget === $groupFileTarget)) {
1142
+                    continue;
1143
+                }
1144
+            }
1145
+
1146
+            $queriesToExecute[] = [
1147
+                'itemType'			=> $itemType,
1148
+                'itemSource'		=> $itemSource,
1149
+                'itemTarget'		=> $itemTarget,
1150
+                'shareType'			=> $userShareType,
1151
+                'shareWith'			=> $user,
1152
+                'uidOwner'			=> $uidOwner,
1153
+                'permissions'		=> $permissions,
1154
+                'shareTime'			=> time(),
1155
+                'fileSource'		=> $fileSource,
1156
+                'fileTarget'		=> $fileTarget,
1157
+                'token'				=> null,
1158
+                'parent'			=> $parent,
1159
+                'expiration'		=> null,
1160
+            ];
1161
+
1162
+        }
1163
+
1164
+        $id = false;
1165
+
1166
+        foreach ($queriesToExecute as $shareQuery) {
1167
+            $shareQuery['parent'] = $parent;
1168
+            $id = self::insertShare($shareQuery);
1169
+        }
1170
+
1171
+        $postHookData = [
1172
+            'itemType' => $itemType,
1173
+            'itemSource' => $itemSource,
1174
+            'parent' => $parent,
1175
+            'shareType' => $shareType,
1176
+            'uidOwner' => $uidOwner,
1177
+            'permissions' => $permissions,
1178
+            'fileSource' => $fileSource,
1179
+            'id' => $parent,
1180
+            'token' => null,
1181
+            'expirationDate' => null,
1182
+        ];
1183
+
1184
+        $postHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith;
1185
+        $postHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget;
1186
+        $postHookData['fileTarget'] = $isGroupShare ? $groupFileTarget : $fileTarget;
1187
+
1188
+        \OC_Hook::emit(\OCP\Share::class, 'post_shared', $postHookData);
1189
+
1190
+
1191
+        return $id ? $id : false;
1192
+    }
1193
+
1194
+    /**
1195
+     * @param string $itemType
1196
+     * @param string $itemSource
1197
+     * @param int $shareType
1198
+     * @param string $shareWith
1199
+     * @param string $uidOwner
1200
+     * @param int $permissions
1201
+     * @param string|null $itemSourceName
1202
+     * @param null|\DateTime $expirationDate
1203
+     * @deprecated TESTS ONLY - this methods is only used by tests
1204
+     * called like this:
1205
+     * self::checkReshare('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions, null, null);
1206
+     */
1207
+    private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
1208
+        $backend = self::getBackend($itemType);
1209
+
1210
+        $result = [];
1211
+
1212
+        $column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
1213
+
1214
+        $checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
1215
+        if ($checkReshare) {
1216
+            // Check if attempting to share back to owner
1217
+            if ($checkReshare['uid_owner'] == $shareWith) {
1218
+                $message = 'Sharing %1$s failed, because the user %2$s is the original sharer';
1219
+                throw new \Exception(sprintf($message, $itemSourceName, $shareWith));
1220
+            }
1221
+        }
1222
+
1223
+        if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1224
+            // Check if share permissions is granted
1225
+            if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1226
+                if (~(int)$checkReshare['permissions'] & $permissions) {
1227
+                    $message = 'Sharing %1$s failed, because the permissions exceed permissions granted to %2$s';
1228
+                    throw new \Exception(sprintf($message, $itemSourceName, $uidOwner));
1229
+                } else {
1230
+                    // TODO Don't check if inside folder
1231
+                    $result['parent'] = $checkReshare['id'];
1232
+
1233
+                    $result['expirationDate'] = $expirationDate;
1234
+                    // $checkReshare['expiration'] could be null and then is always less than any value
1235
+                    if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1236
+                        $result['expirationDate'] = $checkReshare['expiration'];
1237
+                    }
1238
+
1239
+                    // only suggest the same name as new target if it is a reshare of the
1240
+                    // same file/folder and not the reshare of a child
1241
+                    if ($checkReshare[$column] === $itemSource) {
1242
+                        $result['filePath'] = $checkReshare['file_target'];
1243
+                        $result['itemSource'] = $checkReshare['item_source'];
1244
+                        $result['fileSource'] = $checkReshare['file_source'];
1245
+                        $result['suggestedItemTarget'] = $checkReshare['item_target'];
1246
+                        $result['suggestedFileTarget'] = $checkReshare['file_target'];
1247
+                    } else {
1248
+                        $result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
1249
+                        $result['suggestedItemTarget'] = null;
1250
+                        $result['suggestedFileTarget'] = null;
1251
+                        $result['itemSource'] = $itemSource;
1252
+                        $result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
1253
+                    }
1254
+                }
1255
+            } else {
1256
+                $message = 'Sharing %s failed, because resharing is not allowed';
1257
+                throw new \Exception(sprintf($message, $itemSourceName));
1258
+            }
1259
+        } else {
1260
+            $result['parent'] = null;
1261
+            $result['suggestedItemTarget'] = null;
1262
+            $result['suggestedFileTarget'] = null;
1263
+            $result['itemSource'] = $itemSource;
1264
+            $result['expirationDate'] = $expirationDate;
1265
+            if (!$backend->isValidSource($itemSource, $uidOwner)) {
1266
+                $message = 'Sharing %1$s failed, because the sharing backend for '
1267
+                    .'%2$s could not find its source';
1268
+                throw new \Exception(sprintf($message, $itemSource, $itemType));
1269
+            }
1270
+            if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1271
+                $result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
1272
+                    $meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
1273
+                    $result['fileSource'] = $meta['fileid'];
1274
+                if ($result['fileSource'] == -1) {
1275
+                    $message = 'Sharing %s failed, because the file could not be found in the file cache';
1276
+                    throw new \Exception(sprintf($message, $itemSource));
1277
+                }
1278
+            } else {
1279
+                $result['filePath'] = null;
1280
+                $result['fileSource'] = null;
1281
+            }
1282
+        }
1283
+
1284
+        return $result;
1285
+    }
1286
+
1287
+    /**
1288
+     *
1289
+     * @param array $shareData
1290
+     * @return mixed false in case of a failure or the id of the new share
1291
+     */
1292
+    private static function insertShare(array $shareData) {
1293
+
1294
+        $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
1295
+            .' `item_type`, `item_source`, `item_target`, `share_type`,'
1296
+            .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
1297
+            .' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
1298
+        $query->bindValue(1, $shareData['itemType']);
1299
+        $query->bindValue(2, $shareData['itemSource']);
1300
+        $query->bindValue(3, $shareData['itemTarget']);
1301
+        $query->bindValue(4, $shareData['shareType']);
1302
+        $query->bindValue(5, $shareData['shareWith']);
1303
+        $query->bindValue(6, $shareData['uidOwner']);
1304
+        $query->bindValue(7, $shareData['permissions']);
1305
+        $query->bindValue(8, $shareData['shareTime']);
1306
+        $query->bindValue(9, $shareData['fileSource']);
1307
+        $query->bindValue(10, $shareData['fileTarget']);
1308
+        $query->bindValue(11, $shareData['token']);
1309
+        $query->bindValue(12, $shareData['parent']);
1310
+        $query->bindValue(13, $shareData['expiration'], 'datetime');
1311
+        $result = $query->execute();
1312
+
1313
+        $id = false;
1314
+        if ($result) {
1315
+            $id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1316
+        }
1317
+
1318
+        return $id;
1319
+
1320
+    }
1321
+
1322
+    /**
1323
+     * construct select statement
1324
+     * @param int $format
1325
+     * @param boolean $fileDependent ist it a file/folder share or a generla share
1326
+     * @param string $uidOwner
1327
+     * @return string select statement
1328
+     */
1329
+    private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
1330
+        $select = '*';
1331
+        if ($format == self::FORMAT_STATUSES) {
1332
+            if ($fileDependent) {
1333
+                $select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
1334
+                    . '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
1335
+                    . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1336
+                    . '`uid_initiator`';
1337
+            } else {
1338
+                $select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
1339
+            }
1340
+        } else {
1341
+            if (isset($uidOwner)) {
1342
+                if ($fileDependent) {
1343
+                    $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
1344
+                        . ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
1345
+                        . ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
1346
+                        . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1347
+                } else {
1348
+                    $select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
1349
+                        . ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
1350
+                }
1351
+            } else {
1352
+                if ($fileDependent) {
1353
+                    if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
1354
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
1355
+                            . '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
1356
+                            . '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1357
+                            . '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
1358
+                    } else {
1359
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
1360
+                            . '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
1361
+                            . '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
1362
+                            . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
1363
+                            . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1364
+                    }
1365
+                }
1366
+            }
1367
+        }
1368
+        return $select;
1369
+    }
1370
+
1371
+
1372
+    /**
1373
+     * transform db results
1374
+     * @param array $row result
1375
+     */
1376
+    private static function transformDBResults(&$row) {
1377
+        if (isset($row['id'])) {
1378
+            $row['id'] = (int) $row['id'];
1379
+        }
1380
+        if (isset($row['share_type'])) {
1381
+            $row['share_type'] = (int) $row['share_type'];
1382
+        }
1383
+        if (isset($row['parent'])) {
1384
+            $row['parent'] = (int) $row['parent'];
1385
+        }
1386
+        if (isset($row['file_parent'])) {
1387
+            $row['file_parent'] = (int) $row['file_parent'];
1388
+        }
1389
+        if (isset($row['file_source'])) {
1390
+            $row['file_source'] = (int) $row['file_source'];
1391
+        }
1392
+        if (isset($row['permissions'])) {
1393
+            $row['permissions'] = (int) $row['permissions'];
1394
+        }
1395
+        if (isset($row['storage'])) {
1396
+            $row['storage'] = (int) $row['storage'];
1397
+        }
1398
+        if (isset($row['stime'])) {
1399
+            $row['stime'] = (int) $row['stime'];
1400
+        }
1401
+        if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
1402
+            // discard expiration date for non-link shares, which might have been
1403
+            // set by ancient bugs
1404
+            $row['expiration'] = null;
1405
+        }
1406
+    }
1407
+
1408
+    /**
1409
+     * format result
1410
+     * @param array $items result
1411
+     * @param string $column is it a file share or a general share ('file_target' or 'item_target')
1412
+     * @param \OCP\Share_Backend $backend sharing backend
1413
+     * @param int $format
1414
+     * @param array $parameters additional format parameters
1415
+     * @return array format result
1416
+     */
1417
+    private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
1418
+        if ($format === self::FORMAT_NONE) {
1419
+            return $items;
1420
+        } else if ($format === self::FORMAT_STATUSES) {
1421
+            $statuses = [];
1422
+            foreach ($items as $item) {
1423
+                if ($item['share_type'] === self::SHARE_TYPE_LINK) {
1424
+                    if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
1425
+                        continue;
1426
+                    }
1427
+                    $statuses[$item[$column]]['link'] = true;
1428
+                } else if (!isset($statuses[$item[$column]])) {
1429
+                    $statuses[$item[$column]]['link'] = false;
1430
+                }
1431
+                if (!empty($item['file_target'])) {
1432
+                    $statuses[$item[$column]]['path'] = $item['path'];
1433
+                }
1434
+            }
1435
+            return $statuses;
1436
+        } else {
1437
+            return $backend->formatItems($items, $format, $parameters);
1438
+        }
1439
+    }
1440
+
1441
+    /**
1442
+     * remove protocol from URL
1443
+     *
1444
+     * @param string $url
1445
+     * @return string
1446
+     */
1447
+    public static function removeProtocolFromUrl($url) {
1448
+        if (strpos($url, 'https://') === 0) {
1449
+            return substr($url, strlen('https://'));
1450
+        } else if (strpos($url, 'http://') === 0) {
1451
+            return substr($url, strlen('http://'));
1452
+        }
1453
+
1454
+        return $url;
1455
+    }
1456
+
1457
+    /**
1458
+     * try http post first with https and then with http as a fallback
1459
+     *
1460
+     * @param string $remoteDomain
1461
+     * @param string $urlSuffix
1462
+     * @param array $fields post parameters
1463
+     * @return array
1464
+     */
1465
+    private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
1466
+        $protocol = 'https://';
1467
+        $result = [
1468
+            'success' => false,
1469
+            'result' => '',
1470
+        ];
1471
+        $try = 0;
1472
+        $discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
1473
+        while ($result['success'] === false && $try < 2) {
1474
+            $federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
1475
+            $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
1476
+            $client = \OC::$server->getHTTPClientService()->newClient();
1477
+
1478
+            try {
1479
+                $response = $client->post(
1480
+                    $protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
1481
+                    [
1482
+                        'body' => $fields,
1483
+                        'connect_timeout' => 10,
1484
+                    ]
1485
+                );
1486
+
1487
+                $result = ['success' => true, 'result' => $response->getBody()];
1488
+            } catch (\Exception $e) {
1489
+                $result = ['success' => false, 'result' => $e->getMessage()];
1490
+            }
1491
+
1492
+            $try++;
1493
+            $protocol = 'http://';
1494
+        }
1495
+
1496
+        return $result;
1497
+    }
1498
+
1499
+    /**
1500
+     * send server-to-server unshare to remote server
1501
+     *
1502
+     * @param string $remote url
1503
+     * @param int $id share id
1504
+     * @param string $token
1505
+     * @return bool
1506
+     */
1507
+    private static function sendRemoteUnshare($remote, $id, $token) {
1508
+        $url = rtrim($remote, '/');
1509
+        $fields = ['token' => $token, 'format' => 'json'];
1510
+        $url = self::removeProtocolFromUrl($url);
1511
+        $result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
1512
+        $status = json_decode($result['result'], true);
1513
+
1514
+        return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
1515
+    }
1516
+
1517
+    /**
1518
+     * @return int
1519
+     */
1520
+    public static function getExpireInterval() {
1521
+        return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1522
+    }
1523
+
1524
+    /**
1525
+     * Checks whether the given path is reachable for the given owner
1526
+     *
1527
+     * @param string $path path relative to files
1528
+     * @param string $ownerStorageId storage id of the owner
1529
+     *
1530
+     * @return boolean true if file is reachable, false otherwise
1531
+     */
1532
+    private static function isFileReachable($path, $ownerStorageId) {
1533
+        // if outside the home storage, file is always considered reachable
1534
+        if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
1535
+            substr($ownerStorageId, 0, 13) === 'object::user:'
1536
+        )) {
1537
+            return true;
1538
+        }
1539
+
1540
+        // if inside the home storage, the file has to be under "/files/"
1541
+        $path = ltrim($path, '/');
1542
+        if (substr($path, 0, 6) === 'files/') {
1543
+            return true;
1544
+        }
1545
+
1546
+        return false;
1547
+    }
1548 1548
 }
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 
150 150
 		$select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
151 151
 
152
-		$where .= ' `' . $column . '` = ? AND `item_type` = ? ';
152
+		$where .= ' `'.$column.'` = ? AND `item_type` = ? ';
153 153
 		$arguments = [$itemSource, $itemType];
154 154
 		// for link shares $user === null
155 155
 		if ($user !== null) {
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 			$arguments[] = $owner;
168 168
 		}
169 169
 
170
-		$query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
170
+		$query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$fileDependentWhere.$where);
171 171
 
172 172
 		$result = \OC_DB::executeAudited($query, $arguments);
173 173
 
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
176 176
 				continue;
177 177
 			}
178
-			if ($fileDependent && (int)$row['file_parent'] === -1) {
178
+			if ($fileDependent && (int) $row['file_parent'] === -1) {
179 179
 				// if it is a mount point we need to get the path from the mount manager
180 180
 				$mountManager = \OC\Files\Filesystem::getMountManager();
181 181
 				$mountPoint = $mountManager->findByStorageId($row['storage_id']);
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
 					$row['path'] = $path;
187 187
 				} else {
188 188
 					\OC::$server->getLogger()->warning(
189
-						'Could not resolve mount point for ' . $row['storage_id'],
189
+						'Could not resolve mount point for '.$row['storage_id'],
190 190
 						['app' => 'OCP\Share']
191 191
 					);
192 192
 				}
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
 		}
196 196
 
197 197
 		//if didn't found a result than let's look for a group share.
198
-		if(empty($shares) && $user !== null) {
198
+		if (empty($shares) && $user !== null) {
199 199
 			$userObject = \OC::$server->getUserManager()->get($user);
200 200
 			$groups = [];
201 201
 			if ($userObject) {
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
 			}
204 204
 
205 205
 			if (!empty($groups)) {
206
-				$where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
206
+				$where = $fileDependentWhere.' WHERE `'.$column.'` = ? AND `item_type` = ? AND `share_with` in (?)';
207 207
 				$arguments = [$itemSource, $itemType, $groups];
208 208
 				$types = [null, null, IQueryBuilder::PARAM_STR_ARRAY];
209 209
 
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
 				// class isn't static anymore...
218 218
 				$conn = \OC::$server->getDatabaseConnection();
219 219
 				$result = $conn->executeQuery(
220
-					'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
220
+					'SELECT '.$select.' FROM `*PREFIX*share` '.$where,
221 221
 					$arguments,
222 222
 					$types
223 223
 				);
@@ -351,12 +351,12 @@  discard block
 block discarded – undo
351 351
 		$currentUser = $owner ? $owner : \OC_User::getUser();
352 352
 		foreach ($items as $item) {
353 353
 			// delete the item with the expected share_type and owner
354
-			if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
354
+			if ((int) $item['share_type'] === (int) $shareType && $item['uid_owner'] === $currentUser) {
355 355
 				$toDelete = $item;
356 356
 				// if there is more then one result we don't have to delete the children
357 357
 				// but update their parent. For group shares the new parent should always be
358 358
 				// the original group share and not the db entry with the unique name
359
-			} else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
359
+			} else if ((int) $item['share_type'] === self::$shareTypeGroupUserUnique) {
360 360
 				$newParent = $item['parent'];
361 361
 			} else {
362 362
 				$newParent = $item['id'];
@@ -415,7 +415,7 @@  discard block
 block discarded – undo
415 415
 	 */
416 416
 	protected static function unshareItem(array $item, $newParent = null) {
417 417
 
418
-		$shareType = (int)$item['share_type'];
418
+		$shareType = (int) $item['share_type'];
419 419
 		$shareWith = null;
420 420
 		if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
421 421
 			$shareWith = $item['share_with'];
@@ -431,7 +431,7 @@  discard block
 block discarded – undo
431 431
 			'itemParent'    => $item['parent'],
432 432
 			'uidOwner'      => $item['uid_owner'],
433 433
 		];
434
-		if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
434
+		if ($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
435 435
 			$hookParams['fileSource'] = $item['file_source'];
436 436
 			$hookParams['fileTarget'] = $item['file_target'];
437 437
 		}
@@ -441,7 +441,7 @@  discard block
 block discarded – undo
441 441
 		$deletedShares[] = $hookParams;
442 442
 		$hookParams['deletedShares'] = $deletedShares;
443 443
 		\OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
444
-		if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
444
+		if ((int) $item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
445 445
 			list(, $remote) = Helper::splitUserRemote($item['share_with']);
446 446
 			self::sendRemoteUnshare($remote, $item['id'], $item['token']);
447 447
 		}
@@ -605,7 +605,7 @@  discard block
 block discarded – undo
605 605
 		// Get filesystem root to add it to the file target and remove from the
606 606
 		// file source, match file_source with the file cache
607 607
 		if ($itemType == 'file' || $itemType == 'folder') {
608
-			if(!is_null($uidOwner)) {
608
+			if (!is_null($uidOwner)) {
609 609
 				$root = \OC\Files\Filesystem::getRoot();
610 610
 			} else {
611 611
 				$root = '';
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
 		$result = $query->execute($queryArgs);
751 751
 		if ($result === false) {
752 752
 			\OCP\Util::writeLog('OCP\Share',
753
-				\OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
753
+				\OC_DB::getErrorMessage().', select='.$select.' where=',
754 754
 				ILogger::ERROR);
755 755
 		}
756 756
 		$items = [];
@@ -792,14 +792,14 @@  discard block
 block discarded – undo
792 792
 						}
793 793
 						// Switch ids if sharing permission is granted on only
794 794
 						// one share to ensure correct parent is used if resharing
795
-						if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
796
-							&& (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
795
+						if (~(int) $items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
796
+							&& (int) $row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
797 797
 							$items[$row['id']] = $items[$id];
798 798
 							$switchedItems[$id] = $row['id'];
799 799
 							unset($items[$id]);
800 800
 							$id = $row['id'];
801 801
 						}
802
-						$items[$id]['permissions'] |= (int)$row['permissions'];
802
+						$items[$id]['permissions'] |= (int) $row['permissions'];
803 803
 
804 804
 					}
805 805
 					continue;
@@ -813,8 +813,8 @@  discard block
 block discarded – undo
813 813
 					$query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
814 814
 					$parentResult = $query->execute([$row['parent']]);
815 815
 					if ($result === false) {
816
-						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
817
-							\OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
816
+						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: '.
817
+							\OC_DB::getErrorMessage().', select='.$select.' where='.$where,
818 818
 							ILogger::ERROR);
819 819
 					} else {
820 820
 						$parentRow = $parentResult->fetchRow();
@@ -824,7 +824,7 @@  discard block
 block discarded – undo
824 824
 						$subPath = substr($row['path'], $pos);
825 825
 						$splitPath = explode('/', $subPath);
826 826
 						foreach (array_slice($splitPath, 2) as $pathPart) {
827
-							$tmpPath = $tmpPath . '/' . $pathPart;
827
+							$tmpPath = $tmpPath.'/'.$pathPart;
828 828
 						}
829 829
 						$row['path'] = $tmpPath;
830 830
 					}
@@ -843,7 +843,7 @@  discard block
 block discarded – undo
843 843
 				}
844 844
 			}
845 845
 
846
-			if($checkExpireDate) {
846
+			if ($checkExpireDate) {
847 847
 				if (self::expireItem($row)) {
848 848
 					continue;
849 849
 				}
@@ -854,11 +854,11 @@  discard block
 block discarded – undo
854 854
 			}
855 855
 			// Add display names to result
856 856
 			$row['share_with_displayname'] = $row['share_with'];
857
-			if ( isset($row['share_with']) && $row['share_with'] != '' &&
857
+			if (isset($row['share_with']) && $row['share_with'] != '' &&
858 858
 				$row['share_type'] === self::SHARE_TYPE_USER) {
859 859
 				$shareWithUser = \OC::$server->getUserManager()->get($row['share_with']);
860 860
 				$row['share_with_displayname'] = $shareWithUser === null ? $row['share_with'] : $shareWithUser->getDisplayName();
861
-			} else if(isset($row['share_with']) && $row['share_with'] != '' &&
861
+			} else if (isset($row['share_with']) && $row['share_with'] != '' &&
862 862
 				$row['share_type'] === self::SHARE_TYPE_REMOTE) {
863 863
 				$addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
864 864
 				foreach ($addressBookEntries as $entry) {
@@ -869,7 +869,7 @@  discard block
 block discarded – undo
869 869
 					}
870 870
 				}
871 871
 			}
872
-			if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
872
+			if (isset($row['uid_owner']) && $row['uid_owner'] != '') {
873 873
 				$ownerUser = \OC::$server->getUserManager()->get($row['uid_owner']);
874 874
 				$row['displayname_owner'] = $ownerUser === null ? $row['uid_owner'] : $ownerUser->getDisplayName();
875 875
 			}
@@ -975,7 +975,7 @@  discard block
 block discarded – undo
975 975
 
976 976
 			// filter out invalid items, these can appear when subshare entries exist
977 977
 			// for a group in which the requested user isn't a member any more
978
-			$items = array_filter($items, function ($item) {
978
+			$items = array_filter($items, function($item) {
979 979
 				return $item['share_type'] !== self::$shareTypeGroupUserUnique;
980 980
 			});
981 981
 
@@ -1018,7 +1018,7 @@  discard block
 block discarded – undo
1018 1018
 				// for file/folder shares we need to compare file_source, otherwise we compare item_source
1019 1019
 				// only group shares if they already point to the same target, otherwise the file where shared
1020 1020
 				// before grouping of shares was added. In this case we don't group them toi avoid confusions
1021
-				if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1021
+				if (($fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1022 1022
 					(!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
1023 1023
 					// add the first item to the list of grouped shares
1024 1024
 					if (!isset($result[$key]['grouped'])) {
@@ -1063,7 +1063,7 @@  discard block
 block discarded – undo
1063 1063
 		$groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1064 1064
 
1065 1065
 		$result = self::checkReshare('test', $itemSource, self::SHARE_TYPE_USER, $shareWith, $uidOwner, $permissions, null, null);
1066
-		if(!empty($result)) {
1066
+		if (!empty($result)) {
1067 1067
 			$parent = $result['parent'];
1068 1068
 			$itemSource = $result['itemSource'];
1069 1069
 			$fileSource = $result['fileSource'];
@@ -1111,7 +1111,7 @@  discard block
 block discarded – undo
1111 1111
 				$fileTarget = $sourceExists['file_target'];
1112 1112
 				$itemTarget = $sourceExists['item_target'];
1113 1113
 
1114
-			} elseif(!$sourceExists)  {
1114
+			} elseif (!$sourceExists) {
1115 1115
 
1116 1116
 				$itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1117 1117
 					$uidOwner, $suggestedItemTarget, $parent);
@@ -1222,8 +1222,8 @@  discard block
 block discarded – undo
1222 1222
 
1223 1223
 		if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1224 1224
 			// Check if share permissions is granted
1225
-			if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1226
-				if (~(int)$checkReshare['permissions'] & $permissions) {
1225
+			if (self::isResharingAllowed() && (int) $checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1226
+				if (~(int) $checkReshare['permissions'] & $permissions) {
1227 1227
 					$message = 'Sharing %1$s failed, because the permissions exceed permissions granted to %2$s';
1228 1228
 					throw new \Exception(sprintf($message, $itemSourceName, $uidOwner));
1229 1229
 				} else {
@@ -1232,7 +1232,7 @@  discard block
 block discarded – undo
1232 1232
 
1233 1233
 					$result['expirationDate'] = $expirationDate;
1234 1234
 					// $checkReshare['expiration'] could be null and then is always less than any value
1235
-					if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1235
+					if (isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1236 1236
 						$result['expirationDate'] = $checkReshare['expiration'];
1237 1237
 					}
1238 1238
 
@@ -1312,7 +1312,7 @@  discard block
 block discarded – undo
1312 1312
 
1313 1313
 		$id = false;
1314 1314
 		if ($result) {
1315
-			$id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1315
+			$id = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1316 1316
 		}
1317 1317
 
1318 1318
 		return $id;
@@ -1414,7 +1414,7 @@  discard block
 block discarded – undo
1414 1414
 	 * @param array $parameters additional format parameters
1415 1415
 	 * @return array format result
1416 1416
 	 */
1417
-	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
1417
+	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE, $parameters = null) {
1418 1418
 		if ($format === self::FORMAT_NONE) {
1419 1419
 			return $items;
1420 1420
 		} else if ($format === self::FORMAT_STATUSES) {
@@ -1471,13 +1471,13 @@  discard block
 block discarded – undo
1471 1471
 		$try = 0;
1472 1472
 		$discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
1473 1473
 		while ($result['success'] === false && $try < 2) {
1474
-			$federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
1474
+			$federationEndpoints = $discoveryService->discover($protocol.$remoteDomain, 'FEDERATED_SHARING');
1475 1475
 			$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
1476 1476
 			$client = \OC::$server->getHTTPClientService()->newClient();
1477 1477
 
1478 1478
 			try {
1479 1479
 				$response = $client->post(
1480
-					$protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
1480
+					$protocol.$remoteDomain.$endpoint.$urlSuffix.'?format='.self::RESPONSE_FORMAT,
1481 1481
 					[
1482 1482
 						'body' => $fields,
1483 1483
 						'connect_timeout' => 10,
@@ -1518,7 +1518,7 @@  discard block
 block discarded – undo
1518 1518
 	 * @return int
1519 1519
 	 */
1520 1520
 	public static function getExpireInterval() {
1521
-		return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1521
+		return (int) \OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1522 1522
 	}
1523 1523
 
1524 1524
 	/**
Please login to merge, or discard this patch.
lib/private/SubAdmin.php 2 patches
Indentation   +246 added lines, -246 removed lines patch added patch discarded remove patch
@@ -39,252 +39,252 @@
 block discarded – undo
39 39
 
40 40
 class SubAdmin extends PublicEmitter implements ISubAdmin {
41 41
 
42
-	/** @var IUserManager */
43
-	private $userManager;
44
-
45
-	/** @var IGroupManager */
46
-	private $groupManager;
47
-
48
-	/** @var IDBConnection */
49
-	private $dbConn;
50
-
51
-	/**
52
-	 * @param IUserManager $userManager
53
-	 * @param IGroupManager $groupManager
54
-	 * @param IDBConnection $dbConn
55
-	 */
56
-	public function __construct(IUserManager $userManager,
57
-								IGroupManager $groupManager,
58
-								IDBConnection $dbConn) {
59
-		$this->userManager = $userManager;
60
-		$this->groupManager = $groupManager;
61
-		$this->dbConn = $dbConn;
62
-
63
-		$this->userManager->listen('\OC\User', 'postDelete', function ($user) {
64
-			$this->post_deleteUser($user);
65
-		});
66
-		$this->groupManager->listen('\OC\Group', 'postDelete', function ($group) {
67
-			$this->post_deleteGroup($group);
68
-		});
69
-	}
70
-
71
-	/**
72
-	 * add a SubAdmin
73
-	 * @param IUser $user user to be SubAdmin
74
-	 * @param IGroup $group group $user becomes subadmin of
75
-	 */
76
-	public function createSubAdmin(IUser $user, IGroup $group): void {
77
-		$qb = $this->dbConn->getQueryBuilder();
78
-
79
-		$qb->insert('group_admin')
80
-			->values([
81
-				'gid' => $qb->createNamedParameter($group->getGID()),
82
-				'uid' => $qb->createNamedParameter($user->getUID())
83
-			])
84
-			->execute();
85
-
86
-		$this->emit('\OC\SubAdmin', 'postCreateSubAdmin', [$user, $group]);
87
-		\OC_Hook::emit("OC_SubAdmin", "post_createSubAdmin", ["gid" => $group->getGID()]);
88
-	}
89
-
90
-	/**
91
-	 * delete a SubAdmin
92
-	 * @param IUser $user the user that is the SubAdmin
93
-	 * @param IGroup $group the group
94
-	 */
95
-	public function deleteSubAdmin(IUser $user, IGroup $group): void {
96
-		$qb = $this->dbConn->getQueryBuilder();
97
-
98
-		$qb->delete('group_admin')
99
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))
100
-			->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
101
-			->execute();
102
-
103
-		$this->emit('\OC\SubAdmin', 'postDeleteSubAdmin', [$user, $group]);
104
-		\OC_Hook::emit("OC_SubAdmin", "post_deleteSubAdmin", ["gid" => $group->getGID()]);
105
-	}
106
-
107
-	/**
108
-	 * get groups of a SubAdmin
109
-	 * @param IUser $user the SubAdmin
110
-	 * @return IGroup[]
111
-	 */
112
-	public function getSubAdminsGroups(IUser $user): array {
113
-		$qb = $this->dbConn->getQueryBuilder();
114
-
115
-		$result = $qb->select('gid')
116
-			->from('group_admin')
117
-			->where($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
118
-			->execute();
119
-
120
-		$groups = [];
121
-		while($row = $result->fetch()) {
122
-			$group = $this->groupManager->get($row['gid']);
123
-			if(!is_null($group)) {
124
-				$groups[$group->getGID()] = $group;
125
-			}
126
-		}
127
-		$result->closeCursor();
128
-
129
-		return $groups;
130
-	}
131
-
132
-	/**
133
-	 * get an array of groupid and displayName for a user
134
-	 * @param IUser $user
135
-	 * @return array ['displayName' => displayname]
136
-	 */
137
-	public function getSubAdminsGroupsName(IUser $user): array {
138
-		return array_map(function ($group) {
139
-			return ['displayName' => $group->getDisplayName()];
140
-		}, $this->getSubAdminsGroups($user));
141
-	}
142
-
143
-	/**
144
-	 * get SubAdmins of a group
145
-	 * @param IGroup $group the group
146
-	 * @return IUser[]
147
-	 */
148
-	public function getGroupsSubAdmins(IGroup $group): array {
149
-		$qb = $this->dbConn->getQueryBuilder();
150
-
151
-		$result = $qb->select('uid')
152
-			->from('group_admin')
153
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))
154
-			->execute();
155
-
156
-		$users = [];
157
-		while($row = $result->fetch()) {
158
-			$user = $this->userManager->get($row['uid']);
159
-			if(!is_null($user)) {
160
-				$users[] = $user;
161
-			}
162
-		}
163
-		$result->closeCursor();
164
-
165
-		return $users;
166
-	}
167
-
168
-	/**
169
-	 * get all SubAdmins
170
-	 * @return array
171
-	 */
172
-	public function getAllSubAdmins(): array {
173
-		$qb = $this->dbConn->getQueryBuilder();
174
-
175
-		$result = $qb->select('*')
176
-			->from('group_admin')
177
-			->execute();
178
-
179
-		$subadmins = [];
180
-		while($row = $result->fetch()) {
181
-			$user = $this->userManager->get($row['uid']);
182
-			$group = $this->groupManager->get($row['gid']);
183
-			if(!is_null($user) && !is_null($group)) {
184
-				$subadmins[] = [
185
-					'user'  => $user,
186
-					'group' => $group
187
-				];
188
-			}
189
-		}
190
-		$result->closeCursor();
191
-
192
-		return $subadmins;
193
-	}
194
-
195
-	/**
196
-	 * checks if a user is a SubAdmin of a group
197
-	 * @param IUser $user
198
-	 * @param IGroup $group
199
-	 * @return bool
200
-	 */
201
-	public function isSubAdminOfGroup(IUser $user, IGroup $group): bool {
202
-		$qb = $this->dbConn->getQueryBuilder();
203
-
204
-		/*
42
+    /** @var IUserManager */
43
+    private $userManager;
44
+
45
+    /** @var IGroupManager */
46
+    private $groupManager;
47
+
48
+    /** @var IDBConnection */
49
+    private $dbConn;
50
+
51
+    /**
52
+     * @param IUserManager $userManager
53
+     * @param IGroupManager $groupManager
54
+     * @param IDBConnection $dbConn
55
+     */
56
+    public function __construct(IUserManager $userManager,
57
+                                IGroupManager $groupManager,
58
+                                IDBConnection $dbConn) {
59
+        $this->userManager = $userManager;
60
+        $this->groupManager = $groupManager;
61
+        $this->dbConn = $dbConn;
62
+
63
+        $this->userManager->listen('\OC\User', 'postDelete', function ($user) {
64
+            $this->post_deleteUser($user);
65
+        });
66
+        $this->groupManager->listen('\OC\Group', 'postDelete', function ($group) {
67
+            $this->post_deleteGroup($group);
68
+        });
69
+    }
70
+
71
+    /**
72
+     * add a SubAdmin
73
+     * @param IUser $user user to be SubAdmin
74
+     * @param IGroup $group group $user becomes subadmin of
75
+     */
76
+    public function createSubAdmin(IUser $user, IGroup $group): void {
77
+        $qb = $this->dbConn->getQueryBuilder();
78
+
79
+        $qb->insert('group_admin')
80
+            ->values([
81
+                'gid' => $qb->createNamedParameter($group->getGID()),
82
+                'uid' => $qb->createNamedParameter($user->getUID())
83
+            ])
84
+            ->execute();
85
+
86
+        $this->emit('\OC\SubAdmin', 'postCreateSubAdmin', [$user, $group]);
87
+        \OC_Hook::emit("OC_SubAdmin", "post_createSubAdmin", ["gid" => $group->getGID()]);
88
+    }
89
+
90
+    /**
91
+     * delete a SubAdmin
92
+     * @param IUser $user the user that is the SubAdmin
93
+     * @param IGroup $group the group
94
+     */
95
+    public function deleteSubAdmin(IUser $user, IGroup $group): void {
96
+        $qb = $this->dbConn->getQueryBuilder();
97
+
98
+        $qb->delete('group_admin')
99
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))
100
+            ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
101
+            ->execute();
102
+
103
+        $this->emit('\OC\SubAdmin', 'postDeleteSubAdmin', [$user, $group]);
104
+        \OC_Hook::emit("OC_SubAdmin", "post_deleteSubAdmin", ["gid" => $group->getGID()]);
105
+    }
106
+
107
+    /**
108
+     * get groups of a SubAdmin
109
+     * @param IUser $user the SubAdmin
110
+     * @return IGroup[]
111
+     */
112
+    public function getSubAdminsGroups(IUser $user): array {
113
+        $qb = $this->dbConn->getQueryBuilder();
114
+
115
+        $result = $qb->select('gid')
116
+            ->from('group_admin')
117
+            ->where($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
118
+            ->execute();
119
+
120
+        $groups = [];
121
+        while($row = $result->fetch()) {
122
+            $group = $this->groupManager->get($row['gid']);
123
+            if(!is_null($group)) {
124
+                $groups[$group->getGID()] = $group;
125
+            }
126
+        }
127
+        $result->closeCursor();
128
+
129
+        return $groups;
130
+    }
131
+
132
+    /**
133
+     * get an array of groupid and displayName for a user
134
+     * @param IUser $user
135
+     * @return array ['displayName' => displayname]
136
+     */
137
+    public function getSubAdminsGroupsName(IUser $user): array {
138
+        return array_map(function ($group) {
139
+            return ['displayName' => $group->getDisplayName()];
140
+        }, $this->getSubAdminsGroups($user));
141
+    }
142
+
143
+    /**
144
+     * get SubAdmins of a group
145
+     * @param IGroup $group the group
146
+     * @return IUser[]
147
+     */
148
+    public function getGroupsSubAdmins(IGroup $group): array {
149
+        $qb = $this->dbConn->getQueryBuilder();
150
+
151
+        $result = $qb->select('uid')
152
+            ->from('group_admin')
153
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))
154
+            ->execute();
155
+
156
+        $users = [];
157
+        while($row = $result->fetch()) {
158
+            $user = $this->userManager->get($row['uid']);
159
+            if(!is_null($user)) {
160
+                $users[] = $user;
161
+            }
162
+        }
163
+        $result->closeCursor();
164
+
165
+        return $users;
166
+    }
167
+
168
+    /**
169
+     * get all SubAdmins
170
+     * @return array
171
+     */
172
+    public function getAllSubAdmins(): array {
173
+        $qb = $this->dbConn->getQueryBuilder();
174
+
175
+        $result = $qb->select('*')
176
+            ->from('group_admin')
177
+            ->execute();
178
+
179
+        $subadmins = [];
180
+        while($row = $result->fetch()) {
181
+            $user = $this->userManager->get($row['uid']);
182
+            $group = $this->groupManager->get($row['gid']);
183
+            if(!is_null($user) && !is_null($group)) {
184
+                $subadmins[] = [
185
+                    'user'  => $user,
186
+                    'group' => $group
187
+                ];
188
+            }
189
+        }
190
+        $result->closeCursor();
191
+
192
+        return $subadmins;
193
+    }
194
+
195
+    /**
196
+     * checks if a user is a SubAdmin of a group
197
+     * @param IUser $user
198
+     * @param IGroup $group
199
+     * @return bool
200
+     */
201
+    public function isSubAdminOfGroup(IUser $user, IGroup $group): bool {
202
+        $qb = $this->dbConn->getQueryBuilder();
203
+
204
+        /*
205 205
 		 * Primary key is ('gid', 'uid') so max 1 result possible here
206 206
 		 */
207
-		$result = $qb->select('*')
208
-			->from('group_admin')
209
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))
210
-			->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
211
-			->execute();
212
-
213
-		$fetch =  $result->fetch();
214
-		$result->closeCursor();
215
-		$result = !empty($fetch) ? true : false;
216
-
217
-		return $result;
218
-	}
219
-
220
-	/**
221
-	 * checks if a user is a SubAdmin
222
-	 * @param IUser $user
223
-	 * @return bool
224
-	 */
225
-	public function isSubAdmin(IUser $user): bool {
226
-		// Check if the user is already an admin
227
-		if ($this->groupManager->isAdmin($user->getUID())) {
228
-			return true;
229
-		}
230
-
231
-		$qb = $this->dbConn->getQueryBuilder();
232
-
233
-		$result = $qb->select('gid')
234
-			->from('group_admin')
235
-			->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
236
-			->setMaxResults(1)
237
-			->execute();
238
-
239
-		$isSubAdmin = $result->fetch();
240
-		$result->closeCursor();
241
-
242
-		return $isSubAdmin !== false;
243
-	}
244
-
245
-	/**
246
-	 * checks if a user is a accessible by a subadmin
247
-	 * @param IUser $subadmin
248
-	 * @param IUser $user
249
-	 * @return bool
250
-	 */
251
-	public function isUserAccessible(IUser $subadmin, IUser $user): bool {
252
-		if(!$this->isSubAdmin($subadmin)) {
253
-			return false;
254
-		}
255
-		if($this->groupManager->isAdmin($user->getUID())) {
256
-			return false;
257
-		}
258
-		$accessibleGroups = $this->getSubAdminsGroups($subadmin);
259
-		foreach($accessibleGroups as $accessibleGroup) {
260
-			if($accessibleGroup->inGroup($user)) {
261
-				return true;
262
-			}
263
-		}
264
-		return false;
265
-	}
266
-
267
-	/**
268
-	 * delete all SubAdmins by $user
269
-	 * @param IUser $user
270
-	 */
271
-	private function post_deleteUser(IUser $user) {
272
-		$qb = $this->dbConn->getQueryBuilder();
273
-
274
-		$qb->delete('group_admin')
275
-			->where($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
276
-			->execute();
277
-	}
278
-
279
-	/**
280
-	 * delete all SubAdmins by $group
281
-	 * @param IGroup $group
282
-	 */
283
-	private function post_deleteGroup(IGroup $group) {
284
-		$qb = $this->dbConn->getQueryBuilder();
285
-
286
-		$qb->delete('group_admin')
287
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))
288
-			->execute();
289
-	}
207
+        $result = $qb->select('*')
208
+            ->from('group_admin')
209
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))
210
+            ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
211
+            ->execute();
212
+
213
+        $fetch =  $result->fetch();
214
+        $result->closeCursor();
215
+        $result = !empty($fetch) ? true : false;
216
+
217
+        return $result;
218
+    }
219
+
220
+    /**
221
+     * checks if a user is a SubAdmin
222
+     * @param IUser $user
223
+     * @return bool
224
+     */
225
+    public function isSubAdmin(IUser $user): bool {
226
+        // Check if the user is already an admin
227
+        if ($this->groupManager->isAdmin($user->getUID())) {
228
+            return true;
229
+        }
230
+
231
+        $qb = $this->dbConn->getQueryBuilder();
232
+
233
+        $result = $qb->select('gid')
234
+            ->from('group_admin')
235
+            ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
236
+            ->setMaxResults(1)
237
+            ->execute();
238
+
239
+        $isSubAdmin = $result->fetch();
240
+        $result->closeCursor();
241
+
242
+        return $isSubAdmin !== false;
243
+    }
244
+
245
+    /**
246
+     * checks if a user is a accessible by a subadmin
247
+     * @param IUser $subadmin
248
+     * @param IUser $user
249
+     * @return bool
250
+     */
251
+    public function isUserAccessible(IUser $subadmin, IUser $user): bool {
252
+        if(!$this->isSubAdmin($subadmin)) {
253
+            return false;
254
+        }
255
+        if($this->groupManager->isAdmin($user->getUID())) {
256
+            return false;
257
+        }
258
+        $accessibleGroups = $this->getSubAdminsGroups($subadmin);
259
+        foreach($accessibleGroups as $accessibleGroup) {
260
+            if($accessibleGroup->inGroup($user)) {
261
+                return true;
262
+            }
263
+        }
264
+        return false;
265
+    }
266
+
267
+    /**
268
+     * delete all SubAdmins by $user
269
+     * @param IUser $user
270
+     */
271
+    private function post_deleteUser(IUser $user) {
272
+        $qb = $this->dbConn->getQueryBuilder();
273
+
274
+        $qb->delete('group_admin')
275
+            ->where($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
276
+            ->execute();
277
+    }
278
+
279
+    /**
280
+     * delete all SubAdmins by $group
281
+     * @param IGroup $group
282
+     */
283
+    private function post_deleteGroup(IGroup $group) {
284
+        $qb = $this->dbConn->getQueryBuilder();
285
+
286
+        $qb->delete('group_admin')
287
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))
288
+            ->execute();
289
+    }
290 290
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -60,10 +60,10 @@  discard block
 block discarded – undo
60 60
 		$this->groupManager = $groupManager;
61 61
 		$this->dbConn = $dbConn;
62 62
 
63
-		$this->userManager->listen('\OC\User', 'postDelete', function ($user) {
63
+		$this->userManager->listen('\OC\User', 'postDelete', function($user) {
64 64
 			$this->post_deleteUser($user);
65 65
 		});
66
-		$this->groupManager->listen('\OC\Group', 'postDelete', function ($group) {
66
+		$this->groupManager->listen('\OC\Group', 'postDelete', function($group) {
67 67
 			$this->post_deleteGroup($group);
68 68
 		});
69 69
 	}
@@ -118,9 +118,9 @@  discard block
 block discarded – undo
118 118
 			->execute();
119 119
 
120 120
 		$groups = [];
121
-		while($row = $result->fetch()) {
121
+		while ($row = $result->fetch()) {
122 122
 			$group = $this->groupManager->get($row['gid']);
123
-			if(!is_null($group)) {
123
+			if (!is_null($group)) {
124 124
 				$groups[$group->getGID()] = $group;
125 125
 			}
126 126
 		}
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
 	 * @return array ['displayName' => displayname]
136 136
 	 */
137 137
 	public function getSubAdminsGroupsName(IUser $user): array {
138
-		return array_map(function ($group) {
138
+		return array_map(function($group) {
139 139
 			return ['displayName' => $group->getDisplayName()];
140 140
 		}, $this->getSubAdminsGroups($user));
141 141
 	}
@@ -154,9 +154,9 @@  discard block
 block discarded – undo
154 154
 			->execute();
155 155
 
156 156
 		$users = [];
157
-		while($row = $result->fetch()) {
157
+		while ($row = $result->fetch()) {
158 158
 			$user = $this->userManager->get($row['uid']);
159
-			if(!is_null($user)) {
159
+			if (!is_null($user)) {
160 160
 				$users[] = $user;
161 161
 			}
162 162
 		}
@@ -177,10 +177,10 @@  discard block
 block discarded – undo
177 177
 			->execute();
178 178
 
179 179
 		$subadmins = [];
180
-		while($row = $result->fetch()) {
180
+		while ($row = $result->fetch()) {
181 181
 			$user = $this->userManager->get($row['uid']);
182 182
 			$group = $this->groupManager->get($row['gid']);
183
-			if(!is_null($user) && !is_null($group)) {
183
+			if (!is_null($user) && !is_null($group)) {
184 184
 				$subadmins[] = [
185 185
 					'user'  => $user,
186 186
 					'group' => $group
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
 			->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
211 211
 			->execute();
212 212
 
213
-		$fetch =  $result->fetch();
213
+		$fetch = $result->fetch();
214 214
 		$result->closeCursor();
215 215
 		$result = !empty($fetch) ? true : false;
216 216
 
@@ -249,15 +249,15 @@  discard block
 block discarded – undo
249 249
 	 * @return bool
250 250
 	 */
251 251
 	public function isUserAccessible(IUser $subadmin, IUser $user): bool {
252
-		if(!$this->isSubAdmin($subadmin)) {
252
+		if (!$this->isSubAdmin($subadmin)) {
253 253
 			return false;
254 254
 		}
255
-		if($this->groupManager->isAdmin($user->getUID())) {
255
+		if ($this->groupManager->isAdmin($user->getUID())) {
256 256
 			return false;
257 257
 		}
258 258
 		$accessibleGroups = $this->getSubAdminsGroups($subadmin);
259
-		foreach($accessibleGroups as $accessibleGroup) {
260
-			if($accessibleGroup->inGroup($user)) {
259
+		foreach ($accessibleGroups as $accessibleGroup) {
260
+			if ($accessibleGroup->inGroup($user)) {
261 261
 				return true;
262 262
 			}
263 263
 		}
Please login to merge, or discard this patch.
lib/private/SystemTag/SystemTagObjectMapper.php 2 patches
Indentation   +231 added lines, -231 removed lines patch added patch discarded remove patch
@@ -39,235 +39,235 @@
 block discarded – undo
39 39
 
40 40
 class SystemTagObjectMapper implements ISystemTagObjectMapper {
41 41
 
42
-	const RELATION_TABLE = 'systemtag_object_mapping';
43
-
44
-	/** @var ISystemTagManager */
45
-	protected $tagManager;
46
-
47
-	/** @var IDBConnection */
48
-	protected $connection;
49
-
50
-	/** @var EventDispatcherInterface */
51
-	protected $dispatcher;
52
-
53
-	/**
54
-	 * Constructor.
55
-	 *
56
-	 * @param IDBConnection $connection database connection
57
-	 * @param ISystemTagManager $tagManager system tag manager
58
-	 * @param EventDispatcherInterface $dispatcher
59
-	 */
60
-	public function __construct(IDBConnection $connection, ISystemTagManager $tagManager, EventDispatcherInterface $dispatcher) {
61
-		$this->connection = $connection;
62
-		$this->tagManager = $tagManager;
63
-		$this->dispatcher = $dispatcher;
64
-	}
65
-
66
-	/**
67
-	 * {@inheritdoc}
68
-	 */
69
-	public function getTagIdsForObjects($objIds, string $objectType): array {
70
-		if (!\is_array($objIds)) {
71
-			$objIds = [$objIds];
72
-		} else if (empty($objIds)) {
73
-			return [];
74
-		}
75
-
76
-		$query = $this->connection->getQueryBuilder();
77
-		$query->select(['systemtagid', 'objectid'])
78
-			->from(self::RELATION_TABLE)
79
-			->where($query->expr()->in('objectid', $query->createParameter('objectids')))
80
-			->andWhere($query->expr()->eq('objecttype', $query->createParameter('objecttype')))
81
-			->setParameter('objectids', $objIds, IQueryBuilder::PARAM_INT_ARRAY)
82
-			->setParameter('objecttype', $objectType)
83
-			->addOrderBy('objectid', 'ASC')
84
-			->addOrderBy('systemtagid', 'ASC');
85
-
86
-		$mapping = [];
87
-		foreach ($objIds as $objId) {
88
-			$mapping[$objId] = [];
89
-		}
90
-
91
-		$result = $query->execute();
92
-		while ($row = $result->fetch()) {
93
-			$objectId = $row['objectid'];
94
-			$mapping[$objectId][] = $row['systemtagid'];
95
-		}
96
-
97
-		$result->closeCursor();
98
-
99
-		return $mapping;
100
-	}
101
-
102
-	/**
103
-	 * {@inheritdoc}
104
-	 */
105
-	public function getObjectIdsForTags($tagIds, string $objectType, int $limit = 0, string $offset = ''): array {
106
-		if (!\is_array($tagIds)) {
107
-			$tagIds = [$tagIds];
108
-		}
109
-
110
-		$this->assertTagsExist($tagIds);
111
-
112
-		$query = $this->connection->getQueryBuilder();
113
-		$query->selectDistinct('objectid')
114
-			->from(self::RELATION_TABLE)
115
-			->where($query->expr()->in('systemtagid', $query->createNamedParameter($tagIds, IQueryBuilder::PARAM_INT_ARRAY)))
116
-			->andWhere($query->expr()->eq('objecttype', $query->createNamedParameter($objectType)));
117
-
118
-		if ($limit) {
119
-			if (\count($tagIds) !== 1) {
120
-				throw new \InvalidArgumentException('Limit is only allowed with a single tag');
121
-			}
122
-
123
-			$query->setMaxResults($limit)
124
-				->orderBy('objectid', 'ASC');
125
-
126
-			if ($offset !== '') {
127
-				$query->andWhere($query->expr()->gt('objectid', $query->createNamedParameter($offset)));
128
-			}
129
-		}
130
-
131
-		$objectIds = [];
132
-
133
-		$result = $query->execute();
134
-		while ($row = $result->fetch()) {
135
-			$objectIds[] = $row['objectid'];
136
-		}
137
-
138
-		return $objectIds;
139
-	}
140
-
141
-	/**
142
-	 * {@inheritdoc}
143
-	 */
144
-	public function assignTags(string $objId, string $objectType, $tagIds) {
145
-		if (!\is_array($tagIds)) {
146
-			$tagIds = [$tagIds];
147
-		}
148
-
149
-		$this->assertTagsExist($tagIds);
150
-
151
-		$query = $this->connection->getQueryBuilder();
152
-		$query->insert(self::RELATION_TABLE)
153
-			->values([
154
-				'objectid' => $query->createNamedParameter($objId),
155
-				'objecttype' => $query->createNamedParameter($objectType),
156
-				'systemtagid' => $query->createParameter('tagid'),
157
-			]);
158
-
159
-		$tagsAssigned = [];
160
-		foreach ($tagIds as $tagId) {
161
-			try {
162
-				$query->setParameter('tagid', $tagId);
163
-				$query->execute();
164
-				$tagsAssigned[] = $tagId;
165
-			} catch (UniqueConstraintViolationException $e) {
166
-				// ignore existing relations
167
-			}
168
-		}
169
-
170
-		if (empty($tagsAssigned)) {
171
-			return;
172
-		}
173
-
174
-		$this->dispatcher->dispatch(MapperEvent::EVENT_ASSIGN, new MapperEvent(
175
-			MapperEvent::EVENT_ASSIGN,
176
-			$objectType,
177
-			$objId,
178
-			$tagsAssigned
179
-		));
180
-	}
181
-
182
-	/**
183
-	 * {@inheritdoc}
184
-	 */
185
-	public function unassignTags(string $objId, string $objectType, $tagIds) {
186
-		if (!\is_array($tagIds)) {
187
-			$tagIds = [$tagIds];
188
-		}
189
-
190
-		$this->assertTagsExist($tagIds);
191
-
192
-		$query = $this->connection->getQueryBuilder();
193
-		$query->delete(self::RELATION_TABLE)
194
-			->where($query->expr()->eq('objectid', $query->createParameter('objectid')))
195
-			->andWhere($query->expr()->eq('objecttype', $query->createParameter('objecttype')))
196
-			->andWhere($query->expr()->in('systemtagid', $query->createParameter('tagids')))
197
-			->setParameter('objectid', $objId)
198
-			->setParameter('objecttype', $objectType)
199
-			->setParameter('tagids', $tagIds, IQueryBuilder::PARAM_INT_ARRAY)
200
-			->execute();
201
-
202
-		$this->dispatcher->dispatch(MapperEvent::EVENT_UNASSIGN, new MapperEvent(
203
-			MapperEvent::EVENT_UNASSIGN,
204
-			$objectType,
205
-			$objId,
206
-			$tagIds
207
-		));
208
-	}
209
-
210
-	/**
211
-	 * {@inheritdoc}
212
-	 */
213
-	public function haveTag($objIds, string $objectType, string $tagId, bool $all = true): bool {
214
-		$this->assertTagsExist([$tagId]);
215
-
216
-		if (!\is_array($objIds)) {
217
-			$objIds = [$objIds];
218
-		}
219
-
220
-		$query = $this->connection->getQueryBuilder();
221
-
222
-		if (!$all) {
223
-			// If we only need one entry, we make the query lighter, by not
224
-			// counting the elements
225
-			$query->select('*')
226
-				->setMaxResults(1);
227
-		} else {
228
-			$query->select($query->func()->count($query->expr()->literal(1)));
229
-		}
230
-
231
-		$query->from(self::RELATION_TABLE)
232
-			->where($query->expr()->in('objectid', $query->createParameter('objectids')))
233
-			->andWhere($query->expr()->eq('objecttype', $query->createParameter('objecttype')))
234
-			->andWhere($query->expr()->eq('systemtagid', $query->createParameter('tagid')))
235
-			->setParameter('objectids', $objIds, IQueryBuilder::PARAM_STR_ARRAY)
236
-			->setParameter('tagid', $tagId)
237
-			->setParameter('objecttype', $objectType);
238
-
239
-		$result = $query->execute();
240
-		$row = $result->fetch(\PDO::FETCH_NUM);
241
-		$result->closeCursor();
242
-
243
-		if ($all) {
244
-			return ((int)$row[0] === \count($objIds));
245
-		}
246
-
247
-		return (bool) $row;
248
-	}
249
-
250
-	/**
251
-	 * Asserts that all the given tag ids exist.
252
-	 *
253
-	 * @param string[] $tagIds tag ids to check
254
-	 *
255
-	 * @throws \OCP\SystemTag\TagNotFoundException if at least one tag did not exist
256
-	 */
257
-	private function assertTagsExist($tagIds) {
258
-		$tags = $this->tagManager->getTagsByIds($tagIds);
259
-		if (\count($tags) !== \count($tagIds)) {
260
-			// at least one tag missing, bail out
261
-			$foundTagIds = array_map(
262
-				function (ISystemTag $tag) {
263
-					return $tag->getId();
264
-				},
265
-				$tags
266
-			);
267
-			$missingTagIds = array_diff($tagIds, $foundTagIds);
268
-			throw new TagNotFoundException(
269
-				'Tags not found', 0, null, $missingTagIds
270
-			);
271
-		}
272
-	}
42
+    const RELATION_TABLE = 'systemtag_object_mapping';
43
+
44
+    /** @var ISystemTagManager */
45
+    protected $tagManager;
46
+
47
+    /** @var IDBConnection */
48
+    protected $connection;
49
+
50
+    /** @var EventDispatcherInterface */
51
+    protected $dispatcher;
52
+
53
+    /**
54
+     * Constructor.
55
+     *
56
+     * @param IDBConnection $connection database connection
57
+     * @param ISystemTagManager $tagManager system tag manager
58
+     * @param EventDispatcherInterface $dispatcher
59
+     */
60
+    public function __construct(IDBConnection $connection, ISystemTagManager $tagManager, EventDispatcherInterface $dispatcher) {
61
+        $this->connection = $connection;
62
+        $this->tagManager = $tagManager;
63
+        $this->dispatcher = $dispatcher;
64
+    }
65
+
66
+    /**
67
+     * {@inheritdoc}
68
+     */
69
+    public function getTagIdsForObjects($objIds, string $objectType): array {
70
+        if (!\is_array($objIds)) {
71
+            $objIds = [$objIds];
72
+        } else if (empty($objIds)) {
73
+            return [];
74
+        }
75
+
76
+        $query = $this->connection->getQueryBuilder();
77
+        $query->select(['systemtagid', 'objectid'])
78
+            ->from(self::RELATION_TABLE)
79
+            ->where($query->expr()->in('objectid', $query->createParameter('objectids')))
80
+            ->andWhere($query->expr()->eq('objecttype', $query->createParameter('objecttype')))
81
+            ->setParameter('objectids', $objIds, IQueryBuilder::PARAM_INT_ARRAY)
82
+            ->setParameter('objecttype', $objectType)
83
+            ->addOrderBy('objectid', 'ASC')
84
+            ->addOrderBy('systemtagid', 'ASC');
85
+
86
+        $mapping = [];
87
+        foreach ($objIds as $objId) {
88
+            $mapping[$objId] = [];
89
+        }
90
+
91
+        $result = $query->execute();
92
+        while ($row = $result->fetch()) {
93
+            $objectId = $row['objectid'];
94
+            $mapping[$objectId][] = $row['systemtagid'];
95
+        }
96
+
97
+        $result->closeCursor();
98
+
99
+        return $mapping;
100
+    }
101
+
102
+    /**
103
+     * {@inheritdoc}
104
+     */
105
+    public function getObjectIdsForTags($tagIds, string $objectType, int $limit = 0, string $offset = ''): array {
106
+        if (!\is_array($tagIds)) {
107
+            $tagIds = [$tagIds];
108
+        }
109
+
110
+        $this->assertTagsExist($tagIds);
111
+
112
+        $query = $this->connection->getQueryBuilder();
113
+        $query->selectDistinct('objectid')
114
+            ->from(self::RELATION_TABLE)
115
+            ->where($query->expr()->in('systemtagid', $query->createNamedParameter($tagIds, IQueryBuilder::PARAM_INT_ARRAY)))
116
+            ->andWhere($query->expr()->eq('objecttype', $query->createNamedParameter($objectType)));
117
+
118
+        if ($limit) {
119
+            if (\count($tagIds) !== 1) {
120
+                throw new \InvalidArgumentException('Limit is only allowed with a single tag');
121
+            }
122
+
123
+            $query->setMaxResults($limit)
124
+                ->orderBy('objectid', 'ASC');
125
+
126
+            if ($offset !== '') {
127
+                $query->andWhere($query->expr()->gt('objectid', $query->createNamedParameter($offset)));
128
+            }
129
+        }
130
+
131
+        $objectIds = [];
132
+
133
+        $result = $query->execute();
134
+        while ($row = $result->fetch()) {
135
+            $objectIds[] = $row['objectid'];
136
+        }
137
+
138
+        return $objectIds;
139
+    }
140
+
141
+    /**
142
+     * {@inheritdoc}
143
+     */
144
+    public function assignTags(string $objId, string $objectType, $tagIds) {
145
+        if (!\is_array($tagIds)) {
146
+            $tagIds = [$tagIds];
147
+        }
148
+
149
+        $this->assertTagsExist($tagIds);
150
+
151
+        $query = $this->connection->getQueryBuilder();
152
+        $query->insert(self::RELATION_TABLE)
153
+            ->values([
154
+                'objectid' => $query->createNamedParameter($objId),
155
+                'objecttype' => $query->createNamedParameter($objectType),
156
+                'systemtagid' => $query->createParameter('tagid'),
157
+            ]);
158
+
159
+        $tagsAssigned = [];
160
+        foreach ($tagIds as $tagId) {
161
+            try {
162
+                $query->setParameter('tagid', $tagId);
163
+                $query->execute();
164
+                $tagsAssigned[] = $tagId;
165
+            } catch (UniqueConstraintViolationException $e) {
166
+                // ignore existing relations
167
+            }
168
+        }
169
+
170
+        if (empty($tagsAssigned)) {
171
+            return;
172
+        }
173
+
174
+        $this->dispatcher->dispatch(MapperEvent::EVENT_ASSIGN, new MapperEvent(
175
+            MapperEvent::EVENT_ASSIGN,
176
+            $objectType,
177
+            $objId,
178
+            $tagsAssigned
179
+        ));
180
+    }
181
+
182
+    /**
183
+     * {@inheritdoc}
184
+     */
185
+    public function unassignTags(string $objId, string $objectType, $tagIds) {
186
+        if (!\is_array($tagIds)) {
187
+            $tagIds = [$tagIds];
188
+        }
189
+
190
+        $this->assertTagsExist($tagIds);
191
+
192
+        $query = $this->connection->getQueryBuilder();
193
+        $query->delete(self::RELATION_TABLE)
194
+            ->where($query->expr()->eq('objectid', $query->createParameter('objectid')))
195
+            ->andWhere($query->expr()->eq('objecttype', $query->createParameter('objecttype')))
196
+            ->andWhere($query->expr()->in('systemtagid', $query->createParameter('tagids')))
197
+            ->setParameter('objectid', $objId)
198
+            ->setParameter('objecttype', $objectType)
199
+            ->setParameter('tagids', $tagIds, IQueryBuilder::PARAM_INT_ARRAY)
200
+            ->execute();
201
+
202
+        $this->dispatcher->dispatch(MapperEvent::EVENT_UNASSIGN, new MapperEvent(
203
+            MapperEvent::EVENT_UNASSIGN,
204
+            $objectType,
205
+            $objId,
206
+            $tagIds
207
+        ));
208
+    }
209
+
210
+    /**
211
+     * {@inheritdoc}
212
+     */
213
+    public function haveTag($objIds, string $objectType, string $tagId, bool $all = true): bool {
214
+        $this->assertTagsExist([$tagId]);
215
+
216
+        if (!\is_array($objIds)) {
217
+            $objIds = [$objIds];
218
+        }
219
+
220
+        $query = $this->connection->getQueryBuilder();
221
+
222
+        if (!$all) {
223
+            // If we only need one entry, we make the query lighter, by not
224
+            // counting the elements
225
+            $query->select('*')
226
+                ->setMaxResults(1);
227
+        } else {
228
+            $query->select($query->func()->count($query->expr()->literal(1)));
229
+        }
230
+
231
+        $query->from(self::RELATION_TABLE)
232
+            ->where($query->expr()->in('objectid', $query->createParameter('objectids')))
233
+            ->andWhere($query->expr()->eq('objecttype', $query->createParameter('objecttype')))
234
+            ->andWhere($query->expr()->eq('systemtagid', $query->createParameter('tagid')))
235
+            ->setParameter('objectids', $objIds, IQueryBuilder::PARAM_STR_ARRAY)
236
+            ->setParameter('tagid', $tagId)
237
+            ->setParameter('objecttype', $objectType);
238
+
239
+        $result = $query->execute();
240
+        $row = $result->fetch(\PDO::FETCH_NUM);
241
+        $result->closeCursor();
242
+
243
+        if ($all) {
244
+            return ((int)$row[0] === \count($objIds));
245
+        }
246
+
247
+        return (bool) $row;
248
+    }
249
+
250
+    /**
251
+     * Asserts that all the given tag ids exist.
252
+     *
253
+     * @param string[] $tagIds tag ids to check
254
+     *
255
+     * @throws \OCP\SystemTag\TagNotFoundException if at least one tag did not exist
256
+     */
257
+    private function assertTagsExist($tagIds) {
258
+        $tags = $this->tagManager->getTagsByIds($tagIds);
259
+        if (\count($tags) !== \count($tagIds)) {
260
+            // at least one tag missing, bail out
261
+            $foundTagIds = array_map(
262
+                function (ISystemTag $tag) {
263
+                    return $tag->getId();
264
+                },
265
+                $tags
266
+            );
267
+            $missingTagIds = array_diff($tagIds, $foundTagIds);
268
+            throw new TagNotFoundException(
269
+                'Tags not found', 0, null, $missingTagIds
270
+            );
271
+        }
272
+    }
273 273
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
 		$result->closeCursor();
242 242
 
243 243
 		if ($all) {
244
-			return ((int)$row[0] === \count($objIds));
244
+			return ((int) $row[0] === \count($objIds));
245 245
 		}
246 246
 
247 247
 		return (bool) $row;
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
 		if (\count($tags) !== \count($tagIds)) {
260 260
 			// at least one tag missing, bail out
261 261
 			$foundTagIds = array_map(
262
-				function (ISystemTag $tag) {
262
+				function(ISystemTag $tag) {
263 263
 					return $tag->getId();
264 264
 				},
265 265
 				$tags
Please login to merge, or discard this patch.
lib/private/L10N/L10N.php 2 patches
Indentation   +212 added lines, -212 removed lines patch added patch discarded remove patch
@@ -35,216 +35,216 @@
 block discarded – undo
35 35
 
36 36
 class L10N implements IL10N {
37 37
 
38
-	/** @var IFactory */
39
-	protected $factory;
40
-
41
-	/** @var string App of this object */
42
-	protected $app;
43
-
44
-	/** @var string Language of this object */
45
-	protected $lang;
46
-
47
-	/** @var string Locale of this object */
48
-	protected $locale;
49
-
50
-	/** @var string Plural forms (string) */
51
-	private $pluralFormString = 'nplurals=2; plural=(n != 1);';
52
-
53
-	/** @var string Plural forms (function) */
54
-	private $pluralFormFunction = null;
55
-
56
-	/** @var string[] */
57
-	private $translations = [];
58
-
59
-	/**
60
-	 * @param IFactory $factory
61
-	 * @param string $app
62
-	 * @param string $lang
63
-	 * @param string $locale
64
-	 * @param array $files
65
-	 */
66
-	public function __construct(IFactory $factory, $app, $lang, $locale, array $files) {
67
-		$this->factory = $factory;
68
-		$this->app = $app;
69
-		$this->lang = $lang;
70
-		$this->locale = $locale;
71
-
72
-		foreach ($files as $languageFile) {
73
-			$this->load($languageFile);
74
-		}
75
-	}
76
-
77
-	/**
78
-	 * The code (en, de, ...) of the language that is used for this instance
79
-	 *
80
-	 * @return string language
81
-	 */
82
-	public function getLanguageCode(): string {
83
-		return $this->lang;
84
-	}
85
-
86
-	/**
87
-	 * The code (en_US, fr_CA, ...) of the locale that is used for this instance
88
-	 *
89
-	 * @return string locale
90
-	 */
91
-	public function getLocaleCode(): string {
92
-		return $this->locale;
93
-	}
94
-
95
-	/**
96
-	 * Translating
97
-	 * @param string $text The text we need a translation for
98
-	 * @param array|string $parameters default:array() Parameters for sprintf
99
-	 * @return string Translation or the same text
100
-	 *
101
-	 * Returns the translation. If no translation is found, $text will be
102
-	 * returned.
103
-	 */
104
-	public function t(string $text, $parameters = []): string {
105
-		if (!\is_array($parameters)) {
106
-			$parameters = [$parameters];
107
-		}
108
-
109
-		return (string) new L10NString($this, $text, $parameters);
110
-	}
111
-
112
-	/**
113
-	 * Translating
114
-	 * @param string $text_singular the string to translate for exactly one object
115
-	 * @param string $text_plural the string to translate for n objects
116
-	 * @param integer $count Number of objects
117
-	 * @param array $parameters default:array() Parameters for sprintf
118
-	 * @return string Translation or the same text
119
-	 *
120
-	 * Returns the translation. If no translation is found, $text will be
121
-	 * returned. %n will be replaced with the number of objects.
122
-	 *
123
-	 * The correct plural is determined by the plural_forms-function
124
-	 * provided by the po file.
125
-	 *
126
-	 */
127
-	public function n(string $text_singular, string $text_plural, int $count, array $parameters = []): string {
128
-		$identifier = "_${text_singular}_::_${text_plural}_";
129
-		if (isset($this->translations[$identifier])) {
130
-			return (string) new L10NString($this, $identifier, $parameters, $count);
131
-		}
132
-
133
-		if ($count === 1) {
134
-			return (string) new L10NString($this, $text_singular, $parameters, $count);
135
-		}
136
-
137
-		return (string) new L10NString($this, $text_plural, $parameters, $count);
138
-	}
139
-
140
-	/**
141
-	 * Localization
142
-	 * @param string $type Type of localization
143
-	 * @param \DateTime|int|string $data parameters for this localization
144
-	 * @param array $options
145
-	 * @return string|int|false
146
-	 *
147
-	 * Returns the localized data.
148
-	 *
149
-	 * Implemented types:
150
-	 *  - date
151
-	 *    - Creates a date
152
-	 *    - params: timestamp (int/string)
153
-	 *  - datetime
154
-	 *    - Creates date and time
155
-	 *    - params: timestamp (int/string)
156
-	 *  - time
157
-	 *    - Creates a time
158
-	 *    - params: timestamp (int/string)
159
-	 *  - firstday: Returns the first day of the week (0 sunday - 6 saturday)
160
-	 *  - jsdate: Returns the short JS date format
161
-	 */
162
-	public function l(string $type, $data = null, array $options = []) {
163
-		if (null === $this->locale) {
164
-			// Use the language of the instance
165
-			$this->locale = $this->getLanguageCode();
166
-		}
167
-		if ($this->locale === 'sr@latin') {
168
-			$this->locale = 'sr_latn';
169
-		}
170
-
171
-		if ($type === 'firstday') {
172
-			return (int) Calendar::getFirstWeekday($this->locale);
173
-		}
174
-		if ($type === 'jsdate') {
175
-			return (string) Calendar::getDateFormat('short', $this->locale);
176
-		}
177
-
178
-		$value = new \DateTime();
179
-		if ($data instanceof \DateTime) {
180
-			$value = $data;
181
-		} else if (\is_string($data) && !is_numeric($data)) {
182
-			$data = strtotime($data);
183
-			$value->setTimestamp($data);
184
-		} else if ($data !== null) {
185
-			$data = (int)$data;
186
-			$value->setTimestamp($data);
187
-		}
188
-
189
-		$options = array_merge(['width' => 'long'], $options);
190
-		$width = $options['width'];
191
-		switch ($type) {
192
-			case 'date':
193
-				return (string) Calendar::formatDate($value, $width, $this->locale);
194
-			case 'datetime':
195
-				return (string) Calendar::formatDatetime($value, $width, $this->locale);
196
-			case 'time':
197
-				return (string) Calendar::formatTime($value, $width, $this->locale);
198
-			case 'weekdayName':
199
-				return (string) Calendar::getWeekdayName($value, $width, $this->locale);
200
-			default:
201
-				return false;
202
-		}
203
-	}
204
-
205
-	/**
206
-	 * Returns an associative array with all translations
207
-	 *
208
-	 * Called by \OC_L10N_String
209
-	 * @return array
210
-	 */
211
-	public function getTranslations(): array {
212
-		return $this->translations;
213
-	}
214
-
215
-	/**
216
-	 * Returnsed function accepts the argument $n
217
-	 *
218
-	 * Called by \OC_L10N_String
219
-	 * @return \Closure the plural form function
220
-	 */
221
-	public function getPluralFormFunction(): \Closure {
222
-		if (\is_null($this->pluralFormFunction)) {
223
-			$lang = $this->getLanguageCode();
224
-			$this->pluralFormFunction = function ($n) use ($lang) {
225
-				return PluralizationRules::get($n, $lang);
226
-			};
227
-		}
228
-
229
-		return $this->pluralFormFunction;
230
-	}
231
-
232
-	/**
233
-	 * @param string $translationFile
234
-	 * @return bool
235
-	 */
236
-	protected function load(string $translationFile): bool {
237
-		$json = json_decode(file_get_contents($translationFile), true);
238
-		if (!\is_array($json)) {
239
-			$jsonError = json_last_error();
240
-			\OC::$server->getLogger()->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']);
241
-			return false;
242
-		}
243
-
244
-		if (!empty($json['pluralForm'])) {
245
-			$this->pluralFormString = $json['pluralForm'];
246
-		}
247
-		$this->translations = array_merge($this->translations, $json['translations']);
248
-		return true;
249
-	}
38
+    /** @var IFactory */
39
+    protected $factory;
40
+
41
+    /** @var string App of this object */
42
+    protected $app;
43
+
44
+    /** @var string Language of this object */
45
+    protected $lang;
46
+
47
+    /** @var string Locale of this object */
48
+    protected $locale;
49
+
50
+    /** @var string Plural forms (string) */
51
+    private $pluralFormString = 'nplurals=2; plural=(n != 1);';
52
+
53
+    /** @var string Plural forms (function) */
54
+    private $pluralFormFunction = null;
55
+
56
+    /** @var string[] */
57
+    private $translations = [];
58
+
59
+    /**
60
+     * @param IFactory $factory
61
+     * @param string $app
62
+     * @param string $lang
63
+     * @param string $locale
64
+     * @param array $files
65
+     */
66
+    public function __construct(IFactory $factory, $app, $lang, $locale, array $files) {
67
+        $this->factory = $factory;
68
+        $this->app = $app;
69
+        $this->lang = $lang;
70
+        $this->locale = $locale;
71
+
72
+        foreach ($files as $languageFile) {
73
+            $this->load($languageFile);
74
+        }
75
+    }
76
+
77
+    /**
78
+     * The code (en, de, ...) of the language that is used for this instance
79
+     *
80
+     * @return string language
81
+     */
82
+    public function getLanguageCode(): string {
83
+        return $this->lang;
84
+    }
85
+
86
+    /**
87
+     * The code (en_US, fr_CA, ...) of the locale that is used for this instance
88
+     *
89
+     * @return string locale
90
+     */
91
+    public function getLocaleCode(): string {
92
+        return $this->locale;
93
+    }
94
+
95
+    /**
96
+     * Translating
97
+     * @param string $text The text we need a translation for
98
+     * @param array|string $parameters default:array() Parameters for sprintf
99
+     * @return string Translation or the same text
100
+     *
101
+     * Returns the translation. If no translation is found, $text will be
102
+     * returned.
103
+     */
104
+    public function t(string $text, $parameters = []): string {
105
+        if (!\is_array($parameters)) {
106
+            $parameters = [$parameters];
107
+        }
108
+
109
+        return (string) new L10NString($this, $text, $parameters);
110
+    }
111
+
112
+    /**
113
+     * Translating
114
+     * @param string $text_singular the string to translate for exactly one object
115
+     * @param string $text_plural the string to translate for n objects
116
+     * @param integer $count Number of objects
117
+     * @param array $parameters default:array() Parameters for sprintf
118
+     * @return string Translation or the same text
119
+     *
120
+     * Returns the translation. If no translation is found, $text will be
121
+     * returned. %n will be replaced with the number of objects.
122
+     *
123
+     * The correct plural is determined by the plural_forms-function
124
+     * provided by the po file.
125
+     *
126
+     */
127
+    public function n(string $text_singular, string $text_plural, int $count, array $parameters = []): string {
128
+        $identifier = "_${text_singular}_::_${text_plural}_";
129
+        if (isset($this->translations[$identifier])) {
130
+            return (string) new L10NString($this, $identifier, $parameters, $count);
131
+        }
132
+
133
+        if ($count === 1) {
134
+            return (string) new L10NString($this, $text_singular, $parameters, $count);
135
+        }
136
+
137
+        return (string) new L10NString($this, $text_plural, $parameters, $count);
138
+    }
139
+
140
+    /**
141
+     * Localization
142
+     * @param string $type Type of localization
143
+     * @param \DateTime|int|string $data parameters for this localization
144
+     * @param array $options
145
+     * @return string|int|false
146
+     *
147
+     * Returns the localized data.
148
+     *
149
+     * Implemented types:
150
+     *  - date
151
+     *    - Creates a date
152
+     *    - params: timestamp (int/string)
153
+     *  - datetime
154
+     *    - Creates date and time
155
+     *    - params: timestamp (int/string)
156
+     *  - time
157
+     *    - Creates a time
158
+     *    - params: timestamp (int/string)
159
+     *  - firstday: Returns the first day of the week (0 sunday - 6 saturday)
160
+     *  - jsdate: Returns the short JS date format
161
+     */
162
+    public function l(string $type, $data = null, array $options = []) {
163
+        if (null === $this->locale) {
164
+            // Use the language of the instance
165
+            $this->locale = $this->getLanguageCode();
166
+        }
167
+        if ($this->locale === 'sr@latin') {
168
+            $this->locale = 'sr_latn';
169
+        }
170
+
171
+        if ($type === 'firstday') {
172
+            return (int) Calendar::getFirstWeekday($this->locale);
173
+        }
174
+        if ($type === 'jsdate') {
175
+            return (string) Calendar::getDateFormat('short', $this->locale);
176
+        }
177
+
178
+        $value = new \DateTime();
179
+        if ($data instanceof \DateTime) {
180
+            $value = $data;
181
+        } else if (\is_string($data) && !is_numeric($data)) {
182
+            $data = strtotime($data);
183
+            $value->setTimestamp($data);
184
+        } else if ($data !== null) {
185
+            $data = (int)$data;
186
+            $value->setTimestamp($data);
187
+        }
188
+
189
+        $options = array_merge(['width' => 'long'], $options);
190
+        $width = $options['width'];
191
+        switch ($type) {
192
+            case 'date':
193
+                return (string) Calendar::formatDate($value, $width, $this->locale);
194
+            case 'datetime':
195
+                return (string) Calendar::formatDatetime($value, $width, $this->locale);
196
+            case 'time':
197
+                return (string) Calendar::formatTime($value, $width, $this->locale);
198
+            case 'weekdayName':
199
+                return (string) Calendar::getWeekdayName($value, $width, $this->locale);
200
+            default:
201
+                return false;
202
+        }
203
+    }
204
+
205
+    /**
206
+     * Returns an associative array with all translations
207
+     *
208
+     * Called by \OC_L10N_String
209
+     * @return array
210
+     */
211
+    public function getTranslations(): array {
212
+        return $this->translations;
213
+    }
214
+
215
+    /**
216
+     * Returnsed function accepts the argument $n
217
+     *
218
+     * Called by \OC_L10N_String
219
+     * @return \Closure the plural form function
220
+     */
221
+    public function getPluralFormFunction(): \Closure {
222
+        if (\is_null($this->pluralFormFunction)) {
223
+            $lang = $this->getLanguageCode();
224
+            $this->pluralFormFunction = function ($n) use ($lang) {
225
+                return PluralizationRules::get($n, $lang);
226
+            };
227
+        }
228
+
229
+        return $this->pluralFormFunction;
230
+    }
231
+
232
+    /**
233
+     * @param string $translationFile
234
+     * @return bool
235
+     */
236
+    protected function load(string $translationFile): bool {
237
+        $json = json_decode(file_get_contents($translationFile), true);
238
+        if (!\is_array($json)) {
239
+            $jsonError = json_last_error();
240
+            \OC::$server->getLogger()->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']);
241
+            return false;
242
+        }
243
+
244
+        if (!empty($json['pluralForm'])) {
245
+            $this->pluralFormString = $json['pluralForm'];
246
+        }
247
+        $this->translations = array_merge($this->translations, $json['translations']);
248
+        return true;
249
+    }
250 250
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 			$data = strtotime($data);
183 183
 			$value->setTimestamp($data);
184 184
 		} else if ($data !== null) {
185
-			$data = (int)$data;
185
+			$data = (int) $data;
186 186
 			$value->setTimestamp($data);
187 187
 		}
188 188
 
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
 	public function getPluralFormFunction(): \Closure {
222 222
 		if (\is_null($this->pluralFormFunction)) {
223 223
 			$lang = $this->getLanguageCode();
224
-			$this->pluralFormFunction = function ($n) use ($lang) {
224
+			$this->pluralFormFunction = function($n) use ($lang) {
225 225
 				return PluralizationRules::get($n, $lang);
226 226
 			};
227 227
 		}
Please login to merge, or discard this patch.