Completed
Pull Request — master (#3770)
by Thomas
38:05 queued 14:21
created
apps/dav/lib/Connector/Sabre/FilesPlugin.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -31,7 +31,6 @@
 block discarded – undo
31 31
 namespace OCA\DAV\Connector\Sabre;
32 32
 
33 33
 use OC\Files\View;
34
-use OCA\DAV\Upload\FutureFile;
35 34
 use OCP\Files\ForbiddenException;
36 35
 use OCP\IPreview;
37 36
 use Sabre\DAV\Exception\Forbidden;
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -245,7 +245,9 @@
 block discarded – undo
245 245
 	function httpGet(RequestInterface $request, ResponseInterface $response) {
246 246
 		// Only handle valid files
247 247
 		$node = $this->tree->getNodeForPath($request->getPath());
248
-		if (!($node instanceof IFile)) return;
248
+		if (!($node instanceof IFile)) {
249
+		    return;
250
+		}
249 251
 
250 252
 		// adds a 'Content-Disposition: attachment' header in case no disposition
251 253
 		// header has been set before
Please login to merge, or discard this patch.
Indentation   +391 added lines, -391 removed lines patch added patch discarded remove patch
@@ -51,395 +51,395 @@
 block discarded – undo
51 51
 
52 52
 class FilesPlugin extends ServerPlugin {
53 53
 
54
-	// namespace
55
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
56
-	const NS_NEXTCLOUD = 'http://nextcloud.org/ns';
57
-	const FILEID_PROPERTYNAME = '{http://owncloud.org/ns}id';
58
-	const INTERNAL_FILEID_PROPERTYNAME = '{http://owncloud.org/ns}fileid';
59
-	const PERMISSIONS_PROPERTYNAME = '{http://owncloud.org/ns}permissions';
60
-	const SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-collaboration-services.org/ns}share-permissions';
61
-	const DOWNLOADURL_PROPERTYNAME = '{http://owncloud.org/ns}downloadURL';
62
-	const SIZE_PROPERTYNAME = '{http://owncloud.org/ns}size';
63
-	const GETETAG_PROPERTYNAME = '{DAV:}getetag';
64
-	const LASTMODIFIED_PROPERTYNAME = '{DAV:}lastmodified';
65
-	const OWNER_ID_PROPERTYNAME = '{http://owncloud.org/ns}owner-id';
66
-	const OWNER_DISPLAY_NAME_PROPERTYNAME = '{http://owncloud.org/ns}owner-display-name';
67
-	const CHECKSUMS_PROPERTYNAME = '{http://owncloud.org/ns}checksums';
68
-	const DATA_FINGERPRINT_PROPERTYNAME = '{http://owncloud.org/ns}data-fingerprint';
69
-	const HAS_PREVIEW_PROPERTYNAME = '{http://nextcloud.org/ns}has-preview';
70
-
71
-	/**
72
-	 * Reference to main server object
73
-	 *
74
-	 * @var \Sabre\DAV\Server
75
-	 */
76
-	private $server;
77
-
78
-	/**
79
-	 * @var Tree
80
-	 */
81
-	private $tree;
82
-
83
-	/**
84
-	 * Whether this is public webdav.
85
-	 * If true, some returned information will be stripped off.
86
-	 *
87
-	 * @var bool
88
-	 */
89
-	private $isPublic;
90
-
91
-	/**
92
-	 * @var View
93
-	 */
94
-	private $fileView;
95
-
96
-	/**
97
-	 * @var bool
98
-	 */
99
-	private $downloadAttachment;
100
-
101
-	/**
102
-	 * @var IConfig
103
-	 */
104
-	private $config;
105
-
106
-	/**
107
-	 * @var IRequest
108
-	 */
109
-	private $request;
110
-
111
-	/**
112
-	 * @var IPreview
113
-	 */
114
-	private $previewManager;
115
-
116
-	/**
117
-	 * @param Tree $tree
118
-	 * @param IConfig $config
119
-	 * @param IRequest $request
120
-	 * @param IPreview $previewManager
121
-	 * @param bool $isPublic
122
-	 * @param bool $downloadAttachment
123
-	 */
124
-	public function __construct(Tree $tree,
125
-								IConfig $config,
126
-								IRequest $request,
127
-								IPreview $previewManager,
128
-								$isPublic = false,
129
-								$downloadAttachment = true) {
130
-		$this->tree = $tree;
131
-		$this->config = $config;
132
-		$this->request = $request;
133
-		$this->isPublic = $isPublic;
134
-		$this->downloadAttachment = $downloadAttachment;
135
-		$this->previewManager = $previewManager;
136
-	}
137
-
138
-	/**
139
-	 * This initializes the plugin.
140
-	 *
141
-	 * This function is called by \Sabre\DAV\Server, after
142
-	 * addPlugin is called.
143
-	 *
144
-	 * This method should set up the required event subscriptions.
145
-	 *
146
-	 * @param \Sabre\DAV\Server $server
147
-	 * @return void
148
-	 */
149
-	public function initialize(\Sabre\DAV\Server $server) {
150
-
151
-		$server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
152
-		$server->xml->namespaceMap[self::NS_NEXTCLOUD] = 'nc';
153
-		$server->protectedProperties[] = self::FILEID_PROPERTYNAME;
154
-		$server->protectedProperties[] = self::INTERNAL_FILEID_PROPERTYNAME;
155
-		$server->protectedProperties[] = self::PERMISSIONS_PROPERTYNAME;
156
-		$server->protectedProperties[] = self::SHARE_PERMISSIONS_PROPERTYNAME;
157
-		$server->protectedProperties[] = self::SIZE_PROPERTYNAME;
158
-		$server->protectedProperties[] = self::DOWNLOADURL_PROPERTYNAME;
159
-		$server->protectedProperties[] = self::OWNER_ID_PROPERTYNAME;
160
-		$server->protectedProperties[] = self::OWNER_DISPLAY_NAME_PROPERTYNAME;
161
-		$server->protectedProperties[] = self::CHECKSUMS_PROPERTYNAME;
162
-		$server->protectedProperties[] = self::DATA_FINGERPRINT_PROPERTYNAME;
163
-		$server->protectedProperties[] = self::HAS_PREVIEW_PROPERTYNAME;
164
-
165
-		// normally these cannot be changed (RFC4918), but we want them modifiable through PROPPATCH
166
-		$allowedProperties = ['{DAV:}getetag'];
167
-		$server->protectedProperties = array_diff($server->protectedProperties, $allowedProperties);
168
-
169
-		$this->server = $server;
170
-		$this->server->on('propFind', array($this, 'handleGetProperties'));
171
-		$this->server->on('propPatch', array($this, 'handleUpdateProperties'));
172
-		$this->server->on('afterBind', array($this, 'sendFileIdHeader'));
173
-		$this->server->on('afterWriteContent', array($this, 'sendFileIdHeader'));
174
-		$this->server->on('afterMethod:GET', [$this,'httpGet']);
175
-		$this->server->on('afterMethod:GET', array($this, 'handleDownloadToken'));
176
-		$this->server->on('afterResponse', function($request, ResponseInterface $response) {
177
-			$body = $response->getBody();
178
-			if (is_resource($body)) {
179
-				fclose($body);
180
-			}
181
-		});
182
-		$this->server->on('beforeMove', [$this, 'checkMove']);
183
-	}
184
-
185
-	/**
186
-	 * Plugin that checks if a move can actually be performed.
187
-	 *
188
-	 * @param string $source source path
189
-	 * @param string $destination destination path
190
-	 * @throws Forbidden
191
-	 * @throws NotFound
192
-	 */
193
-	function checkMove($source, $destination) {
194
-		$sourceNode = $this->tree->getNodeForPath($source);
195
-		if (!$sourceNode instanceof Node) {
196
-			return;
197
-		}
198
-		list($sourceDir,) = \Sabre\HTTP\URLUtil::splitPath($source);
199
-		list($destinationDir,) = \Sabre\HTTP\URLUtil::splitPath($destination);
200
-
201
-		if ($sourceDir !== $destinationDir) {
202
-			$sourceNodeFileInfo = $sourceNode->getFileInfo();
203
-			if (is_null($sourceNodeFileInfo)) {
204
-				throw new NotFound($source . ' does not exist');
205
-			}
206
-
207
-			if (!$sourceNodeFileInfo->isDeletable()) {
208
-				throw new Forbidden($source . " cannot be deleted");
209
-			}
210
-		}
211
-	}
212
-
213
-	/**
214
-	 * This sets a cookie to be able to recognize the start of the download
215
-	 * the content must not be longer than 32 characters and must only contain
216
-	 * alphanumeric characters
217
-	 *
218
-	 * @param RequestInterface $request
219
-	 * @param ResponseInterface $response
220
-	 */
221
-	function handleDownloadToken(RequestInterface $request, ResponseInterface $response) {
222
-		$queryParams = $request->getQueryParameters();
223
-
224
-		/**
225
-		 * this sets a cookie to be able to recognize the start of the download
226
-		 * the content must not be longer than 32 characters and must only contain
227
-		 * alphanumeric characters
228
-		 */
229
-		if (isset($queryParams['downloadStartSecret'])) {
230
-			$token = $queryParams['downloadStartSecret'];
231
-			if (!isset($token[32])
232
-				&& preg_match('!^[a-zA-Z0-9]+$!', $token) === 1) {
233
-				// FIXME: use $response->setHeader() instead
234
-				setcookie('ocDownloadStarted', $token, time() + 20, '/');
235
-			}
236
-		}
237
-	}
238
-
239
-	/**
240
-	 * Add headers to file download
241
-	 *
242
-	 * @param RequestInterface $request
243
-	 * @param ResponseInterface $response
244
-	 */
245
-	function httpGet(RequestInterface $request, ResponseInterface $response) {
246
-		// Only handle valid files
247
-		$node = $this->tree->getNodeForPath($request->getPath());
248
-		if (!($node instanceof IFile)) return;
249
-
250
-		// adds a 'Content-Disposition: attachment' header in case no disposition
251
-		// header has been set before
252
-		if ($this->downloadAttachment &&
253
-			$response->getHeader('Content-Disposition') === null) {
254
-			$filename = $node->getName();
255
-			if ($this->request->isUserAgent(
256
-				[
257
-					\OC\AppFramework\Http\Request::USER_AGENT_IE,
258
-					\OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
259
-					\OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
260
-				])) {
261
-				$response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
262
-			} else {
263
-				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
264
-													 . '; filename="' . rawurlencode($filename) . '"');
265
-			}
266
-		}
267
-
268
-		if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
269
-			//Add OC-Checksum header
270
-			/** @var $node File */
271
-			$checksum = $node->getChecksum();
272
-			if ($checksum !== null && $checksum !== '') {
273
-				$response->addHeader('OC-Checksum', $checksum);
274
-			}
275
-		}
276
-	}
277
-
278
-	/**
279
-	 * Adds all ownCloud-specific properties
280
-	 *
281
-	 * @param PropFind $propFind
282
-	 * @param \Sabre\DAV\INode $node
283
-	 * @return void
284
-	 */
285
-	public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) {
286
-
287
-		$httpRequest = $this->server->httpRequest;
288
-
289
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
290
-
291
-			$propFind->handle(self::FILEID_PROPERTYNAME, function() use ($node) {
292
-				return $node->getFileId();
293
-			});
294
-
295
-			$propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function() use ($node) {
296
-				return $node->getInternalFileId();
297
-			});
298
-
299
-			$propFind->handle(self::PERMISSIONS_PROPERTYNAME, function() use ($node) {
300
-				$perms = $node->getDavPermissions();
301
-				if ($this->isPublic) {
302
-					// remove mount information
303
-					$perms = str_replace(['S', 'M'], '', $perms);
304
-				}
305
-				return $perms;
306
-			});
307
-
308
-			$propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
309
-				return $node->getSharePermissions(
310
-					$httpRequest->getRawServerValue('PHP_AUTH_USER')
311
-				);
312
-			});
313
-
314
-			$propFind->handle(self::GETETAG_PROPERTYNAME, function() use ($node) {
315
-				return $node->getETag();
316
-			});
317
-
318
-			$propFind->handle(self::OWNER_ID_PROPERTYNAME, function() use ($node) {
319
-				$owner = $node->getOwner();
320
-				if (!$owner) {
321
-					return null;
322
-				} else {
323
-					return $owner->getUID();
324
-				}
325
-			});
326
-			$propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function() use ($node) {
327
-				$owner = $node->getOwner();
328
-				if (!$owner) {
329
-					return null;
330
-				} else {
331
-					return $owner->getDisplayName();
332
-				}
333
-			});
334
-
335
-			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
336
-				return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
337
-			});
338
-			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
339
-				return $node->getSize();
340
-			});
341
-		}
342
-
343
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
344
-			$propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function() use ($node) {
345
-				return $this->config->getSystemValue('data-fingerprint', '');
346
-			});
347
-		}
348
-
349
-		if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
350
-			$propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function() use ($node) {
351
-				/** @var $node \OCA\DAV\Connector\Sabre\File */
352
-				try {
353
-					$directDownloadUrl = $node->getDirectDownload();
354
-					if (isset($directDownloadUrl['url'])) {
355
-						return $directDownloadUrl['url'];
356
-					}
357
-				} catch (StorageNotAvailableException $e) {
358
-					return false;
359
-				} catch (ForbiddenException $e) {
360
-					return false;
361
-				}
362
-				return false;
363
-			});
364
-
365
-			$propFind->handle(self::CHECKSUMS_PROPERTYNAME, function() use ($node) {
366
-				$checksum = $node->getChecksum();
367
-				if ($checksum === NULL || $checksum === '') {
368
-					return null;
369
-				}
370
-
371
-				return new ChecksumList($checksum);
372
-			});
373
-
374
-		}
375
-
376
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Directory) {
377
-			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
378
-				return $node->getSize();
379
-			});
380
-		}
381
-	}
382
-
383
-	/**
384
-	 * Update ownCloud-specific properties
385
-	 *
386
-	 * @param string $path
387
-	 * @param PropPatch $propPatch
388
-	 *
389
-	 * @return void
390
-	 */
391
-	public function handleUpdateProperties($path, PropPatch $propPatch) {
392
-		$propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function($time) use ($path) {
393
-			if (empty($time)) {
394
-				return false;
395
-			}
396
-			$node = $this->tree->getNodeForPath($path);
397
-			if (is_null($node)) {
398
-				return 404;
399
-			}
400
-			$node->touch($time);
401
-			return true;
402
-		});
403
-		$propPatch->handle(self::GETETAG_PROPERTYNAME, function($etag) use ($path) {
404
-			if (empty($etag)) {
405
-				return false;
406
-			}
407
-			$node = $this->tree->getNodeForPath($path);
408
-			if (is_null($node)) {
409
-				return 404;
410
-			}
411
-			if ($node->setEtag($etag) !== -1) {
412
-				return true;
413
-			}
414
-			return false;
415
-		});
416
-	}
417
-
418
-	/**
419
-	 * @param string $filePath
420
-	 * @param \Sabre\DAV\INode $node
421
-	 * @throws \Sabre\DAV\Exception\BadRequest
422
-	 */
423
-	public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) {
424
-		// chunked upload handling
425
-		if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
426
-			list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($filePath);
427
-			$info = \OC_FileChunking::decodeName($name);
428
-			if (!empty($info)) {
429
-				$filePath = $path . '/' . $info['name'];
430
-			}
431
-		}
432
-
433
-		// we get the node for the given $filePath here because in case of afterCreateFile $node is the parent folder
434
-		if (!$this->server->tree->nodeExists($filePath)) {
435
-			return;
436
-		}
437
-		$node = $this->server->tree->getNodeForPath($filePath);
438
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
439
-			$fileId = $node->getFileId();
440
-			if (!is_null($fileId)) {
441
-				$this->server->httpResponse->setHeader('OC-FileId', $fileId);
442
-			}
443
-		}
444
-	}
54
+    // namespace
55
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
56
+    const NS_NEXTCLOUD = 'http://nextcloud.org/ns';
57
+    const FILEID_PROPERTYNAME = '{http://owncloud.org/ns}id';
58
+    const INTERNAL_FILEID_PROPERTYNAME = '{http://owncloud.org/ns}fileid';
59
+    const PERMISSIONS_PROPERTYNAME = '{http://owncloud.org/ns}permissions';
60
+    const SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-collaboration-services.org/ns}share-permissions';
61
+    const DOWNLOADURL_PROPERTYNAME = '{http://owncloud.org/ns}downloadURL';
62
+    const SIZE_PROPERTYNAME = '{http://owncloud.org/ns}size';
63
+    const GETETAG_PROPERTYNAME = '{DAV:}getetag';
64
+    const LASTMODIFIED_PROPERTYNAME = '{DAV:}lastmodified';
65
+    const OWNER_ID_PROPERTYNAME = '{http://owncloud.org/ns}owner-id';
66
+    const OWNER_DISPLAY_NAME_PROPERTYNAME = '{http://owncloud.org/ns}owner-display-name';
67
+    const CHECKSUMS_PROPERTYNAME = '{http://owncloud.org/ns}checksums';
68
+    const DATA_FINGERPRINT_PROPERTYNAME = '{http://owncloud.org/ns}data-fingerprint';
69
+    const HAS_PREVIEW_PROPERTYNAME = '{http://nextcloud.org/ns}has-preview';
70
+
71
+    /**
72
+     * Reference to main server object
73
+     *
74
+     * @var \Sabre\DAV\Server
75
+     */
76
+    private $server;
77
+
78
+    /**
79
+     * @var Tree
80
+     */
81
+    private $tree;
82
+
83
+    /**
84
+     * Whether this is public webdav.
85
+     * If true, some returned information will be stripped off.
86
+     *
87
+     * @var bool
88
+     */
89
+    private $isPublic;
90
+
91
+    /**
92
+     * @var View
93
+     */
94
+    private $fileView;
95
+
96
+    /**
97
+     * @var bool
98
+     */
99
+    private $downloadAttachment;
100
+
101
+    /**
102
+     * @var IConfig
103
+     */
104
+    private $config;
105
+
106
+    /**
107
+     * @var IRequest
108
+     */
109
+    private $request;
110
+
111
+    /**
112
+     * @var IPreview
113
+     */
114
+    private $previewManager;
115
+
116
+    /**
117
+     * @param Tree $tree
118
+     * @param IConfig $config
119
+     * @param IRequest $request
120
+     * @param IPreview $previewManager
121
+     * @param bool $isPublic
122
+     * @param bool $downloadAttachment
123
+     */
124
+    public function __construct(Tree $tree,
125
+                                IConfig $config,
126
+                                IRequest $request,
127
+                                IPreview $previewManager,
128
+                                $isPublic = false,
129
+                                $downloadAttachment = true) {
130
+        $this->tree = $tree;
131
+        $this->config = $config;
132
+        $this->request = $request;
133
+        $this->isPublic = $isPublic;
134
+        $this->downloadAttachment = $downloadAttachment;
135
+        $this->previewManager = $previewManager;
136
+    }
137
+
138
+    /**
139
+     * This initializes the plugin.
140
+     *
141
+     * This function is called by \Sabre\DAV\Server, after
142
+     * addPlugin is called.
143
+     *
144
+     * This method should set up the required event subscriptions.
145
+     *
146
+     * @param \Sabre\DAV\Server $server
147
+     * @return void
148
+     */
149
+    public function initialize(\Sabre\DAV\Server $server) {
150
+
151
+        $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
152
+        $server->xml->namespaceMap[self::NS_NEXTCLOUD] = 'nc';
153
+        $server->protectedProperties[] = self::FILEID_PROPERTYNAME;
154
+        $server->protectedProperties[] = self::INTERNAL_FILEID_PROPERTYNAME;
155
+        $server->protectedProperties[] = self::PERMISSIONS_PROPERTYNAME;
156
+        $server->protectedProperties[] = self::SHARE_PERMISSIONS_PROPERTYNAME;
157
+        $server->protectedProperties[] = self::SIZE_PROPERTYNAME;
158
+        $server->protectedProperties[] = self::DOWNLOADURL_PROPERTYNAME;
159
+        $server->protectedProperties[] = self::OWNER_ID_PROPERTYNAME;
160
+        $server->protectedProperties[] = self::OWNER_DISPLAY_NAME_PROPERTYNAME;
161
+        $server->protectedProperties[] = self::CHECKSUMS_PROPERTYNAME;
162
+        $server->protectedProperties[] = self::DATA_FINGERPRINT_PROPERTYNAME;
163
+        $server->protectedProperties[] = self::HAS_PREVIEW_PROPERTYNAME;
164
+
165
+        // normally these cannot be changed (RFC4918), but we want them modifiable through PROPPATCH
166
+        $allowedProperties = ['{DAV:}getetag'];
167
+        $server->protectedProperties = array_diff($server->protectedProperties, $allowedProperties);
168
+
169
+        $this->server = $server;
170
+        $this->server->on('propFind', array($this, 'handleGetProperties'));
171
+        $this->server->on('propPatch', array($this, 'handleUpdateProperties'));
172
+        $this->server->on('afterBind', array($this, 'sendFileIdHeader'));
173
+        $this->server->on('afterWriteContent', array($this, 'sendFileIdHeader'));
174
+        $this->server->on('afterMethod:GET', [$this,'httpGet']);
175
+        $this->server->on('afterMethod:GET', array($this, 'handleDownloadToken'));
176
+        $this->server->on('afterResponse', function($request, ResponseInterface $response) {
177
+            $body = $response->getBody();
178
+            if (is_resource($body)) {
179
+                fclose($body);
180
+            }
181
+        });
182
+        $this->server->on('beforeMove', [$this, 'checkMove']);
183
+    }
184
+
185
+    /**
186
+     * Plugin that checks if a move can actually be performed.
187
+     *
188
+     * @param string $source source path
189
+     * @param string $destination destination path
190
+     * @throws Forbidden
191
+     * @throws NotFound
192
+     */
193
+    function checkMove($source, $destination) {
194
+        $sourceNode = $this->tree->getNodeForPath($source);
195
+        if (!$sourceNode instanceof Node) {
196
+            return;
197
+        }
198
+        list($sourceDir,) = \Sabre\HTTP\URLUtil::splitPath($source);
199
+        list($destinationDir,) = \Sabre\HTTP\URLUtil::splitPath($destination);
200
+
201
+        if ($sourceDir !== $destinationDir) {
202
+            $sourceNodeFileInfo = $sourceNode->getFileInfo();
203
+            if (is_null($sourceNodeFileInfo)) {
204
+                throw new NotFound($source . ' does not exist');
205
+            }
206
+
207
+            if (!$sourceNodeFileInfo->isDeletable()) {
208
+                throw new Forbidden($source . " cannot be deleted");
209
+            }
210
+        }
211
+    }
212
+
213
+    /**
214
+     * This sets a cookie to be able to recognize the start of the download
215
+     * the content must not be longer than 32 characters and must only contain
216
+     * alphanumeric characters
217
+     *
218
+     * @param RequestInterface $request
219
+     * @param ResponseInterface $response
220
+     */
221
+    function handleDownloadToken(RequestInterface $request, ResponseInterface $response) {
222
+        $queryParams = $request->getQueryParameters();
223
+
224
+        /**
225
+         * this sets a cookie to be able to recognize the start of the download
226
+         * the content must not be longer than 32 characters and must only contain
227
+         * alphanumeric characters
228
+         */
229
+        if (isset($queryParams['downloadStartSecret'])) {
230
+            $token = $queryParams['downloadStartSecret'];
231
+            if (!isset($token[32])
232
+                && preg_match('!^[a-zA-Z0-9]+$!', $token) === 1) {
233
+                // FIXME: use $response->setHeader() instead
234
+                setcookie('ocDownloadStarted', $token, time() + 20, '/');
235
+            }
236
+        }
237
+    }
238
+
239
+    /**
240
+     * Add headers to file download
241
+     *
242
+     * @param RequestInterface $request
243
+     * @param ResponseInterface $response
244
+     */
245
+    function httpGet(RequestInterface $request, ResponseInterface $response) {
246
+        // Only handle valid files
247
+        $node = $this->tree->getNodeForPath($request->getPath());
248
+        if (!($node instanceof IFile)) return;
249
+
250
+        // adds a 'Content-Disposition: attachment' header in case no disposition
251
+        // header has been set before
252
+        if ($this->downloadAttachment &&
253
+            $response->getHeader('Content-Disposition') === null) {
254
+            $filename = $node->getName();
255
+            if ($this->request->isUserAgent(
256
+                [
257
+                    \OC\AppFramework\Http\Request::USER_AGENT_IE,
258
+                    \OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
259
+                    \OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
260
+                ])) {
261
+                $response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
262
+            } else {
263
+                $response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
264
+                                                        . '; filename="' . rawurlencode($filename) . '"');
265
+            }
266
+        }
267
+
268
+        if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
269
+            //Add OC-Checksum header
270
+            /** @var $node File */
271
+            $checksum = $node->getChecksum();
272
+            if ($checksum !== null && $checksum !== '') {
273
+                $response->addHeader('OC-Checksum', $checksum);
274
+            }
275
+        }
276
+    }
277
+
278
+    /**
279
+     * Adds all ownCloud-specific properties
280
+     *
281
+     * @param PropFind $propFind
282
+     * @param \Sabre\DAV\INode $node
283
+     * @return void
284
+     */
285
+    public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) {
286
+
287
+        $httpRequest = $this->server->httpRequest;
288
+
289
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
290
+
291
+            $propFind->handle(self::FILEID_PROPERTYNAME, function() use ($node) {
292
+                return $node->getFileId();
293
+            });
294
+
295
+            $propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function() use ($node) {
296
+                return $node->getInternalFileId();
297
+            });
298
+
299
+            $propFind->handle(self::PERMISSIONS_PROPERTYNAME, function() use ($node) {
300
+                $perms = $node->getDavPermissions();
301
+                if ($this->isPublic) {
302
+                    // remove mount information
303
+                    $perms = str_replace(['S', 'M'], '', $perms);
304
+                }
305
+                return $perms;
306
+            });
307
+
308
+            $propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
309
+                return $node->getSharePermissions(
310
+                    $httpRequest->getRawServerValue('PHP_AUTH_USER')
311
+                );
312
+            });
313
+
314
+            $propFind->handle(self::GETETAG_PROPERTYNAME, function() use ($node) {
315
+                return $node->getETag();
316
+            });
317
+
318
+            $propFind->handle(self::OWNER_ID_PROPERTYNAME, function() use ($node) {
319
+                $owner = $node->getOwner();
320
+                if (!$owner) {
321
+                    return null;
322
+                } else {
323
+                    return $owner->getUID();
324
+                }
325
+            });
326
+            $propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function() use ($node) {
327
+                $owner = $node->getOwner();
328
+                if (!$owner) {
329
+                    return null;
330
+                } else {
331
+                    return $owner->getDisplayName();
332
+                }
333
+            });
334
+
335
+            $propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
336
+                return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
337
+            });
338
+            $propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
339
+                return $node->getSize();
340
+            });
341
+        }
342
+
343
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
344
+            $propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function() use ($node) {
345
+                return $this->config->getSystemValue('data-fingerprint', '');
346
+            });
347
+        }
348
+
349
+        if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
350
+            $propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function() use ($node) {
351
+                /** @var $node \OCA\DAV\Connector\Sabre\File */
352
+                try {
353
+                    $directDownloadUrl = $node->getDirectDownload();
354
+                    if (isset($directDownloadUrl['url'])) {
355
+                        return $directDownloadUrl['url'];
356
+                    }
357
+                } catch (StorageNotAvailableException $e) {
358
+                    return false;
359
+                } catch (ForbiddenException $e) {
360
+                    return false;
361
+                }
362
+                return false;
363
+            });
364
+
365
+            $propFind->handle(self::CHECKSUMS_PROPERTYNAME, function() use ($node) {
366
+                $checksum = $node->getChecksum();
367
+                if ($checksum === NULL || $checksum === '') {
368
+                    return null;
369
+                }
370
+
371
+                return new ChecksumList($checksum);
372
+            });
373
+
374
+        }
375
+
376
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Directory) {
377
+            $propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
378
+                return $node->getSize();
379
+            });
380
+        }
381
+    }
382
+
383
+    /**
384
+     * Update ownCloud-specific properties
385
+     *
386
+     * @param string $path
387
+     * @param PropPatch $propPatch
388
+     *
389
+     * @return void
390
+     */
391
+    public function handleUpdateProperties($path, PropPatch $propPatch) {
392
+        $propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function($time) use ($path) {
393
+            if (empty($time)) {
394
+                return false;
395
+            }
396
+            $node = $this->tree->getNodeForPath($path);
397
+            if (is_null($node)) {
398
+                return 404;
399
+            }
400
+            $node->touch($time);
401
+            return true;
402
+        });
403
+        $propPatch->handle(self::GETETAG_PROPERTYNAME, function($etag) use ($path) {
404
+            if (empty($etag)) {
405
+                return false;
406
+            }
407
+            $node = $this->tree->getNodeForPath($path);
408
+            if (is_null($node)) {
409
+                return 404;
410
+            }
411
+            if ($node->setEtag($etag) !== -1) {
412
+                return true;
413
+            }
414
+            return false;
415
+        });
416
+    }
417
+
418
+    /**
419
+     * @param string $filePath
420
+     * @param \Sabre\DAV\INode $node
421
+     * @throws \Sabre\DAV\Exception\BadRequest
422
+     */
423
+    public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) {
424
+        // chunked upload handling
425
+        if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
426
+            list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($filePath);
427
+            $info = \OC_FileChunking::decodeName($name);
428
+            if (!empty($info)) {
429
+                $filePath = $path . '/' . $info['name'];
430
+            }
431
+        }
432
+
433
+        // we get the node for the given $filePath here because in case of afterCreateFile $node is the parent folder
434
+        if (!$this->server->tree->nodeExists($filePath)) {
435
+            return;
436
+        }
437
+        $node = $this->server->tree->getNodeForPath($filePath);
438
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
439
+            $fileId = $node->getFileId();
440
+            if (!is_null($fileId)) {
441
+                $this->server->httpResponse->setHeader('OC-FileId', $fileId);
442
+            }
443
+        }
444
+    }
445 445
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 		$this->server->on('propPatch', array($this, 'handleUpdateProperties'));
172 172
 		$this->server->on('afterBind', array($this, 'sendFileIdHeader'));
173 173
 		$this->server->on('afterWriteContent', array($this, 'sendFileIdHeader'));
174
-		$this->server->on('afterMethod:GET', [$this,'httpGet']);
174
+		$this->server->on('afterMethod:GET', [$this, 'httpGet']);
175 175
 		$this->server->on('afterMethod:GET', array($this, 'handleDownloadToken'));
176 176
 		$this->server->on('afterResponse', function($request, ResponseInterface $response) {
177 177
 			$body = $response->getBody();
@@ -201,11 +201,11 @@  discard block
 block discarded – undo
201 201
 		if ($sourceDir !== $destinationDir) {
202 202
 			$sourceNodeFileInfo = $sourceNode->getFileInfo();
203 203
 			if (is_null($sourceNodeFileInfo)) {
204
-				throw new NotFound($source . ' does not exist');
204
+				throw new NotFound($source.' does not exist');
205 205
 			}
206 206
 
207 207
 			if (!$sourceNodeFileInfo->isDeletable()) {
208
-				throw new Forbidden($source . " cannot be deleted");
208
+				throw new Forbidden($source." cannot be deleted");
209 209
 			}
210 210
 		}
211 211
 	}
@@ -258,10 +258,10 @@  discard block
 block discarded – undo
258 258
 					\OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
259 259
 					\OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
260 260
 				])) {
261
-				$response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
261
+				$response->addHeader('Content-Disposition', 'attachment; filename="'.rawurlencode($filename).'"');
262 262
 			} else {
263
-				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
264
-													 . '; filename="' . rawurlencode($filename) . '"');
263
+				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\''.rawurlencode($filename)
264
+													 . '; filename="'.rawurlencode($filename).'"');
265 265
 			}
266 266
 		}
267 267
 
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
 				}
333 333
 			});
334 334
 
335
-			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
335
+			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function() use ($node) {
336 336
 				return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
337 337
 			});
338 338
 			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
@@ -426,7 +426,7 @@  discard block
 block discarded – undo
426 426
 			list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($filePath);
427 427
 			$info = \OC_FileChunking::decodeName($name);
428 428
 			if (!empty($info)) {
429
-				$filePath = $path . '/' . $info['name'];
429
+				$filePath = $path.'/'.$info['name'];
430 430
 			}
431 431
 		}
432 432
 
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/FTP.php 4 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -139,6 +139,9 @@
 block discarded – undo
139 139
 		return false;
140 140
 	}
141 141
 
142
+	/**
143
+	 * @param string $path
144
+	 */
142 145
 	public function writeBack($tmpFile, $path) {
143 146
 		$this->uploadFile($tmpFile, $path);
144 147
 		unlink($tmpFile);
Please login to merge, or discard this patch.
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -37,122 +37,122 @@
 block discarded – undo
37 37
 use Icewind\Streams\RetryWrapper;
38 38
 
39 39
 class FTP extends StreamWrapper{
40
-	private $password;
41
-	private $user;
42
-	private $host;
43
-	private $secure;
44
-	private $root;
40
+    private $password;
41
+    private $user;
42
+    private $host;
43
+    private $secure;
44
+    private $root;
45 45
 
46
-	private static $tempFiles=array();
46
+    private static $tempFiles=array();
47 47
 
48
-	public function __construct($params) {
49
-		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
50
-			$this->host=$params['host'];
51
-			$this->user=$params['user'];
52
-			$this->password=$params['password'];
53
-			if (isset($params['secure'])) {
54
-				$this->secure = $params['secure'];
55
-			} else {
56
-				$this->secure = false;
57
-			}
58
-			$this->root=isset($params['root'])?$params['root']:'/';
59
-			if ( ! $this->root || $this->root[0]!='/') {
60
-				$this->root='/'.$this->root;
61
-			}
62
-			if (substr($this->root, -1) !== '/') {
63
-				$this->root .= '/';
64
-			}
65
-		} else {
66
-			throw new \Exception('Creating FTP storage failed');
67
-		}
48
+    public function __construct($params) {
49
+        if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
50
+            $this->host=$params['host'];
51
+            $this->user=$params['user'];
52
+            $this->password=$params['password'];
53
+            if (isset($params['secure'])) {
54
+                $this->secure = $params['secure'];
55
+            } else {
56
+                $this->secure = false;
57
+            }
58
+            $this->root=isset($params['root'])?$params['root']:'/';
59
+            if ( ! $this->root || $this->root[0]!='/') {
60
+                $this->root='/'.$this->root;
61
+            }
62
+            if (substr($this->root, -1) !== '/') {
63
+                $this->root .= '/';
64
+            }
65
+        } else {
66
+            throw new \Exception('Creating FTP storage failed');
67
+        }
68 68
 		
69
-	}
69
+    }
70 70
 
71
-	public function getId(){
72
-		return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
73
-	}
71
+    public function getId(){
72
+        return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
73
+    }
74 74
 
75
-	/**
76
-	 * construct the ftp url
77
-	 * @param string $path
78
-	 * @return string
79
-	 */
80
-	public function constructUrl($path) {
81
-		$url='ftp';
82
-		if ($this->secure) {
83
-			$url.='s';
84
-		}
85
-		$url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
86
-		return $url;
87
-	}
75
+    /**
76
+     * construct the ftp url
77
+     * @param string $path
78
+     * @return string
79
+     */
80
+    public function constructUrl($path) {
81
+        $url='ftp';
82
+        if ($this->secure) {
83
+            $url.='s';
84
+        }
85
+        $url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
86
+        return $url;
87
+    }
88 88
 
89
-	/**
90
-	 * Unlinks file or directory
91
-	 * @param string $path
92
-	 */
93
-	public function unlink($path) {
94
-		if ($this->is_dir($path)) {
95
-			return $this->rmdir($path);
96
-		}
97
-		else {
98
-			$url = $this->constructUrl($path);
99
-			$result = unlink($url);
100
-			clearstatcache(true, $url);
101
-			return $result;
102
-		}
103
-	}
104
-	public function fopen($path,$mode) {
105
-		switch($mode) {
106
-			case 'r':
107
-			case 'rb':
108
-			case 'w':
109
-			case 'wb':
110
-			case 'a':
111
-			case 'ab':
112
-				//these are supported by the wrapper
113
-				$context = stream_context_create(array('ftp' => array('overwrite' => true)));
114
-				$handle = fopen($this->constructUrl($path), $mode, false, $context);
115
-				return RetryWrapper::wrap($handle);
116
-			case 'r+':
117
-			case 'w+':
118
-			case 'wb+':
119
-			case 'a+':
120
-			case 'x':
121
-			case 'x+':
122
-			case 'c':
123
-			case 'c+':
124
-				//emulate these
125
-				if (strrpos($path, '.')!==false) {
126
-					$ext=substr($path, strrpos($path, '.'));
127
-				} else {
128
-					$ext='';
129
-				}
130
-				$tmpFile=\OCP\Files::tmpFile($ext);
131
-				if ($this->file_exists($path)) {
132
-					$this->getFile($path, $tmpFile);
133
-				}
134
-				$handle = fopen($tmpFile, $mode);
135
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
136
-					$this->writeBack($tmpFile, $path);
137
-				});
138
-		}
139
-		return false;
140
-	}
89
+    /**
90
+     * Unlinks file or directory
91
+     * @param string $path
92
+     */
93
+    public function unlink($path) {
94
+        if ($this->is_dir($path)) {
95
+            return $this->rmdir($path);
96
+        }
97
+        else {
98
+            $url = $this->constructUrl($path);
99
+            $result = unlink($url);
100
+            clearstatcache(true, $url);
101
+            return $result;
102
+        }
103
+    }
104
+    public function fopen($path,$mode) {
105
+        switch($mode) {
106
+            case 'r':
107
+            case 'rb':
108
+            case 'w':
109
+            case 'wb':
110
+            case 'a':
111
+            case 'ab':
112
+                //these are supported by the wrapper
113
+                $context = stream_context_create(array('ftp' => array('overwrite' => true)));
114
+                $handle = fopen($this->constructUrl($path), $mode, false, $context);
115
+                return RetryWrapper::wrap($handle);
116
+            case 'r+':
117
+            case 'w+':
118
+            case 'wb+':
119
+            case 'a+':
120
+            case 'x':
121
+            case 'x+':
122
+            case 'c':
123
+            case 'c+':
124
+                //emulate these
125
+                if (strrpos($path, '.')!==false) {
126
+                    $ext=substr($path, strrpos($path, '.'));
127
+                } else {
128
+                    $ext='';
129
+                }
130
+                $tmpFile=\OCP\Files::tmpFile($ext);
131
+                if ($this->file_exists($path)) {
132
+                    $this->getFile($path, $tmpFile);
133
+                }
134
+                $handle = fopen($tmpFile, $mode);
135
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
136
+                    $this->writeBack($tmpFile, $path);
137
+                });
138
+        }
139
+        return false;
140
+    }
141 141
 
142
-	public function writeBack($tmpFile, $path) {
143
-		$this->uploadFile($tmpFile, $path);
144
-		unlink($tmpFile);
145
-	}
142
+    public function writeBack($tmpFile, $path) {
143
+        $this->uploadFile($tmpFile, $path);
144
+        unlink($tmpFile);
145
+    }
146 146
 
147
-	/**
148
-	 * check if php-ftp is installed
149
-	 */
150
-	public static function checkDependencies() {
151
-		if (function_exists('ftp_login')) {
152
-			return(true);
153
-		} else {
154
-			return array('ftp');
155
-		}
156
-	}
147
+    /**
148
+     * check if php-ftp is installed
149
+     */
150
+    public static function checkDependencies() {
151
+        if (function_exists('ftp_login')) {
152
+            return(true);
153
+        } else {
154
+            return array('ftp');
155
+        }
156
+    }
157 157
 
158 158
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -36,28 +36,28 @@  discard block
 block discarded – undo
36 36
 use Icewind\Streams\CallbackWrapper;
37 37
 use Icewind\Streams\RetryWrapper;
38 38
 
39
-class FTP extends StreamWrapper{
39
+class FTP extends StreamWrapper {
40 40
 	private $password;
41 41
 	private $user;
42 42
 	private $host;
43 43
 	private $secure;
44 44
 	private $root;
45 45
 
46
-	private static $tempFiles=array();
46
+	private static $tempFiles = array();
47 47
 
48 48
 	public function __construct($params) {
49 49
 		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
50
-			$this->host=$params['host'];
51
-			$this->user=$params['user'];
52
-			$this->password=$params['password'];
50
+			$this->host = $params['host'];
51
+			$this->user = $params['user'];
52
+			$this->password = $params['password'];
53 53
 			if (isset($params['secure'])) {
54 54
 				$this->secure = $params['secure'];
55 55
 			} else {
56 56
 				$this->secure = false;
57 57
 			}
58
-			$this->root=isset($params['root'])?$params['root']:'/';
59
-			if ( ! $this->root || $this->root[0]!='/') {
60
-				$this->root='/'.$this->root;
58
+			$this->root = isset($params['root']) ? $params['root'] : '/';
59
+			if (!$this->root || $this->root[0] != '/') {
60
+				$this->root = '/'.$this->root;
61 61
 			}
62 62
 			if (substr($this->root, -1) !== '/') {
63 63
 				$this->root .= '/';
@@ -68,8 +68,8 @@  discard block
 block discarded – undo
68 68
 		
69 69
 	}
70 70
 
71
-	public function getId(){
72
-		return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
71
+	public function getId() {
72
+		return 'ftp::'.$this->user.'@'.$this->host.'/'.$this->root;
73 73
 	}
74 74
 
75 75
 	/**
@@ -78,11 +78,11 @@  discard block
 block discarded – undo
78 78
 	 * @return string
79 79
 	 */
80 80
 	public function constructUrl($path) {
81
-		$url='ftp';
81
+		$url = 'ftp';
82 82
 		if ($this->secure) {
83
-			$url.='s';
83
+			$url .= 's';
84 84
 		}
85
-		$url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
85
+		$url .= '://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
86 86
 		return $url;
87 87
 	}
88 88
 
@@ -101,8 +101,8 @@  discard block
 block discarded – undo
101 101
 			return $result;
102 102
 		}
103 103
 	}
104
-	public function fopen($path,$mode) {
105
-		switch($mode) {
104
+	public function fopen($path, $mode) {
105
+		switch ($mode) {
106 106
 			case 'r':
107 107
 			case 'rb':
108 108
 			case 'w':
@@ -122,17 +122,17 @@  discard block
 block discarded – undo
122 122
 			case 'c':
123 123
 			case 'c+':
124 124
 				//emulate these
125
-				if (strrpos($path, '.')!==false) {
126
-					$ext=substr($path, strrpos($path, '.'));
125
+				if (strrpos($path, '.') !== false) {
126
+					$ext = substr($path, strrpos($path, '.'));
127 127
 				} else {
128
-					$ext='';
128
+					$ext = '';
129 129
 				}
130
-				$tmpFile=\OCP\Files::tmpFile($ext);
130
+				$tmpFile = \OCP\Files::tmpFile($ext);
131 131
 				if ($this->file_exists($path)) {
132 132
 					$this->getFile($path, $tmpFile);
133 133
 				}
134 134
 				$handle = fopen($tmpFile, $mode);
135
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
135
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
136 136
 					$this->writeBack($tmpFile, $path);
137 137
 				});
138 138
 		}
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -93,8 +93,7 @@
 block discarded – undo
93 93
 	public function unlink($path) {
94 94
 		if ($this->is_dir($path)) {
95 95
 			return $this->rmdir($path);
96
-		}
97
-		else {
96
+		} else {
98 97
 			$url = $this->constructUrl($path);
99 98
 			$result = unlink($url);
100 99
 			clearstatcache(true, $url);
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/Swift.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -616,6 +616,9 @@
 block discarded – undo
616 616
 		return $this->container;
617 617
 	}
618 618
 
619
+	/**
620
+	 * @param string $path
621
+	 */
619 622
 	public function writeBack($tmpFile, $path) {
620 623
 		$fileData = fopen($tmpFile, 'r');
621 624
 		$this->getContainer()->uploadObject($path, $fileData);
Please login to merge, or discard this patch.
Indentation   +604 added lines, -604 removed lines patch added patch discarded remove patch
@@ -48,609 +48,609 @@
 block discarded – undo
48 48
 
49 49
 class Swift extends \OC\Files\Storage\Common {
50 50
 
51
-	/**
52
-	 * @var \OpenCloud\ObjectStore\Service
53
-	 */
54
-	private $connection;
55
-	/**
56
-	 * @var \OpenCloud\ObjectStore\Resource\Container
57
-	 */
58
-	private $container;
59
-	/**
60
-	 * @var \OpenCloud\OpenStack
61
-	 */
62
-	private $anchor;
63
-	/**
64
-	 * @var string
65
-	 */
66
-	private $bucket;
67
-	/**
68
-	 * Connection parameters
69
-	 *
70
-	 * @var array
71
-	 */
72
-	private $params;
73
-
74
-	/** @var string  */
75
-	private $id;
76
-
77
-	/**
78
-	 * @var array
79
-	 */
80
-	private static $tmpFiles = array();
81
-
82
-	/**
83
-	 * Key value cache mapping path to data object. Maps path to
84
-	 * \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject for existing
85
-	 * paths and path to false for not existing paths.
86
-	 * @var \OCP\ICache
87
-	 */
88
-	private $objectCache;
89
-
90
-	/**
91
-	 * @param string $path
92
-	 */
93
-	private function normalizePath($path) {
94
-		$path = trim($path, '/');
95
-
96
-		if (!$path) {
97
-			$path = '.';
98
-		}
99
-
100
-		$path = str_replace('#', '%23', $path);
101
-
102
-		return $path;
103
-	}
104
-
105
-	const SUBCONTAINER_FILE = '.subcontainers';
106
-
107
-	/**
108
-	 * translate directory path to container name
109
-	 *
110
-	 * @param string $path
111
-	 * @return string
112
-	 */
113
-
114
-	/**
115
-	 * Fetches an object from the API.
116
-	 * If the object is cached already or a
117
-	 * failed "doesn't exist" response was cached,
118
-	 * that one will be returned.
119
-	 *
120
-	 * @param string $path
121
-	 * @return \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject|bool object
122
-	 * or false if the object did not exist
123
-	 */
124
-	private function fetchObject($path) {
125
-		if ($this->objectCache->hasKey($path)) {
126
-			// might be "false" if object did not exist from last check
127
-			return $this->objectCache->get($path);
128
-		}
129
-		try {
130
-			$object = $this->getContainer()->getPartialObject($path);
131
-			$this->objectCache->set($path, $object);
132
-			return $object;
133
-		} catch (ClientErrorResponseException $e) {
134
-			// this exception happens when the object does not exist, which
135
-			// is expected in most cases
136
-			$this->objectCache->set($path, false);
137
-			return false;
138
-		} catch (ClientErrorResponseException $e) {
139
-			// Expected response is "404 Not Found", so only log if it isn't
140
-			if ($e->getResponse()->getStatusCode() !== 404) {
141
-				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
142
-			}
143
-			return false;
144
-		}
145
-	}
146
-
147
-	/**
148
-	 * Returns whether the given path exists.
149
-	 *
150
-	 * @param string $path
151
-	 *
152
-	 * @return bool true if the object exist, false otherwise
153
-	 */
154
-	private function doesObjectExist($path) {
155
-		return $this->fetchObject($path) !== false;
156
-	}
157
-
158
-	public function __construct($params) {
159
-		if ((empty($params['key']) and empty($params['password']))
160
-			or empty($params['user']) or empty($params['bucket'])
161
-			or empty($params['region'])
162
-		) {
163
-			throw new \Exception("API Key or password, Username, Bucket and Region have to be configured.");
164
-		}
165
-
166
-		$this->id = 'swift::' . $params['user'] . md5($params['bucket']);
167
-
168
-		$bucketUrl = Url::factory($params['bucket']);
169
-		if ($bucketUrl->isAbsolute()) {
170
-			$this->bucket = end(($bucketUrl->getPathSegments()));
171
-			$params['endpoint_url'] = $bucketUrl->addPath('..')->normalizePath();
172
-		} else {
173
-			$this->bucket = $params['bucket'];
174
-		}
175
-
176
-		if (empty($params['url'])) {
177
-			$params['url'] = 'https://identity.api.rackspacecloud.com/v2.0/';
178
-		}
179
-
180
-		if (empty($params['service_name'])) {
181
-			$params['service_name'] = 'cloudFiles';
182
-		}
183
-
184
-		$this->params = $params;
185
-		// FIXME: private class...
186
-		$this->objectCache = new \OC\Cache\CappedMemoryCache();
187
-	}
188
-
189
-	public function mkdir($path) {
190
-		$path = $this->normalizePath($path);
191
-
192
-		if ($this->is_dir($path)) {
193
-			return false;
194
-		}
195
-
196
-		if ($path !== '.') {
197
-			$path .= '/';
198
-		}
199
-
200
-		try {
201
-			$customHeaders = array('content-type' => 'httpd/unix-directory');
202
-			$metadataHeaders = DataObject::stockHeaders(array());
203
-			$allHeaders = $customHeaders + $metadataHeaders;
204
-			$this->getContainer()->uploadObject($path, '', $allHeaders);
205
-			// invalidate so that the next access gets the real object
206
-			// with all properties
207
-			$this->objectCache->remove($path);
208
-		} catch (Exceptions\CreateUpdateError $e) {
209
-			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
210
-			return false;
211
-		}
212
-
213
-		return true;
214
-	}
215
-
216
-	public function file_exists($path) {
217
-		$path = $this->normalizePath($path);
218
-
219
-		if ($path !== '.' && $this->is_dir($path)) {
220
-			$path .= '/';
221
-		}
222
-
223
-		return $this->doesObjectExist($path);
224
-	}
225
-
226
-	public function rmdir($path) {
227
-		$path = $this->normalizePath($path);
228
-
229
-		if (!$this->is_dir($path) || !$this->isDeletable($path)) {
230
-			return false;
231
-		}
232
-
233
-		$dh = $this->opendir($path);
234
-		while ($file = readdir($dh)) {
235
-			if (\OC\Files\Filesystem::isIgnoredDir($file)) {
236
-				continue;
237
-			}
238
-
239
-			if ($this->is_dir($path . '/' . $file)) {
240
-				$this->rmdir($path . '/' . $file);
241
-			} else {
242
-				$this->unlink($path . '/' . $file);
243
-			}
244
-		}
245
-
246
-		try {
247
-			$this->getContainer()->dataObject()->setName($path . '/')->delete();
248
-			$this->objectCache->remove($path . '/');
249
-		} catch (Exceptions\DeleteError $e) {
250
-			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
251
-			return false;
252
-		}
253
-
254
-		return true;
255
-	}
256
-
257
-	public function opendir($path) {
258
-		$path = $this->normalizePath($path);
259
-
260
-		if ($path === '.') {
261
-			$path = '';
262
-		} else {
263
-			$path .= '/';
264
-		}
265
-
266
-		$path = str_replace('%23', '#', $path); // the prefix is sent as a query param, so revert the encoding of #
267
-
268
-		try {
269
-			$files = array();
270
-			/** @var OpenCloud\Common\Collection $objects */
271
-			$objects = $this->getContainer()->objectList(array(
272
-				'prefix' => $path,
273
-				'delimiter' => '/'
274
-			));
275
-
276
-			/** @var OpenCloud\ObjectStore\Resource\DataObject $object */
277
-			foreach ($objects as $object) {
278
-				$file = basename($object->getName());
279
-				if ($file !== basename($path)) {
280
-					$files[] = $file;
281
-				}
282
-			}
283
-
284
-			return IteratorDirectory::wrap($files);
285
-		} catch (\Exception $e) {
286
-			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
287
-			return false;
288
-		}
289
-
290
-	}
291
-
292
-	public function stat($path) {
293
-		$path = $this->normalizePath($path);
294
-
295
-		if ($path === '.') {
296
-			$path = '';
297
-		} else if ($this->is_dir($path)) {
298
-			$path .= '/';
299
-		}
300
-
301
-		try {
302
-			/** @var DataObject $object */
303
-			$object = $this->fetchObject($path);
304
-			if (!$object) {
305
-				return false;
306
-			}
307
-		} catch (ClientErrorResponseException $e) {
308
-			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
309
-			return false;
310
-		}
311
-
312
-		$dateTime = \DateTime::createFromFormat(\DateTime::RFC1123, $object->getLastModified());
313
-		if ($dateTime !== false) {
314
-			$mtime = $dateTime->getTimestamp();
315
-		} else {
316
-			$mtime = null;
317
-		}
318
-		$objectMetadata = $object->getMetadata();
319
-		$metaTimestamp = $objectMetadata->getProperty('timestamp');
320
-		if (isset($metaTimestamp)) {
321
-			$mtime = $metaTimestamp;
322
-		}
323
-
324
-		if (!empty($mtime)) {
325
-			$mtime = floor($mtime);
326
-		}
327
-
328
-		$stat = array();
329
-		$stat['size'] = (int)$object->getContentLength();
330
-		$stat['mtime'] = $mtime;
331
-		$stat['atime'] = time();
332
-		return $stat;
333
-	}
334
-
335
-	public function filetype($path) {
336
-		$path = $this->normalizePath($path);
337
-
338
-		if ($path !== '.' && $this->doesObjectExist($path)) {
339
-			return 'file';
340
-		}
341
-
342
-		if ($path !== '.') {
343
-			$path .= '/';
344
-		}
345
-
346
-		if ($this->doesObjectExist($path)) {
347
-			return 'dir';
348
-		}
349
-	}
350
-
351
-	public function unlink($path) {
352
-		$path = $this->normalizePath($path);
353
-
354
-		if ($this->is_dir($path)) {
355
-			return $this->rmdir($path);
356
-		}
357
-
358
-		try {
359
-			$this->getContainer()->dataObject()->setName($path)->delete();
360
-			$this->objectCache->remove($path);
361
-			$this->objectCache->remove($path . '/');
362
-		} catch (ClientErrorResponseException $e) {
363
-			if ($e->getResponse()->getStatusCode() !== 404) {
364
-				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
365
-			}
366
-			return false;
367
-		}
368
-
369
-		return true;
370
-	}
371
-
372
-	public function fopen($path, $mode) {
373
-		$path = $this->normalizePath($path);
374
-
375
-		switch ($mode) {
376
-			case 'r':
377
-			case 'rb':
378
-				try {
379
-					$c = $this->getContainer();
380
-					$streamFactory = new \Guzzle\Stream\PhpStreamRequestFactory();
381
-					$streamInterface = $streamFactory->fromRequest(
382
-						$c->getClient()
383
-							->get($c->getUrl($path)));
384
-					$streamInterface->rewind();
385
-					$stream = $streamInterface->getStream();
386
-					stream_context_set_option($stream, 'swift','content', $streamInterface);
387
-					if(!strrpos($streamInterface
388
-						->getMetaData('wrapper_data')[0], '404 Not Found')) {
389
-						return $stream;
390
-					}
391
-					return false;
392
-				} catch (\Guzzle\Http\Exception\BadResponseException $e) {
393
-					\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
394
-					return false;
395
-				}
396
-			case 'w':
397
-			case 'wb':
398
-			case 'a':
399
-			case 'ab':
400
-			case 'r+':
401
-			case 'w+':
402
-			case 'wb+':
403
-			case 'a+':
404
-			case 'x':
405
-			case 'x+':
406
-			case 'c':
407
-			case 'c+':
408
-				if (strrpos($path, '.') !== false) {
409
-					$ext = substr($path, strrpos($path, '.'));
410
-				} else {
411
-					$ext = '';
412
-				}
413
-				$tmpFile = \OCP\Files::tmpFile($ext);
414
-				// Fetch existing file if required
415
-				if ($mode[0] !== 'w' && $this->file_exists($path)) {
416
-					if ($mode[0] === 'x') {
417
-						// File cannot already exist
418
-						return false;
419
-					}
420
-					$source = $this->fopen($path, 'r');
421
-					file_put_contents($tmpFile, $source);
422
-					// Seek to end if required
423
-					if ($mode[0] === 'a') {
424
-						fseek($tmpFile, 0, SEEK_END);
425
-					}
426
-				}
427
-				$handle = fopen($tmpFile, $mode);
428
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
429
-					$this->writeBack($tmpFile, $path);
430
-				});
431
-		}
432
-	}
433
-
434
-	public function touch($path, $mtime = null) {
435
-		$path = $this->normalizePath($path);
436
-		if (is_null($mtime)) {
437
-			$mtime = time();
438
-		}
439
-		$metadata = array('timestamp' => $mtime);
440
-		if ($this->file_exists($path)) {
441
-			if ($this->is_dir($path) && $path != '.') {
442
-				$path .= '/';
443
-			}
444
-
445
-			$object = $this->fetchObject($path);
446
-			if ($object->saveMetadata($metadata)) {
447
-				// invalidate target object to force repopulation on fetch
448
-				$this->objectCache->remove($path);
449
-			}
450
-			return true;
451
-		} else {
452
-			$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
453
-			$customHeaders = array('content-type' => $mimeType);
454
-			$metadataHeaders = DataObject::stockHeaders($metadata);
455
-			$allHeaders = $customHeaders + $metadataHeaders;
456
-			$this->getContainer()->uploadObject($path, '', $allHeaders);
457
-			// invalidate target object to force repopulation on fetch
458
-			$this->objectCache->remove($path);
459
-			return true;
460
-		}
461
-	}
462
-
463
-	public function copy($path1, $path2) {
464
-		$path1 = $this->normalizePath($path1);
465
-		$path2 = $this->normalizePath($path2);
466
-
467
-		$fileType = $this->filetype($path1);
468
-		if ($fileType === 'file') {
469
-
470
-			// make way
471
-			$this->unlink($path2);
472
-
473
-			try {
474
-				$source = $this->fetchObject($path1);
475
-				$source->copy($this->bucket . '/' . $path2);
476
-				// invalidate target object to force repopulation on fetch
477
-				$this->objectCache->remove($path2);
478
-				$this->objectCache->remove($path2 . '/');
479
-			} catch (ClientErrorResponseException $e) {
480
-				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
481
-				return false;
482
-			}
483
-
484
-		} else if ($fileType === 'dir') {
485
-
486
-			// make way
487
-			$this->unlink($path2);
488
-
489
-			try {
490
-				$source = $this->fetchObject($path1 . '/');
491
-				$source->copy($this->bucket . '/' . $path2 . '/');
492
-				// invalidate target object to force repopulation on fetch
493
-				$this->objectCache->remove($path2);
494
-				$this->objectCache->remove($path2 . '/');
495
-			} catch (ClientErrorResponseException $e) {
496
-				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
497
-				return false;
498
-			}
499
-
500
-			$dh = $this->opendir($path1);
501
-			while ($file = readdir($dh)) {
502
-				if (\OC\Files\Filesystem::isIgnoredDir($file)) {
503
-					continue;
504
-				}
505
-
506
-				$source = $path1 . '/' . $file;
507
-				$target = $path2 . '/' . $file;
508
-				$this->copy($source, $target);
509
-			}
510
-
511
-		} else {
512
-			//file does not exist
513
-			return false;
514
-		}
515
-
516
-		return true;
517
-	}
518
-
519
-	public function rename($path1, $path2) {
520
-		$path1 = $this->normalizePath($path1);
521
-		$path2 = $this->normalizePath($path2);
522
-
523
-		$fileType = $this->filetype($path1);
524
-
525
-		if ($fileType === 'dir' || $fileType === 'file') {
526
-			// copy
527
-			if ($this->copy($path1, $path2) === false) {
528
-				return false;
529
-			}
530
-
531
-			// cleanup
532
-			if ($this->unlink($path1) === false) {
533
-				$this->unlink($path2);
534
-				return false;
535
-			}
536
-
537
-			return true;
538
-		}
539
-
540
-		return false;
541
-	}
542
-
543
-	public function getId() {
544
-		return $this->id;
545
-	}
546
-
547
-	/**
548
-	 * Returns the connection
549
-	 *
550
-	 * @return OpenCloud\ObjectStore\Service connected client
551
-	 * @throws \Exception if connection could not be made
552
-	 */
553
-	public function getConnection() {
554
-		if (!is_null($this->connection)) {
555
-			return $this->connection;
556
-		}
557
-
558
-		$settings = array(
559
-			'username' => $this->params['user'],
560
-		);
561
-
562
-		if (!empty($this->params['password'])) {
563
-			$settings['password'] = $this->params['password'];
564
-		} else if (!empty($this->params['key'])) {
565
-			$settings['apiKey'] = $this->params['key'];
566
-		}
567
-
568
-		if (!empty($this->params['tenant'])) {
569
-			$settings['tenantName'] = $this->params['tenant'];
570
-		}
571
-
572
-		if (!empty($this->params['timeout'])) {
573
-			$settings['timeout'] = $this->params['timeout'];
574
-		}
575
-
576
-		if (isset($settings['apiKey'])) {
577
-			$this->anchor = new Rackspace($this->params['url'], $settings);
578
-		} else {
579
-			$this->anchor = new OpenStack($this->params['url'], $settings);
580
-		}
581
-
582
-		$connection = $this->anchor->objectStoreService($this->params['service_name'], $this->params['region']);
583
-
584
-		if (!empty($this->params['endpoint_url'])) {
585
-			$endpoint = $connection->getEndpoint();
586
-			$endpoint->setPublicUrl($this->params['endpoint_url']);
587
-			$endpoint->setPrivateUrl($this->params['endpoint_url']);
588
-			$connection->setEndpoint($endpoint);
589
-		}
590
-
591
-		$this->connection = $connection;
592
-
593
-		return $this->connection;
594
-	}
595
-
596
-	/**
597
-	 * Returns the initialized object store container.
598
-	 *
599
-	 * @return OpenCloud\ObjectStore\Resource\Container
600
-	 */
601
-	public function getContainer() {
602
-		if (!is_null($this->container)) {
603
-			return $this->container;
604
-		}
605
-
606
-		try {
607
-			$this->container = $this->getConnection()->getContainer($this->bucket);
608
-		} catch (ClientErrorResponseException $e) {
609
-			$this->container = $this->getConnection()->createContainer($this->bucket);
610
-		}
611
-
612
-		if (!$this->file_exists('.')) {
613
-			$this->mkdir('.');
614
-		}
615
-
616
-		return $this->container;
617
-	}
618
-
619
-	public function writeBack($tmpFile, $path) {
620
-		$fileData = fopen($tmpFile, 'r');
621
-		$this->getContainer()->uploadObject($path, $fileData);
622
-		// invalidate target object to force repopulation on fetch
623
-		$this->objectCache->remove(self::$tmpFiles[$tmpFile]);
624
-		unlink($tmpFile);
625
-	}
626
-
627
-	public function hasUpdated($path, $time) {
628
-		if ($this->is_file($path)) {
629
-			return parent::hasUpdated($path, $time);
630
-		}
631
-		$path = $this->normalizePath($path);
632
-		$dh = $this->opendir($path);
633
-		$content = array();
634
-		while (($file = readdir($dh)) !== false) {
635
-			$content[] = $file;
636
-		}
637
-		if ($path === '.') {
638
-			$path = '';
639
-		}
640
-		$cachedContent = $this->getCache()->getFolderContents($path);
641
-		$cachedNames = array_map(function ($content) {
642
-			return $content['name'];
643
-		}, $cachedContent);
644
-		sort($cachedNames);
645
-		sort($content);
646
-		return $cachedNames != $content;
647
-	}
648
-
649
-	/**
650
-	 * check if curl is installed
651
-	 */
652
-	public static function checkDependencies() {
653
-		return true;
654
-	}
51
+    /**
52
+     * @var \OpenCloud\ObjectStore\Service
53
+     */
54
+    private $connection;
55
+    /**
56
+     * @var \OpenCloud\ObjectStore\Resource\Container
57
+     */
58
+    private $container;
59
+    /**
60
+     * @var \OpenCloud\OpenStack
61
+     */
62
+    private $anchor;
63
+    /**
64
+     * @var string
65
+     */
66
+    private $bucket;
67
+    /**
68
+     * Connection parameters
69
+     *
70
+     * @var array
71
+     */
72
+    private $params;
73
+
74
+    /** @var string  */
75
+    private $id;
76
+
77
+    /**
78
+     * @var array
79
+     */
80
+    private static $tmpFiles = array();
81
+
82
+    /**
83
+     * Key value cache mapping path to data object. Maps path to
84
+     * \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject for existing
85
+     * paths and path to false for not existing paths.
86
+     * @var \OCP\ICache
87
+     */
88
+    private $objectCache;
89
+
90
+    /**
91
+     * @param string $path
92
+     */
93
+    private function normalizePath($path) {
94
+        $path = trim($path, '/');
95
+
96
+        if (!$path) {
97
+            $path = '.';
98
+        }
99
+
100
+        $path = str_replace('#', '%23', $path);
101
+
102
+        return $path;
103
+    }
104
+
105
+    const SUBCONTAINER_FILE = '.subcontainers';
106
+
107
+    /**
108
+     * translate directory path to container name
109
+     *
110
+     * @param string $path
111
+     * @return string
112
+     */
113
+
114
+    /**
115
+     * Fetches an object from the API.
116
+     * If the object is cached already or a
117
+     * failed "doesn't exist" response was cached,
118
+     * that one will be returned.
119
+     *
120
+     * @param string $path
121
+     * @return \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject|bool object
122
+     * or false if the object did not exist
123
+     */
124
+    private function fetchObject($path) {
125
+        if ($this->objectCache->hasKey($path)) {
126
+            // might be "false" if object did not exist from last check
127
+            return $this->objectCache->get($path);
128
+        }
129
+        try {
130
+            $object = $this->getContainer()->getPartialObject($path);
131
+            $this->objectCache->set($path, $object);
132
+            return $object;
133
+        } catch (ClientErrorResponseException $e) {
134
+            // this exception happens when the object does not exist, which
135
+            // is expected in most cases
136
+            $this->objectCache->set($path, false);
137
+            return false;
138
+        } catch (ClientErrorResponseException $e) {
139
+            // Expected response is "404 Not Found", so only log if it isn't
140
+            if ($e->getResponse()->getStatusCode() !== 404) {
141
+                \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
142
+            }
143
+            return false;
144
+        }
145
+    }
146
+
147
+    /**
148
+     * Returns whether the given path exists.
149
+     *
150
+     * @param string $path
151
+     *
152
+     * @return bool true if the object exist, false otherwise
153
+     */
154
+    private function doesObjectExist($path) {
155
+        return $this->fetchObject($path) !== false;
156
+    }
157
+
158
+    public function __construct($params) {
159
+        if ((empty($params['key']) and empty($params['password']))
160
+            or empty($params['user']) or empty($params['bucket'])
161
+            or empty($params['region'])
162
+        ) {
163
+            throw new \Exception("API Key or password, Username, Bucket and Region have to be configured.");
164
+        }
165
+
166
+        $this->id = 'swift::' . $params['user'] . md5($params['bucket']);
167
+
168
+        $bucketUrl = Url::factory($params['bucket']);
169
+        if ($bucketUrl->isAbsolute()) {
170
+            $this->bucket = end(($bucketUrl->getPathSegments()));
171
+            $params['endpoint_url'] = $bucketUrl->addPath('..')->normalizePath();
172
+        } else {
173
+            $this->bucket = $params['bucket'];
174
+        }
175
+
176
+        if (empty($params['url'])) {
177
+            $params['url'] = 'https://identity.api.rackspacecloud.com/v2.0/';
178
+        }
179
+
180
+        if (empty($params['service_name'])) {
181
+            $params['service_name'] = 'cloudFiles';
182
+        }
183
+
184
+        $this->params = $params;
185
+        // FIXME: private class...
186
+        $this->objectCache = new \OC\Cache\CappedMemoryCache();
187
+    }
188
+
189
+    public function mkdir($path) {
190
+        $path = $this->normalizePath($path);
191
+
192
+        if ($this->is_dir($path)) {
193
+            return false;
194
+        }
195
+
196
+        if ($path !== '.') {
197
+            $path .= '/';
198
+        }
199
+
200
+        try {
201
+            $customHeaders = array('content-type' => 'httpd/unix-directory');
202
+            $metadataHeaders = DataObject::stockHeaders(array());
203
+            $allHeaders = $customHeaders + $metadataHeaders;
204
+            $this->getContainer()->uploadObject($path, '', $allHeaders);
205
+            // invalidate so that the next access gets the real object
206
+            // with all properties
207
+            $this->objectCache->remove($path);
208
+        } catch (Exceptions\CreateUpdateError $e) {
209
+            \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
210
+            return false;
211
+        }
212
+
213
+        return true;
214
+    }
215
+
216
+    public function file_exists($path) {
217
+        $path = $this->normalizePath($path);
218
+
219
+        if ($path !== '.' && $this->is_dir($path)) {
220
+            $path .= '/';
221
+        }
222
+
223
+        return $this->doesObjectExist($path);
224
+    }
225
+
226
+    public function rmdir($path) {
227
+        $path = $this->normalizePath($path);
228
+
229
+        if (!$this->is_dir($path) || !$this->isDeletable($path)) {
230
+            return false;
231
+        }
232
+
233
+        $dh = $this->opendir($path);
234
+        while ($file = readdir($dh)) {
235
+            if (\OC\Files\Filesystem::isIgnoredDir($file)) {
236
+                continue;
237
+            }
238
+
239
+            if ($this->is_dir($path . '/' . $file)) {
240
+                $this->rmdir($path . '/' . $file);
241
+            } else {
242
+                $this->unlink($path . '/' . $file);
243
+            }
244
+        }
245
+
246
+        try {
247
+            $this->getContainer()->dataObject()->setName($path . '/')->delete();
248
+            $this->objectCache->remove($path . '/');
249
+        } catch (Exceptions\DeleteError $e) {
250
+            \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
251
+            return false;
252
+        }
253
+
254
+        return true;
255
+    }
256
+
257
+    public function opendir($path) {
258
+        $path = $this->normalizePath($path);
259
+
260
+        if ($path === '.') {
261
+            $path = '';
262
+        } else {
263
+            $path .= '/';
264
+        }
265
+
266
+        $path = str_replace('%23', '#', $path); // the prefix is sent as a query param, so revert the encoding of #
267
+
268
+        try {
269
+            $files = array();
270
+            /** @var OpenCloud\Common\Collection $objects */
271
+            $objects = $this->getContainer()->objectList(array(
272
+                'prefix' => $path,
273
+                'delimiter' => '/'
274
+            ));
275
+
276
+            /** @var OpenCloud\ObjectStore\Resource\DataObject $object */
277
+            foreach ($objects as $object) {
278
+                $file = basename($object->getName());
279
+                if ($file !== basename($path)) {
280
+                    $files[] = $file;
281
+                }
282
+            }
283
+
284
+            return IteratorDirectory::wrap($files);
285
+        } catch (\Exception $e) {
286
+            \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
287
+            return false;
288
+        }
289
+
290
+    }
291
+
292
+    public function stat($path) {
293
+        $path = $this->normalizePath($path);
294
+
295
+        if ($path === '.') {
296
+            $path = '';
297
+        } else if ($this->is_dir($path)) {
298
+            $path .= '/';
299
+        }
300
+
301
+        try {
302
+            /** @var DataObject $object */
303
+            $object = $this->fetchObject($path);
304
+            if (!$object) {
305
+                return false;
306
+            }
307
+        } catch (ClientErrorResponseException $e) {
308
+            \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
309
+            return false;
310
+        }
311
+
312
+        $dateTime = \DateTime::createFromFormat(\DateTime::RFC1123, $object->getLastModified());
313
+        if ($dateTime !== false) {
314
+            $mtime = $dateTime->getTimestamp();
315
+        } else {
316
+            $mtime = null;
317
+        }
318
+        $objectMetadata = $object->getMetadata();
319
+        $metaTimestamp = $objectMetadata->getProperty('timestamp');
320
+        if (isset($metaTimestamp)) {
321
+            $mtime = $metaTimestamp;
322
+        }
323
+
324
+        if (!empty($mtime)) {
325
+            $mtime = floor($mtime);
326
+        }
327
+
328
+        $stat = array();
329
+        $stat['size'] = (int)$object->getContentLength();
330
+        $stat['mtime'] = $mtime;
331
+        $stat['atime'] = time();
332
+        return $stat;
333
+    }
334
+
335
+    public function filetype($path) {
336
+        $path = $this->normalizePath($path);
337
+
338
+        if ($path !== '.' && $this->doesObjectExist($path)) {
339
+            return 'file';
340
+        }
341
+
342
+        if ($path !== '.') {
343
+            $path .= '/';
344
+        }
345
+
346
+        if ($this->doesObjectExist($path)) {
347
+            return 'dir';
348
+        }
349
+    }
350
+
351
+    public function unlink($path) {
352
+        $path = $this->normalizePath($path);
353
+
354
+        if ($this->is_dir($path)) {
355
+            return $this->rmdir($path);
356
+        }
357
+
358
+        try {
359
+            $this->getContainer()->dataObject()->setName($path)->delete();
360
+            $this->objectCache->remove($path);
361
+            $this->objectCache->remove($path . '/');
362
+        } catch (ClientErrorResponseException $e) {
363
+            if ($e->getResponse()->getStatusCode() !== 404) {
364
+                \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
365
+            }
366
+            return false;
367
+        }
368
+
369
+        return true;
370
+    }
371
+
372
+    public function fopen($path, $mode) {
373
+        $path = $this->normalizePath($path);
374
+
375
+        switch ($mode) {
376
+            case 'r':
377
+            case 'rb':
378
+                try {
379
+                    $c = $this->getContainer();
380
+                    $streamFactory = new \Guzzle\Stream\PhpStreamRequestFactory();
381
+                    $streamInterface = $streamFactory->fromRequest(
382
+                        $c->getClient()
383
+                            ->get($c->getUrl($path)));
384
+                    $streamInterface->rewind();
385
+                    $stream = $streamInterface->getStream();
386
+                    stream_context_set_option($stream, 'swift','content', $streamInterface);
387
+                    if(!strrpos($streamInterface
388
+                        ->getMetaData('wrapper_data')[0], '404 Not Found')) {
389
+                        return $stream;
390
+                    }
391
+                    return false;
392
+                } catch (\Guzzle\Http\Exception\BadResponseException $e) {
393
+                    \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
394
+                    return false;
395
+                }
396
+            case 'w':
397
+            case 'wb':
398
+            case 'a':
399
+            case 'ab':
400
+            case 'r+':
401
+            case 'w+':
402
+            case 'wb+':
403
+            case 'a+':
404
+            case 'x':
405
+            case 'x+':
406
+            case 'c':
407
+            case 'c+':
408
+                if (strrpos($path, '.') !== false) {
409
+                    $ext = substr($path, strrpos($path, '.'));
410
+                } else {
411
+                    $ext = '';
412
+                }
413
+                $tmpFile = \OCP\Files::tmpFile($ext);
414
+                // Fetch existing file if required
415
+                if ($mode[0] !== 'w' && $this->file_exists($path)) {
416
+                    if ($mode[0] === 'x') {
417
+                        // File cannot already exist
418
+                        return false;
419
+                    }
420
+                    $source = $this->fopen($path, 'r');
421
+                    file_put_contents($tmpFile, $source);
422
+                    // Seek to end if required
423
+                    if ($mode[0] === 'a') {
424
+                        fseek($tmpFile, 0, SEEK_END);
425
+                    }
426
+                }
427
+                $handle = fopen($tmpFile, $mode);
428
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
429
+                    $this->writeBack($tmpFile, $path);
430
+                });
431
+        }
432
+    }
433
+
434
+    public function touch($path, $mtime = null) {
435
+        $path = $this->normalizePath($path);
436
+        if (is_null($mtime)) {
437
+            $mtime = time();
438
+        }
439
+        $metadata = array('timestamp' => $mtime);
440
+        if ($this->file_exists($path)) {
441
+            if ($this->is_dir($path) && $path != '.') {
442
+                $path .= '/';
443
+            }
444
+
445
+            $object = $this->fetchObject($path);
446
+            if ($object->saveMetadata($metadata)) {
447
+                // invalidate target object to force repopulation on fetch
448
+                $this->objectCache->remove($path);
449
+            }
450
+            return true;
451
+        } else {
452
+            $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
453
+            $customHeaders = array('content-type' => $mimeType);
454
+            $metadataHeaders = DataObject::stockHeaders($metadata);
455
+            $allHeaders = $customHeaders + $metadataHeaders;
456
+            $this->getContainer()->uploadObject($path, '', $allHeaders);
457
+            // invalidate target object to force repopulation on fetch
458
+            $this->objectCache->remove($path);
459
+            return true;
460
+        }
461
+    }
462
+
463
+    public function copy($path1, $path2) {
464
+        $path1 = $this->normalizePath($path1);
465
+        $path2 = $this->normalizePath($path2);
466
+
467
+        $fileType = $this->filetype($path1);
468
+        if ($fileType === 'file') {
469
+
470
+            // make way
471
+            $this->unlink($path2);
472
+
473
+            try {
474
+                $source = $this->fetchObject($path1);
475
+                $source->copy($this->bucket . '/' . $path2);
476
+                // invalidate target object to force repopulation on fetch
477
+                $this->objectCache->remove($path2);
478
+                $this->objectCache->remove($path2 . '/');
479
+            } catch (ClientErrorResponseException $e) {
480
+                \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
481
+                return false;
482
+            }
483
+
484
+        } else if ($fileType === 'dir') {
485
+
486
+            // make way
487
+            $this->unlink($path2);
488
+
489
+            try {
490
+                $source = $this->fetchObject($path1 . '/');
491
+                $source->copy($this->bucket . '/' . $path2 . '/');
492
+                // invalidate target object to force repopulation on fetch
493
+                $this->objectCache->remove($path2);
494
+                $this->objectCache->remove($path2 . '/');
495
+            } catch (ClientErrorResponseException $e) {
496
+                \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
497
+                return false;
498
+            }
499
+
500
+            $dh = $this->opendir($path1);
501
+            while ($file = readdir($dh)) {
502
+                if (\OC\Files\Filesystem::isIgnoredDir($file)) {
503
+                    continue;
504
+                }
505
+
506
+                $source = $path1 . '/' . $file;
507
+                $target = $path2 . '/' . $file;
508
+                $this->copy($source, $target);
509
+            }
510
+
511
+        } else {
512
+            //file does not exist
513
+            return false;
514
+        }
515
+
516
+        return true;
517
+    }
518
+
519
+    public function rename($path1, $path2) {
520
+        $path1 = $this->normalizePath($path1);
521
+        $path2 = $this->normalizePath($path2);
522
+
523
+        $fileType = $this->filetype($path1);
524
+
525
+        if ($fileType === 'dir' || $fileType === 'file') {
526
+            // copy
527
+            if ($this->copy($path1, $path2) === false) {
528
+                return false;
529
+            }
530
+
531
+            // cleanup
532
+            if ($this->unlink($path1) === false) {
533
+                $this->unlink($path2);
534
+                return false;
535
+            }
536
+
537
+            return true;
538
+        }
539
+
540
+        return false;
541
+    }
542
+
543
+    public function getId() {
544
+        return $this->id;
545
+    }
546
+
547
+    /**
548
+     * Returns the connection
549
+     *
550
+     * @return OpenCloud\ObjectStore\Service connected client
551
+     * @throws \Exception if connection could not be made
552
+     */
553
+    public function getConnection() {
554
+        if (!is_null($this->connection)) {
555
+            return $this->connection;
556
+        }
557
+
558
+        $settings = array(
559
+            'username' => $this->params['user'],
560
+        );
561
+
562
+        if (!empty($this->params['password'])) {
563
+            $settings['password'] = $this->params['password'];
564
+        } else if (!empty($this->params['key'])) {
565
+            $settings['apiKey'] = $this->params['key'];
566
+        }
567
+
568
+        if (!empty($this->params['tenant'])) {
569
+            $settings['tenantName'] = $this->params['tenant'];
570
+        }
571
+
572
+        if (!empty($this->params['timeout'])) {
573
+            $settings['timeout'] = $this->params['timeout'];
574
+        }
575
+
576
+        if (isset($settings['apiKey'])) {
577
+            $this->anchor = new Rackspace($this->params['url'], $settings);
578
+        } else {
579
+            $this->anchor = new OpenStack($this->params['url'], $settings);
580
+        }
581
+
582
+        $connection = $this->anchor->objectStoreService($this->params['service_name'], $this->params['region']);
583
+
584
+        if (!empty($this->params['endpoint_url'])) {
585
+            $endpoint = $connection->getEndpoint();
586
+            $endpoint->setPublicUrl($this->params['endpoint_url']);
587
+            $endpoint->setPrivateUrl($this->params['endpoint_url']);
588
+            $connection->setEndpoint($endpoint);
589
+        }
590
+
591
+        $this->connection = $connection;
592
+
593
+        return $this->connection;
594
+    }
595
+
596
+    /**
597
+     * Returns the initialized object store container.
598
+     *
599
+     * @return OpenCloud\ObjectStore\Resource\Container
600
+     */
601
+    public function getContainer() {
602
+        if (!is_null($this->container)) {
603
+            return $this->container;
604
+        }
605
+
606
+        try {
607
+            $this->container = $this->getConnection()->getContainer($this->bucket);
608
+        } catch (ClientErrorResponseException $e) {
609
+            $this->container = $this->getConnection()->createContainer($this->bucket);
610
+        }
611
+
612
+        if (!$this->file_exists('.')) {
613
+            $this->mkdir('.');
614
+        }
615
+
616
+        return $this->container;
617
+    }
618
+
619
+    public function writeBack($tmpFile, $path) {
620
+        $fileData = fopen($tmpFile, 'r');
621
+        $this->getContainer()->uploadObject($path, $fileData);
622
+        // invalidate target object to force repopulation on fetch
623
+        $this->objectCache->remove(self::$tmpFiles[$tmpFile]);
624
+        unlink($tmpFile);
625
+    }
626
+
627
+    public function hasUpdated($path, $time) {
628
+        if ($this->is_file($path)) {
629
+            return parent::hasUpdated($path, $time);
630
+        }
631
+        $path = $this->normalizePath($path);
632
+        $dh = $this->opendir($path);
633
+        $content = array();
634
+        while (($file = readdir($dh)) !== false) {
635
+            $content[] = $file;
636
+        }
637
+        if ($path === '.') {
638
+            $path = '';
639
+        }
640
+        $cachedContent = $this->getCache()->getFolderContents($path);
641
+        $cachedNames = array_map(function ($content) {
642
+            return $content['name'];
643
+        }, $cachedContent);
644
+        sort($cachedNames);
645
+        sort($content);
646
+        return $cachedNames != $content;
647
+    }
648
+
649
+    /**
650
+     * check if curl is installed
651
+     */
652
+    public static function checkDependencies() {
653
+        return true;
654
+    }
655 655
 
656 656
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 			throw new \Exception("API Key or password, Username, Bucket and Region have to be configured.");
164 164
 		}
165 165
 
166
-		$this->id = 'swift::' . $params['user'] . md5($params['bucket']);
166
+		$this->id = 'swift::'.$params['user'].md5($params['bucket']);
167 167
 
168 168
 		$bucketUrl = Url::factory($params['bucket']);
169 169
 		if ($bucketUrl->isAbsolute()) {
@@ -236,16 +236,16 @@  discard block
 block discarded – undo
236 236
 				continue;
237 237
 			}
238 238
 
239
-			if ($this->is_dir($path . '/' . $file)) {
240
-				$this->rmdir($path . '/' . $file);
239
+			if ($this->is_dir($path.'/'.$file)) {
240
+				$this->rmdir($path.'/'.$file);
241 241
 			} else {
242
-				$this->unlink($path . '/' . $file);
242
+				$this->unlink($path.'/'.$file);
243 243
 			}
244 244
 		}
245 245
 
246 246
 		try {
247
-			$this->getContainer()->dataObject()->setName($path . '/')->delete();
248
-			$this->objectCache->remove($path . '/');
247
+			$this->getContainer()->dataObject()->setName($path.'/')->delete();
248
+			$this->objectCache->remove($path.'/');
249 249
 		} catch (Exceptions\DeleteError $e) {
250 250
 			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
251 251
 			return false;
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
 		}
327 327
 
328 328
 		$stat = array();
329
-		$stat['size'] = (int)$object->getContentLength();
329
+		$stat['size'] = (int) $object->getContentLength();
330 330
 		$stat['mtime'] = $mtime;
331 331
 		$stat['atime'] = time();
332 332
 		return $stat;
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
 		try {
359 359
 			$this->getContainer()->dataObject()->setName($path)->delete();
360 360
 			$this->objectCache->remove($path);
361
-			$this->objectCache->remove($path . '/');
361
+			$this->objectCache->remove($path.'/');
362 362
 		} catch (ClientErrorResponseException $e) {
363 363
 			if ($e->getResponse()->getStatusCode() !== 404) {
364 364
 				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
@@ -383,8 +383,8 @@  discard block
 block discarded – undo
383 383
 							->get($c->getUrl($path)));
384 384
 					$streamInterface->rewind();
385 385
 					$stream = $streamInterface->getStream();
386
-					stream_context_set_option($stream, 'swift','content', $streamInterface);
387
-					if(!strrpos($streamInterface
386
+					stream_context_set_option($stream, 'swift', 'content', $streamInterface);
387
+					if (!strrpos($streamInterface
388 388
 						->getMetaData('wrapper_data')[0], '404 Not Found')) {
389 389
 						return $stream;
390 390
 					}
@@ -425,7 +425,7 @@  discard block
 block discarded – undo
425 425
 					}
426 426
 				}
427 427
 				$handle = fopen($tmpFile, $mode);
428
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
428
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
429 429
 					$this->writeBack($tmpFile, $path);
430 430
 				});
431 431
 		}
@@ -472,10 +472,10 @@  discard block
 block discarded – undo
472 472
 
473 473
 			try {
474 474
 				$source = $this->fetchObject($path1);
475
-				$source->copy($this->bucket . '/' . $path2);
475
+				$source->copy($this->bucket.'/'.$path2);
476 476
 				// invalidate target object to force repopulation on fetch
477 477
 				$this->objectCache->remove($path2);
478
-				$this->objectCache->remove($path2 . '/');
478
+				$this->objectCache->remove($path2.'/');
479 479
 			} catch (ClientErrorResponseException $e) {
480 480
 				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
481 481
 				return false;
@@ -487,11 +487,11 @@  discard block
 block discarded – undo
487 487
 			$this->unlink($path2);
488 488
 
489 489
 			try {
490
-				$source = $this->fetchObject($path1 . '/');
491
-				$source->copy($this->bucket . '/' . $path2 . '/');
490
+				$source = $this->fetchObject($path1.'/');
491
+				$source->copy($this->bucket.'/'.$path2.'/');
492 492
 				// invalidate target object to force repopulation on fetch
493 493
 				$this->objectCache->remove($path2);
494
-				$this->objectCache->remove($path2 . '/');
494
+				$this->objectCache->remove($path2.'/');
495 495
 			} catch (ClientErrorResponseException $e) {
496 496
 				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
497 497
 				return false;
@@ -503,8 +503,8 @@  discard block
 block discarded – undo
503 503
 					continue;
504 504
 				}
505 505
 
506
-				$source = $path1 . '/' . $file;
507
-				$target = $path2 . '/' . $file;
506
+				$source = $path1.'/'.$file;
507
+				$target = $path2.'/'.$file;
508 508
 				$this->copy($source, $target);
509 509
 			}
510 510
 
@@ -638,7 +638,7 @@  discard block
 block discarded – undo
638 638
 			$path = '';
639 639
 		}
640 640
 		$cachedContent = $this->getCache()->getFolderContents($path);
641
-		$cachedNames = array_map(function ($content) {
641
+		$cachedNames = array_map(function($content) {
642 642
 			return $content['name'];
643 643
 		}, $cachedContent);
644 644
 		sort($cachedNames);
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareController.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -597,7 +597,7 @@
 block discarded – undo
597 597
 	 * publish activity
598 598
 	 *
599 599
 	 * @param string $subject
600
-	 * @param array $parameters
600
+	 * @param string[] $parameters
601 601
 	 * @param string $affectedUser
602 602
 	 * @param int $fileId
603 603
 	 * @param string $filePath
Please login to merge, or discard this patch.
Indentation   +550 added lines, -550 removed lines patch added patch discarded remove patch
@@ -64,558 +64,558 @@
 block discarded – undo
64 64
  */
65 65
 class ShareController extends Controller {
66 66
 
67
-	/** @var IConfig */
68
-	protected $config;
69
-	/** @var IURLGenerator */
70
-	protected $urlGenerator;
71
-	/** @var IUserManager */
72
-	protected $userManager;
73
-	/** @var ILogger */
74
-	protected $logger;
75
-	/** @var \OCP\Activity\IManager */
76
-	protected $activityManager;
77
-	/** @var \OCP\Share\IManager */
78
-	protected $shareManager;
79
-	/** @var ISession */
80
-	protected $session;
81
-	/** @var IPreview */
82
-	protected $previewManager;
83
-	/** @var IRootFolder */
84
-	protected $rootFolder;
85
-	/** @var FederatedShareProvider */
86
-	protected $federatedShareProvider;
87
-	/** @var EventDispatcherInterface */
88
-	protected $eventDispatcher;
89
-	/** @var IL10N */
90
-	protected $l10n;
91
-	/** @var Defaults */
92
-	protected $defaults;
93
-
94
-	/**
95
-	 * @param string $appName
96
-	 * @param IRequest $request
97
-	 * @param IConfig $config
98
-	 * @param IURLGenerator $urlGenerator
99
-	 * @param IUserManager $userManager
100
-	 * @param ILogger $logger
101
-	 * @param \OCP\Activity\IManager $activityManager
102
-	 * @param \OCP\Share\IManager $shareManager
103
-	 * @param ISession $session
104
-	 * @param IPreview $previewManager
105
-	 * @param IRootFolder $rootFolder
106
-	 * @param FederatedShareProvider $federatedShareProvider
107
-	 * @param EventDispatcherInterface $eventDispatcher
108
-	 * @param IL10N $l10n
109
-	 * @param \OC_Defaults $defaults
110
-	 */
111
-	public function __construct($appName,
112
-								IRequest $request,
113
-								IConfig $config,
114
-								IURLGenerator $urlGenerator,
115
-								IUserManager $userManager,
116
-								ILogger $logger,
117
-								\OCP\Activity\IManager $activityManager,
118
-								\OCP\Share\IManager $shareManager,
119
-								ISession $session,
120
-								IPreview $previewManager,
121
-								IRootFolder $rootFolder,
122
-								FederatedShareProvider $federatedShareProvider,
123
-								EventDispatcherInterface $eventDispatcher,
124
-								IL10N $l10n,
125
-								\OC_Defaults $defaults) {
126
-		parent::__construct($appName, $request);
127
-
128
-		$this->config = $config;
129
-		$this->urlGenerator = $urlGenerator;
130
-		$this->userManager = $userManager;
131
-		$this->logger = $logger;
132
-		$this->activityManager = $activityManager;
133
-		$this->shareManager = $shareManager;
134
-		$this->session = $session;
135
-		$this->previewManager = $previewManager;
136
-		$this->rootFolder = $rootFolder;
137
-		$this->federatedShareProvider = $federatedShareProvider;
138
-		$this->eventDispatcher = $eventDispatcher;
139
-		$this->l10n = $l10n;
140
-		$this->defaults = $defaults;
141
-	}
142
-
143
-	/**
144
-	 * @PublicPage
145
-	 * @NoCSRFRequired
146
-	 *
147
-	 * @param string $token
148
-	 * @return TemplateResponse|RedirectResponse
149
-	 */
150
-	public function showAuthenticate($token) {
151
-		$share = $this->shareManager->getShareByToken($token);
152
-
153
-		if($this->linkShareAuth($share)) {
154
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
155
-		}
156
-
157
-		return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
158
-	}
159
-
160
-	/**
161
-	 * @PublicPage
162
-	 * @UseSession
163
-	 * @BruteForceProtection publicLinkAuth
164
-	 *
165
-	 * Authenticates against password-protected shares
166
-	 * @param string $token
167
-	 * @param string $password
168
-	 * @return RedirectResponse|TemplateResponse|NotFoundResponse
169
-	 */
170
-	public function authenticate($token, $password = '') {
171
-
172
-		// Check whether share exists
173
-		try {
174
-			$share = $this->shareManager->getShareByToken($token);
175
-		} catch (ShareNotFound $e) {
176
-			return new NotFoundResponse();
177
-		}
178
-
179
-		$authenticate = $this->linkShareAuth($share, $password);
180
-
181
-		if($authenticate === true) {
182
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
183
-		}
184
-
185
-		return new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
186
-	}
187
-
188
-	/**
189
-	 * Authenticate a link item with the given password.
190
-	 * Or use the session if no password is provided.
191
-	 *
192
-	 * This is a modified version of Helper::authenticate
193
-	 * TODO: Try to merge back eventually with Helper::authenticate
194
-	 *
195
-	 * @param \OCP\Share\IShare $share
196
-	 * @param string|null $password
197
-	 * @return bool
198
-	 */
199
-	private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
200
-		if ($password !== null) {
201
-			if ($this->shareManager->checkPassword($share, $password)) {
202
-				$this->session->set('public_link_authenticated', (string)$share->getId());
203
-			} else {
204
-				$this->emitAccessShareHook($share, 403, 'Wrong password');
205
-				return false;
206
-			}
207
-		} else {
208
-			// not authenticated ?
209
-			if ( ! $this->session->exists('public_link_authenticated')
210
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
211
-				return false;
212
-			}
213
-		}
214
-		return true;
215
-	}
216
-
217
-	/**
218
-	 * throws hooks when a share is attempted to be accessed
219
-	 *
220
-	 * @param \OCP\Share\IShare|string $share the Share instance if available,
221
-	 * otherwise token
222
-	 * @param int $errorCode
223
-	 * @param string $errorMessage
224
-	 * @throws \OC\HintException
225
-	 * @throws \OC\ServerNotAvailableException
226
-	 */
227
-	protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
228
-		$itemType = $itemSource = $uidOwner = '';
229
-		$token = $share;
230
-		$exception = null;
231
-		if($share instanceof \OCP\Share\IShare) {
232
-			try {
233
-				$token = $share->getToken();
234
-				$uidOwner = $share->getSharedBy();
235
-				$itemType = $share->getNodeType();
236
-				$itemSource = $share->getNodeId();
237
-			} catch (\Exception $e) {
238
-				// we log what we know and pass on the exception afterwards
239
-				$exception = $e;
240
-			}
241
-		}
242
-		\OC_Hook::emit('OCP\Share', 'share_link_access', [
243
-			'itemType' => $itemType,
244
-			'itemSource' => $itemSource,
245
-			'uidOwner' => $uidOwner,
246
-			'token' => $token,
247
-			'errorCode' => $errorCode,
248
-			'errorMessage' => $errorMessage,
249
-		]);
250
-		if(!is_null($exception)) {
251
-			throw $exception;
252
-		}
253
-	}
254
-
255
-	/**
256
-	 * Validate the permissions of the share
257
-	 *
258
-	 * @param Share\IShare $share
259
-	 * @return bool
260
-	 */
261
-	private function validateShare(\OCP\Share\IShare $share) {
262
-		return $share->getNode()->isReadable() && $share->getNode()->isShareable();
263
-	}
264
-
265
-	/**
266
-	 * @PublicPage
267
-	 * @NoCSRFRequired
268
-	 *
269
-	 * @param string $token
270
-	 * @param string $path
271
-	 * @return TemplateResponse|RedirectResponse|NotFoundResponse
272
-	 * @throws NotFoundException
273
-	 * @throws \Exception
274
-	 */
275
-	public function showShare($token, $path = '') {
276
-		\OC_User::setIncognitoMode(true);
277
-
278
-		// Check whether share exists
279
-		try {
280
-			$share = $this->shareManager->getShareByToken($token);
281
-		} catch (ShareNotFound $e) {
282
-			$this->emitAccessShareHook($token, 404, 'Share not found');
283
-			return new NotFoundResponse();
284
-		}
285
-
286
-		// Share is password protected - check whether the user is permitted to access the share
287
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
288
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
289
-				array('token' => $token)));
290
-		}
291
-
292
-		if (!$this->validateShare($share)) {
293
-			throw new NotFoundException();
294
-		}
295
-		// We can't get the path of a file share
296
-		try {
297
-			if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
298
-				$this->emitAccessShareHook($share, 404, 'Share not found');
299
-				throw new NotFoundException();
300
-			}
301
-		} catch (\Exception $e) {
302
-			$this->emitAccessShareHook($share, 404, 'Share not found');
303
-			throw $e;
304
-		}
305
-
306
-		$shareTmpl = [];
307
-		$shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
308
-		$shareTmpl['owner'] = $share->getShareOwner();
309
-		$shareTmpl['filename'] = $share->getNode()->getName();
310
-		$shareTmpl['directory_path'] = $share->getTarget();
311
-		$shareTmpl['mimetype'] = $share->getNode()->getMimetype();
312
-		$shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
313
-		$shareTmpl['dirToken'] = $token;
314
-		$shareTmpl['sharingToken'] = $token;
315
-		$shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
316
-		$shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
317
-		$shareTmpl['dir'] = '';
318
-		$shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
319
-		$shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
320
-
321
-		// Show file list
322
-		$hideFileList = false;
323
-		if ($share->getNode() instanceof \OCP\Files\Folder) {
324
-			/** @var \OCP\Files\Folder $rootFolder */
325
-			$rootFolder = $share->getNode();
326
-
327
-			try {
328
-				$folderNode = $rootFolder->get($path);
329
-			} catch (\OCP\Files\NotFoundException $e) {
330
-				$this->emitAccessShareHook($share, 404, 'Share not found');
331
-				throw new NotFoundException();
332
-			}
333
-
334
-			$shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
335
-
336
-			/*
67
+    /** @var IConfig */
68
+    protected $config;
69
+    /** @var IURLGenerator */
70
+    protected $urlGenerator;
71
+    /** @var IUserManager */
72
+    protected $userManager;
73
+    /** @var ILogger */
74
+    protected $logger;
75
+    /** @var \OCP\Activity\IManager */
76
+    protected $activityManager;
77
+    /** @var \OCP\Share\IManager */
78
+    protected $shareManager;
79
+    /** @var ISession */
80
+    protected $session;
81
+    /** @var IPreview */
82
+    protected $previewManager;
83
+    /** @var IRootFolder */
84
+    protected $rootFolder;
85
+    /** @var FederatedShareProvider */
86
+    protected $federatedShareProvider;
87
+    /** @var EventDispatcherInterface */
88
+    protected $eventDispatcher;
89
+    /** @var IL10N */
90
+    protected $l10n;
91
+    /** @var Defaults */
92
+    protected $defaults;
93
+
94
+    /**
95
+     * @param string $appName
96
+     * @param IRequest $request
97
+     * @param IConfig $config
98
+     * @param IURLGenerator $urlGenerator
99
+     * @param IUserManager $userManager
100
+     * @param ILogger $logger
101
+     * @param \OCP\Activity\IManager $activityManager
102
+     * @param \OCP\Share\IManager $shareManager
103
+     * @param ISession $session
104
+     * @param IPreview $previewManager
105
+     * @param IRootFolder $rootFolder
106
+     * @param FederatedShareProvider $federatedShareProvider
107
+     * @param EventDispatcherInterface $eventDispatcher
108
+     * @param IL10N $l10n
109
+     * @param \OC_Defaults $defaults
110
+     */
111
+    public function __construct($appName,
112
+                                IRequest $request,
113
+                                IConfig $config,
114
+                                IURLGenerator $urlGenerator,
115
+                                IUserManager $userManager,
116
+                                ILogger $logger,
117
+                                \OCP\Activity\IManager $activityManager,
118
+                                \OCP\Share\IManager $shareManager,
119
+                                ISession $session,
120
+                                IPreview $previewManager,
121
+                                IRootFolder $rootFolder,
122
+                                FederatedShareProvider $federatedShareProvider,
123
+                                EventDispatcherInterface $eventDispatcher,
124
+                                IL10N $l10n,
125
+                                \OC_Defaults $defaults) {
126
+        parent::__construct($appName, $request);
127
+
128
+        $this->config = $config;
129
+        $this->urlGenerator = $urlGenerator;
130
+        $this->userManager = $userManager;
131
+        $this->logger = $logger;
132
+        $this->activityManager = $activityManager;
133
+        $this->shareManager = $shareManager;
134
+        $this->session = $session;
135
+        $this->previewManager = $previewManager;
136
+        $this->rootFolder = $rootFolder;
137
+        $this->federatedShareProvider = $federatedShareProvider;
138
+        $this->eventDispatcher = $eventDispatcher;
139
+        $this->l10n = $l10n;
140
+        $this->defaults = $defaults;
141
+    }
142
+
143
+    /**
144
+     * @PublicPage
145
+     * @NoCSRFRequired
146
+     *
147
+     * @param string $token
148
+     * @return TemplateResponse|RedirectResponse
149
+     */
150
+    public function showAuthenticate($token) {
151
+        $share = $this->shareManager->getShareByToken($token);
152
+
153
+        if($this->linkShareAuth($share)) {
154
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
155
+        }
156
+
157
+        return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
158
+    }
159
+
160
+    /**
161
+     * @PublicPage
162
+     * @UseSession
163
+     * @BruteForceProtection publicLinkAuth
164
+     *
165
+     * Authenticates against password-protected shares
166
+     * @param string $token
167
+     * @param string $password
168
+     * @return RedirectResponse|TemplateResponse|NotFoundResponse
169
+     */
170
+    public function authenticate($token, $password = '') {
171
+
172
+        // Check whether share exists
173
+        try {
174
+            $share = $this->shareManager->getShareByToken($token);
175
+        } catch (ShareNotFound $e) {
176
+            return new NotFoundResponse();
177
+        }
178
+
179
+        $authenticate = $this->linkShareAuth($share, $password);
180
+
181
+        if($authenticate === true) {
182
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
183
+        }
184
+
185
+        return new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
186
+    }
187
+
188
+    /**
189
+     * Authenticate a link item with the given password.
190
+     * Or use the session if no password is provided.
191
+     *
192
+     * This is a modified version of Helper::authenticate
193
+     * TODO: Try to merge back eventually with Helper::authenticate
194
+     *
195
+     * @param \OCP\Share\IShare $share
196
+     * @param string|null $password
197
+     * @return bool
198
+     */
199
+    private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
200
+        if ($password !== null) {
201
+            if ($this->shareManager->checkPassword($share, $password)) {
202
+                $this->session->set('public_link_authenticated', (string)$share->getId());
203
+            } else {
204
+                $this->emitAccessShareHook($share, 403, 'Wrong password');
205
+                return false;
206
+            }
207
+        } else {
208
+            // not authenticated ?
209
+            if ( ! $this->session->exists('public_link_authenticated')
210
+                || $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
211
+                return false;
212
+            }
213
+        }
214
+        return true;
215
+    }
216
+
217
+    /**
218
+     * throws hooks when a share is attempted to be accessed
219
+     *
220
+     * @param \OCP\Share\IShare|string $share the Share instance if available,
221
+     * otherwise token
222
+     * @param int $errorCode
223
+     * @param string $errorMessage
224
+     * @throws \OC\HintException
225
+     * @throws \OC\ServerNotAvailableException
226
+     */
227
+    protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
228
+        $itemType = $itemSource = $uidOwner = '';
229
+        $token = $share;
230
+        $exception = null;
231
+        if($share instanceof \OCP\Share\IShare) {
232
+            try {
233
+                $token = $share->getToken();
234
+                $uidOwner = $share->getSharedBy();
235
+                $itemType = $share->getNodeType();
236
+                $itemSource = $share->getNodeId();
237
+            } catch (\Exception $e) {
238
+                // we log what we know and pass on the exception afterwards
239
+                $exception = $e;
240
+            }
241
+        }
242
+        \OC_Hook::emit('OCP\Share', 'share_link_access', [
243
+            'itemType' => $itemType,
244
+            'itemSource' => $itemSource,
245
+            'uidOwner' => $uidOwner,
246
+            'token' => $token,
247
+            'errorCode' => $errorCode,
248
+            'errorMessage' => $errorMessage,
249
+        ]);
250
+        if(!is_null($exception)) {
251
+            throw $exception;
252
+        }
253
+    }
254
+
255
+    /**
256
+     * Validate the permissions of the share
257
+     *
258
+     * @param Share\IShare $share
259
+     * @return bool
260
+     */
261
+    private function validateShare(\OCP\Share\IShare $share) {
262
+        return $share->getNode()->isReadable() && $share->getNode()->isShareable();
263
+    }
264
+
265
+    /**
266
+     * @PublicPage
267
+     * @NoCSRFRequired
268
+     *
269
+     * @param string $token
270
+     * @param string $path
271
+     * @return TemplateResponse|RedirectResponse|NotFoundResponse
272
+     * @throws NotFoundException
273
+     * @throws \Exception
274
+     */
275
+    public function showShare($token, $path = '') {
276
+        \OC_User::setIncognitoMode(true);
277
+
278
+        // Check whether share exists
279
+        try {
280
+            $share = $this->shareManager->getShareByToken($token);
281
+        } catch (ShareNotFound $e) {
282
+            $this->emitAccessShareHook($token, 404, 'Share not found');
283
+            return new NotFoundResponse();
284
+        }
285
+
286
+        // Share is password protected - check whether the user is permitted to access the share
287
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
288
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
289
+                array('token' => $token)));
290
+        }
291
+
292
+        if (!$this->validateShare($share)) {
293
+            throw new NotFoundException();
294
+        }
295
+        // We can't get the path of a file share
296
+        try {
297
+            if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
298
+                $this->emitAccessShareHook($share, 404, 'Share not found');
299
+                throw new NotFoundException();
300
+            }
301
+        } catch (\Exception $e) {
302
+            $this->emitAccessShareHook($share, 404, 'Share not found');
303
+            throw $e;
304
+        }
305
+
306
+        $shareTmpl = [];
307
+        $shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
308
+        $shareTmpl['owner'] = $share->getShareOwner();
309
+        $shareTmpl['filename'] = $share->getNode()->getName();
310
+        $shareTmpl['directory_path'] = $share->getTarget();
311
+        $shareTmpl['mimetype'] = $share->getNode()->getMimetype();
312
+        $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
313
+        $shareTmpl['dirToken'] = $token;
314
+        $shareTmpl['sharingToken'] = $token;
315
+        $shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
316
+        $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
317
+        $shareTmpl['dir'] = '';
318
+        $shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
319
+        $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
320
+
321
+        // Show file list
322
+        $hideFileList = false;
323
+        if ($share->getNode() instanceof \OCP\Files\Folder) {
324
+            /** @var \OCP\Files\Folder $rootFolder */
325
+            $rootFolder = $share->getNode();
326
+
327
+            try {
328
+                $folderNode = $rootFolder->get($path);
329
+            } catch (\OCP\Files\NotFoundException $e) {
330
+                $this->emitAccessShareHook($share, 404, 'Share not found');
331
+                throw new NotFoundException();
332
+            }
333
+
334
+            $shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
335
+
336
+            /*
337 337
 			 * The OC_Util methods require a view. This just uses the node API
338 338
 			 */
339
-			$freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
340
-			if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
341
-				$freeSpace = max($freeSpace, 0);
342
-			} else {
343
-				$freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
344
-			}
345
-
346
-			$hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true;
347
-			$maxUploadFilesize = $freeSpace;
348
-
349
-			$folder = new Template('files', 'list', '');
350
-			$folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
351
-			$folder->assign('dirToken', $token);
352
-			$folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
353
-			$folder->assign('isPublic', true);
354
-			$folder->assign('hideFileList', $hideFileList);
355
-			$folder->assign('publicUploadEnabled', 'no');
356
-			$folder->assign('uploadMaxFilesize', $maxUploadFilesize);
357
-			$folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
358
-			$folder->assign('freeSpace', $freeSpace);
359
-			$folder->assign('usedSpacePercent', 0);
360
-			$folder->assign('trash', false);
361
-			$shareTmpl['folder'] = $folder->fetchPage();
362
-		}
363
-
364
-		$shareTmpl['hideFileList'] = $hideFileList;
365
-		$shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
366
-		$shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
367
-		$shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
368
-		$shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
369
-		$shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
370
-		$shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
371
-		$shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
372
-		$shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
373
-		if ($shareTmpl['previewSupported']) {
374
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
375
-				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
376
-		} else {
377
-			$shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
378
-		}
379
-
380
-		// Load files we need
381
-		\OCP\Util::addScript('files', 'file-upload');
382
-		\OCP\Util::addStyle('files_sharing', 'public');
383
-		\OCP\Util::addStyle('files_sharing', 'mobile');
384
-		\OCP\Util::addScript('files_sharing', 'public');
385
-		\OCP\Util::addScript('files', 'fileactions');
386
-		\OCP\Util::addScript('files', 'fileactionsmenu');
387
-		\OCP\Util::addScript('files', 'jquery.fileupload');
388
-		\OCP\Util::addScript('files_sharing', 'files_drop');
389
-
390
-		if (isset($shareTmpl['folder'])) {
391
-			// JS required for folders
392
-			\OCP\Util::addStyle('files', 'files');
393
-			\OCP\Util::addStyle('files', 'upload');
394
-			\OCP\Util::addScript('files', 'filesummary');
395
-			\OCP\Util::addScript('files', 'breadcrumb');
396
-			\OCP\Util::addScript('files', 'fileinfomodel');
397
-			\OCP\Util::addScript('files', 'newfilemenu');
398
-			\OCP\Util::addScript('files', 'files');
399
-			\OCP\Util::addScript('files', 'filelist');
400
-			\OCP\Util::addScript('files', 'keyboardshortcuts');
401
-		}
402
-
403
-		// OpenGraph Support: http://ogp.me/
404
-		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName() . ' - ' . $this->defaults->getSlogan()]);
405
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->l10n->t('%s is publicly shared', [$shareTmpl['filename']])]);
406
-		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
407
-		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
408
-		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
409
-		\OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $shareTmpl['previewImage']]);
410
-
411
-		$this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
412
-
413
-		$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
414
-		$csp->addAllowedFrameDomain('\'self\'');
415
-		$response = new TemplateResponse($this->appName, 'public', $shareTmpl, 'base');
416
-		$response->setContentSecurityPolicy($csp);
417
-
418
-		$this->emitAccessShareHook($share);
419
-
420
-		return $response;
421
-	}
422
-
423
-	/**
424
-	 * @PublicPage
425
-	 * @NoCSRFRequired
426
-	 *
427
-	 * @param string $token
428
-	 * @param string $files
429
-	 * @param string $path
430
-	 * @param string $downloadStartSecret
431
-	 * @return void|\OCP\AppFramework\Http\Response
432
-	 * @throws NotFoundException
433
-	 */
434
-	public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
435
-		\OC_User::setIncognitoMode(true);
436
-
437
-		$share = $this->shareManager->getShareByToken($token);
438
-
439
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
440
-			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
441
-		}
442
-
443
-		// Share is password protected - check whether the user is permitted to access the share
444
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
445
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
446
-				['token' => $token]));
447
-		}
448
-
449
-		$files_list = null;
450
-		if (!is_null($files)) { // download selected files
451
-			$files_list = json_decode($files);
452
-			// in case we get only a single file
453
-			if ($files_list === null) {
454
-				$files_list = [$files];
455
-			}
456
-		}
457
-
458
-		$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
459
-		$originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
460
-
461
-		if (!$this->validateShare($share)) {
462
-			throw new NotFoundException();
463
-		}
464
-
465
-		// Single file share
466
-		if ($share->getNode() instanceof \OCP\Files\File) {
467
-			// Single file download
468
-			$this->singleFileDownloaded($share, $share->getNode());
469
-		}
470
-		// Directory share
471
-		else {
472
-			/** @var \OCP\Files\Folder $node */
473
-			$node = $share->getNode();
474
-
475
-			// Try to get the path
476
-			if ($path !== '') {
477
-				try {
478
-					$node = $node->get($path);
479
-				} catch (NotFoundException $e) {
480
-					$this->emitAccessShareHook($share, 404, 'Share not found');
481
-					return new NotFoundResponse();
482
-				}
483
-			}
484
-
485
-			$originalSharePath = $userFolder->getRelativePath($node->getPath());
486
-
487
-			if ($node instanceof \OCP\Files\File) {
488
-				// Single file download
489
-				$this->singleFileDownloaded($share, $share->getNode());
490
-			} else if (!empty($files_list)) {
491
-				$this->fileListDownloaded($share, $files_list, $node);
492
-			} else {
493
-				// The folder is downloaded
494
-				$this->singleFileDownloaded($share, $share->getNode());
495
-			}
496
-		}
497
-
498
-		/* FIXME: We should do this all nicely in OCP */
499
-		OC_Util::tearDownFS();
500
-		OC_Util::setupFS($share->getShareOwner());
501
-
502
-		/**
503
-		 * this sets a cookie to be able to recognize the start of the download
504
-		 * the content must not be longer than 32 characters and must only contain
505
-		 * alphanumeric characters
506
-		 */
507
-		if (!empty($downloadStartSecret)
508
-			&& !isset($downloadStartSecret[32])
509
-			&& preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
510
-
511
-			// FIXME: set on the response once we use an actual app framework response
512
-			setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
513
-		}
514
-
515
-		$this->emitAccessShareHook($share);
516
-
517
-		$server_params = array( 'head' => $this->request->getMethod() == 'HEAD' );
518
-
519
-		/**
520
-		 * Http range requests support
521
-		 */
522
-		if (isset($_SERVER['HTTP_RANGE'])) {
523
-			$server_params['range'] = $this->request->getHeader('Range');
524
-		}
525
-
526
-		// download selected files
527
-		if (!is_null($files) && $files !== '') {
528
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
529
-			// after dispatching the request which results in a "Cannot modify header information" notice.
530
-			OC_Files::get($originalSharePath, $files_list, $server_params);
531
-			exit();
532
-		} else {
533
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
534
-			// after dispatching the request which results in a "Cannot modify header information" notice.
535
-			OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
536
-			exit();
537
-		}
538
-	}
539
-
540
-	/**
541
-	 * create activity for every downloaded file
542
-	 *
543
-	 * @param Share\IShare $share
544
-	 * @param array $files_list
545
-	 * @param \OCP\Files\Folder $node
546
-	 */
547
-	protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
548
-		foreach ($files_list as $file) {
549
-			$subNode = $node->get($file);
550
-			$this->singleFileDownloaded($share, $subNode);
551
-		}
552
-
553
-	}
554
-
555
-	/**
556
-	 * create activity if a single file was downloaded from a link share
557
-	 *
558
-	 * @param Share\IShare $share
559
-	 */
560
-	protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
561
-
562
-		$fileId = $node->getId();
563
-
564
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
565
-		$userNodeList = $userFolder->getById($fileId);
566
-		$userNode = $userNodeList[0];
567
-		$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
568
-		$userPath = $userFolder->getRelativePath($userNode->getPath());
569
-		$ownerPath = $ownerFolder->getRelativePath($node->getPath());
570
-
571
-		$parameters = [$userPath];
572
-
573
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
574
-			if ($node instanceof \OCP\Files\File) {
575
-				$subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
576
-			} else {
577
-				$subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
578
-			}
579
-			$parameters[] = $share->getSharedWith();
580
-		} else {
581
-			if ($node instanceof \OCP\Files\File) {
582
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
583
-			} else {
584
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
585
-			}
586
-		}
587
-
588
-		$this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
589
-
590
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
591
-			$parameters[0] = $ownerPath;
592
-			$this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
593
-		}
594
-	}
595
-
596
-	/**
597
-	 * publish activity
598
-	 *
599
-	 * @param string $subject
600
-	 * @param array $parameters
601
-	 * @param string $affectedUser
602
-	 * @param int $fileId
603
-	 * @param string $filePath
604
-	 */
605
-	protected function publishActivity($subject,
606
-										array $parameters,
607
-										$affectedUser,
608
-										$fileId,
609
-										$filePath) {
610
-
611
-		$event = $this->activityManager->generateEvent();
612
-		$event->setApp('files_sharing')
613
-			->setType('public_links')
614
-			->setSubject($subject, $parameters)
615
-			->setAffectedUser($affectedUser)
616
-			->setObject('files', $fileId, $filePath);
617
-		$this->activityManager->publish($event);
618
-	}
339
+            $freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
340
+            if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
341
+                $freeSpace = max($freeSpace, 0);
342
+            } else {
343
+                $freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
344
+            }
345
+
346
+            $hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true;
347
+            $maxUploadFilesize = $freeSpace;
348
+
349
+            $folder = new Template('files', 'list', '');
350
+            $folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
351
+            $folder->assign('dirToken', $token);
352
+            $folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
353
+            $folder->assign('isPublic', true);
354
+            $folder->assign('hideFileList', $hideFileList);
355
+            $folder->assign('publicUploadEnabled', 'no');
356
+            $folder->assign('uploadMaxFilesize', $maxUploadFilesize);
357
+            $folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
358
+            $folder->assign('freeSpace', $freeSpace);
359
+            $folder->assign('usedSpacePercent', 0);
360
+            $folder->assign('trash', false);
361
+            $shareTmpl['folder'] = $folder->fetchPage();
362
+        }
363
+
364
+        $shareTmpl['hideFileList'] = $hideFileList;
365
+        $shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
366
+        $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
367
+        $shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
368
+        $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
369
+        $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
370
+        $shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
371
+        $shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
372
+        $shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
373
+        if ($shareTmpl['previewSupported']) {
374
+            $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
375
+                ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
376
+        } else {
377
+            $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
378
+        }
379
+
380
+        // Load files we need
381
+        \OCP\Util::addScript('files', 'file-upload');
382
+        \OCP\Util::addStyle('files_sharing', 'public');
383
+        \OCP\Util::addStyle('files_sharing', 'mobile');
384
+        \OCP\Util::addScript('files_sharing', 'public');
385
+        \OCP\Util::addScript('files', 'fileactions');
386
+        \OCP\Util::addScript('files', 'fileactionsmenu');
387
+        \OCP\Util::addScript('files', 'jquery.fileupload');
388
+        \OCP\Util::addScript('files_sharing', 'files_drop');
389
+
390
+        if (isset($shareTmpl['folder'])) {
391
+            // JS required for folders
392
+            \OCP\Util::addStyle('files', 'files');
393
+            \OCP\Util::addStyle('files', 'upload');
394
+            \OCP\Util::addScript('files', 'filesummary');
395
+            \OCP\Util::addScript('files', 'breadcrumb');
396
+            \OCP\Util::addScript('files', 'fileinfomodel');
397
+            \OCP\Util::addScript('files', 'newfilemenu');
398
+            \OCP\Util::addScript('files', 'files');
399
+            \OCP\Util::addScript('files', 'filelist');
400
+            \OCP\Util::addScript('files', 'keyboardshortcuts');
401
+        }
402
+
403
+        // OpenGraph Support: http://ogp.me/
404
+        \OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName() . ' - ' . $this->defaults->getSlogan()]);
405
+        \OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->l10n->t('%s is publicly shared', [$shareTmpl['filename']])]);
406
+        \OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
407
+        \OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
408
+        \OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
409
+        \OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $shareTmpl['previewImage']]);
410
+
411
+        $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
412
+
413
+        $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
414
+        $csp->addAllowedFrameDomain('\'self\'');
415
+        $response = new TemplateResponse($this->appName, 'public', $shareTmpl, 'base');
416
+        $response->setContentSecurityPolicy($csp);
417
+
418
+        $this->emitAccessShareHook($share);
419
+
420
+        return $response;
421
+    }
422
+
423
+    /**
424
+     * @PublicPage
425
+     * @NoCSRFRequired
426
+     *
427
+     * @param string $token
428
+     * @param string $files
429
+     * @param string $path
430
+     * @param string $downloadStartSecret
431
+     * @return void|\OCP\AppFramework\Http\Response
432
+     * @throws NotFoundException
433
+     */
434
+    public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
435
+        \OC_User::setIncognitoMode(true);
436
+
437
+        $share = $this->shareManager->getShareByToken($token);
438
+
439
+        if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
440
+            return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
441
+        }
442
+
443
+        // Share is password protected - check whether the user is permitted to access the share
444
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
445
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
446
+                ['token' => $token]));
447
+        }
448
+
449
+        $files_list = null;
450
+        if (!is_null($files)) { // download selected files
451
+            $files_list = json_decode($files);
452
+            // in case we get only a single file
453
+            if ($files_list === null) {
454
+                $files_list = [$files];
455
+            }
456
+        }
457
+
458
+        $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
459
+        $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
460
+
461
+        if (!$this->validateShare($share)) {
462
+            throw new NotFoundException();
463
+        }
464
+
465
+        // Single file share
466
+        if ($share->getNode() instanceof \OCP\Files\File) {
467
+            // Single file download
468
+            $this->singleFileDownloaded($share, $share->getNode());
469
+        }
470
+        // Directory share
471
+        else {
472
+            /** @var \OCP\Files\Folder $node */
473
+            $node = $share->getNode();
474
+
475
+            // Try to get the path
476
+            if ($path !== '') {
477
+                try {
478
+                    $node = $node->get($path);
479
+                } catch (NotFoundException $e) {
480
+                    $this->emitAccessShareHook($share, 404, 'Share not found');
481
+                    return new NotFoundResponse();
482
+                }
483
+            }
484
+
485
+            $originalSharePath = $userFolder->getRelativePath($node->getPath());
486
+
487
+            if ($node instanceof \OCP\Files\File) {
488
+                // Single file download
489
+                $this->singleFileDownloaded($share, $share->getNode());
490
+            } else if (!empty($files_list)) {
491
+                $this->fileListDownloaded($share, $files_list, $node);
492
+            } else {
493
+                // The folder is downloaded
494
+                $this->singleFileDownloaded($share, $share->getNode());
495
+            }
496
+        }
497
+
498
+        /* FIXME: We should do this all nicely in OCP */
499
+        OC_Util::tearDownFS();
500
+        OC_Util::setupFS($share->getShareOwner());
501
+
502
+        /**
503
+         * this sets a cookie to be able to recognize the start of the download
504
+         * the content must not be longer than 32 characters and must only contain
505
+         * alphanumeric characters
506
+         */
507
+        if (!empty($downloadStartSecret)
508
+            && !isset($downloadStartSecret[32])
509
+            && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
510
+
511
+            // FIXME: set on the response once we use an actual app framework response
512
+            setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
513
+        }
514
+
515
+        $this->emitAccessShareHook($share);
516
+
517
+        $server_params = array( 'head' => $this->request->getMethod() == 'HEAD' );
518
+
519
+        /**
520
+         * Http range requests support
521
+         */
522
+        if (isset($_SERVER['HTTP_RANGE'])) {
523
+            $server_params['range'] = $this->request->getHeader('Range');
524
+        }
525
+
526
+        // download selected files
527
+        if (!is_null($files) && $files !== '') {
528
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
529
+            // after dispatching the request which results in a "Cannot modify header information" notice.
530
+            OC_Files::get($originalSharePath, $files_list, $server_params);
531
+            exit();
532
+        } else {
533
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
534
+            // after dispatching the request which results in a "Cannot modify header information" notice.
535
+            OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
536
+            exit();
537
+        }
538
+    }
539
+
540
+    /**
541
+     * create activity for every downloaded file
542
+     *
543
+     * @param Share\IShare $share
544
+     * @param array $files_list
545
+     * @param \OCP\Files\Folder $node
546
+     */
547
+    protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
548
+        foreach ($files_list as $file) {
549
+            $subNode = $node->get($file);
550
+            $this->singleFileDownloaded($share, $subNode);
551
+        }
552
+
553
+    }
554
+
555
+    /**
556
+     * create activity if a single file was downloaded from a link share
557
+     *
558
+     * @param Share\IShare $share
559
+     */
560
+    protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
561
+
562
+        $fileId = $node->getId();
563
+
564
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
565
+        $userNodeList = $userFolder->getById($fileId);
566
+        $userNode = $userNodeList[0];
567
+        $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
568
+        $userPath = $userFolder->getRelativePath($userNode->getPath());
569
+        $ownerPath = $ownerFolder->getRelativePath($node->getPath());
570
+
571
+        $parameters = [$userPath];
572
+
573
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
574
+            if ($node instanceof \OCP\Files\File) {
575
+                $subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
576
+            } else {
577
+                $subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
578
+            }
579
+            $parameters[] = $share->getSharedWith();
580
+        } else {
581
+            if ($node instanceof \OCP\Files\File) {
582
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
583
+            } else {
584
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
585
+            }
586
+        }
587
+
588
+        $this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
589
+
590
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
591
+            $parameters[0] = $ownerPath;
592
+            $this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
593
+        }
594
+    }
595
+
596
+    /**
597
+     * publish activity
598
+     *
599
+     * @param string $subject
600
+     * @param array $parameters
601
+     * @param string $affectedUser
602
+     * @param int $fileId
603
+     * @param string $filePath
604
+     */
605
+    protected function publishActivity($subject,
606
+                                        array $parameters,
607
+                                        $affectedUser,
608
+                                        $fileId,
609
+                                        $filePath) {
610
+
611
+        $event = $this->activityManager->generateEvent();
612
+        $event->setApp('files_sharing')
613
+            ->setType('public_links')
614
+            ->setSubject($subject, $parameters)
615
+            ->setAffectedUser($affectedUser)
616
+            ->setObject('files', $fileId, $filePath);
617
+        $this->activityManager->publish($event);
618
+    }
619 619
 
620 620
 
621 621
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 	public function showAuthenticate($token) {
151 151
 		$share = $this->shareManager->getShareByToken($token);
152 152
 
153
-		if($this->linkShareAuth($share)) {
153
+		if ($this->linkShareAuth($share)) {
154 154
 			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
155 155
 		}
156 156
 
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 
179 179
 		$authenticate = $this->linkShareAuth($share, $password);
180 180
 
181
-		if($authenticate === true) {
181
+		if ($authenticate === true) {
182 182
 			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
183 183
 		}
184 184
 
@@ -199,15 +199,15 @@  discard block
 block discarded – undo
199 199
 	private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
200 200
 		if ($password !== null) {
201 201
 			if ($this->shareManager->checkPassword($share, $password)) {
202
-				$this->session->set('public_link_authenticated', (string)$share->getId());
202
+				$this->session->set('public_link_authenticated', (string) $share->getId());
203 203
 			} else {
204 204
 				$this->emitAccessShareHook($share, 403, 'Wrong password');
205 205
 				return false;
206 206
 			}
207 207
 		} else {
208 208
 			// not authenticated ?
209
-			if ( ! $this->session->exists('public_link_authenticated')
210
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
209
+			if (!$this->session->exists('public_link_authenticated')
210
+				|| $this->session->get('public_link_authenticated') !== (string) $share->getId()) {
211 211
 				return false;
212 212
 			}
213 213
 		}
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 		$itemType = $itemSource = $uidOwner = '';
229 229
 		$token = $share;
230 230
 		$exception = null;
231
-		if($share instanceof \OCP\Share\IShare) {
231
+		if ($share instanceof \OCP\Share\IShare) {
232 232
 			try {
233 233
 				$token = $share->getToken();
234 234
 				$uidOwner = $share->getSharedBy();
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
 			'errorCode' => $errorCode,
248 248
 			'errorMessage' => $errorMessage,
249 249
 		]);
250
-		if(!is_null($exception)) {
250
+		if (!is_null($exception)) {
251 251
 			throw $exception;
252 252
 		}
253 253
 	}
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
 			if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
341 341
 				$freeSpace = max($freeSpace, 0);
342 342
 			} else {
343
-				$freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
343
+				$freeSpace = (INF > 0) ? INF : PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
344 344
 			}
345 345
 
346 346
 			$hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true;
@@ -371,7 +371,7 @@  discard block
 block discarded – undo
371 371
 		$shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
372 372
 		$shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
373 373
 		if ($shareTmpl['previewSupported']) {
374
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
374
+			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview',
375 375
 				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
376 376
 		} else {
377 377
 			$shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
 		}
402 402
 
403 403
 		// OpenGraph Support: http://ogp.me/
404
-		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName() . ' - ' . $this->defaults->getSlogan()]);
404
+		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName().' - '.$this->defaults->getSlogan()]);
405 405
 		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->l10n->t('%s is publicly shared', [$shareTmpl['filename']])]);
406 406
 		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
407 407
 		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
@@ -436,7 +436,7 @@  discard block
 block discarded – undo
436 436
 
437 437
 		$share = $this->shareManager->getShareByToken($token);
438 438
 
439
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
439
+		if (!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
440 440
 			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
441 441
 		}
442 442
 
@@ -514,7 +514,7 @@  discard block
 block discarded – undo
514 514
 
515 515
 		$this->emitAccessShareHook($share);
516 516
 
517
-		$server_params = array( 'head' => $this->request->getMethod() == 'HEAD' );
517
+		$server_params = array('head' => $this->request->getMethod() == 'HEAD');
518 518
 
519 519
 		/**
520 520
 		 * Http range requests support
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareesAPIController.php 3 patches
Doc Comments   +4 added lines, -1 removed lines patch added patch discarded remove patch
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
 	 * split user and remote from federated cloud id
359 359
 	 *
360 360
 	 * @param string $address federated share address
361
-	 * @return array [user, remoteURL]
361
+	 * @return string[] [user, remoteURL]
362 362
 	 * @throws \Exception
363 363
 	 */
364 364
 	public function splitUserRemote($address) {
@@ -633,6 +633,9 @@  discard block
 block discarded – undo
633 633
 		return $result;
634 634
 	}
635 635
 
636
+	/**
637
+	 * @param string $search
638
+	 */
636 639
 	protected function getLookup($search) {
637 640
 		$isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
638 641
 		$result = [];
Please login to merge, or discard this patch.
Indentation   +639 added lines, -639 removed lines patch added patch discarded remove patch
@@ -43,643 +43,643 @@
 block discarded – undo
43 43
 
44 44
 class ShareesAPIController extends OCSController {
45 45
 
46
-	/** @var IGroupManager */
47
-	protected $groupManager;
48
-
49
-	/** @var IUserManager */
50
-	protected $userManager;
51
-
52
-	/** @var IManager */
53
-	protected $contactsManager;
54
-
55
-	/** @var IConfig */
56
-	protected $config;
57
-
58
-	/** @var IUserSession */
59
-	protected $userSession;
60
-
61
-	/** @var IURLGenerator */
62
-	protected $urlGenerator;
63
-
64
-	/** @var ILogger */
65
-	protected $logger;
66
-
67
-	/** @var \OCP\Share\IManager */
68
-	protected $shareManager;
69
-
70
-	/** @var IClientService */
71
-	protected $clientService;
72
-
73
-	/** @var ICloudIdManager  */
74
-	protected $cloudIdManager;
75
-
76
-	/** @var bool */
77
-	protected $shareWithGroupOnly = false;
78
-
79
-	/** @var bool */
80
-	protected $shareeEnumeration = true;
81
-
82
-	/** @var int */
83
-	protected $offset = 0;
84
-
85
-	/** @var int */
86
-	protected $limit = 10;
87
-
88
-	/** @var array */
89
-	protected $result = [
90
-		'exact' => [
91
-			'users' => [],
92
-			'groups' => [],
93
-			'remotes' => [],
94
-			'emails' => [],
95
-		],
96
-		'users' => [],
97
-		'groups' => [],
98
-		'remotes' => [],
99
-		'emails' => [],
100
-		'lookup' => [],
101
-	];
102
-
103
-	protected $reachedEndFor = [];
104
-
105
-	/**
106
-	 * @param string $appName
107
-	 * @param IRequest $request
108
-	 * @param IGroupManager $groupManager
109
-	 * @param IUserManager $userManager
110
-	 * @param IManager $contactsManager
111
-	 * @param IConfig $config
112
-	 * @param IUserSession $userSession
113
-	 * @param IURLGenerator $urlGenerator
114
-	 * @param ILogger $logger
115
-	 * @param \OCP\Share\IManager $shareManager
116
-	 * @param IClientService $clientService
117
-	 * @param ICloudIdManager $cloudIdManager
118
-	 */
119
-	public function __construct($appName,
120
-								IRequest $request,
121
-								IGroupManager $groupManager,
122
-								IUserManager $userManager,
123
-								IManager $contactsManager,
124
-								IConfig $config,
125
-								IUserSession $userSession,
126
-								IURLGenerator $urlGenerator,
127
-								ILogger $logger,
128
-								\OCP\Share\IManager $shareManager,
129
-								IClientService $clientService,
130
-								ICloudIdManager $cloudIdManager
131
-	) {
132
-		parent::__construct($appName, $request);
133
-
134
-		$this->groupManager = $groupManager;
135
-		$this->userManager = $userManager;
136
-		$this->contactsManager = $contactsManager;
137
-		$this->config = $config;
138
-		$this->userSession = $userSession;
139
-		$this->urlGenerator = $urlGenerator;
140
-		$this->logger = $logger;
141
-		$this->shareManager = $shareManager;
142
-		$this->clientService = $clientService;
143
-		$this->cloudIdManager = $cloudIdManager;
144
-	}
145
-
146
-	/**
147
-	 * @param string $search
148
-	 */
149
-	protected function getUsers($search) {
150
-		$this->result['users'] = $this->result['exact']['users'] = $users = [];
151
-
152
-		$userGroups = [];
153
-		if ($this->shareWithGroupOnly) {
154
-			// Search in all the groups this user is part of
155
-			$userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
156
-			foreach ($userGroups as $userGroup) {
157
-				$usersTmp = $this->groupManager->displayNamesInGroup($userGroup, $search, $this->limit, $this->offset);
158
-				foreach ($usersTmp as $uid => $userDisplayName) {
159
-					$users[$uid] = $userDisplayName;
160
-				}
161
-			}
162
-		} else {
163
-			// Search in all users
164
-			$usersTmp = $this->userManager->searchDisplayName($search, $this->limit, $this->offset);
165
-
166
-			foreach ($usersTmp as $user) {
167
-				$users[$user->getUID()] = $user->getDisplayName();
168
-			}
169
-		}
170
-
171
-		if (!$this->shareeEnumeration || sizeof($users) < $this->limit) {
172
-			$this->reachedEndFor[] = 'users';
173
-		}
174
-
175
-		$foundUserById = false;
176
-		$lowerSearch = strtolower($search);
177
-		foreach ($users as $uid => $userDisplayName) {
178
-			if (strtolower($uid) === $lowerSearch || strtolower($userDisplayName) === $lowerSearch) {
179
-				if (strtolower($uid) === $lowerSearch) {
180
-					$foundUserById = true;
181
-				}
182
-				$this->result['exact']['users'][] = [
183
-					'label' => $userDisplayName,
184
-					'value' => [
185
-						'shareType' => Share::SHARE_TYPE_USER,
186
-						'shareWith' => $uid,
187
-					],
188
-				];
189
-			} else {
190
-				$this->result['users'][] = [
191
-					'label' => $userDisplayName,
192
-					'value' => [
193
-						'shareType' => Share::SHARE_TYPE_USER,
194
-						'shareWith' => $uid,
195
-					],
196
-				];
197
-			}
198
-		}
199
-
200
-		if ($this->offset === 0 && !$foundUserById) {
201
-			// On page one we try if the search result has a direct hit on the
202
-			// user id and if so, we add that to the exact match list
203
-			$user = $this->userManager->get($search);
204
-			if ($user instanceof IUser) {
205
-				$addUser = true;
206
-
207
-				if ($this->shareWithGroupOnly) {
208
-					// Only add, if we have a common group
209
-					$commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user));
210
-					$addUser = !empty($commonGroups);
211
-				}
212
-
213
-				if ($addUser) {
214
-					array_push($this->result['exact']['users'], [
215
-						'label' => $user->getDisplayName(),
216
-						'value' => [
217
-							'shareType' => Share::SHARE_TYPE_USER,
218
-							'shareWith' => $user->getUID(),
219
-						],
220
-					]);
221
-				}
222
-			}
223
-		}
224
-
225
-		if (!$this->shareeEnumeration) {
226
-			$this->result['users'] = [];
227
-		}
228
-	}
229
-
230
-	/**
231
-	 * @param string $search
232
-	 */
233
-	protected function getGroups($search) {
234
-		$this->result['groups'] = $this->result['exact']['groups'] = [];
235
-
236
-		$groups = $this->groupManager->search($search, $this->limit, $this->offset);
237
-		$groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
238
-
239
-		if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
240
-			$this->reachedEndFor[] = 'groups';
241
-		}
242
-
243
-		$userGroups =  [];
244
-		if (!empty($groups) && $this->shareWithGroupOnly) {
245
-			// Intersect all the groups that match with the groups this user is a member of
246
-			$userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
247
-			$userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
248
-			$groupIds = array_intersect($groupIds, $userGroups);
249
-		}
250
-
251
-		$lowerSearch = strtolower($search);
252
-		foreach ($groups as $group) {
253
-			// FIXME: use a more efficient approach
254
-			$gid = $group->getGID();
255
-			if (!in_array($gid, $groupIds)) {
256
-				continue;
257
-			}
258
-			if (strtolower($gid) === $lowerSearch || strtolower($group->getDisplayName()) === $lowerSearch) {
259
-				$this->result['exact']['groups'][] = [
260
-					'label' => $group->getDisplayName(),
261
-					'value' => [
262
-						'shareType' => Share::SHARE_TYPE_GROUP,
263
-						'shareWith' => $gid,
264
-					],
265
-				];
266
-			} else {
267
-				$this->result['groups'][] = [
268
-					'label' => $group->getDisplayName(),
269
-					'value' => [
270
-						'shareType' => Share::SHARE_TYPE_GROUP,
271
-						'shareWith' => $gid,
272
-					],
273
-				];
274
-			}
275
-		}
276
-
277
-		if ($this->offset === 0 && empty($this->result['exact']['groups'])) {
278
-			// On page one we try if the search result has a direct hit on the
279
-			// user id and if so, we add that to the exact match list
280
-			$group = $this->groupManager->get($search);
281
-			if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) {
282
-				array_push($this->result['exact']['groups'], [
283
-					'label' => $group->getDisplayName(),
284
-					'value' => [
285
-						'shareType' => Share::SHARE_TYPE_GROUP,
286
-						'shareWith' => $group->getGID(),
287
-					],
288
-				]);
289
-			}
290
-		}
291
-
292
-		if (!$this->shareeEnumeration) {
293
-			$this->result['groups'] = [];
294
-		}
295
-	}
296
-
297
-	/**
298
-	 * @param string $search
299
-	 * @return array
300
-	 */
301
-	protected function getRemote($search) {
302
-		$result = ['results' => [], 'exact' => []];
303
-
304
-		// Search in contacts
305
-		//@todo Pagination missing
306
-		$addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN']);
307
-		$result['exactIdMatch'] = false;
308
-		foreach ($addressBookContacts as $contact) {
309
-			if (isset($contact['isLocalSystemBook'])) {
310
-				continue;
311
-			}
312
-			if (isset($contact['CLOUD'])) {
313
-				$cloudIds = $contact['CLOUD'];
314
-				if (!is_array($cloudIds)) {
315
-					$cloudIds = [$cloudIds];
316
-				}
317
-				$lowerSearch = strtolower($search);
318
-				foreach ($cloudIds as $cloudId) {
319
-					list(, $serverUrl) = $this->splitUserRemote($cloudId);
320
-					if (strtolower($contact['FN']) === $lowerSearch || strtolower($cloudId) === $lowerSearch) {
321
-						if (strtolower($cloudId) === $lowerSearch) {
322
-							$result['exactIdMatch'] = true;
323
-						}
324
-						$result['exact'][] = [
325
-							'label' => $contact['FN'] . " ($cloudId)",
326
-							'value' => [
327
-								'shareType' => Share::SHARE_TYPE_REMOTE,
328
-								'shareWith' => $cloudId,
329
-								'server' => $serverUrl,
330
-							],
331
-						];
332
-					} else {
333
-						$result['results'][] = [
334
-							'label' => $contact['FN'] . " ($cloudId)",
335
-							'value' => [
336
-								'shareType' => Share::SHARE_TYPE_REMOTE,
337
-								'shareWith' => $cloudId,
338
-								'server' => $serverUrl,
339
-							],
340
-						];
341
-					}
342
-				}
343
-			}
344
-		}
345
-
346
-		if (!$this->shareeEnumeration) {
347
-			$result['results'] = [];
348
-		}
349
-
350
-		if (!$result['exactIdMatch'] && $this->cloudIdManager->isValidCloudId($search) && $this->offset === 0) {
351
-			$result['exact'][] = [
352
-				'label' => $search,
353
-				'value' => [
354
-					'shareType' => Share::SHARE_TYPE_REMOTE,
355
-					'shareWith' => $search,
356
-				],
357
-			];
358
-		}
359
-
360
-		$this->reachedEndFor[] = 'remotes';
361
-
362
-		return $result;
363
-	}
364
-
365
-	/**
366
-	 * split user and remote from federated cloud id
367
-	 *
368
-	 * @param string $address federated share address
369
-	 * @return array [user, remoteURL]
370
-	 * @throws \Exception
371
-	 */
372
-	public function splitUserRemote($address) {
373
-		try {
374
-			$cloudId = $this->cloudIdManager->resolveCloudId($address);
375
-			return [$cloudId->getUser(), $cloudId->getRemote()];
376
-		} catch (\InvalidArgumentException $e) {
377
-			throw new \Exception('Invalid Federated Cloud ID', 0, $e);
378
-		}
379
-	}
380
-
381
-	/**
382
-	 * Strips away a potential file names and trailing slashes:
383
-	 * - http://localhost
384
-	 * - http://localhost/
385
-	 * - http://localhost/index.php
386
-	 * - http://localhost/index.php/s/{shareToken}
387
-	 *
388
-	 * all return: http://localhost
389
-	 *
390
-	 * @param string $remote
391
-	 * @return string
392
-	 */
393
-	protected function fixRemoteURL($remote) {
394
-		$remote = str_replace('\\', '/', $remote);
395
-		if ($fileNamePosition = strpos($remote, '/index.php')) {
396
-			$remote = substr($remote, 0, $fileNamePosition);
397
-		}
398
-		$remote = rtrim($remote, '/');
399
-
400
-		return $remote;
401
-	}
402
-
403
-	/**
404
-	 * @NoAdminRequired
405
-	 *
406
-	 * @param string $search
407
-	 * @param string $itemType
408
-	 * @param int $page
409
-	 * @param int $perPage
410
-	 * @param int|int[] $shareType
411
-	 * @param bool $lookup
412
-	 * @return DataResponse
413
-	 * @throws OCSBadRequestException
414
-	 */
415
-	public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) {
416
-
417
-		// only search for string larger than a given threshold
418
-		$threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
419
-		if (strlen($search) < $threshold) {
420
-			return new DataResponse($this->result);
421
-		}
422
-
423
-		// never return more than the max. number of results configured in the config.php
424
-		$maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
425
-		if ($maxResults > 0) {
426
-			$perPage = min($perPage, $maxResults);
427
-		}
428
-		if ($perPage <= 0) {
429
-			throw new OCSBadRequestException('Invalid perPage argument');
430
-		}
431
-		if ($page <= 0) {
432
-			throw new OCSBadRequestException('Invalid page');
433
-		}
434
-
435
-		$shareTypes = [
436
-			Share::SHARE_TYPE_USER,
437
-		];
438
-
439
-		if ($itemType === 'file' || $itemType === 'folder') {
440
-			if ($this->shareManager->allowGroupSharing()) {
441
-				$shareTypes[] = Share::SHARE_TYPE_GROUP;
442
-			}
443
-
444
-			if ($this->isRemoteSharingAllowed($itemType)) {
445
-				$shareTypes[] = Share::SHARE_TYPE_REMOTE;
446
-			}
447
-
448
-			if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
449
-				$shareTypes[] = Share::SHARE_TYPE_EMAIL;
450
-			}
451
-		} else {
452
-			$shareTypes[] = Share::SHARE_TYPE_GROUP;
453
-			$shareTypes[] = Share::SHARE_TYPE_EMAIL;
454
-		}
455
-
456
-		if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
457
-			$shareTypes = array_intersect($shareTypes, $_GET['shareType']);
458
-			sort($shareTypes);
459
-		} else if (is_numeric($shareType)) {
460
-			$shareTypes = array_intersect($shareTypes, [(int) $shareType]);
461
-			sort($shareTypes);
462
-		}
463
-
464
-		$this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
465
-		$this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
466
-		$this->limit = (int) $perPage;
467
-		$this->offset = $perPage * ($page - 1);
468
-
469
-		return $this->searchSharees($search, $itemType, $shareTypes, $page, $perPage, $lookup);
470
-	}
471
-
472
-	/**
473
-	 * Method to get out the static call for better testing
474
-	 *
475
-	 * @param string $itemType
476
-	 * @return bool
477
-	 */
478
-	protected function isRemoteSharingAllowed($itemType) {
479
-		try {
480
-			$backend = Share::getBackend($itemType);
481
-			return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
482
-		} catch (\Exception $e) {
483
-			return false;
484
-		}
485
-	}
486
-
487
-	/**
488
-	 * Testable search function that does not need globals
489
-	 *
490
-	 * @param string $search
491
-	 * @param string $itemType
492
-	 * @param array $shareTypes
493
-	 * @param int $page
494
-	 * @param int $perPage
495
-	 * @param bool $lookup
496
-	 * @return DataResponse
497
-	 * @throws OCSBadRequestException
498
-	 */
499
-	protected function searchSharees($search, $itemType, array $shareTypes, $page, $perPage, $lookup) {
500
-		// Verify arguments
501
-		if ($itemType === null) {
502
-			throw new OCSBadRequestException('Missing itemType');
503
-		}
504
-
505
-		// Get users
506
-		if (in_array(Share::SHARE_TYPE_USER, $shareTypes)) {
507
-			$this->getUsers($search);
508
-		}
509
-
510
-		// Get groups
511
-		if (in_array(Share::SHARE_TYPE_GROUP, $shareTypes)) {
512
-			$this->getGroups($search);
513
-		}
514
-
515
-		// Get remote
516
-		$remoteResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
517
-		if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes)) {
518
-			$remoteResults = $this->getRemote($search);
519
-		}
520
-
521
-		// Get emails
522
-		$mailResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
523
-		if (in_array(Share::SHARE_TYPE_EMAIL, $shareTypes)) {
524
-			$mailResults = $this->getEmail($search);
525
-		}
526
-
527
-		// Get from lookup server
528
-		if ($lookup) {
529
-			$this->getLookup($search);
530
-		}
531
-
532
-		// if we have a exact match, either for the federated cloud id or for the
533
-		// email address we only return the exact match. It is highly unlikely
534
-		// that the exact same email address and federated cloud id exists
535
-		if ($mailResults['exactIdMatch'] && !$remoteResults['exactIdMatch']) {
536
-			$this->result['emails'] = $mailResults['results'];
537
-			$this->result['exact']['emails'] = $mailResults['exact'];
538
-		} else if (!$mailResults['exactIdMatch'] && $remoteResults['exactIdMatch']) {
539
-			$this->result['remotes'] = $remoteResults['results'];
540
-			$this->result['exact']['remotes'] = $remoteResults['exact'];
541
-		} else {
542
-			$this->result['remotes'] = $remoteResults['results'];
543
-			$this->result['exact']['remotes'] = $remoteResults['exact'];
544
-			$this->result['emails'] = $mailResults['results'];
545
-			$this->result['exact']['emails'] = $mailResults['exact'];
546
-		}
547
-
548
-		$response = new DataResponse($this->result);
549
-
550
-		if (sizeof($this->reachedEndFor) < 3) {
551
-			$response->addHeader('Link', $this->getPaginationLink($page, [
552
-				'search' => $search,
553
-				'itemType' => $itemType,
554
-				'shareType' => $shareTypes,
555
-				'perPage' => $perPage,
556
-			]));
557
-		}
558
-
559
-		return $response;
560
-	}
561
-
562
-	/**
563
-	 * @param string $search
564
-	 * @return array
565
-	 */
566
-	protected function getEmail($search) {
567
-		$result = ['results' => [], 'exact' => []];
568
-
569
-		// Search in contacts
570
-		//@todo Pagination missing
571
-		$addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN']);
572
-		$result['exactIdMatch'] = false;
573
-		foreach ($addressBookContacts as $contact) {
574
-			if (isset($contact['isLocalSystemBook'])) {
575
-				continue;
576
-			}
577
-			if (isset($contact['EMAIL'])) {
578
-				$emailAddresses = $contact['EMAIL'];
579
-				if (!is_array($emailAddresses)) {
580
-					$emailAddresses = [$emailAddresses];
581
-				}
582
-				foreach ($emailAddresses as $emailAddress) {
583
-					if (strtolower($contact['FN']) === strtolower($search) || strtolower($emailAddress) === strtolower($search)) {
584
-						if (strtolower($emailAddress) === strtolower($search)) {
585
-							$result['exactIdMatch'] = true;
586
-						}
587
-						$result['exact'][] = [
588
-							'label' => $contact['FN'] . " ($emailAddress)",
589
-							'value' => [
590
-								'shareType' => Share::SHARE_TYPE_EMAIL,
591
-								'shareWith' => $emailAddress,
592
-							],
593
-						];
594
-					} else {
595
-						$result['results'][] = [
596
-							'label' => $contact['FN'] . " ($emailAddress)",
597
-							'value' => [
598
-								'shareType' => Share::SHARE_TYPE_EMAIL,
599
-								'shareWith' => $emailAddress,
600
-							],
601
-						];
602
-					}
603
-				}
604
-			}
605
-		}
606
-
607
-		if (!$this->shareeEnumeration) {
608
-			$result['results'] = [];
609
-		}
610
-
611
-		if (!$result['exactIdMatch'] && filter_var($search, FILTER_VALIDATE_EMAIL)) {
612
-			$result['exact'][] = [
613
-				'label' => $search,
614
-				'value' => [
615
-					'shareType' => Share::SHARE_TYPE_EMAIL,
616
-					'shareWith' => $search,
617
-				],
618
-			];
619
-		}
620
-
621
-		$this->reachedEndFor[] = 'emails';
622
-
623
-		return $result;
624
-	}
625
-
626
-	protected function getLookup($search) {
627
-		$isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
628
-		$result = [];
629
-
630
-		if($isEnabled === 'yes') {
631
-			try {
632
-				$client = $this->clientService->newClient();
633
-				$response = $client->get(
634
-					'https://lookup.nextcloud.com/users?search=' . urlencode($search),
635
-					[
636
-						'timeout' => 10,
637
-						'connect_timeout' => 3,
638
-					]
639
-				);
640
-
641
-				$body = json_decode($response->getBody(), true);
642
-
643
-				$result = [];
644
-				foreach ($body as $lookup) {
645
-					$result[] = [
646
-						'label' => $lookup['federationId'],
647
-						'value' => [
648
-							'shareType' => Share::SHARE_TYPE_REMOTE,
649
-							'shareWith' => $lookup['federationId'],
650
-						],
651
-						'extra' => $lookup,
652
-					];
653
-				}
654
-			} catch (\Exception $e) {}
655
-		}
656
-
657
-		$this->result['lookup'] = $result;
658
-	}
659
-
660
-	/**
661
-	 * Generates a bunch of pagination links for the current page
662
-	 *
663
-	 * @param int $page Current page
664
-	 * @param array $params Parameters for the URL
665
-	 * @return string
666
-	 */
667
-	protected function getPaginationLink($page, array $params) {
668
-		if ($this->isV2()) {
669
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
670
-		} else {
671
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
672
-		}
673
-		$params['page'] = $page + 1;
674
-		$link = '<' . $url . http_build_query($params) . '>; rel="next"';
675
-
676
-		return $link;
677
-	}
678
-
679
-	/**
680
-	 * @return bool
681
-	 */
682
-	protected function isV2() {
683
-		return $this->request->getScriptName() === '/ocs/v2.php';
684
-	}
46
+    /** @var IGroupManager */
47
+    protected $groupManager;
48
+
49
+    /** @var IUserManager */
50
+    protected $userManager;
51
+
52
+    /** @var IManager */
53
+    protected $contactsManager;
54
+
55
+    /** @var IConfig */
56
+    protected $config;
57
+
58
+    /** @var IUserSession */
59
+    protected $userSession;
60
+
61
+    /** @var IURLGenerator */
62
+    protected $urlGenerator;
63
+
64
+    /** @var ILogger */
65
+    protected $logger;
66
+
67
+    /** @var \OCP\Share\IManager */
68
+    protected $shareManager;
69
+
70
+    /** @var IClientService */
71
+    protected $clientService;
72
+
73
+    /** @var ICloudIdManager  */
74
+    protected $cloudIdManager;
75
+
76
+    /** @var bool */
77
+    protected $shareWithGroupOnly = false;
78
+
79
+    /** @var bool */
80
+    protected $shareeEnumeration = true;
81
+
82
+    /** @var int */
83
+    protected $offset = 0;
84
+
85
+    /** @var int */
86
+    protected $limit = 10;
87
+
88
+    /** @var array */
89
+    protected $result = [
90
+        'exact' => [
91
+            'users' => [],
92
+            'groups' => [],
93
+            'remotes' => [],
94
+            'emails' => [],
95
+        ],
96
+        'users' => [],
97
+        'groups' => [],
98
+        'remotes' => [],
99
+        'emails' => [],
100
+        'lookup' => [],
101
+    ];
102
+
103
+    protected $reachedEndFor = [];
104
+
105
+    /**
106
+     * @param string $appName
107
+     * @param IRequest $request
108
+     * @param IGroupManager $groupManager
109
+     * @param IUserManager $userManager
110
+     * @param IManager $contactsManager
111
+     * @param IConfig $config
112
+     * @param IUserSession $userSession
113
+     * @param IURLGenerator $urlGenerator
114
+     * @param ILogger $logger
115
+     * @param \OCP\Share\IManager $shareManager
116
+     * @param IClientService $clientService
117
+     * @param ICloudIdManager $cloudIdManager
118
+     */
119
+    public function __construct($appName,
120
+                                IRequest $request,
121
+                                IGroupManager $groupManager,
122
+                                IUserManager $userManager,
123
+                                IManager $contactsManager,
124
+                                IConfig $config,
125
+                                IUserSession $userSession,
126
+                                IURLGenerator $urlGenerator,
127
+                                ILogger $logger,
128
+                                \OCP\Share\IManager $shareManager,
129
+                                IClientService $clientService,
130
+                                ICloudIdManager $cloudIdManager
131
+    ) {
132
+        parent::__construct($appName, $request);
133
+
134
+        $this->groupManager = $groupManager;
135
+        $this->userManager = $userManager;
136
+        $this->contactsManager = $contactsManager;
137
+        $this->config = $config;
138
+        $this->userSession = $userSession;
139
+        $this->urlGenerator = $urlGenerator;
140
+        $this->logger = $logger;
141
+        $this->shareManager = $shareManager;
142
+        $this->clientService = $clientService;
143
+        $this->cloudIdManager = $cloudIdManager;
144
+    }
145
+
146
+    /**
147
+     * @param string $search
148
+     */
149
+    protected function getUsers($search) {
150
+        $this->result['users'] = $this->result['exact']['users'] = $users = [];
151
+
152
+        $userGroups = [];
153
+        if ($this->shareWithGroupOnly) {
154
+            // Search in all the groups this user is part of
155
+            $userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
156
+            foreach ($userGroups as $userGroup) {
157
+                $usersTmp = $this->groupManager->displayNamesInGroup($userGroup, $search, $this->limit, $this->offset);
158
+                foreach ($usersTmp as $uid => $userDisplayName) {
159
+                    $users[$uid] = $userDisplayName;
160
+                }
161
+            }
162
+        } else {
163
+            // Search in all users
164
+            $usersTmp = $this->userManager->searchDisplayName($search, $this->limit, $this->offset);
165
+
166
+            foreach ($usersTmp as $user) {
167
+                $users[$user->getUID()] = $user->getDisplayName();
168
+            }
169
+        }
170
+
171
+        if (!$this->shareeEnumeration || sizeof($users) < $this->limit) {
172
+            $this->reachedEndFor[] = 'users';
173
+        }
174
+
175
+        $foundUserById = false;
176
+        $lowerSearch = strtolower($search);
177
+        foreach ($users as $uid => $userDisplayName) {
178
+            if (strtolower($uid) === $lowerSearch || strtolower($userDisplayName) === $lowerSearch) {
179
+                if (strtolower($uid) === $lowerSearch) {
180
+                    $foundUserById = true;
181
+                }
182
+                $this->result['exact']['users'][] = [
183
+                    'label' => $userDisplayName,
184
+                    'value' => [
185
+                        'shareType' => Share::SHARE_TYPE_USER,
186
+                        'shareWith' => $uid,
187
+                    ],
188
+                ];
189
+            } else {
190
+                $this->result['users'][] = [
191
+                    'label' => $userDisplayName,
192
+                    'value' => [
193
+                        'shareType' => Share::SHARE_TYPE_USER,
194
+                        'shareWith' => $uid,
195
+                    ],
196
+                ];
197
+            }
198
+        }
199
+
200
+        if ($this->offset === 0 && !$foundUserById) {
201
+            // On page one we try if the search result has a direct hit on the
202
+            // user id and if so, we add that to the exact match list
203
+            $user = $this->userManager->get($search);
204
+            if ($user instanceof IUser) {
205
+                $addUser = true;
206
+
207
+                if ($this->shareWithGroupOnly) {
208
+                    // Only add, if we have a common group
209
+                    $commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user));
210
+                    $addUser = !empty($commonGroups);
211
+                }
212
+
213
+                if ($addUser) {
214
+                    array_push($this->result['exact']['users'], [
215
+                        'label' => $user->getDisplayName(),
216
+                        'value' => [
217
+                            'shareType' => Share::SHARE_TYPE_USER,
218
+                            'shareWith' => $user->getUID(),
219
+                        ],
220
+                    ]);
221
+                }
222
+            }
223
+        }
224
+
225
+        if (!$this->shareeEnumeration) {
226
+            $this->result['users'] = [];
227
+        }
228
+    }
229
+
230
+    /**
231
+     * @param string $search
232
+     */
233
+    protected function getGroups($search) {
234
+        $this->result['groups'] = $this->result['exact']['groups'] = [];
235
+
236
+        $groups = $this->groupManager->search($search, $this->limit, $this->offset);
237
+        $groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
238
+
239
+        if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
240
+            $this->reachedEndFor[] = 'groups';
241
+        }
242
+
243
+        $userGroups =  [];
244
+        if (!empty($groups) && $this->shareWithGroupOnly) {
245
+            // Intersect all the groups that match with the groups this user is a member of
246
+            $userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
247
+            $userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
248
+            $groupIds = array_intersect($groupIds, $userGroups);
249
+        }
250
+
251
+        $lowerSearch = strtolower($search);
252
+        foreach ($groups as $group) {
253
+            // FIXME: use a more efficient approach
254
+            $gid = $group->getGID();
255
+            if (!in_array($gid, $groupIds)) {
256
+                continue;
257
+            }
258
+            if (strtolower($gid) === $lowerSearch || strtolower($group->getDisplayName()) === $lowerSearch) {
259
+                $this->result['exact']['groups'][] = [
260
+                    'label' => $group->getDisplayName(),
261
+                    'value' => [
262
+                        'shareType' => Share::SHARE_TYPE_GROUP,
263
+                        'shareWith' => $gid,
264
+                    ],
265
+                ];
266
+            } else {
267
+                $this->result['groups'][] = [
268
+                    'label' => $group->getDisplayName(),
269
+                    'value' => [
270
+                        'shareType' => Share::SHARE_TYPE_GROUP,
271
+                        'shareWith' => $gid,
272
+                    ],
273
+                ];
274
+            }
275
+        }
276
+
277
+        if ($this->offset === 0 && empty($this->result['exact']['groups'])) {
278
+            // On page one we try if the search result has a direct hit on the
279
+            // user id and if so, we add that to the exact match list
280
+            $group = $this->groupManager->get($search);
281
+            if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) {
282
+                array_push($this->result['exact']['groups'], [
283
+                    'label' => $group->getDisplayName(),
284
+                    'value' => [
285
+                        'shareType' => Share::SHARE_TYPE_GROUP,
286
+                        'shareWith' => $group->getGID(),
287
+                    ],
288
+                ]);
289
+            }
290
+        }
291
+
292
+        if (!$this->shareeEnumeration) {
293
+            $this->result['groups'] = [];
294
+        }
295
+    }
296
+
297
+    /**
298
+     * @param string $search
299
+     * @return array
300
+     */
301
+    protected function getRemote($search) {
302
+        $result = ['results' => [], 'exact' => []];
303
+
304
+        // Search in contacts
305
+        //@todo Pagination missing
306
+        $addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN']);
307
+        $result['exactIdMatch'] = false;
308
+        foreach ($addressBookContacts as $contact) {
309
+            if (isset($contact['isLocalSystemBook'])) {
310
+                continue;
311
+            }
312
+            if (isset($contact['CLOUD'])) {
313
+                $cloudIds = $contact['CLOUD'];
314
+                if (!is_array($cloudIds)) {
315
+                    $cloudIds = [$cloudIds];
316
+                }
317
+                $lowerSearch = strtolower($search);
318
+                foreach ($cloudIds as $cloudId) {
319
+                    list(, $serverUrl) = $this->splitUserRemote($cloudId);
320
+                    if (strtolower($contact['FN']) === $lowerSearch || strtolower($cloudId) === $lowerSearch) {
321
+                        if (strtolower($cloudId) === $lowerSearch) {
322
+                            $result['exactIdMatch'] = true;
323
+                        }
324
+                        $result['exact'][] = [
325
+                            'label' => $contact['FN'] . " ($cloudId)",
326
+                            'value' => [
327
+                                'shareType' => Share::SHARE_TYPE_REMOTE,
328
+                                'shareWith' => $cloudId,
329
+                                'server' => $serverUrl,
330
+                            ],
331
+                        ];
332
+                    } else {
333
+                        $result['results'][] = [
334
+                            'label' => $contact['FN'] . " ($cloudId)",
335
+                            'value' => [
336
+                                'shareType' => Share::SHARE_TYPE_REMOTE,
337
+                                'shareWith' => $cloudId,
338
+                                'server' => $serverUrl,
339
+                            ],
340
+                        ];
341
+                    }
342
+                }
343
+            }
344
+        }
345
+
346
+        if (!$this->shareeEnumeration) {
347
+            $result['results'] = [];
348
+        }
349
+
350
+        if (!$result['exactIdMatch'] && $this->cloudIdManager->isValidCloudId($search) && $this->offset === 0) {
351
+            $result['exact'][] = [
352
+                'label' => $search,
353
+                'value' => [
354
+                    'shareType' => Share::SHARE_TYPE_REMOTE,
355
+                    'shareWith' => $search,
356
+                ],
357
+            ];
358
+        }
359
+
360
+        $this->reachedEndFor[] = 'remotes';
361
+
362
+        return $result;
363
+    }
364
+
365
+    /**
366
+     * split user and remote from federated cloud id
367
+     *
368
+     * @param string $address federated share address
369
+     * @return array [user, remoteURL]
370
+     * @throws \Exception
371
+     */
372
+    public function splitUserRemote($address) {
373
+        try {
374
+            $cloudId = $this->cloudIdManager->resolveCloudId($address);
375
+            return [$cloudId->getUser(), $cloudId->getRemote()];
376
+        } catch (\InvalidArgumentException $e) {
377
+            throw new \Exception('Invalid Federated Cloud ID', 0, $e);
378
+        }
379
+    }
380
+
381
+    /**
382
+     * Strips away a potential file names and trailing slashes:
383
+     * - http://localhost
384
+     * - http://localhost/
385
+     * - http://localhost/index.php
386
+     * - http://localhost/index.php/s/{shareToken}
387
+     *
388
+     * all return: http://localhost
389
+     *
390
+     * @param string $remote
391
+     * @return string
392
+     */
393
+    protected function fixRemoteURL($remote) {
394
+        $remote = str_replace('\\', '/', $remote);
395
+        if ($fileNamePosition = strpos($remote, '/index.php')) {
396
+            $remote = substr($remote, 0, $fileNamePosition);
397
+        }
398
+        $remote = rtrim($remote, '/');
399
+
400
+        return $remote;
401
+    }
402
+
403
+    /**
404
+     * @NoAdminRequired
405
+     *
406
+     * @param string $search
407
+     * @param string $itemType
408
+     * @param int $page
409
+     * @param int $perPage
410
+     * @param int|int[] $shareType
411
+     * @param bool $lookup
412
+     * @return DataResponse
413
+     * @throws OCSBadRequestException
414
+     */
415
+    public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) {
416
+
417
+        // only search for string larger than a given threshold
418
+        $threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
419
+        if (strlen($search) < $threshold) {
420
+            return new DataResponse($this->result);
421
+        }
422
+
423
+        // never return more than the max. number of results configured in the config.php
424
+        $maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
425
+        if ($maxResults > 0) {
426
+            $perPage = min($perPage, $maxResults);
427
+        }
428
+        if ($perPage <= 0) {
429
+            throw new OCSBadRequestException('Invalid perPage argument');
430
+        }
431
+        if ($page <= 0) {
432
+            throw new OCSBadRequestException('Invalid page');
433
+        }
434
+
435
+        $shareTypes = [
436
+            Share::SHARE_TYPE_USER,
437
+        ];
438
+
439
+        if ($itemType === 'file' || $itemType === 'folder') {
440
+            if ($this->shareManager->allowGroupSharing()) {
441
+                $shareTypes[] = Share::SHARE_TYPE_GROUP;
442
+            }
443
+
444
+            if ($this->isRemoteSharingAllowed($itemType)) {
445
+                $shareTypes[] = Share::SHARE_TYPE_REMOTE;
446
+            }
447
+
448
+            if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
449
+                $shareTypes[] = Share::SHARE_TYPE_EMAIL;
450
+            }
451
+        } else {
452
+            $shareTypes[] = Share::SHARE_TYPE_GROUP;
453
+            $shareTypes[] = Share::SHARE_TYPE_EMAIL;
454
+        }
455
+
456
+        if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
457
+            $shareTypes = array_intersect($shareTypes, $_GET['shareType']);
458
+            sort($shareTypes);
459
+        } else if (is_numeric($shareType)) {
460
+            $shareTypes = array_intersect($shareTypes, [(int) $shareType]);
461
+            sort($shareTypes);
462
+        }
463
+
464
+        $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
465
+        $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
466
+        $this->limit = (int) $perPage;
467
+        $this->offset = $perPage * ($page - 1);
468
+
469
+        return $this->searchSharees($search, $itemType, $shareTypes, $page, $perPage, $lookup);
470
+    }
471
+
472
+    /**
473
+     * Method to get out the static call for better testing
474
+     *
475
+     * @param string $itemType
476
+     * @return bool
477
+     */
478
+    protected function isRemoteSharingAllowed($itemType) {
479
+        try {
480
+            $backend = Share::getBackend($itemType);
481
+            return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
482
+        } catch (\Exception $e) {
483
+            return false;
484
+        }
485
+    }
486
+
487
+    /**
488
+     * Testable search function that does not need globals
489
+     *
490
+     * @param string $search
491
+     * @param string $itemType
492
+     * @param array $shareTypes
493
+     * @param int $page
494
+     * @param int $perPage
495
+     * @param bool $lookup
496
+     * @return DataResponse
497
+     * @throws OCSBadRequestException
498
+     */
499
+    protected function searchSharees($search, $itemType, array $shareTypes, $page, $perPage, $lookup) {
500
+        // Verify arguments
501
+        if ($itemType === null) {
502
+            throw new OCSBadRequestException('Missing itemType');
503
+        }
504
+
505
+        // Get users
506
+        if (in_array(Share::SHARE_TYPE_USER, $shareTypes)) {
507
+            $this->getUsers($search);
508
+        }
509
+
510
+        // Get groups
511
+        if (in_array(Share::SHARE_TYPE_GROUP, $shareTypes)) {
512
+            $this->getGroups($search);
513
+        }
514
+
515
+        // Get remote
516
+        $remoteResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
517
+        if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes)) {
518
+            $remoteResults = $this->getRemote($search);
519
+        }
520
+
521
+        // Get emails
522
+        $mailResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
523
+        if (in_array(Share::SHARE_TYPE_EMAIL, $shareTypes)) {
524
+            $mailResults = $this->getEmail($search);
525
+        }
526
+
527
+        // Get from lookup server
528
+        if ($lookup) {
529
+            $this->getLookup($search);
530
+        }
531
+
532
+        // if we have a exact match, either for the federated cloud id or for the
533
+        // email address we only return the exact match. It is highly unlikely
534
+        // that the exact same email address and federated cloud id exists
535
+        if ($mailResults['exactIdMatch'] && !$remoteResults['exactIdMatch']) {
536
+            $this->result['emails'] = $mailResults['results'];
537
+            $this->result['exact']['emails'] = $mailResults['exact'];
538
+        } else if (!$mailResults['exactIdMatch'] && $remoteResults['exactIdMatch']) {
539
+            $this->result['remotes'] = $remoteResults['results'];
540
+            $this->result['exact']['remotes'] = $remoteResults['exact'];
541
+        } else {
542
+            $this->result['remotes'] = $remoteResults['results'];
543
+            $this->result['exact']['remotes'] = $remoteResults['exact'];
544
+            $this->result['emails'] = $mailResults['results'];
545
+            $this->result['exact']['emails'] = $mailResults['exact'];
546
+        }
547
+
548
+        $response = new DataResponse($this->result);
549
+
550
+        if (sizeof($this->reachedEndFor) < 3) {
551
+            $response->addHeader('Link', $this->getPaginationLink($page, [
552
+                'search' => $search,
553
+                'itemType' => $itemType,
554
+                'shareType' => $shareTypes,
555
+                'perPage' => $perPage,
556
+            ]));
557
+        }
558
+
559
+        return $response;
560
+    }
561
+
562
+    /**
563
+     * @param string $search
564
+     * @return array
565
+     */
566
+    protected function getEmail($search) {
567
+        $result = ['results' => [], 'exact' => []];
568
+
569
+        // Search in contacts
570
+        //@todo Pagination missing
571
+        $addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN']);
572
+        $result['exactIdMatch'] = false;
573
+        foreach ($addressBookContacts as $contact) {
574
+            if (isset($contact['isLocalSystemBook'])) {
575
+                continue;
576
+            }
577
+            if (isset($contact['EMAIL'])) {
578
+                $emailAddresses = $contact['EMAIL'];
579
+                if (!is_array($emailAddresses)) {
580
+                    $emailAddresses = [$emailAddresses];
581
+                }
582
+                foreach ($emailAddresses as $emailAddress) {
583
+                    if (strtolower($contact['FN']) === strtolower($search) || strtolower($emailAddress) === strtolower($search)) {
584
+                        if (strtolower($emailAddress) === strtolower($search)) {
585
+                            $result['exactIdMatch'] = true;
586
+                        }
587
+                        $result['exact'][] = [
588
+                            'label' => $contact['FN'] . " ($emailAddress)",
589
+                            'value' => [
590
+                                'shareType' => Share::SHARE_TYPE_EMAIL,
591
+                                'shareWith' => $emailAddress,
592
+                            ],
593
+                        ];
594
+                    } else {
595
+                        $result['results'][] = [
596
+                            'label' => $contact['FN'] . " ($emailAddress)",
597
+                            'value' => [
598
+                                'shareType' => Share::SHARE_TYPE_EMAIL,
599
+                                'shareWith' => $emailAddress,
600
+                            ],
601
+                        ];
602
+                    }
603
+                }
604
+            }
605
+        }
606
+
607
+        if (!$this->shareeEnumeration) {
608
+            $result['results'] = [];
609
+        }
610
+
611
+        if (!$result['exactIdMatch'] && filter_var($search, FILTER_VALIDATE_EMAIL)) {
612
+            $result['exact'][] = [
613
+                'label' => $search,
614
+                'value' => [
615
+                    'shareType' => Share::SHARE_TYPE_EMAIL,
616
+                    'shareWith' => $search,
617
+                ],
618
+            ];
619
+        }
620
+
621
+        $this->reachedEndFor[] = 'emails';
622
+
623
+        return $result;
624
+    }
625
+
626
+    protected function getLookup($search) {
627
+        $isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
628
+        $result = [];
629
+
630
+        if($isEnabled === 'yes') {
631
+            try {
632
+                $client = $this->clientService->newClient();
633
+                $response = $client->get(
634
+                    'https://lookup.nextcloud.com/users?search=' . urlencode($search),
635
+                    [
636
+                        'timeout' => 10,
637
+                        'connect_timeout' => 3,
638
+                    ]
639
+                );
640
+
641
+                $body = json_decode($response->getBody(), true);
642
+
643
+                $result = [];
644
+                foreach ($body as $lookup) {
645
+                    $result[] = [
646
+                        'label' => $lookup['federationId'],
647
+                        'value' => [
648
+                            'shareType' => Share::SHARE_TYPE_REMOTE,
649
+                            'shareWith' => $lookup['federationId'],
650
+                        ],
651
+                        'extra' => $lookup,
652
+                    ];
653
+                }
654
+            } catch (\Exception $e) {}
655
+        }
656
+
657
+        $this->result['lookup'] = $result;
658
+    }
659
+
660
+    /**
661
+     * Generates a bunch of pagination links for the current page
662
+     *
663
+     * @param int $page Current page
664
+     * @param array $params Parameters for the URL
665
+     * @return string
666
+     */
667
+    protected function getPaginationLink($page, array $params) {
668
+        if ($this->isV2()) {
669
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
670
+        } else {
671
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
672
+        }
673
+        $params['page'] = $page + 1;
674
+        $link = '<' . $url . http_build_query($params) . '>; rel="next"';
675
+
676
+        return $link;
677
+    }
678
+
679
+    /**
680
+     * @return bool
681
+     */
682
+    protected function isV2() {
683
+        return $this->request->getScriptName() === '/ocs/v2.php';
684
+    }
685 685
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -234,17 +234,17 @@  discard block
 block discarded – undo
234 234
 		$this->result['groups'] = $this->result['exact']['groups'] = [];
235 235
 
236 236
 		$groups = $this->groupManager->search($search, $this->limit, $this->offset);
237
-		$groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
237
+		$groupIds = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
238 238
 
239 239
 		if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
240 240
 			$this->reachedEndFor[] = 'groups';
241 241
 		}
242 242
 
243
-		$userGroups =  [];
243
+		$userGroups = [];
244 244
 		if (!empty($groups) && $this->shareWithGroupOnly) {
245 245
 			// Intersect all the groups that match with the groups this user is a member of
246 246
 			$userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
247
-			$userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
247
+			$userGroups = array_map(function(IGroup $group) { return $group->getGID(); }, $userGroups);
248 248
 			$groupIds = array_intersect($groupIds, $userGroups);
249 249
 		}
250 250
 
@@ -322,7 +322,7 @@  discard block
 block discarded – undo
322 322
 							$result['exactIdMatch'] = true;
323 323
 						}
324 324
 						$result['exact'][] = [
325
-							'label' => $contact['FN'] . " ($cloudId)",
325
+							'label' => $contact['FN']." ($cloudId)",
326 326
 							'value' => [
327 327
 								'shareType' => Share::SHARE_TYPE_REMOTE,
328 328
 								'shareWith' => $cloudId,
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 						];
332 332
 					} else {
333 333
 						$result['results'][] = [
334
-							'label' => $contact['FN'] . " ($cloudId)",
334
+							'label' => $contact['FN']." ($cloudId)",
335 335
 							'value' => [
336 336
 								'shareType' => Share::SHARE_TYPE_REMOTE,
337 337
 								'shareWith' => $cloudId,
@@ -415,13 +415,13 @@  discard block
 block discarded – undo
415 415
 	public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) {
416 416
 
417 417
 		// only search for string larger than a given threshold
418
-		$threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
418
+		$threshold = (int) $this->config->getSystemValue('sharing.minSearchStringLength', 0);
419 419
 		if (strlen($search) < $threshold) {
420 420
 			return new DataResponse($this->result);
421 421
 		}
422 422
 
423 423
 		// never return more than the max. number of results configured in the config.php
424
-		$maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
424
+		$maxResults = (int) $this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
425 425
 		if ($maxResults > 0) {
426 426
 			$perPage = min($perPage, $maxResults);
427 427
 		}
@@ -585,7 +585,7 @@  discard block
 block discarded – undo
585 585
 							$result['exactIdMatch'] = true;
586 586
 						}
587 587
 						$result['exact'][] = [
588
-							'label' => $contact['FN'] . " ($emailAddress)",
588
+							'label' => $contact['FN']." ($emailAddress)",
589 589
 							'value' => [
590 590
 								'shareType' => Share::SHARE_TYPE_EMAIL,
591 591
 								'shareWith' => $emailAddress,
@@ -593,7 +593,7 @@  discard block
 block discarded – undo
593 593
 						];
594 594
 					} else {
595 595
 						$result['results'][] = [
596
-							'label' => $contact['FN'] . " ($emailAddress)",
596
+							'label' => $contact['FN']." ($emailAddress)",
597 597
 							'value' => [
598 598
 								'shareType' => Share::SHARE_TYPE_EMAIL,
599 599
 								'shareWith' => $emailAddress,
@@ -627,11 +627,11 @@  discard block
 block discarded – undo
627 627
 		$isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
628 628
 		$result = [];
629 629
 
630
-		if($isEnabled === 'yes') {
630
+		if ($isEnabled === 'yes') {
631 631
 			try {
632 632
 				$client = $this->clientService->newClient();
633 633
 				$response = $client->get(
634
-					'https://lookup.nextcloud.com/users?search=' . urlencode($search),
634
+					'https://lookup.nextcloud.com/users?search='.urlencode($search),
635 635
 					[
636 636
 						'timeout' => 10,
637 637
 						'connect_timeout' => 3,
@@ -666,12 +666,12 @@  discard block
 block discarded – undo
666 666
 	 */
667 667
 	protected function getPaginationLink($page, array $params) {
668 668
 		if ($this->isV2()) {
669
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
669
+			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees').'?';
670 670
 		} else {
671
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
671
+			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees').'?';
672 672
 		}
673 673
 		$params['page'] = $page + 1;
674
-		$link = '<' . $url . http_build_query($params) . '>; rel="next"';
674
+		$link = '<'.$url.http_build_query($params).'>; rel="next"';
675 675
 
676 676
 		return $link;
677 677
 	}
Please login to merge, or discard this patch.
apps/files_sharing/lib/SharedStorage.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -32,7 +32,6 @@
 block discarded – undo
32 32
 namespace OCA\Files_Sharing;
33 33
 
34 34
 use OC\Files\Filesystem;
35
-use OC\Files\Cache\FailedCache;
36 35
 use OC\Files\Storage\Wrapper\PermissionsMask;
37 36
 use OCA\Files_Sharing\ISharedStorage;
38 37
 use OC\Files\Storage\FailedStorage;
Please login to merge, or discard this patch.
Indentation   +429 added lines, -429 removed lines patch added patch discarded remove patch
@@ -47,433 +47,433 @@
 block discarded – undo
47 47
  */
48 48
 class SharedStorage extends \OC\Files\Storage\Wrapper\Jail implements ISharedStorage {
49 49
 
50
-	/** @var \OCP\Share\IShare */
51
-	private $superShare;
52
-
53
-	/** @var \OCP\Share\IShare[] */
54
-	private $groupedShares;
55
-
56
-	/**
57
-	 * @var \OC\Files\View
58
-	 */
59
-	private $ownerView;
60
-
61
-	private $initialized = false;
62
-
63
-	/**
64
-	 * @var ICacheEntry
65
-	 */
66
-	private $sourceRootInfo;
67
-
68
-	/** @var string */
69
-	private $user;
70
-
71
-	/**
72
-	 * @var \OCP\ILogger
73
-	 */
74
-	private $logger;
75
-
76
-	/** @var  IStorage */
77
-	private $nonMaskedStorage;
78
-
79
-	private $options;
80
-
81
-	public function __construct($arguments) {
82
-		$this->ownerView = $arguments['ownerView'];
83
-		$this->logger = \OC::$server->getLogger();
84
-
85
-		$this->superShare = $arguments['superShare'];
86
-		$this->groupedShares = $arguments['groupedShares'];
87
-
88
-		$this->user = $arguments['user'];
89
-
90
-		parent::__construct([
91
-			'storage' => null,
92
-			'root' => null,
93
-		]);
94
-	}
95
-
96
-	/**
97
-	 * @return ICacheEntry
98
-	 */
99
-	private function getSourceRootInfo() {
100
-		if (is_null($this->sourceRootInfo)) {
101
-			if (is_null($this->superShare->getNodeCacheEntry())) {
102
-				$this->sourceRootInfo = $this->nonMaskedStorage->getCache()->get($this->rootPath);
103
-			} else {
104
-				$this->sourceRootInfo = $this->superShare->getNodeCacheEntry();
105
-			}
106
-		}
107
-		return $this->sourceRootInfo;
108
-	}
109
-
110
-	private function init() {
111
-		if ($this->initialized) {
112
-			return;
113
-		}
114
-		$this->initialized = true;
115
-		try {
116
-			Filesystem::initMountPoints($this->superShare->getShareOwner());
117
-			$sourcePath = $this->ownerView->getPath($this->superShare->getNodeId());
118
-			list($this->nonMaskedStorage, $this->rootPath) = $this->ownerView->resolvePath($sourcePath);
119
-			$this->storage = new PermissionsMask([
120
-				'storage' => $this->nonMaskedStorage,
121
-				'mask' => $this->superShare->getPermissions()
122
-			]);
123
-		} catch (NotFoundException $e) {
124
-			$this->storage = new FailedStorage(['exception' => $e]);
125
-			$this->rootPath = '';
126
-		} catch (\Exception $e) {
127
-			$this->storage = new FailedStorage(['exception' => $e]);
128
-			$this->rootPath = '';
129
-			$this->logger->logException($e);
130
-		}
131
-	}
132
-
133
-	/**
134
-	 * @inheritdoc
135
-	 */
136
-	public function instanceOfStorage($class) {
137
-		if ($class === '\OC\Files\Storage\Common') {
138
-			return true;
139
-		}
140
-		if (in_array($class, ['\OC\Files\Storage\Home', '\OC\Files\ObjectStore\HomeObjectStoreStorage'])) {
141
-			return false;
142
-		}
143
-		return parent::instanceOfStorage($class);
144
-	}
145
-
146
-	/**
147
-	 * @return string
148
-	 */
149
-	public function getShareId() {
150
-		return $this->superShare->getId();
151
-	}
152
-
153
-	private function isValid() {
154
-		return $this->getSourceRootInfo() && ($this->getSourceRootInfo()->getPermissions() & Constants::PERMISSION_SHARE) === Constants::PERMISSION_SHARE;
155
-	}
156
-
157
-	/**
158
-	 * get id of the mount point
159
-	 *
160
-	 * @return string
161
-	 */
162
-	public function getId() {
163
-		return 'shared::' . $this->getMountPoint();
164
-	}
165
-
166
-	/**
167
-	 * Get the permissions granted for a shared file
168
-	 *
169
-	 * @param string $target Shared target file path
170
-	 * @return int CRUDS permissions granted
171
-	 */
172
-	public function getPermissions($target = '') {
173
-		if (!$this->isValid()) {
174
-			return 0;
175
-		}
176
-		$permissions = $this->superShare->getPermissions();
177
-		// part files and the mount point always have delete permissions
178
-		if ($target === '' || pathinfo($target, PATHINFO_EXTENSION) === 'part') {
179
-			$permissions |= \OCP\Constants::PERMISSION_DELETE;
180
-		}
181
-
182
-		if (\OCP\Util::isSharingDisabledForUser()) {
183
-			$permissions &= ~\OCP\Constants::PERMISSION_SHARE;
184
-		}
185
-
186
-		return $permissions;
187
-	}
188
-
189
-	public function isCreatable($path) {
190
-		return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_CREATE);
191
-	}
192
-
193
-	public function isReadable($path) {
194
-		if (!$this->isValid()) {
195
-			return false;
196
-		}
197
-		if (!$this->file_exists($path)) {
198
-			return false;
199
-		}
200
-		/** @var IStorage $storage */
201
-		/** @var string $internalPath */
202
-		list($storage, $internalPath) = $this->resolvePath($path);
203
-		return $storage->isReadable($internalPath);
204
-	}
205
-
206
-	public function isUpdatable($path) {
207
-		return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_UPDATE);
208
-	}
209
-
210
-	public function isDeletable($path) {
211
-		return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_DELETE);
212
-	}
213
-
214
-	public function isSharable($path) {
215
-		if (\OCP\Util::isSharingDisabledForUser() || !\OC\Share\Share::isResharingAllowed()) {
216
-			return false;
217
-		}
218
-		return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_SHARE);
219
-	}
220
-
221
-	public function fopen($path, $mode) {
222
-		if ($source = $this->getSourcePath($path)) {
223
-			switch ($mode) {
224
-				case 'r+':
225
-				case 'rb+':
226
-				case 'w+':
227
-				case 'wb+':
228
-				case 'x+':
229
-				case 'xb+':
230
-				case 'a+':
231
-				case 'ab+':
232
-				case 'w':
233
-				case 'wb':
234
-				case 'x':
235
-				case 'xb':
236
-				case 'a':
237
-				case 'ab':
238
-					$creatable = $this->isCreatable($path);
239
-					$updatable = $this->isUpdatable($path);
240
-					// if neither permissions given, no need to continue
241
-					if (!$creatable && !$updatable) {
242
-						return false;
243
-					}
244
-
245
-					$exists = $this->file_exists($path);
246
-					// if a file exists, updatable permissions are required
247
-					if ($exists && !$updatable) {
248
-						return false;
249
-					}
250
-
251
-					// part file is allowed if !$creatable but the final file is $updatable
252
-					if (pathinfo($path, PATHINFO_EXTENSION) !== 'part') {
253
-						if (!$exists && !$creatable) {
254
-							return false;
255
-						}
256
-					}
257
-			}
258
-			$info = array(
259
-				'target' => $this->getMountPoint() . $path,
260
-				'source' => $source,
261
-				'mode' => $mode,
262
-			);
263
-			\OCP\Util::emitHook('\OC\Files\Storage\Shared', 'fopen', $info);
264
-			return $this->nonMaskedStorage->fopen($this->getSourcePath($path), $mode);
265
-		}
266
-		return false;
267
-	}
268
-
269
-	/**
270
-	 * see http://php.net/manual/en/function.rename.php
271
-	 *
272
-	 * @param string $path1
273
-	 * @param string $path2
274
-	 * @return bool
275
-	 */
276
-	public function rename($path1, $path2) {
277
-		$this->init();
278
-		$isPartFile = pathinfo($path1, PATHINFO_EXTENSION) === 'part';
279
-		$targetExists = $this->file_exists($path2);
280
-		$sameFodler = dirname($path1) === dirname($path2);
281
-
282
-		if ($targetExists || ($sameFodler && !$isPartFile)) {
283
-			if (!$this->isUpdatable('')) {
284
-				return false;
285
-			}
286
-		} else {
287
-			if (!$this->isCreatable('')) {
288
-				return false;
289
-			}
290
-		}
291
-
292
-		return $this->nonMaskedStorage->rename($this->getSourcePath($path1), $this->getSourcePath($path2));
293
-	}
294
-
295
-	/**
296
-	 * return mount point of share, relative to data/user/files
297
-	 *
298
-	 * @return string
299
-	 */
300
-	public function getMountPoint() {
301
-		return $this->superShare->getTarget();
302
-	}
303
-
304
-	/**
305
-	 * @param string $path
306
-	 */
307
-	public function setMountPoint($path) {
308
-		$this->superShare->setTarget($path);
309
-
310
-		foreach ($this->groupedShares as $share) {
311
-			$share->setTarget($path);
312
-		}
313
-	}
314
-
315
-	/**
316
-	 * get the user who shared the file
317
-	 *
318
-	 * @return string
319
-	 */
320
-	public function getSharedFrom() {
321
-		return $this->superShare->getShareOwner();
322
-	}
323
-
324
-	/**
325
-	 * @return \OCP\Share\IShare
326
-	 */
327
-	public function getShare() {
328
-		return $this->superShare;
329
-	}
330
-
331
-	/**
332
-	 * return share type, can be "file" or "folder"
333
-	 *
334
-	 * @return string
335
-	 */
336
-	public function getItemType() {
337
-		return $this->superShare->getNodeType();
338
-	}
339
-
340
-	public function getCache($path = '', $storage = null) {
341
-		if ($this->cache) {
342
-			return $this->cache;
343
-		}
344
-		if (!$storage) {
345
-			$storage = $this;
346
-		}
347
-		$this->cache = new \OCA\Files_Sharing\Cache($storage, $this->getSourceRootInfo(), $this->superShare);
348
-		return $this->cache;
349
-	}
350
-
351
-	public function getScanner($path = '', $storage = null) {
352
-		if (!$storage) {
353
-			$storage = $this;
354
-		}
355
-		return new \OCA\Files_Sharing\Scanner($storage);
356
-	}
357
-
358
-	public function getPropagator($storage = null) {
359
-		if (isset($this->propagator)) {
360
-			return $this->propagator;
361
-		}
362
-
363
-		if (!$storage) {
364
-			$storage = $this;
365
-		}
366
-		$this->propagator = new \OCA\Files_Sharing\SharedPropagator($storage, \OC::$server->getDatabaseConnection());
367
-		return $this->propagator;
368
-	}
369
-
370
-	public function getOwner($path) {
371
-		return $this->superShare->getShareOwner();
372
-	}
373
-
374
-	/**
375
-	 * unshare complete storage, also the grouped shares
376
-	 *
377
-	 * @return bool
378
-	 */
379
-	public function unshareStorage() {
380
-		foreach ($this->groupedShares as $share) {
381
-			\OC::$server->getShareManager()->deleteFromSelf($share, $this->user);
382
-		}
383
-		return true;
384
-	}
385
-
386
-	/**
387
-	 * @param string $path
388
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
389
-	 * @param \OCP\Lock\ILockingProvider $provider
390
-	 * @throws \OCP\Lock\LockedException
391
-	 */
392
-	public function acquireLock($path, $type, ILockingProvider $provider) {
393
-		/** @var \OCP\Files\Storage $targetStorage */
394
-		list($targetStorage, $targetInternalPath) = $this->resolvePath($path);
395
-		$targetStorage->acquireLock($targetInternalPath, $type, $provider);
396
-		// lock the parent folders of the owner when locking the share as recipient
397
-		if ($path === '') {
398
-			$sourcePath = $this->ownerView->getPath($this->superShare->getNodeId());
399
-			$this->ownerView->lockFile(dirname($sourcePath), ILockingProvider::LOCK_SHARED, true);
400
-		}
401
-	}
402
-
403
-	/**
404
-	 * @param string $path
405
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
406
-	 * @param \OCP\Lock\ILockingProvider $provider
407
-	 */
408
-	public function releaseLock($path, $type, ILockingProvider $provider) {
409
-		/** @var \OCP\Files\Storage $targetStorage */
410
-		list($targetStorage, $targetInternalPath) = $this->resolvePath($path);
411
-		$targetStorage->releaseLock($targetInternalPath, $type, $provider);
412
-		// unlock the parent folders of the owner when unlocking the share as recipient
413
-		if ($path === '') {
414
-			$sourcePath = $this->ownerView->getPath($this->superShare->getNodeId());
415
-			$this->ownerView->unlockFile(dirname($sourcePath), ILockingProvider::LOCK_SHARED, true);
416
-		}
417
-	}
418
-
419
-	/**
420
-	 * @param string $path
421
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
422
-	 * @param \OCP\Lock\ILockingProvider $provider
423
-	 */
424
-	public function changeLock($path, $type, ILockingProvider $provider) {
425
-		/** @var \OCP\Files\Storage $targetStorage */
426
-		list($targetStorage, $targetInternalPath) = $this->resolvePath($path);
427
-		$targetStorage->changeLock($targetInternalPath, $type, $provider);
428
-	}
429
-
430
-	/**
431
-	 * @return array [ available, last_checked ]
432
-	 */
433
-	public function getAvailability() {
434
-		// shares do not participate in availability logic
435
-		return [
436
-			'available' => true,
437
-			'last_checked' => 0
438
-		];
439
-	}
440
-
441
-	/**
442
-	 * @param bool $available
443
-	 */
444
-	public function setAvailability($available) {
445
-		// shares do not participate in availability logic
446
-	}
447
-
448
-	public function getSourceStorage() {
449
-		$this->init();
450
-		return $this->nonMaskedStorage;
451
-	}
452
-
453
-	public function getWrapperStorage() {
454
-		$this->init();
455
-		return $this->storage;
456
-	}
457
-
458
-	public function file_get_contents($path) {
459
-		$info = [
460
-			'target' => $this->getMountPoint() . '/' . $path,
461
-			'source' => $this->getSourcePath($path),
462
-		];
463
-		\OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_get_contents', $info);
464
-		return parent::file_get_contents($path);
465
-	}
466
-
467
-	public function file_put_contents($path, $data) {
468
-		$info = [
469
-			'target' => $this->getMountPoint() . '/' . $path,
470
-			'source' => $this->getSourcePath($path),
471
-		];
472
-		\OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_put_contents', $info);
473
-		return parent::file_put_contents($path, $data);
474
-	}
475
-
476
-	public function setMountOptions(array $options) {
477
-		$this->mountOptions = $options;
478
-	}
50
+    /** @var \OCP\Share\IShare */
51
+    private $superShare;
52
+
53
+    /** @var \OCP\Share\IShare[] */
54
+    private $groupedShares;
55
+
56
+    /**
57
+     * @var \OC\Files\View
58
+     */
59
+    private $ownerView;
60
+
61
+    private $initialized = false;
62
+
63
+    /**
64
+     * @var ICacheEntry
65
+     */
66
+    private $sourceRootInfo;
67
+
68
+    /** @var string */
69
+    private $user;
70
+
71
+    /**
72
+     * @var \OCP\ILogger
73
+     */
74
+    private $logger;
75
+
76
+    /** @var  IStorage */
77
+    private $nonMaskedStorage;
78
+
79
+    private $options;
80
+
81
+    public function __construct($arguments) {
82
+        $this->ownerView = $arguments['ownerView'];
83
+        $this->logger = \OC::$server->getLogger();
84
+
85
+        $this->superShare = $arguments['superShare'];
86
+        $this->groupedShares = $arguments['groupedShares'];
87
+
88
+        $this->user = $arguments['user'];
89
+
90
+        parent::__construct([
91
+            'storage' => null,
92
+            'root' => null,
93
+        ]);
94
+    }
95
+
96
+    /**
97
+     * @return ICacheEntry
98
+     */
99
+    private function getSourceRootInfo() {
100
+        if (is_null($this->sourceRootInfo)) {
101
+            if (is_null($this->superShare->getNodeCacheEntry())) {
102
+                $this->sourceRootInfo = $this->nonMaskedStorage->getCache()->get($this->rootPath);
103
+            } else {
104
+                $this->sourceRootInfo = $this->superShare->getNodeCacheEntry();
105
+            }
106
+        }
107
+        return $this->sourceRootInfo;
108
+    }
109
+
110
+    private function init() {
111
+        if ($this->initialized) {
112
+            return;
113
+        }
114
+        $this->initialized = true;
115
+        try {
116
+            Filesystem::initMountPoints($this->superShare->getShareOwner());
117
+            $sourcePath = $this->ownerView->getPath($this->superShare->getNodeId());
118
+            list($this->nonMaskedStorage, $this->rootPath) = $this->ownerView->resolvePath($sourcePath);
119
+            $this->storage = new PermissionsMask([
120
+                'storage' => $this->nonMaskedStorage,
121
+                'mask' => $this->superShare->getPermissions()
122
+            ]);
123
+        } catch (NotFoundException $e) {
124
+            $this->storage = new FailedStorage(['exception' => $e]);
125
+            $this->rootPath = '';
126
+        } catch (\Exception $e) {
127
+            $this->storage = new FailedStorage(['exception' => $e]);
128
+            $this->rootPath = '';
129
+            $this->logger->logException($e);
130
+        }
131
+    }
132
+
133
+    /**
134
+     * @inheritdoc
135
+     */
136
+    public function instanceOfStorage($class) {
137
+        if ($class === '\OC\Files\Storage\Common') {
138
+            return true;
139
+        }
140
+        if (in_array($class, ['\OC\Files\Storage\Home', '\OC\Files\ObjectStore\HomeObjectStoreStorage'])) {
141
+            return false;
142
+        }
143
+        return parent::instanceOfStorage($class);
144
+    }
145
+
146
+    /**
147
+     * @return string
148
+     */
149
+    public function getShareId() {
150
+        return $this->superShare->getId();
151
+    }
152
+
153
+    private function isValid() {
154
+        return $this->getSourceRootInfo() && ($this->getSourceRootInfo()->getPermissions() & Constants::PERMISSION_SHARE) === Constants::PERMISSION_SHARE;
155
+    }
156
+
157
+    /**
158
+     * get id of the mount point
159
+     *
160
+     * @return string
161
+     */
162
+    public function getId() {
163
+        return 'shared::' . $this->getMountPoint();
164
+    }
165
+
166
+    /**
167
+     * Get the permissions granted for a shared file
168
+     *
169
+     * @param string $target Shared target file path
170
+     * @return int CRUDS permissions granted
171
+     */
172
+    public function getPermissions($target = '') {
173
+        if (!$this->isValid()) {
174
+            return 0;
175
+        }
176
+        $permissions = $this->superShare->getPermissions();
177
+        // part files and the mount point always have delete permissions
178
+        if ($target === '' || pathinfo($target, PATHINFO_EXTENSION) === 'part') {
179
+            $permissions |= \OCP\Constants::PERMISSION_DELETE;
180
+        }
181
+
182
+        if (\OCP\Util::isSharingDisabledForUser()) {
183
+            $permissions &= ~\OCP\Constants::PERMISSION_SHARE;
184
+        }
185
+
186
+        return $permissions;
187
+    }
188
+
189
+    public function isCreatable($path) {
190
+        return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_CREATE);
191
+    }
192
+
193
+    public function isReadable($path) {
194
+        if (!$this->isValid()) {
195
+            return false;
196
+        }
197
+        if (!$this->file_exists($path)) {
198
+            return false;
199
+        }
200
+        /** @var IStorage $storage */
201
+        /** @var string $internalPath */
202
+        list($storage, $internalPath) = $this->resolvePath($path);
203
+        return $storage->isReadable($internalPath);
204
+    }
205
+
206
+    public function isUpdatable($path) {
207
+        return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_UPDATE);
208
+    }
209
+
210
+    public function isDeletable($path) {
211
+        return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_DELETE);
212
+    }
213
+
214
+    public function isSharable($path) {
215
+        if (\OCP\Util::isSharingDisabledForUser() || !\OC\Share\Share::isResharingAllowed()) {
216
+            return false;
217
+        }
218
+        return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_SHARE);
219
+    }
220
+
221
+    public function fopen($path, $mode) {
222
+        if ($source = $this->getSourcePath($path)) {
223
+            switch ($mode) {
224
+                case 'r+':
225
+                case 'rb+':
226
+                case 'w+':
227
+                case 'wb+':
228
+                case 'x+':
229
+                case 'xb+':
230
+                case 'a+':
231
+                case 'ab+':
232
+                case 'w':
233
+                case 'wb':
234
+                case 'x':
235
+                case 'xb':
236
+                case 'a':
237
+                case 'ab':
238
+                    $creatable = $this->isCreatable($path);
239
+                    $updatable = $this->isUpdatable($path);
240
+                    // if neither permissions given, no need to continue
241
+                    if (!$creatable && !$updatable) {
242
+                        return false;
243
+                    }
244
+
245
+                    $exists = $this->file_exists($path);
246
+                    // if a file exists, updatable permissions are required
247
+                    if ($exists && !$updatable) {
248
+                        return false;
249
+                    }
250
+
251
+                    // part file is allowed if !$creatable but the final file is $updatable
252
+                    if (pathinfo($path, PATHINFO_EXTENSION) !== 'part') {
253
+                        if (!$exists && !$creatable) {
254
+                            return false;
255
+                        }
256
+                    }
257
+            }
258
+            $info = array(
259
+                'target' => $this->getMountPoint() . $path,
260
+                'source' => $source,
261
+                'mode' => $mode,
262
+            );
263
+            \OCP\Util::emitHook('\OC\Files\Storage\Shared', 'fopen', $info);
264
+            return $this->nonMaskedStorage->fopen($this->getSourcePath($path), $mode);
265
+        }
266
+        return false;
267
+    }
268
+
269
+    /**
270
+     * see http://php.net/manual/en/function.rename.php
271
+     *
272
+     * @param string $path1
273
+     * @param string $path2
274
+     * @return bool
275
+     */
276
+    public function rename($path1, $path2) {
277
+        $this->init();
278
+        $isPartFile = pathinfo($path1, PATHINFO_EXTENSION) === 'part';
279
+        $targetExists = $this->file_exists($path2);
280
+        $sameFodler = dirname($path1) === dirname($path2);
281
+
282
+        if ($targetExists || ($sameFodler && !$isPartFile)) {
283
+            if (!$this->isUpdatable('')) {
284
+                return false;
285
+            }
286
+        } else {
287
+            if (!$this->isCreatable('')) {
288
+                return false;
289
+            }
290
+        }
291
+
292
+        return $this->nonMaskedStorage->rename($this->getSourcePath($path1), $this->getSourcePath($path2));
293
+    }
294
+
295
+    /**
296
+     * return mount point of share, relative to data/user/files
297
+     *
298
+     * @return string
299
+     */
300
+    public function getMountPoint() {
301
+        return $this->superShare->getTarget();
302
+    }
303
+
304
+    /**
305
+     * @param string $path
306
+     */
307
+    public function setMountPoint($path) {
308
+        $this->superShare->setTarget($path);
309
+
310
+        foreach ($this->groupedShares as $share) {
311
+            $share->setTarget($path);
312
+        }
313
+    }
314
+
315
+    /**
316
+     * get the user who shared the file
317
+     *
318
+     * @return string
319
+     */
320
+    public function getSharedFrom() {
321
+        return $this->superShare->getShareOwner();
322
+    }
323
+
324
+    /**
325
+     * @return \OCP\Share\IShare
326
+     */
327
+    public function getShare() {
328
+        return $this->superShare;
329
+    }
330
+
331
+    /**
332
+     * return share type, can be "file" or "folder"
333
+     *
334
+     * @return string
335
+     */
336
+    public function getItemType() {
337
+        return $this->superShare->getNodeType();
338
+    }
339
+
340
+    public function getCache($path = '', $storage = null) {
341
+        if ($this->cache) {
342
+            return $this->cache;
343
+        }
344
+        if (!$storage) {
345
+            $storage = $this;
346
+        }
347
+        $this->cache = new \OCA\Files_Sharing\Cache($storage, $this->getSourceRootInfo(), $this->superShare);
348
+        return $this->cache;
349
+    }
350
+
351
+    public function getScanner($path = '', $storage = null) {
352
+        if (!$storage) {
353
+            $storage = $this;
354
+        }
355
+        return new \OCA\Files_Sharing\Scanner($storage);
356
+    }
357
+
358
+    public function getPropagator($storage = null) {
359
+        if (isset($this->propagator)) {
360
+            return $this->propagator;
361
+        }
362
+
363
+        if (!$storage) {
364
+            $storage = $this;
365
+        }
366
+        $this->propagator = new \OCA\Files_Sharing\SharedPropagator($storage, \OC::$server->getDatabaseConnection());
367
+        return $this->propagator;
368
+    }
369
+
370
+    public function getOwner($path) {
371
+        return $this->superShare->getShareOwner();
372
+    }
373
+
374
+    /**
375
+     * unshare complete storage, also the grouped shares
376
+     *
377
+     * @return bool
378
+     */
379
+    public function unshareStorage() {
380
+        foreach ($this->groupedShares as $share) {
381
+            \OC::$server->getShareManager()->deleteFromSelf($share, $this->user);
382
+        }
383
+        return true;
384
+    }
385
+
386
+    /**
387
+     * @param string $path
388
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
389
+     * @param \OCP\Lock\ILockingProvider $provider
390
+     * @throws \OCP\Lock\LockedException
391
+     */
392
+    public function acquireLock($path, $type, ILockingProvider $provider) {
393
+        /** @var \OCP\Files\Storage $targetStorage */
394
+        list($targetStorage, $targetInternalPath) = $this->resolvePath($path);
395
+        $targetStorage->acquireLock($targetInternalPath, $type, $provider);
396
+        // lock the parent folders of the owner when locking the share as recipient
397
+        if ($path === '') {
398
+            $sourcePath = $this->ownerView->getPath($this->superShare->getNodeId());
399
+            $this->ownerView->lockFile(dirname($sourcePath), ILockingProvider::LOCK_SHARED, true);
400
+        }
401
+    }
402
+
403
+    /**
404
+     * @param string $path
405
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
406
+     * @param \OCP\Lock\ILockingProvider $provider
407
+     */
408
+    public function releaseLock($path, $type, ILockingProvider $provider) {
409
+        /** @var \OCP\Files\Storage $targetStorage */
410
+        list($targetStorage, $targetInternalPath) = $this->resolvePath($path);
411
+        $targetStorage->releaseLock($targetInternalPath, $type, $provider);
412
+        // unlock the parent folders of the owner when unlocking the share as recipient
413
+        if ($path === '') {
414
+            $sourcePath = $this->ownerView->getPath($this->superShare->getNodeId());
415
+            $this->ownerView->unlockFile(dirname($sourcePath), ILockingProvider::LOCK_SHARED, true);
416
+        }
417
+    }
418
+
419
+    /**
420
+     * @param string $path
421
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
422
+     * @param \OCP\Lock\ILockingProvider $provider
423
+     */
424
+    public function changeLock($path, $type, ILockingProvider $provider) {
425
+        /** @var \OCP\Files\Storage $targetStorage */
426
+        list($targetStorage, $targetInternalPath) = $this->resolvePath($path);
427
+        $targetStorage->changeLock($targetInternalPath, $type, $provider);
428
+    }
429
+
430
+    /**
431
+     * @return array [ available, last_checked ]
432
+     */
433
+    public function getAvailability() {
434
+        // shares do not participate in availability logic
435
+        return [
436
+            'available' => true,
437
+            'last_checked' => 0
438
+        ];
439
+    }
440
+
441
+    /**
442
+     * @param bool $available
443
+     */
444
+    public function setAvailability($available) {
445
+        // shares do not participate in availability logic
446
+    }
447
+
448
+    public function getSourceStorage() {
449
+        $this->init();
450
+        return $this->nonMaskedStorage;
451
+    }
452
+
453
+    public function getWrapperStorage() {
454
+        $this->init();
455
+        return $this->storage;
456
+    }
457
+
458
+    public function file_get_contents($path) {
459
+        $info = [
460
+            'target' => $this->getMountPoint() . '/' . $path,
461
+            'source' => $this->getSourcePath($path),
462
+        ];
463
+        \OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_get_contents', $info);
464
+        return parent::file_get_contents($path);
465
+    }
466
+
467
+    public function file_put_contents($path, $data) {
468
+        $info = [
469
+            'target' => $this->getMountPoint() . '/' . $path,
470
+            'source' => $this->getSourcePath($path),
471
+        ];
472
+        \OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_put_contents', $info);
473
+        return parent::file_put_contents($path, $data);
474
+    }
475
+
476
+    public function setMountOptions(array $options) {
477
+        $this->mountOptions = $options;
478
+    }
479 479
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
 	 * @return string
161 161
 	 */
162 162
 	public function getId() {
163
-		return 'shared::' . $this->getMountPoint();
163
+		return 'shared::'.$this->getMountPoint();
164 164
 	}
165 165
 
166 166
 	/**
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 					}
257 257
 			}
258 258
 			$info = array(
259
-				'target' => $this->getMountPoint() . $path,
259
+				'target' => $this->getMountPoint().$path,
260 260
 				'source' => $source,
261 261
 				'mode' => $mode,
262 262
 			);
@@ -457,7 +457,7 @@  discard block
 block discarded – undo
457 457
 
458 458
 	public function file_get_contents($path) {
459 459
 		$info = [
460
-			'target' => $this->getMountPoint() . '/' . $path,
460
+			'target' => $this->getMountPoint().'/'.$path,
461 461
 			'source' => $this->getSourcePath($path),
462 462
 		];
463 463
 		\OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_get_contents', $info);
@@ -466,7 +466,7 @@  discard block
 block discarded – undo
466 466
 
467 467
 	public function file_put_contents($path, $data) {
468 468
 		$info = [
469
-			'target' => $this->getMountPoint() . '/' . $path,
469
+			'target' => $this->getMountPoint().'/'.$path,
470 470
 			'source' => $this->getSourcePath($path),
471 471
 		];
472 472
 		\OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_put_contents', $info);
Please login to merge, or discard this patch.
apps/provisioning_api/lib/Controller/UsersController.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -225,7 +225,7 @@
 block discarded – undo
225 225
 	/**
226 226
 	 * creates a array with all user data
227 227
 	 *
228
-	 * @param $userId
228
+	 * @param string $userId
229 229
 	 * @return array
230 230
 	 * @throws OCSException
231 231
 	 */
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -335,7 +335,7 @@
 block discarded – undo
335 335
 					}
336 336
 					if($quota === 0) {
337 337
 						$quota = 'default';
338
-					}else if($quota === -1) {
338
+					} else if($quota === -1) {
339 339
 						$quota = 'none';
340 340
 					} else {
341 341
 						$quota = \OCP\Util::humanFileSize($quota);
Please login to merge, or discard this patch.
Spacing   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 		// Admin? Or SubAdmin?
134 134
 		$uid = $user->getUID();
135 135
 		$subAdminManager = $this->groupManager->getSubAdmin();
136
-		if($this->groupManager->isAdmin($uid)){
136
+		if ($this->groupManager->isAdmin($uid)) {
137 137
 			$users = $this->userManager->search($search, $limit, $offset);
138 138
 		} else if ($subAdminManager->isSubAdmin($user)) {
139 139
 			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 				$subAdminOfGroups[$key] = $group->getGID();
142 142
 			}
143 143
 
144
-			if($offset === null) {
144
+			if ($offset === null) {
145 145
 				$offset = 0;
146 146
 			}
147 147
 
@@ -175,22 +175,22 @@  discard block
 block discarded – undo
175 175
 		$isAdmin = $this->groupManager->isAdmin($user->getUID());
176 176
 		$subAdminManager = $this->groupManager->getSubAdmin();
177 177
 
178
-		if($this->userManager->userExists($userid)) {
178
+		if ($this->userManager->userExists($userid)) {
179 179
 			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
180 180
 			throw new OCSException('User already exists', 102);
181 181
 		}
182 182
 
183
-		if(is_array($groups)) {
183
+		if (is_array($groups)) {
184 184
 			foreach ($groups as $group) {
185
-				if(!$this->groupManager->groupExists($group)) {
185
+				if (!$this->groupManager->groupExists($group)) {
186 186
 					throw new OCSException('group '.$group.' does not exist', 104);
187 187
 				}
188
-				if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
189
-					throw new OCSException('insufficient privileges for group '. $group, 105);
188
+				if (!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
189
+					throw new OCSException('insufficient privileges for group '.$group, 105);
190 190
 				}
191 191
 			}
192 192
 		} else {
193
-			if(!$isAdmin) {
193
+			if (!$isAdmin) {
194 194
 				throw new OCSException('no group specified (required for subadmins)', 106);
195 195
 			}
196 196
 		}
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
 	public function getCurrentUser() {
240 240
 		$user = $this->userSession->getUser();
241 241
 		if ($user) {
242
-			$data =  $this->getUserData($user->getUID());
242
+			$data = $this->getUserData($user->getUID());
243 243
 			// rename "displayname" to "display-name" only for this call to keep
244 244
 			// the API stable.
245 245
 			$data['display-name'] = $data['displayname'];
@@ -265,17 +265,17 @@  discard block
 block discarded – undo
265 265
 
266 266
 		// Check if the target user exists
267 267
 		$targetUserObject = $this->userManager->get($userId);
268
-		if($targetUserObject === null) {
268
+		if ($targetUserObject === null) {
269 269
 			throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
270 270
 		}
271 271
 
272 272
 		// Admin? Or SubAdmin?
273
-		if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
273
+		if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())
274 274
 			|| $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
275 275
 			$data['enabled'] = $this->config->getUserValue($userId, 'core', 'enabled', 'true');
276 276
 		} else {
277 277
 			// Check they are looking up themselves
278
-			if($currentLoggedInUser->getUID() !== $userId) {
278
+			if ($currentLoggedInUser->getUID() !== $userId) {
279 279
 				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
280 280
 			}
281 281
 		}
@@ -319,24 +319,24 @@  discard block
 block discarded – undo
319 319
 		$currentLoggedInUser = $this->userSession->getUser();
320 320
 
321 321
 		$targetUser = $this->userManager->get($userId);
322
-		if($targetUser === null) {
322
+		if ($targetUser === null) {
323 323
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
324 324
 		}
325 325
 
326 326
 		$permittedFields = [];
327
-		if($userId === $currentLoggedInUser->getUID()) {
327
+		if ($userId === $currentLoggedInUser->getUID()) {
328 328
 			// Editing self (display, email)
329 329
 			$permittedFields[] = 'display';
330 330
 			$permittedFields[] = 'email';
331 331
 			$permittedFields[] = 'password';
332 332
 			// If admin they can edit their own quota
333
-			if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
333
+			if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
334 334
 				$permittedFields[] = 'quota';
335 335
 			}
336 336
 		} else {
337 337
 			// Check if admin / subadmin
338 338
 			$subAdminManager = $this->groupManager->getSubAdmin();
339
-			if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
339
+			if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
340 340
 			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
341 341
 				// They have permissions over the user
342 342
 				$permittedFields[] = 'display';
@@ -349,17 +349,17 @@  discard block
 block discarded – undo
349 349
 			}
350 350
 		}
351 351
 		// Check if permitted to edit this field
352
-		if(!in_array($key, $permittedFields)) {
352
+		if (!in_array($key, $permittedFields)) {
353 353
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
354 354
 		}
355 355
 		// Process the edit
356
-		switch($key) {
356
+		switch ($key) {
357 357
 			case 'display':
358 358
 				$targetUser->setDisplayName($value);
359 359
 				break;
360 360
 			case 'quota':
361 361
 				$quota = $value;
362
-				if($quota !== 'none' && $quota !== 'default') {
362
+				if ($quota !== 'none' && $quota !== 'default') {
363 363
 					if (is_numeric($quota)) {
364 364
 						$quota = (float) $quota;
365 365
 					} else {
@@ -368,9 +368,9 @@  discard block
 block discarded – undo
368 368
 					if ($quota === false) {
369 369
 						throw new OCSException('Invalid quota value '.$value, 103);
370 370
 					}
371
-					if($quota === 0) {
371
+					if ($quota === 0) {
372 372
 						$quota = 'default';
373
-					}else if($quota === -1) {
373
+					} else if ($quota === -1) {
374 374
 						$quota = 'none';
375 375
 					} else {
376 376
 						$quota = \OCP\Util::humanFileSize($quota);
@@ -382,7 +382,7 @@  discard block
 block discarded – undo
382 382
 				$targetUser->setPassword($value);
383 383
 				break;
384 384
 			case 'email':
385
-				if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
385
+				if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
386 386
 					$targetUser->setEMailAddress($value);
387 387
 				} else {
388 388
 					throw new OCSException('', 102);
@@ -408,18 +408,18 @@  discard block
 block discarded – undo
408 408
 
409 409
 		$targetUser = $this->userManager->get($userId);
410 410
 
411
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
411
+		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
412 412
 			throw new OCSException('', 101);
413 413
 		}
414 414
 
415 415
 		// If not permitted
416 416
 		$subAdminManager = $this->groupManager->getSubAdmin();
417
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
417
+		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
418 418
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
419 419
 		}
420 420
 
421 421
 		// Go ahead with the delete
422
-		if($targetUser->delete()) {
422
+		if ($targetUser->delete()) {
423 423
 			return new DataResponse();
424 424
 		} else {
425 425
 			throw new OCSException('', 101);
@@ -463,13 +463,13 @@  discard block
 block discarded – undo
463 463
 		$currentLoggedInUser = $this->userSession->getUser();
464 464
 
465 465
 		$targetUser = $this->userManager->get($userId);
466
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
466
+		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
467 467
 			throw new OCSException('', 101);
468 468
 		}
469 469
 
470 470
 		// If not permitted
471 471
 		$subAdminManager = $this->groupManager->getSubAdmin();
472
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
472
+		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
473 473
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
474 474
 		}
475 475
 
@@ -490,11 +490,11 @@  discard block
 block discarded – undo
490 490
 		$loggedInUser = $this->userSession->getUser();
491 491
 
492 492
 		$targetUser = $this->userManager->get($userId);
493
-		if($targetUser === null) {
493
+		if ($targetUser === null) {
494 494
 			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
495 495
 		}
496 496
 
497
-		if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
497
+		if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
498 498
 			// Self lookup or admin lookup
499 499
 			return new DataResponse([
500 500
 				'groups' => $this->groupManager->getUserGroupIds($targetUser)
@@ -503,7 +503,7 @@  discard block
 block discarded – undo
503 503
 			$subAdminManager = $this->groupManager->getSubAdmin();
504 504
 
505 505
 			// Looking up someone else
506
-			if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
506
+			if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
507 507
 				// Return the group that the method caller is subadmin of for the user in question
508 508
 				/** @var IGroup[] $getSubAdminsGroups */
509 509
 				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
@@ -533,16 +533,16 @@  discard block
 block discarded – undo
533 533
 	 * @throws OCSException
534 534
 	 */
535 535
 	public function addToGroup($userId, $groupid = '') {
536
-		if($groupid === '') {
536
+		if ($groupid === '') {
537 537
 			throw new OCSException('', 101);
538 538
 		}
539 539
 
540 540
 		$group = $this->groupManager->get($groupid);
541 541
 		$targetUser = $this->userManager->get($userId);
542
-		if($group === null) {
542
+		if ($group === null) {
543 543
 			throw new OCSException('', 102);
544 544
 		}
545
-		if($targetUser === null) {
545
+		if ($targetUser === null) {
546 546
 			throw new OCSException('', 103);
547 547
 		}
548 548
 
@@ -570,17 +570,17 @@  discard block
 block discarded – undo
570 570
 	public function removeFromGroup($userId, $groupid) {
571 571
 		$loggedInUser = $this->userSession->getUser();
572 572
 
573
-		if($groupid === null) {
573
+		if ($groupid === null) {
574 574
 			throw new OCSException('', 101);
575 575
 		}
576 576
 
577 577
 		$group = $this->groupManager->get($groupid);
578
-		if($group === null) {
578
+		if ($group === null) {
579 579
 			throw new OCSException('', 102);
580 580
 		}
581 581
 
582 582
 		$targetUser = $this->userManager->get($userId);
583
-		if($targetUser === null) {
583
+		if ($targetUser === null) {
584 584
 			throw new OCSException('', 103);
585 585
 		}
586 586
 
@@ -604,7 +604,7 @@  discard block
 block discarded – undo
604 604
 		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
605 605
 			/** @var IGroup[] $subAdminGroups */
606 606
 			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
607
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
607
+			$subAdminGroups = array_map(function(IGroup $subAdminGroup) {
608 608
 				return $subAdminGroup->getGID();
609 609
 			}, $subAdminGroups);
610 610
 			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
@@ -636,15 +636,15 @@  discard block
 block discarded – undo
636 636
 		$user = $this->userManager->get($userId);
637 637
 
638 638
 		// Check if the user exists
639
-		if($user === null) {
639
+		if ($user === null) {
640 640
 			throw new OCSException('User does not exist', 101);
641 641
 		}
642 642
 		// Check if group exists
643
-		if($group === null) {
644
-			throw new OCSException('Group:'.$groupid.' does not exist',  102);
643
+		if ($group === null) {
644
+			throw new OCSException('Group:'.$groupid.' does not exist', 102);
645 645
 		}
646 646
 		// Check if trying to make subadmin of admin group
647
-		if(strtolower($groupid) === 'admin') {
647
+		if (strtolower($groupid) === 'admin') {
648 648
 			throw new OCSException('Cannot create subadmins for admin group', 103);
649 649
 		}
650 650
 
@@ -655,7 +655,7 @@  discard block
 block discarded – undo
655 655
 			return new DataResponse();
656 656
 		}
657 657
 		// Go
658
-		if($subAdminManager->createSubAdmin($user, $group)) {
658
+		if ($subAdminManager->createSubAdmin($user, $group)) {
659 659
 			return new DataResponse();
660 660
 		} else {
661 661
 			throw new OCSException('Unknown error occurred', 103);
@@ -678,20 +678,20 @@  discard block
 block discarded – undo
678 678
 		$subAdminManager = $this->groupManager->getSubAdmin();
679 679
 
680 680
 		// Check if the user exists
681
-		if($user === null) {
681
+		if ($user === null) {
682 682
 			throw new OCSException('User does not exist', 101);
683 683
 		}
684 684
 		// Check if the group exists
685
-		if($group === null) {
685
+		if ($group === null) {
686 686
 			throw new OCSException('Group does not exist', 101);
687 687
 		}
688 688
 		// Check if they are a subadmin of this said group
689
-		if(!$subAdminManager->isSubAdminofGroup($user, $group)) {
689
+		if (!$subAdminManager->isSubAdminofGroup($user, $group)) {
690 690
 			throw new OCSException('User is not a subadmin of this group', 102);
691 691
 		}
692 692
 
693 693
 		// Go
694
-		if($subAdminManager->deleteSubAdmin($user, $group)) {
694
+		if ($subAdminManager->deleteSubAdmin($user, $group)) {
695 695
 			return new DataResponse();
696 696
 		} else {
697 697
 			throw new OCSException('Unknown error occurred', 103);
@@ -708,7 +708,7 @@  discard block
 block discarded – undo
708 708
 	public function getUserSubAdminGroups($userId) {
709 709
 		$user = $this->userManager->get($userId);
710 710
 		// Check if the user exists
711
-		if($user === null) {
711
+		if ($user === null) {
712 712
 			throw new OCSException('User does not exist', 101);
713 713
 		}
714 714
 
@@ -718,7 +718,7 @@  discard block
 block discarded – undo
718 718
 			$groups[$key] = $group->getGID();
719 719
 		}
720 720
 
721
-		if(!$groups) {
721
+		if (!$groups) {
722 722
 			throw new OCSException('Unknown error occurred', 102);
723 723
 		} else {
724 724
 			return new DataResponse($groups);
@@ -763,13 +763,13 @@  discard block
 block discarded – undo
763 763
 		$currentLoggedInUser = $this->userSession->getUser();
764 764
 
765 765
 		$targetUser = $this->userManager->get($userId);
766
-		if($targetUser === null) {
766
+		if ($targetUser === null) {
767 767
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
768 768
 		}
769 769
 
770 770
 		// Check if admin / subadmin
771 771
 		$subAdminManager = $this->groupManager->getSubAdmin();
772
-		if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
772
+		if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
773 773
 			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
774 774
 			// No rights
775 775
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
@@ -811,8 +811,8 @@  discard block
 block discarded – undo
811 811
 			$message->setPlainBody($plainTextMailContent);
812 812
 			$message->setFrom([$this->fromMailAddress => $this->defaults->getName()]);
813 813
 			$this->mailer->send($message);
814
-		} catch(\Exception $e) {
815
-			$this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
814
+		} catch (\Exception $e) {
815
+			$this->logger->error("Can't send new user mail to $email: ".$e->getMessage(), array('app' => 'settings'));
816 816
 			throw new OCSException('Sending email failed', 102);
817 817
 		}
818 818
 
Please login to merge, or discard this patch.
Indentation   +767 added lines, -767 removed lines patch added patch discarded remove patch
@@ -50,771 +50,771 @@
 block discarded – undo
50 50
 
51 51
 class UsersController extends OCSController {
52 52
 
53
-	/** @var IUserManager */
54
-	private $userManager;
55
-	/** @var IConfig */
56
-	private $config;
57
-	/** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface
58
-	private $groupManager;
59
-	/** @var IUserSession */
60
-	private $userSession;
61
-	/** @var AccountManager */
62
-	private $accountManager;
63
-	/** @var ILogger */
64
-	private $logger;
65
-	/** @var string */
66
-	private $fromMailAddress;
67
-	/** @var IURLGenerator */
68
-	private $urlGenerator;
69
-	/** @var IMailer */
70
-	private $mailer;
71
-	/** @var \OC_Defaults */
72
-	private $defaults;
73
-	/** @var IFactory */
74
-	private $l10nFactory;
75
-
76
-	/**
77
-	 * @param string $appName
78
-	 * @param IRequest $request
79
-	 * @param IUserManager $userManager
80
-	 * @param IConfig $config
81
-	 * @param IGroupManager $groupManager
82
-	 * @param IUserSession $userSession
83
-	 * @param AccountManager $accountManager
84
-	 * @param ILogger $logger
85
-	 * @param string $fromMailAddress
86
-	 * @param IURLGenerator $urlGenerator
87
-	 * @param IMailer $mailer
88
-	 * @param \OC_Defaults $defaults
89
-	 * @param IFactory $l10nFactory
90
-	 */
91
-	public function __construct($appName,
92
-								IRequest $request,
93
-								IUserManager $userManager,
94
-								IConfig $config,
95
-								IGroupManager $groupManager,
96
-								IUserSession $userSession,
97
-								AccountManager $accountManager,
98
-								ILogger $logger,
99
-								$fromMailAddress,
100
-								IURLGenerator $urlGenerator,
101
-								IMailer $mailer,
102
-								\OC_Defaults $defaults,
103
-								IFactory $l10nFactory) {
104
-		parent::__construct($appName, $request);
105
-
106
-		$this->userManager = $userManager;
107
-		$this->config = $config;
108
-		$this->groupManager = $groupManager;
109
-		$this->userSession = $userSession;
110
-		$this->accountManager = $accountManager;
111
-		$this->logger = $logger;
112
-		$this->fromMailAddress = $fromMailAddress;
113
-		$this->urlGenerator = $urlGenerator;
114
-		$this->mailer = $mailer;
115
-		$this->defaults = $defaults;
116
-		$this->l10nFactory = $l10nFactory;
117
-	}
118
-
119
-	/**
120
-	 * @NoAdminRequired
121
-	 *
122
-	 * returns a list of users
123
-	 *
124
-	 * @param string $search
125
-	 * @param int $limit
126
-	 * @param int $offset
127
-	 * @return DataResponse
128
-	 */
129
-	public function getUsers($search = '', $limit = null, $offset = null) {
130
-		$user = $this->userSession->getUser();
131
-		$users = [];
132
-
133
-		// Admin? Or SubAdmin?
134
-		$uid = $user->getUID();
135
-		$subAdminManager = $this->groupManager->getSubAdmin();
136
-		if($this->groupManager->isAdmin($uid)){
137
-			$users = $this->userManager->search($search, $limit, $offset);
138
-		} else if ($subAdminManager->isSubAdmin($user)) {
139
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
140
-			foreach ($subAdminOfGroups as $key => $group) {
141
-				$subAdminOfGroups[$key] = $group->getGID();
142
-			}
143
-
144
-			if($offset === null) {
145
-				$offset = 0;
146
-			}
147
-
148
-			$users = [];
149
-			foreach ($subAdminOfGroups as $group) {
150
-				$users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search));
151
-			}
152
-
153
-			$users = array_slice($users, $offset, $limit);
154
-		}
155
-
156
-		$users = array_keys($users);
157
-
158
-		return new DataResponse([
159
-			'users' => $users
160
-		]);
161
-	}
162
-
163
-	/**
164
-	 * @PasswordConfirmationRequired
165
-	 * @NoAdminRequired
166
-	 *
167
-	 * @param string $userid
168
-	 * @param string $password
169
-	 * @param array $groups
170
-	 * @return DataResponse
171
-	 * @throws OCSException
172
-	 */
173
-	public function addUser($userid, $password, $groups = null) {
174
-		$user = $this->userSession->getUser();
175
-		$isAdmin = $this->groupManager->isAdmin($user->getUID());
176
-		$subAdminManager = $this->groupManager->getSubAdmin();
177
-
178
-		if($this->userManager->userExists($userid)) {
179
-			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
180
-			throw new OCSException('User already exists', 102);
181
-		}
182
-
183
-		if(is_array($groups)) {
184
-			foreach ($groups as $group) {
185
-				if(!$this->groupManager->groupExists($group)) {
186
-					throw new OCSException('group '.$group.' does not exist', 104);
187
-				}
188
-				if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
189
-					throw new OCSException('insufficient privileges for group '. $group, 105);
190
-				}
191
-			}
192
-		} else {
193
-			if(!$isAdmin) {
194
-				throw new OCSException('no group specified (required for subadmins)', 106);
195
-			}
196
-		}
197
-
198
-		try {
199
-			$newUser = $this->userManager->createUser($userid, $password);
200
-			$this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
201
-
202
-			if (is_array($groups)) {
203
-				foreach ($groups as $group) {
204
-					$this->groupManager->get($group)->addUser($newUser);
205
-					$this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
206
-				}
207
-			}
208
-			return new DataResponse();
209
-		} catch (\Exception $e) {
210
-			$this->logger->error('Failed addUser attempt with exception: '.$e->getMessage(), ['app' => 'ocs_api']);
211
-			throw new OCSException('Bad request', 101);
212
-		}
213
-	}
214
-
215
-	/**
216
-	 * @NoAdminRequired
217
-	 * @NoSubAdminRequired
218
-	 *
219
-	 * gets user info
220
-	 *
221
-	 * @param string $userId
222
-	 * @return DataResponse
223
-	 * @throws OCSException
224
-	 */
225
-	public function getUser($userId) {
226
-		$data = $this->getUserData($userId);
227
-		return new DataResponse($data);
228
-	}
229
-
230
-	/**
231
-	 * @NoAdminRequired
232
-	 * @NoSubAdminRequired
233
-	 *
234
-	 * gets user info from the currently logged in user
235
-	 *
236
-	 * @return DataResponse
237
-	 * @throws OCSException
238
-	 */
239
-	public function getCurrentUser() {
240
-		$user = $this->userSession->getUser();
241
-		if ($user) {
242
-			$data =  $this->getUserData($user->getUID());
243
-			// rename "displayname" to "display-name" only for this call to keep
244
-			// the API stable.
245
-			$data['display-name'] = $data['displayname'];
246
-			unset($data['displayname']);
247
-			return new DataResponse($data);
248
-
249
-		}
250
-
251
-		throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
252
-	}
253
-
254
-	/**
255
-	 * creates a array with all user data
256
-	 *
257
-	 * @param $userId
258
-	 * @return array
259
-	 * @throws OCSException
260
-	 */
261
-	protected function getUserData($userId) {
262
-		$currentLoggedInUser = $this->userSession->getUser();
263
-
264
-		$data = [];
265
-
266
-		// Check if the target user exists
267
-		$targetUserObject = $this->userManager->get($userId);
268
-		if($targetUserObject === null) {
269
-			throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
270
-		}
271
-
272
-		// Admin? Or SubAdmin?
273
-		if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
274
-			|| $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
275
-			$data['enabled'] = $this->config->getUserValue($userId, 'core', 'enabled', 'true');
276
-		} else {
277
-			// Check they are looking up themselves
278
-			if($currentLoggedInUser->getUID() !== $userId) {
279
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
280
-			}
281
-		}
282
-
283
-		$userAccount = $this->accountManager->getUser($targetUserObject);
284
-		$groups = $this->groupManager->getUserGroups($targetUserObject);
285
-		$gids = [];
286
-		foreach ($groups as $group) {
287
-			$gids[] = $group->getDisplayName();
288
-		}
289
-
290
-		// Find the data
291
-		$data['id'] = $targetUserObject->getUID();
292
-		$data['quota'] = $this->fillStorageInfo($userId);
293
-		$data['email'] = $targetUserObject->getEMailAddress();
294
-		$data['displayname'] = $targetUserObject->getDisplayName();
295
-		$data['phone'] = $userAccount[\OC\Accounts\AccountManager::PROPERTY_PHONE]['value'];
296
-		$data['address'] = $userAccount[\OC\Accounts\AccountManager::PROPERTY_ADDRESS]['value'];
297
-		$data['webpage'] = $userAccount[\OC\Accounts\AccountManager::PROPERTY_WEBSITE]['value'];
298
-		$data['twitter'] = $userAccount[\OC\Accounts\AccountManager::PROPERTY_TWITTER]['value'];
299
-		$data['groups'] = $gids;
300
-
301
-		return $data;
302
-	}
303
-
304
-	/**
305
-	 * @NoAdminRequired
306
-	 * @NoSubAdminRequired
307
-	 * @PasswordConfirmationRequired
308
-	 *
309
-	 * edit users
310
-	 *
311
-	 * @param string $userId
312
-	 * @param string $key
313
-	 * @param string $value
314
-	 * @return DataResponse
315
-	 * @throws OCSException
316
-	 * @throws OCSForbiddenException
317
-	 */
318
-	public function editUser($userId, $key, $value) {
319
-		$currentLoggedInUser = $this->userSession->getUser();
320
-
321
-		$targetUser = $this->userManager->get($userId);
322
-		if($targetUser === null) {
323
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
324
-		}
325
-
326
-		$permittedFields = [];
327
-		if($userId === $currentLoggedInUser->getUID()) {
328
-			// Editing self (display, email)
329
-			$permittedFields[] = 'display';
330
-			$permittedFields[] = 'email';
331
-			$permittedFields[] = 'password';
332
-			// If admin they can edit their own quota
333
-			if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
334
-				$permittedFields[] = 'quota';
335
-			}
336
-		} else {
337
-			// Check if admin / subadmin
338
-			$subAdminManager = $this->groupManager->getSubAdmin();
339
-			if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
340
-			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
341
-				// They have permissions over the user
342
-				$permittedFields[] = 'display';
343
-				$permittedFields[] = 'quota';
344
-				$permittedFields[] = 'password';
345
-				$permittedFields[] = 'email';
346
-			} else {
347
-				// No rights
348
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
349
-			}
350
-		}
351
-		// Check if permitted to edit this field
352
-		if(!in_array($key, $permittedFields)) {
353
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
354
-		}
355
-		// Process the edit
356
-		switch($key) {
357
-			case 'display':
358
-				$targetUser->setDisplayName($value);
359
-				break;
360
-			case 'quota':
361
-				$quota = $value;
362
-				if($quota !== 'none' && $quota !== 'default') {
363
-					if (is_numeric($quota)) {
364
-						$quota = (float) $quota;
365
-					} else {
366
-						$quota = \OCP\Util::computerFileSize($quota);
367
-					}
368
-					if ($quota === false) {
369
-						throw new OCSException('Invalid quota value '.$value, 103);
370
-					}
371
-					if($quota === 0) {
372
-						$quota = 'default';
373
-					}else if($quota === -1) {
374
-						$quota = 'none';
375
-					} else {
376
-						$quota = \OCP\Util::humanFileSize($quota);
377
-					}
378
-				}
379
-				$targetUser->setQuota($quota);
380
-				break;
381
-			case 'password':
382
-				$targetUser->setPassword($value);
383
-				break;
384
-			case 'email':
385
-				if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
386
-					$targetUser->setEMailAddress($value);
387
-				} else {
388
-					throw new OCSException('', 102);
389
-				}
390
-				break;
391
-			default:
392
-				throw new OCSException('', 103);
393
-		}
394
-		return new DataResponse();
395
-	}
396
-
397
-	/**
398
-	 * @PasswordConfirmationRequired
399
-	 * @NoAdminRequired
400
-	 *
401
-	 * @param string $userId
402
-	 * @return DataResponse
403
-	 * @throws OCSException
404
-	 * @throws OCSForbiddenException
405
-	 */
406
-	public function deleteUser($userId) {
407
-		$currentLoggedInUser = $this->userSession->getUser();
408
-
409
-		$targetUser = $this->userManager->get($userId);
410
-
411
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
412
-			throw new OCSException('', 101);
413
-		}
414
-
415
-		// If not permitted
416
-		$subAdminManager = $this->groupManager->getSubAdmin();
417
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
418
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
419
-		}
420
-
421
-		// Go ahead with the delete
422
-		if($targetUser->delete()) {
423
-			return new DataResponse();
424
-		} else {
425
-			throw new OCSException('', 101);
426
-		}
427
-	}
428
-
429
-	/**
430
-	 * @PasswordConfirmationRequired
431
-	 * @NoAdminRequired
432
-	 *
433
-	 * @param string $userId
434
-	 * @return DataResponse
435
-	 * @throws OCSException
436
-	 * @throws OCSForbiddenException
437
-	 */
438
-	public function disableUser($userId) {
439
-		return $this->setEnabled($userId, false);
440
-	}
441
-
442
-	/**
443
-	 * @PasswordConfirmationRequired
444
-	 * @NoAdminRequired
445
-	 *
446
-	 * @param string $userId
447
-	 * @return DataResponse
448
-	 * @throws OCSException
449
-	 * @throws OCSForbiddenException
450
-	 */
451
-	public function enableUser($userId) {
452
-		return $this->setEnabled($userId, true);
453
-	}
454
-
455
-	/**
456
-	 * @param string $userId
457
-	 * @param bool $value
458
-	 * @return DataResponse
459
-	 * @throws OCSException
460
-	 * @throws OCSForbiddenException
461
-	 */
462
-	private function setEnabled($userId, $value) {
463
-		$currentLoggedInUser = $this->userSession->getUser();
464
-
465
-		$targetUser = $this->userManager->get($userId);
466
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
467
-			throw new OCSException('', 101);
468
-		}
469
-
470
-		// If not permitted
471
-		$subAdminManager = $this->groupManager->getSubAdmin();
472
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
473
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
474
-		}
475
-
476
-		// enable/disable the user now
477
-		$targetUser->setEnabled($value);
478
-		return new DataResponse();
479
-	}
480
-
481
-	/**
482
-	 * @NoAdminRequired
483
-	 * @NoSubAdminRequired
484
-	 *
485
-	 * @param string $userId
486
-	 * @return DataResponse
487
-	 * @throws OCSException
488
-	 */
489
-	public function getUsersGroups($userId) {
490
-		$loggedInUser = $this->userSession->getUser();
491
-
492
-		$targetUser = $this->userManager->get($userId);
493
-		if($targetUser === null) {
494
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
495
-		}
496
-
497
-		if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
498
-			// Self lookup or admin lookup
499
-			return new DataResponse([
500
-				'groups' => $this->groupManager->getUserGroupIds($targetUser)
501
-			]);
502
-		} else {
503
-			$subAdminManager = $this->groupManager->getSubAdmin();
504
-
505
-			// Looking up someone else
506
-			if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
507
-				// Return the group that the method caller is subadmin of for the user in question
508
-				/** @var IGroup[] $getSubAdminsGroups */
509
-				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
510
-				foreach ($getSubAdminsGroups as $key => $group) {
511
-					$getSubAdminsGroups[$key] = $group->getGID();
512
-				}
513
-				$groups = array_intersect(
514
-					$getSubAdminsGroups,
515
-					$this->groupManager->getUserGroupIds($targetUser)
516
-				);
517
-				return new DataResponse(['groups' => $groups]);
518
-			} else {
519
-				// Not permitted
520
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
521
-			}
522
-		}
523
-
524
-	}
525
-
526
-	/**
527
-	 * @PasswordConfirmationRequired
528
-	 * @NoAdminRequired
529
-	 *
530
-	 * @param string $userId
531
-	 * @param string $groupid
532
-	 * @return DataResponse
533
-	 * @throws OCSException
534
-	 */
535
-	public function addToGroup($userId, $groupid = '') {
536
-		if($groupid === '') {
537
-			throw new OCSException('', 101);
538
-		}
539
-
540
-		$group = $this->groupManager->get($groupid);
541
-		$targetUser = $this->userManager->get($userId);
542
-		if($group === null) {
543
-			throw new OCSException('', 102);
544
-		}
545
-		if($targetUser === null) {
546
-			throw new OCSException('', 103);
547
-		}
548
-
549
-		// If they're not an admin, check they are a subadmin of the group in question
550
-		$loggedInUser = $this->userSession->getUser();
551
-		$subAdminManager = $this->groupManager->getSubAdmin();
552
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
553
-			throw new OCSException('', 104);
554
-		}
555
-
556
-		// Add user to group
557
-		$group->addUser($targetUser);
558
-		return new DataResponse();
559
-	}
560
-
561
-	/**
562
-	 * @PasswordConfirmationRequired
563
-	 * @NoAdminRequired
564
-	 *
565
-	 * @param string $userId
566
-	 * @param string $groupid
567
-	 * @return DataResponse
568
-	 * @throws OCSException
569
-	 */
570
-	public function removeFromGroup($userId, $groupid) {
571
-		$loggedInUser = $this->userSession->getUser();
572
-
573
-		if($groupid === null) {
574
-			throw new OCSException('', 101);
575
-		}
576
-
577
-		$group = $this->groupManager->get($groupid);
578
-		if($group === null) {
579
-			throw new OCSException('', 102);
580
-		}
581
-
582
-		$targetUser = $this->userManager->get($userId);
583
-		if($targetUser === null) {
584
-			throw new OCSException('', 103);
585
-		}
586
-
587
-		// If they're not an admin, check they are a subadmin of the group in question
588
-		$subAdminManager = $this->groupManager->getSubAdmin();
589
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
590
-			throw new OCSException('', 104);
591
-		}
592
-
593
-		// Check they aren't removing themselves from 'admin' or their 'subadmin; group
594
-		if ($userId === $loggedInUser->getUID()) {
595
-			if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
596
-				if ($group->getGID() === 'admin') {
597
-					throw new OCSException('Cannot remove yourself from the admin group', 105);
598
-				}
599
-			} else {
600
-				// Not an admin, so the user must be a subadmin of this group, but that is not allowed.
601
-				throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
602
-			}
603
-
604
-		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
605
-			/** @var IGroup[] $subAdminGroups */
606
-			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
607
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
608
-				return $subAdminGroup->getGID();
609
-			}, $subAdminGroups);
610
-			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
611
-			$userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
612
-
613
-			if (count($userSubAdminGroups) <= 1) {
614
-				// Subadmin must not be able to remove a user from all their subadmin groups.
615
-				throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
616
-			}
617
-		}
618
-
619
-		// Remove user from group
620
-		$group->removeUser($targetUser);
621
-		return new DataResponse();
622
-	}
623
-
624
-	/**
625
-	 * Creates a subadmin
626
-	 *
627
-	 * @PasswordConfirmationRequired
628
-	 *
629
-	 * @param string $userId
630
-	 * @param string $groupid
631
-	 * @return DataResponse
632
-	 * @throws OCSException
633
-	 */
634
-	public function addSubAdmin($userId, $groupid) {
635
-		$group = $this->groupManager->get($groupid);
636
-		$user = $this->userManager->get($userId);
637
-
638
-		// Check if the user exists
639
-		if($user === null) {
640
-			throw new OCSException('User does not exist', 101);
641
-		}
642
-		// Check if group exists
643
-		if($group === null) {
644
-			throw new OCSException('Group:'.$groupid.' does not exist',  102);
645
-		}
646
-		// Check if trying to make subadmin of admin group
647
-		if(strtolower($groupid) === 'admin') {
648
-			throw new OCSException('Cannot create subadmins for admin group', 103);
649
-		}
650
-
651
-		$subAdminManager = $this->groupManager->getSubAdmin();
652
-
653
-		// We cannot be subadmin twice
654
-		if ($subAdminManager->isSubAdminofGroup($user, $group)) {
655
-			return new DataResponse();
656
-		}
657
-		// Go
658
-		if($subAdminManager->createSubAdmin($user, $group)) {
659
-			return new DataResponse();
660
-		} else {
661
-			throw new OCSException('Unknown error occurred', 103);
662
-		}
663
-	}
664
-
665
-	/**
666
-	 * Removes a subadmin from a group
667
-	 *
668
-	 * @PasswordConfirmationRequired
669
-	 *
670
-	 * @param string $userId
671
-	 * @param string $groupid
672
-	 * @return DataResponse
673
-	 * @throws OCSException
674
-	 */
675
-	public function removeSubAdmin($userId, $groupid) {
676
-		$group = $this->groupManager->get($groupid);
677
-		$user = $this->userManager->get($userId);
678
-		$subAdminManager = $this->groupManager->getSubAdmin();
679
-
680
-		// Check if the user exists
681
-		if($user === null) {
682
-			throw new OCSException('User does not exist', 101);
683
-		}
684
-		// Check if the group exists
685
-		if($group === null) {
686
-			throw new OCSException('Group does not exist', 101);
687
-		}
688
-		// Check if they are a subadmin of this said group
689
-		if(!$subAdminManager->isSubAdminofGroup($user, $group)) {
690
-			throw new OCSException('User is not a subadmin of this group', 102);
691
-		}
692
-
693
-		// Go
694
-		if($subAdminManager->deleteSubAdmin($user, $group)) {
695
-			return new DataResponse();
696
-		} else {
697
-			throw new OCSException('Unknown error occurred', 103);
698
-		}
699
-	}
700
-
701
-	/**
702
-	 * Get the groups a user is a subadmin of
703
-	 *
704
-	 * @param string $userId
705
-	 * @return DataResponse
706
-	 * @throws OCSException
707
-	 */
708
-	public function getUserSubAdminGroups($userId) {
709
-		$user = $this->userManager->get($userId);
710
-		// Check if the user exists
711
-		if($user === null) {
712
-			throw new OCSException('User does not exist', 101);
713
-		}
714
-
715
-		// Get the subadmin groups
716
-		$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
717
-		foreach ($groups as $key => $group) {
718
-			$groups[$key] = $group->getGID();
719
-		}
720
-
721
-		if(!$groups) {
722
-			throw new OCSException('Unknown error occurred', 102);
723
-		} else {
724
-			return new DataResponse($groups);
725
-		}
726
-	}
727
-
728
-	/**
729
-	 * @param string $userId
730
-	 * @return array
731
-	 * @throws \OCP\Files\NotFoundException
732
-	 */
733
-	protected function fillStorageInfo($userId) {
734
-		try {
735
-			\OC_Util::tearDownFS();
736
-			\OC_Util::setupFS($userId);
737
-			$storage = OC_Helper::getStorageInfo('/');
738
-			$data = [
739
-				'free' => $storage['free'],
740
-				'used' => $storage['used'],
741
-				'total' => $storage['total'],
742
-				'relative' => $storage['relative'],
743
-				'quota' => $storage['quota'],
744
-			];
745
-		} catch (NotFoundException $ex) {
746
-			$data = [];
747
-		}
748
-		return $data;
749
-	}
750
-
751
-	/**
752
-	 * @NoAdminRequired
753
-	 * @PasswordConfirmationRequired
754
-	 *
755
-	 * resend welcome message
756
-	 *
757
-	 * @param string $userId
758
-	 * @return DataResponse
759
-	 * @throws OCSException
760
-	 */
761
-	public function resendWelcomeMessage($userId) {
762
-		$currentLoggedInUser = $this->userSession->getUser();
763
-
764
-		$targetUser = $this->userManager->get($userId);
765
-		if($targetUser === null) {
766
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
767
-		}
768
-
769
-		// Check if admin / subadmin
770
-		$subAdminManager = $this->groupManager->getSubAdmin();
771
-		if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
772
-			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
773
-			// No rights
774
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
775
-		}
776
-
777
-		$email = $targetUser->getEMailAddress();
778
-		if ($email === '' || $email === null) {
779
-			throw new OCSException('Email address not available', 101);
780
-		}
781
-		$username = $targetUser->getUID();
782
-		$lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
783
-		if (!$this->l10nFactory->languageExists('settings', $lang)) {
784
-			$lang = 'en';
785
-		}
786
-
787
-		$l10n = $this->l10nFactory->get('settings', $lang);
788
-
789
-		// data for the mail template
790
-		$mailData = [
791
-			'username' => $username,
792
-			'url' => $this->urlGenerator->getAbsoluteURL('/')
793
-		];
794
-
795
-		// FIXME: set users language in email
796
-		$mail = new TemplateResponse('settings', 'email.new_user', $mailData, 'blank');
797
-		$mailContent = $mail->render();
798
-
799
-		// FIXME: set users language in email
800
-		$mail = new TemplateResponse('settings', 'email.new_user_plain_text', $mailData, 'blank');
801
-		$plainTextMailContent = $mail->render();
802
-
803
-		$subject = $l10n->t('Your %s account was created', [$this->defaults->getName()]);
804
-
805
-		try {
806
-			$message = $this->mailer->createMessage();
807
-			$message->setTo([$email => $username]);
808
-			$message->setSubject($subject);
809
-			$message->setHtmlBody($mailContent);
810
-			$message->setPlainBody($plainTextMailContent);
811
-			$message->setFrom([$this->fromMailAddress => $this->defaults->getName()]);
812
-			$this->mailer->send($message);
813
-		} catch(\Exception $e) {
814
-			$this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
815
-			throw new OCSException('Sending email failed', 102);
816
-		}
817
-
818
-		return new DataResponse();
819
-	}
53
+    /** @var IUserManager */
54
+    private $userManager;
55
+    /** @var IConfig */
56
+    private $config;
57
+    /** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface
58
+    private $groupManager;
59
+    /** @var IUserSession */
60
+    private $userSession;
61
+    /** @var AccountManager */
62
+    private $accountManager;
63
+    /** @var ILogger */
64
+    private $logger;
65
+    /** @var string */
66
+    private $fromMailAddress;
67
+    /** @var IURLGenerator */
68
+    private $urlGenerator;
69
+    /** @var IMailer */
70
+    private $mailer;
71
+    /** @var \OC_Defaults */
72
+    private $defaults;
73
+    /** @var IFactory */
74
+    private $l10nFactory;
75
+
76
+    /**
77
+     * @param string $appName
78
+     * @param IRequest $request
79
+     * @param IUserManager $userManager
80
+     * @param IConfig $config
81
+     * @param IGroupManager $groupManager
82
+     * @param IUserSession $userSession
83
+     * @param AccountManager $accountManager
84
+     * @param ILogger $logger
85
+     * @param string $fromMailAddress
86
+     * @param IURLGenerator $urlGenerator
87
+     * @param IMailer $mailer
88
+     * @param \OC_Defaults $defaults
89
+     * @param IFactory $l10nFactory
90
+     */
91
+    public function __construct($appName,
92
+                                IRequest $request,
93
+                                IUserManager $userManager,
94
+                                IConfig $config,
95
+                                IGroupManager $groupManager,
96
+                                IUserSession $userSession,
97
+                                AccountManager $accountManager,
98
+                                ILogger $logger,
99
+                                $fromMailAddress,
100
+                                IURLGenerator $urlGenerator,
101
+                                IMailer $mailer,
102
+                                \OC_Defaults $defaults,
103
+                                IFactory $l10nFactory) {
104
+        parent::__construct($appName, $request);
105
+
106
+        $this->userManager = $userManager;
107
+        $this->config = $config;
108
+        $this->groupManager = $groupManager;
109
+        $this->userSession = $userSession;
110
+        $this->accountManager = $accountManager;
111
+        $this->logger = $logger;
112
+        $this->fromMailAddress = $fromMailAddress;
113
+        $this->urlGenerator = $urlGenerator;
114
+        $this->mailer = $mailer;
115
+        $this->defaults = $defaults;
116
+        $this->l10nFactory = $l10nFactory;
117
+    }
118
+
119
+    /**
120
+     * @NoAdminRequired
121
+     *
122
+     * returns a list of users
123
+     *
124
+     * @param string $search
125
+     * @param int $limit
126
+     * @param int $offset
127
+     * @return DataResponse
128
+     */
129
+    public function getUsers($search = '', $limit = null, $offset = null) {
130
+        $user = $this->userSession->getUser();
131
+        $users = [];
132
+
133
+        // Admin? Or SubAdmin?
134
+        $uid = $user->getUID();
135
+        $subAdminManager = $this->groupManager->getSubAdmin();
136
+        if($this->groupManager->isAdmin($uid)){
137
+            $users = $this->userManager->search($search, $limit, $offset);
138
+        } else if ($subAdminManager->isSubAdmin($user)) {
139
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
140
+            foreach ($subAdminOfGroups as $key => $group) {
141
+                $subAdminOfGroups[$key] = $group->getGID();
142
+            }
143
+
144
+            if($offset === null) {
145
+                $offset = 0;
146
+            }
147
+
148
+            $users = [];
149
+            foreach ($subAdminOfGroups as $group) {
150
+                $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search));
151
+            }
152
+
153
+            $users = array_slice($users, $offset, $limit);
154
+        }
155
+
156
+        $users = array_keys($users);
157
+
158
+        return new DataResponse([
159
+            'users' => $users
160
+        ]);
161
+    }
162
+
163
+    /**
164
+     * @PasswordConfirmationRequired
165
+     * @NoAdminRequired
166
+     *
167
+     * @param string $userid
168
+     * @param string $password
169
+     * @param array $groups
170
+     * @return DataResponse
171
+     * @throws OCSException
172
+     */
173
+    public function addUser($userid, $password, $groups = null) {
174
+        $user = $this->userSession->getUser();
175
+        $isAdmin = $this->groupManager->isAdmin($user->getUID());
176
+        $subAdminManager = $this->groupManager->getSubAdmin();
177
+
178
+        if($this->userManager->userExists($userid)) {
179
+            $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
180
+            throw new OCSException('User already exists', 102);
181
+        }
182
+
183
+        if(is_array($groups)) {
184
+            foreach ($groups as $group) {
185
+                if(!$this->groupManager->groupExists($group)) {
186
+                    throw new OCSException('group '.$group.' does not exist', 104);
187
+                }
188
+                if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
189
+                    throw new OCSException('insufficient privileges for group '. $group, 105);
190
+                }
191
+            }
192
+        } else {
193
+            if(!$isAdmin) {
194
+                throw new OCSException('no group specified (required for subadmins)', 106);
195
+            }
196
+        }
197
+
198
+        try {
199
+            $newUser = $this->userManager->createUser($userid, $password);
200
+            $this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
201
+
202
+            if (is_array($groups)) {
203
+                foreach ($groups as $group) {
204
+                    $this->groupManager->get($group)->addUser($newUser);
205
+                    $this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
206
+                }
207
+            }
208
+            return new DataResponse();
209
+        } catch (\Exception $e) {
210
+            $this->logger->error('Failed addUser attempt with exception: '.$e->getMessage(), ['app' => 'ocs_api']);
211
+            throw new OCSException('Bad request', 101);
212
+        }
213
+    }
214
+
215
+    /**
216
+     * @NoAdminRequired
217
+     * @NoSubAdminRequired
218
+     *
219
+     * gets user info
220
+     *
221
+     * @param string $userId
222
+     * @return DataResponse
223
+     * @throws OCSException
224
+     */
225
+    public function getUser($userId) {
226
+        $data = $this->getUserData($userId);
227
+        return new DataResponse($data);
228
+    }
229
+
230
+    /**
231
+     * @NoAdminRequired
232
+     * @NoSubAdminRequired
233
+     *
234
+     * gets user info from the currently logged in user
235
+     *
236
+     * @return DataResponse
237
+     * @throws OCSException
238
+     */
239
+    public function getCurrentUser() {
240
+        $user = $this->userSession->getUser();
241
+        if ($user) {
242
+            $data =  $this->getUserData($user->getUID());
243
+            // rename "displayname" to "display-name" only for this call to keep
244
+            // the API stable.
245
+            $data['display-name'] = $data['displayname'];
246
+            unset($data['displayname']);
247
+            return new DataResponse($data);
248
+
249
+        }
250
+
251
+        throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
252
+    }
253
+
254
+    /**
255
+     * creates a array with all user data
256
+     *
257
+     * @param $userId
258
+     * @return array
259
+     * @throws OCSException
260
+     */
261
+    protected function getUserData($userId) {
262
+        $currentLoggedInUser = $this->userSession->getUser();
263
+
264
+        $data = [];
265
+
266
+        // Check if the target user exists
267
+        $targetUserObject = $this->userManager->get($userId);
268
+        if($targetUserObject === null) {
269
+            throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
270
+        }
271
+
272
+        // Admin? Or SubAdmin?
273
+        if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
274
+            || $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
275
+            $data['enabled'] = $this->config->getUserValue($userId, 'core', 'enabled', 'true');
276
+        } else {
277
+            // Check they are looking up themselves
278
+            if($currentLoggedInUser->getUID() !== $userId) {
279
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
280
+            }
281
+        }
282
+
283
+        $userAccount = $this->accountManager->getUser($targetUserObject);
284
+        $groups = $this->groupManager->getUserGroups($targetUserObject);
285
+        $gids = [];
286
+        foreach ($groups as $group) {
287
+            $gids[] = $group->getDisplayName();
288
+        }
289
+
290
+        // Find the data
291
+        $data['id'] = $targetUserObject->getUID();
292
+        $data['quota'] = $this->fillStorageInfo($userId);
293
+        $data['email'] = $targetUserObject->getEMailAddress();
294
+        $data['displayname'] = $targetUserObject->getDisplayName();
295
+        $data['phone'] = $userAccount[\OC\Accounts\AccountManager::PROPERTY_PHONE]['value'];
296
+        $data['address'] = $userAccount[\OC\Accounts\AccountManager::PROPERTY_ADDRESS]['value'];
297
+        $data['webpage'] = $userAccount[\OC\Accounts\AccountManager::PROPERTY_WEBSITE]['value'];
298
+        $data['twitter'] = $userAccount[\OC\Accounts\AccountManager::PROPERTY_TWITTER]['value'];
299
+        $data['groups'] = $gids;
300
+
301
+        return $data;
302
+    }
303
+
304
+    /**
305
+     * @NoAdminRequired
306
+     * @NoSubAdminRequired
307
+     * @PasswordConfirmationRequired
308
+     *
309
+     * edit users
310
+     *
311
+     * @param string $userId
312
+     * @param string $key
313
+     * @param string $value
314
+     * @return DataResponse
315
+     * @throws OCSException
316
+     * @throws OCSForbiddenException
317
+     */
318
+    public function editUser($userId, $key, $value) {
319
+        $currentLoggedInUser = $this->userSession->getUser();
320
+
321
+        $targetUser = $this->userManager->get($userId);
322
+        if($targetUser === null) {
323
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
324
+        }
325
+
326
+        $permittedFields = [];
327
+        if($userId === $currentLoggedInUser->getUID()) {
328
+            // Editing self (display, email)
329
+            $permittedFields[] = 'display';
330
+            $permittedFields[] = 'email';
331
+            $permittedFields[] = 'password';
332
+            // If admin they can edit their own quota
333
+            if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
334
+                $permittedFields[] = 'quota';
335
+            }
336
+        } else {
337
+            // Check if admin / subadmin
338
+            $subAdminManager = $this->groupManager->getSubAdmin();
339
+            if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
340
+            || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
341
+                // They have permissions over the user
342
+                $permittedFields[] = 'display';
343
+                $permittedFields[] = 'quota';
344
+                $permittedFields[] = 'password';
345
+                $permittedFields[] = 'email';
346
+            } else {
347
+                // No rights
348
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
349
+            }
350
+        }
351
+        // Check if permitted to edit this field
352
+        if(!in_array($key, $permittedFields)) {
353
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
354
+        }
355
+        // Process the edit
356
+        switch($key) {
357
+            case 'display':
358
+                $targetUser->setDisplayName($value);
359
+                break;
360
+            case 'quota':
361
+                $quota = $value;
362
+                if($quota !== 'none' && $quota !== 'default') {
363
+                    if (is_numeric($quota)) {
364
+                        $quota = (float) $quota;
365
+                    } else {
366
+                        $quota = \OCP\Util::computerFileSize($quota);
367
+                    }
368
+                    if ($quota === false) {
369
+                        throw new OCSException('Invalid quota value '.$value, 103);
370
+                    }
371
+                    if($quota === 0) {
372
+                        $quota = 'default';
373
+                    }else if($quota === -1) {
374
+                        $quota = 'none';
375
+                    } else {
376
+                        $quota = \OCP\Util::humanFileSize($quota);
377
+                    }
378
+                }
379
+                $targetUser->setQuota($quota);
380
+                break;
381
+            case 'password':
382
+                $targetUser->setPassword($value);
383
+                break;
384
+            case 'email':
385
+                if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
386
+                    $targetUser->setEMailAddress($value);
387
+                } else {
388
+                    throw new OCSException('', 102);
389
+                }
390
+                break;
391
+            default:
392
+                throw new OCSException('', 103);
393
+        }
394
+        return new DataResponse();
395
+    }
396
+
397
+    /**
398
+     * @PasswordConfirmationRequired
399
+     * @NoAdminRequired
400
+     *
401
+     * @param string $userId
402
+     * @return DataResponse
403
+     * @throws OCSException
404
+     * @throws OCSForbiddenException
405
+     */
406
+    public function deleteUser($userId) {
407
+        $currentLoggedInUser = $this->userSession->getUser();
408
+
409
+        $targetUser = $this->userManager->get($userId);
410
+
411
+        if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
412
+            throw new OCSException('', 101);
413
+        }
414
+
415
+        // If not permitted
416
+        $subAdminManager = $this->groupManager->getSubAdmin();
417
+        if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
418
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
419
+        }
420
+
421
+        // Go ahead with the delete
422
+        if($targetUser->delete()) {
423
+            return new DataResponse();
424
+        } else {
425
+            throw new OCSException('', 101);
426
+        }
427
+    }
428
+
429
+    /**
430
+     * @PasswordConfirmationRequired
431
+     * @NoAdminRequired
432
+     *
433
+     * @param string $userId
434
+     * @return DataResponse
435
+     * @throws OCSException
436
+     * @throws OCSForbiddenException
437
+     */
438
+    public function disableUser($userId) {
439
+        return $this->setEnabled($userId, false);
440
+    }
441
+
442
+    /**
443
+     * @PasswordConfirmationRequired
444
+     * @NoAdminRequired
445
+     *
446
+     * @param string $userId
447
+     * @return DataResponse
448
+     * @throws OCSException
449
+     * @throws OCSForbiddenException
450
+     */
451
+    public function enableUser($userId) {
452
+        return $this->setEnabled($userId, true);
453
+    }
454
+
455
+    /**
456
+     * @param string $userId
457
+     * @param bool $value
458
+     * @return DataResponse
459
+     * @throws OCSException
460
+     * @throws OCSForbiddenException
461
+     */
462
+    private function setEnabled($userId, $value) {
463
+        $currentLoggedInUser = $this->userSession->getUser();
464
+
465
+        $targetUser = $this->userManager->get($userId);
466
+        if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
467
+            throw new OCSException('', 101);
468
+        }
469
+
470
+        // If not permitted
471
+        $subAdminManager = $this->groupManager->getSubAdmin();
472
+        if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
473
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
474
+        }
475
+
476
+        // enable/disable the user now
477
+        $targetUser->setEnabled($value);
478
+        return new DataResponse();
479
+    }
480
+
481
+    /**
482
+     * @NoAdminRequired
483
+     * @NoSubAdminRequired
484
+     *
485
+     * @param string $userId
486
+     * @return DataResponse
487
+     * @throws OCSException
488
+     */
489
+    public function getUsersGroups($userId) {
490
+        $loggedInUser = $this->userSession->getUser();
491
+
492
+        $targetUser = $this->userManager->get($userId);
493
+        if($targetUser === null) {
494
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
495
+        }
496
+
497
+        if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
498
+            // Self lookup or admin lookup
499
+            return new DataResponse([
500
+                'groups' => $this->groupManager->getUserGroupIds($targetUser)
501
+            ]);
502
+        } else {
503
+            $subAdminManager = $this->groupManager->getSubAdmin();
504
+
505
+            // Looking up someone else
506
+            if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
507
+                // Return the group that the method caller is subadmin of for the user in question
508
+                /** @var IGroup[] $getSubAdminsGroups */
509
+                $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
510
+                foreach ($getSubAdminsGroups as $key => $group) {
511
+                    $getSubAdminsGroups[$key] = $group->getGID();
512
+                }
513
+                $groups = array_intersect(
514
+                    $getSubAdminsGroups,
515
+                    $this->groupManager->getUserGroupIds($targetUser)
516
+                );
517
+                return new DataResponse(['groups' => $groups]);
518
+            } else {
519
+                // Not permitted
520
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
521
+            }
522
+        }
523
+
524
+    }
525
+
526
+    /**
527
+     * @PasswordConfirmationRequired
528
+     * @NoAdminRequired
529
+     *
530
+     * @param string $userId
531
+     * @param string $groupid
532
+     * @return DataResponse
533
+     * @throws OCSException
534
+     */
535
+    public function addToGroup($userId, $groupid = '') {
536
+        if($groupid === '') {
537
+            throw new OCSException('', 101);
538
+        }
539
+
540
+        $group = $this->groupManager->get($groupid);
541
+        $targetUser = $this->userManager->get($userId);
542
+        if($group === null) {
543
+            throw new OCSException('', 102);
544
+        }
545
+        if($targetUser === null) {
546
+            throw new OCSException('', 103);
547
+        }
548
+
549
+        // If they're not an admin, check they are a subadmin of the group in question
550
+        $loggedInUser = $this->userSession->getUser();
551
+        $subAdminManager = $this->groupManager->getSubAdmin();
552
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
553
+            throw new OCSException('', 104);
554
+        }
555
+
556
+        // Add user to group
557
+        $group->addUser($targetUser);
558
+        return new DataResponse();
559
+    }
560
+
561
+    /**
562
+     * @PasswordConfirmationRequired
563
+     * @NoAdminRequired
564
+     *
565
+     * @param string $userId
566
+     * @param string $groupid
567
+     * @return DataResponse
568
+     * @throws OCSException
569
+     */
570
+    public function removeFromGroup($userId, $groupid) {
571
+        $loggedInUser = $this->userSession->getUser();
572
+
573
+        if($groupid === null) {
574
+            throw new OCSException('', 101);
575
+        }
576
+
577
+        $group = $this->groupManager->get($groupid);
578
+        if($group === null) {
579
+            throw new OCSException('', 102);
580
+        }
581
+
582
+        $targetUser = $this->userManager->get($userId);
583
+        if($targetUser === null) {
584
+            throw new OCSException('', 103);
585
+        }
586
+
587
+        // If they're not an admin, check they are a subadmin of the group in question
588
+        $subAdminManager = $this->groupManager->getSubAdmin();
589
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
590
+            throw new OCSException('', 104);
591
+        }
592
+
593
+        // Check they aren't removing themselves from 'admin' or their 'subadmin; group
594
+        if ($userId === $loggedInUser->getUID()) {
595
+            if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
596
+                if ($group->getGID() === 'admin') {
597
+                    throw new OCSException('Cannot remove yourself from the admin group', 105);
598
+                }
599
+            } else {
600
+                // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
601
+                throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
602
+            }
603
+
604
+        } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
605
+            /** @var IGroup[] $subAdminGroups */
606
+            $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
607
+            $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
608
+                return $subAdminGroup->getGID();
609
+            }, $subAdminGroups);
610
+            $userGroups = $this->groupManager->getUserGroupIds($targetUser);
611
+            $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
612
+
613
+            if (count($userSubAdminGroups) <= 1) {
614
+                // Subadmin must not be able to remove a user from all their subadmin groups.
615
+                throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
616
+            }
617
+        }
618
+
619
+        // Remove user from group
620
+        $group->removeUser($targetUser);
621
+        return new DataResponse();
622
+    }
623
+
624
+    /**
625
+     * Creates a subadmin
626
+     *
627
+     * @PasswordConfirmationRequired
628
+     *
629
+     * @param string $userId
630
+     * @param string $groupid
631
+     * @return DataResponse
632
+     * @throws OCSException
633
+     */
634
+    public function addSubAdmin($userId, $groupid) {
635
+        $group = $this->groupManager->get($groupid);
636
+        $user = $this->userManager->get($userId);
637
+
638
+        // Check if the user exists
639
+        if($user === null) {
640
+            throw new OCSException('User does not exist', 101);
641
+        }
642
+        // Check if group exists
643
+        if($group === null) {
644
+            throw new OCSException('Group:'.$groupid.' does not exist',  102);
645
+        }
646
+        // Check if trying to make subadmin of admin group
647
+        if(strtolower($groupid) === 'admin') {
648
+            throw new OCSException('Cannot create subadmins for admin group', 103);
649
+        }
650
+
651
+        $subAdminManager = $this->groupManager->getSubAdmin();
652
+
653
+        // We cannot be subadmin twice
654
+        if ($subAdminManager->isSubAdminofGroup($user, $group)) {
655
+            return new DataResponse();
656
+        }
657
+        // Go
658
+        if($subAdminManager->createSubAdmin($user, $group)) {
659
+            return new DataResponse();
660
+        } else {
661
+            throw new OCSException('Unknown error occurred', 103);
662
+        }
663
+    }
664
+
665
+    /**
666
+     * Removes a subadmin from a group
667
+     *
668
+     * @PasswordConfirmationRequired
669
+     *
670
+     * @param string $userId
671
+     * @param string $groupid
672
+     * @return DataResponse
673
+     * @throws OCSException
674
+     */
675
+    public function removeSubAdmin($userId, $groupid) {
676
+        $group = $this->groupManager->get($groupid);
677
+        $user = $this->userManager->get($userId);
678
+        $subAdminManager = $this->groupManager->getSubAdmin();
679
+
680
+        // Check if the user exists
681
+        if($user === null) {
682
+            throw new OCSException('User does not exist', 101);
683
+        }
684
+        // Check if the group exists
685
+        if($group === null) {
686
+            throw new OCSException('Group does not exist', 101);
687
+        }
688
+        // Check if they are a subadmin of this said group
689
+        if(!$subAdminManager->isSubAdminofGroup($user, $group)) {
690
+            throw new OCSException('User is not a subadmin of this group', 102);
691
+        }
692
+
693
+        // Go
694
+        if($subAdminManager->deleteSubAdmin($user, $group)) {
695
+            return new DataResponse();
696
+        } else {
697
+            throw new OCSException('Unknown error occurred', 103);
698
+        }
699
+    }
700
+
701
+    /**
702
+     * Get the groups a user is a subadmin of
703
+     *
704
+     * @param string $userId
705
+     * @return DataResponse
706
+     * @throws OCSException
707
+     */
708
+    public function getUserSubAdminGroups($userId) {
709
+        $user = $this->userManager->get($userId);
710
+        // Check if the user exists
711
+        if($user === null) {
712
+            throw new OCSException('User does not exist', 101);
713
+        }
714
+
715
+        // Get the subadmin groups
716
+        $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
717
+        foreach ($groups as $key => $group) {
718
+            $groups[$key] = $group->getGID();
719
+        }
720
+
721
+        if(!$groups) {
722
+            throw new OCSException('Unknown error occurred', 102);
723
+        } else {
724
+            return new DataResponse($groups);
725
+        }
726
+    }
727
+
728
+    /**
729
+     * @param string $userId
730
+     * @return array
731
+     * @throws \OCP\Files\NotFoundException
732
+     */
733
+    protected function fillStorageInfo($userId) {
734
+        try {
735
+            \OC_Util::tearDownFS();
736
+            \OC_Util::setupFS($userId);
737
+            $storage = OC_Helper::getStorageInfo('/');
738
+            $data = [
739
+                'free' => $storage['free'],
740
+                'used' => $storage['used'],
741
+                'total' => $storage['total'],
742
+                'relative' => $storage['relative'],
743
+                'quota' => $storage['quota'],
744
+            ];
745
+        } catch (NotFoundException $ex) {
746
+            $data = [];
747
+        }
748
+        return $data;
749
+    }
750
+
751
+    /**
752
+     * @NoAdminRequired
753
+     * @PasswordConfirmationRequired
754
+     *
755
+     * resend welcome message
756
+     *
757
+     * @param string $userId
758
+     * @return DataResponse
759
+     * @throws OCSException
760
+     */
761
+    public function resendWelcomeMessage($userId) {
762
+        $currentLoggedInUser = $this->userSession->getUser();
763
+
764
+        $targetUser = $this->userManager->get($userId);
765
+        if($targetUser === null) {
766
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
767
+        }
768
+
769
+        // Check if admin / subadmin
770
+        $subAdminManager = $this->groupManager->getSubAdmin();
771
+        if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
772
+            && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
773
+            // No rights
774
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
775
+        }
776
+
777
+        $email = $targetUser->getEMailAddress();
778
+        if ($email === '' || $email === null) {
779
+            throw new OCSException('Email address not available', 101);
780
+        }
781
+        $username = $targetUser->getUID();
782
+        $lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
783
+        if (!$this->l10nFactory->languageExists('settings', $lang)) {
784
+            $lang = 'en';
785
+        }
786
+
787
+        $l10n = $this->l10nFactory->get('settings', $lang);
788
+
789
+        // data for the mail template
790
+        $mailData = [
791
+            'username' => $username,
792
+            'url' => $this->urlGenerator->getAbsoluteURL('/')
793
+        ];
794
+
795
+        // FIXME: set users language in email
796
+        $mail = new TemplateResponse('settings', 'email.new_user', $mailData, 'blank');
797
+        $mailContent = $mail->render();
798
+
799
+        // FIXME: set users language in email
800
+        $mail = new TemplateResponse('settings', 'email.new_user_plain_text', $mailData, 'blank');
801
+        $plainTextMailContent = $mail->render();
802
+
803
+        $subject = $l10n->t('Your %s account was created', [$this->defaults->getName()]);
804
+
805
+        try {
806
+            $message = $this->mailer->createMessage();
807
+            $message->setTo([$email => $username]);
808
+            $message->setSubject($subject);
809
+            $message->setHtmlBody($mailContent);
810
+            $message->setPlainBody($plainTextMailContent);
811
+            $message->setFrom([$this->fromMailAddress => $this->defaults->getName()]);
812
+            $this->mailer->send($message);
813
+        } catch(\Exception $e) {
814
+            $this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
815
+            throw new OCSException('Sending email failed', 102);
816
+        }
817
+
818
+        return new DataResponse();
819
+    }
820 820
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/ShareByMailProvider.php 3 patches
Doc Comments   +11 added lines, -4 removed lines patch added patch discarded remove patch
@@ -185,10 +185,10 @@  discard block
 block discarded – undo
185 185
 	 * publish activity if a file/folder was shared by mail
186 186
 	 *
187 187
 	 * @param $subject
188
-	 * @param $parameters
189
-	 * @param $affectedUser
188
+	 * @param string[] $parameters
189
+	 * @param string $affectedUser
190 190
 	 * @param $fileId
191
-	 * @param $filePath
191
+	 * @param string $filePath
192 192
 	 */
193 193
 	protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
194 194
 		$event = $this->activityManager->generateEvent();
@@ -240,6 +240,12 @@  discard block
 block discarded – undo
240 240
 
241 241
 	}
242 242
 
243
+	/**
244
+	 * @param string $link
245
+	 * @param string $owner
246
+	 * @param string $initiator
247
+	 * @param string $shareWith
248
+	 */
243 249
 	protected function sendMailNotification($filename, $link, $owner, $initiator, $shareWith) {
244 250
 		$ownerUser = $this->userManager->get($owner);
245 251
 		$initiatorUser = $this->userManager->get($initiator);
@@ -269,6 +275,7 @@  discard block
 block discarded – undo
269 275
 	 * @param $link
270 276
 	 * @param $owner
271 277
 	 * @param $initiator
278
+	 * @param string $template
272 279
 	 * @return string plain text mail
273 280
 	 * @throws HintException
274 281
 	 */
@@ -708,7 +715,7 @@  discard block
 block discarded – undo
708 715
 	/**
709 716
 	 * get database row of a give share
710 717
 	 *
711
-	 * @param $id
718
+	 * @param integer $id
712 719
 	 * @return array
713 720
 	 * @throws ShareNotFound
714 721
 	 */
Please login to merge, or discard this patch.
Indentation   +716 added lines, -716 removed lines patch added patch discarded remove patch
@@ -48,728 +48,728 @@
 block discarded – undo
48 48
  */
49 49
 class ShareByMailProvider implements IShareProvider {
50 50
 
51
-	/** @var  IDBConnection */
52
-	private $dbConnection;
53
-
54
-	/** @var ILogger */
55
-	private $logger;
56
-
57
-	/** @var ISecureRandom */
58
-	private $secureRandom;
59
-
60
-	/** @var IUserManager */
61
-	private $userManager;
62
-
63
-	/** @var IRootFolder */
64
-	private $rootFolder;
65
-
66
-	/** @var IL10N */
67
-	private $l;
68
-
69
-	/** @var IMailer */
70
-	private $mailer;
71
-
72
-	/** @var IURLGenerator */
73
-	private $urlGenerator;
74
-
75
-	/** @var IManager  */
76
-	private $activityManager;
77
-
78
-	/**
79
-	 * Return the identifier of this provider.
80
-	 *
81
-	 * @return string Containing only [a-zA-Z0-9]
82
-	 */
83
-	public function identifier() {
84
-		return 'ocShareByMail';
85
-	}
86
-
87
-	/**
88
-	 * DefaultShareProvider constructor.
89
-	 *
90
-	 * @param IDBConnection $connection
91
-	 * @param ISecureRandom $secureRandom
92
-	 * @param IUserManager $userManager
93
-	 * @param IRootFolder $rootFolder
94
-	 * @param IL10N $l
95
-	 * @param ILogger $logger
96
-	 * @param IMailer $mailer
97
-	 * @param IURLGenerator $urlGenerator
98
-	 * @param IManager $activityManager
99
-	 */
100
-	public function __construct(
101
-		IDBConnection $connection,
102
-		ISecureRandom $secureRandom,
103
-		IUserManager $userManager,
104
-		IRootFolder $rootFolder,
105
-		IL10N $l,
106
-		ILogger $logger,
107
-		IMailer $mailer,
108
-		IURLGenerator $urlGenerator,
109
-		IManager $activityManager
110
-	) {
111
-		$this->dbConnection = $connection;
112
-		$this->secureRandom = $secureRandom;
113
-		$this->userManager = $userManager;
114
-		$this->rootFolder = $rootFolder;
115
-		$this->l = $l;
116
-		$this->logger = $logger;
117
-		$this->mailer = $mailer;
118
-		$this->urlGenerator = $urlGenerator;
119
-		$this->activityManager = $activityManager;
120
-	}
121
-
122
-	/**
123
-	 * Share a path
124
-	 *
125
-	 * @param IShare $share
126
-	 * @return IShare The share object
127
-	 * @throws ShareNotFound
128
-	 * @throws \Exception
129
-	 */
130
-	public function create(IShare $share) {
131
-
132
-		$shareWith = $share->getSharedWith();
133
-		/*
51
+    /** @var  IDBConnection */
52
+    private $dbConnection;
53
+
54
+    /** @var ILogger */
55
+    private $logger;
56
+
57
+    /** @var ISecureRandom */
58
+    private $secureRandom;
59
+
60
+    /** @var IUserManager */
61
+    private $userManager;
62
+
63
+    /** @var IRootFolder */
64
+    private $rootFolder;
65
+
66
+    /** @var IL10N */
67
+    private $l;
68
+
69
+    /** @var IMailer */
70
+    private $mailer;
71
+
72
+    /** @var IURLGenerator */
73
+    private $urlGenerator;
74
+
75
+    /** @var IManager  */
76
+    private $activityManager;
77
+
78
+    /**
79
+     * Return the identifier of this provider.
80
+     *
81
+     * @return string Containing only [a-zA-Z0-9]
82
+     */
83
+    public function identifier() {
84
+        return 'ocShareByMail';
85
+    }
86
+
87
+    /**
88
+     * DefaultShareProvider constructor.
89
+     *
90
+     * @param IDBConnection $connection
91
+     * @param ISecureRandom $secureRandom
92
+     * @param IUserManager $userManager
93
+     * @param IRootFolder $rootFolder
94
+     * @param IL10N $l
95
+     * @param ILogger $logger
96
+     * @param IMailer $mailer
97
+     * @param IURLGenerator $urlGenerator
98
+     * @param IManager $activityManager
99
+     */
100
+    public function __construct(
101
+        IDBConnection $connection,
102
+        ISecureRandom $secureRandom,
103
+        IUserManager $userManager,
104
+        IRootFolder $rootFolder,
105
+        IL10N $l,
106
+        ILogger $logger,
107
+        IMailer $mailer,
108
+        IURLGenerator $urlGenerator,
109
+        IManager $activityManager
110
+    ) {
111
+        $this->dbConnection = $connection;
112
+        $this->secureRandom = $secureRandom;
113
+        $this->userManager = $userManager;
114
+        $this->rootFolder = $rootFolder;
115
+        $this->l = $l;
116
+        $this->logger = $logger;
117
+        $this->mailer = $mailer;
118
+        $this->urlGenerator = $urlGenerator;
119
+        $this->activityManager = $activityManager;
120
+    }
121
+
122
+    /**
123
+     * Share a path
124
+     *
125
+     * @param IShare $share
126
+     * @return IShare The share object
127
+     * @throws ShareNotFound
128
+     * @throws \Exception
129
+     */
130
+    public function create(IShare $share) {
131
+
132
+        $shareWith = $share->getSharedWith();
133
+        /*
134 134
 		 * Check if file is not already shared with the remote user
135 135
 		 */
136
-		$alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
137
-		if (!empty($alreadyShared)) {
138
-			$message = 'Sharing %s failed, this item is already shared with %s';
139
-			$message_t = $this->l->t('Sharing %s failed, this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
140
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
141
-			throw new \Exception($message_t);
142
-		}
143
-
144
-		$shareId = $this->createMailShare($share);
145
-		$this->createActivity($share);
146
-		$data = $this->getRawShare($shareId);
147
-		return $this->createShareObject($data);
148
-
149
-	}
150
-
151
-	/**
152
-	 * create activity if a file/folder was shared by mail
153
-	 *
154
-	 * @param IShare $share
155
-	 */
156
-	protected function createActivity(IShare $share) {
157
-
158
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
159
-
160
-		$this->publishActivity(
161
-			Activity::SUBJECT_SHARED_EMAIL_SELF,
162
-			[$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
163
-			$share->getSharedBy(),
164
-			$share->getNode()->getId(),
165
-			$userFolder->getRelativePath($share->getNode()->getPath())
166
-		);
167
-
168
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
169
-			$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
170
-			$fileId = $share->getNode()->getId();
171
-			$nodes = $ownerFolder->getById($fileId);
172
-			$ownerPath = $nodes[0]->getPath();
173
-			$this->publishActivity(
174
-				Activity::SUBJECT_SHARED_EMAIL_BY,
175
-				[$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
176
-				$share->getShareOwner(),
177
-				$fileId,
178
-				$ownerFolder->getRelativePath($ownerPath)
179
-			);
180
-		}
181
-
182
-	}
183
-
184
-	/**
185
-	 * publish activity if a file/folder was shared by mail
186
-	 *
187
-	 * @param $subject
188
-	 * @param $parameters
189
-	 * @param $affectedUser
190
-	 * @param $fileId
191
-	 * @param $filePath
192
-	 */
193
-	protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
194
-		$event = $this->activityManager->generateEvent();
195
-		$event->setApp('sharebymail')
196
-			->setType('shared')
197
-			->setSubject($subject, $parameters)
198
-			->setAffectedUser($affectedUser)
199
-			->setObject('files', $fileId, $filePath);
200
-		$this->activityManager->publish($event);
201
-
202
-	}
203
-
204
-	/**
205
-	 * @param IShare $share
206
-	 * @return int
207
-	 * @throws \Exception
208
-	 */
209
-	protected function createMailShare(IShare $share) {
210
-		$share->setToken($this->generateToken());
211
-		$shareId = $this->addShareToDB(
212
-			$share->getNodeId(),
213
-			$share->getNodeType(),
214
-			$share->getSharedWith(),
215
-			$share->getSharedBy(),
216
-			$share->getShareOwner(),
217
-			$share->getPermissions(),
218
-			$share->getToken()
219
-		);
220
-
221
-		try {
222
-			$link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
223
-				['token' => $share->getToken()]);
224
-			$this->sendMailNotification($share->getNode()->getName(),
225
-				$link,
226
-				$share->getShareOwner(),
227
-				$share->getSharedBy(), $share->getSharedWith());
228
-		} catch (HintException $hintException) {
229
-			$this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
230
-			$this->removeShareFromTable($shareId);
231
-			throw $hintException;
232
-		} catch (\Exception $e) {
233
-			$this->logger->error('Failed to send share by mail: ' . $e->getMessage());
234
-			$this->removeShareFromTable($shareId);
235
-			throw new HintException('Failed to send share by mail',
236
-				$this->l->t('Failed to send share by E-mail'));
237
-		}
238
-
239
-		return $shareId;
240
-
241
-	}
242
-
243
-	protected function sendMailNotification($filename, $link, $owner, $initiator, $shareWith) {
244
-		$ownerUser = $this->userManager->get($owner);
245
-		$initiatorUser = $this->userManager->get($initiator);
246
-		$ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
247
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
248
-		if ($owner === $initiator) {
249
-			$subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
250
-		} else {
251
-			$subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
252
-		}
253
-
254
-		$message = $this->mailer->createMessage();
255
-		$htmlBody = $this->createMailBody('mail', $filename, $link, $ownerDisplayName, $initiatorDisplayName);
256
-		$textBody = $this->createMailBody('altmail', $filename, $link, $ownerDisplayName, $initiatorDisplayName);
257
-		$message->setTo([$shareWith]);
258
-		$message->setSubject($subject);
259
-		$message->setBody($textBody, 'text/plain');
260
-		$message->setHtmlBody($htmlBody);
261
-		$this->mailer->send($message);
262
-
263
-	}
264
-
265
-	/**
266
-	 * create mail body
267
-	 *
268
-	 * @param $filename
269
-	 * @param $link
270
-	 * @param $owner
271
-	 * @param $initiator
272
-	 * @return string plain text mail
273
-	 * @throws HintException
274
-	 */
275
-	protected function createMailBody($template, $filename, $link, $owner, $initiator) {
276
-
277
-		$mailBodyTemplate = new Template('sharebymail', $template, '');
278
-		$mailBodyTemplate->assign ('filename', $filename);
279
-		$mailBodyTemplate->assign ('link', $link);
280
-		$mailBodyTemplate->assign ('owner', $owner);
281
-		$mailBodyTemplate->assign ('initiator', $initiator);
282
-		$mailBodyTemplate->assign ('onBehalfOf', $initiator !== $owner);
283
-		$mailBody = $mailBodyTemplate->fetchPage();
284
-
285
-		if (is_string($mailBody)) {
286
-			return $mailBody;
287
-		}
288
-
289
-		throw new HintException('Failed to create the E-mail',
290
-			$this->l->t('Failed to create the E-mail'));
291
-	}
292
-
293
-	/**
294
-	 * generate share token
295
-	 *
296
-	 * @return string
297
-	 */
298
-	protected function generateToken() {
299
-		$token = $this->secureRandom->generate(
300
-			15, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
301
-		return $token;
302
-	}
303
-
304
-	/**
305
-	 * Get all children of this share
306
-	 *
307
-	 * @param IShare $parent
308
-	 * @return IShare[]
309
-	 */
310
-	public function getChildren(IShare $parent) {
311
-		$children = [];
312
-
313
-		$qb = $this->dbConnection->getQueryBuilder();
314
-		$qb->select('*')
315
-			->from('share')
316
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
317
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
318
-			->orderBy('id');
319
-
320
-		$cursor = $qb->execute();
321
-		while($data = $cursor->fetch()) {
322
-			$children[] = $this->createShareObject($data);
323
-		}
324
-		$cursor->closeCursor();
325
-
326
-		return $children;
327
-	}
328
-
329
-	/**
330
-	 * add share to the database and return the ID
331
-	 *
332
-	 * @param int $itemSource
333
-	 * @param string $itemType
334
-	 * @param string $shareWith
335
-	 * @param string $sharedBy
336
-	 * @param string $uidOwner
337
-	 * @param int $permissions
338
-	 * @param string $token
339
-	 * @return int
340
-	 */
341
-	protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
342
-		$qb = $this->dbConnection->getQueryBuilder();
343
-		$qb->insert('share')
344
-			->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
345
-			->setValue('item_type', $qb->createNamedParameter($itemType))
346
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
347
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
348
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
349
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
350
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
351
-			->setValue('permissions', $qb->createNamedParameter($permissions))
352
-			->setValue('token', $qb->createNamedParameter($token))
353
-			->setValue('stime', $qb->createNamedParameter(time()));
354
-
355
-		/*
136
+        $alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
137
+        if (!empty($alreadyShared)) {
138
+            $message = 'Sharing %s failed, this item is already shared with %s';
139
+            $message_t = $this->l->t('Sharing %s failed, this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
140
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
141
+            throw new \Exception($message_t);
142
+        }
143
+
144
+        $shareId = $this->createMailShare($share);
145
+        $this->createActivity($share);
146
+        $data = $this->getRawShare($shareId);
147
+        return $this->createShareObject($data);
148
+
149
+    }
150
+
151
+    /**
152
+     * create activity if a file/folder was shared by mail
153
+     *
154
+     * @param IShare $share
155
+     */
156
+    protected function createActivity(IShare $share) {
157
+
158
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
159
+
160
+        $this->publishActivity(
161
+            Activity::SUBJECT_SHARED_EMAIL_SELF,
162
+            [$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
163
+            $share->getSharedBy(),
164
+            $share->getNode()->getId(),
165
+            $userFolder->getRelativePath($share->getNode()->getPath())
166
+        );
167
+
168
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
169
+            $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
170
+            $fileId = $share->getNode()->getId();
171
+            $nodes = $ownerFolder->getById($fileId);
172
+            $ownerPath = $nodes[0]->getPath();
173
+            $this->publishActivity(
174
+                Activity::SUBJECT_SHARED_EMAIL_BY,
175
+                [$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
176
+                $share->getShareOwner(),
177
+                $fileId,
178
+                $ownerFolder->getRelativePath($ownerPath)
179
+            );
180
+        }
181
+
182
+    }
183
+
184
+    /**
185
+     * publish activity if a file/folder was shared by mail
186
+     *
187
+     * @param $subject
188
+     * @param $parameters
189
+     * @param $affectedUser
190
+     * @param $fileId
191
+     * @param $filePath
192
+     */
193
+    protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
194
+        $event = $this->activityManager->generateEvent();
195
+        $event->setApp('sharebymail')
196
+            ->setType('shared')
197
+            ->setSubject($subject, $parameters)
198
+            ->setAffectedUser($affectedUser)
199
+            ->setObject('files', $fileId, $filePath);
200
+        $this->activityManager->publish($event);
201
+
202
+    }
203
+
204
+    /**
205
+     * @param IShare $share
206
+     * @return int
207
+     * @throws \Exception
208
+     */
209
+    protected function createMailShare(IShare $share) {
210
+        $share->setToken($this->generateToken());
211
+        $shareId = $this->addShareToDB(
212
+            $share->getNodeId(),
213
+            $share->getNodeType(),
214
+            $share->getSharedWith(),
215
+            $share->getSharedBy(),
216
+            $share->getShareOwner(),
217
+            $share->getPermissions(),
218
+            $share->getToken()
219
+        );
220
+
221
+        try {
222
+            $link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
223
+                ['token' => $share->getToken()]);
224
+            $this->sendMailNotification($share->getNode()->getName(),
225
+                $link,
226
+                $share->getShareOwner(),
227
+                $share->getSharedBy(), $share->getSharedWith());
228
+        } catch (HintException $hintException) {
229
+            $this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
230
+            $this->removeShareFromTable($shareId);
231
+            throw $hintException;
232
+        } catch (\Exception $e) {
233
+            $this->logger->error('Failed to send share by mail: ' . $e->getMessage());
234
+            $this->removeShareFromTable($shareId);
235
+            throw new HintException('Failed to send share by mail',
236
+                $this->l->t('Failed to send share by E-mail'));
237
+        }
238
+
239
+        return $shareId;
240
+
241
+    }
242
+
243
+    protected function sendMailNotification($filename, $link, $owner, $initiator, $shareWith) {
244
+        $ownerUser = $this->userManager->get($owner);
245
+        $initiatorUser = $this->userManager->get($initiator);
246
+        $ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
247
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
248
+        if ($owner === $initiator) {
249
+            $subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
250
+        } else {
251
+            $subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
252
+        }
253
+
254
+        $message = $this->mailer->createMessage();
255
+        $htmlBody = $this->createMailBody('mail', $filename, $link, $ownerDisplayName, $initiatorDisplayName);
256
+        $textBody = $this->createMailBody('altmail', $filename, $link, $ownerDisplayName, $initiatorDisplayName);
257
+        $message->setTo([$shareWith]);
258
+        $message->setSubject($subject);
259
+        $message->setBody($textBody, 'text/plain');
260
+        $message->setHtmlBody($htmlBody);
261
+        $this->mailer->send($message);
262
+
263
+    }
264
+
265
+    /**
266
+     * create mail body
267
+     *
268
+     * @param $filename
269
+     * @param $link
270
+     * @param $owner
271
+     * @param $initiator
272
+     * @return string plain text mail
273
+     * @throws HintException
274
+     */
275
+    protected function createMailBody($template, $filename, $link, $owner, $initiator) {
276
+
277
+        $mailBodyTemplate = new Template('sharebymail', $template, '');
278
+        $mailBodyTemplate->assign ('filename', $filename);
279
+        $mailBodyTemplate->assign ('link', $link);
280
+        $mailBodyTemplate->assign ('owner', $owner);
281
+        $mailBodyTemplate->assign ('initiator', $initiator);
282
+        $mailBodyTemplate->assign ('onBehalfOf', $initiator !== $owner);
283
+        $mailBody = $mailBodyTemplate->fetchPage();
284
+
285
+        if (is_string($mailBody)) {
286
+            return $mailBody;
287
+        }
288
+
289
+        throw new HintException('Failed to create the E-mail',
290
+            $this->l->t('Failed to create the E-mail'));
291
+    }
292
+
293
+    /**
294
+     * generate share token
295
+     *
296
+     * @return string
297
+     */
298
+    protected function generateToken() {
299
+        $token = $this->secureRandom->generate(
300
+            15, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
301
+        return $token;
302
+    }
303
+
304
+    /**
305
+     * Get all children of this share
306
+     *
307
+     * @param IShare $parent
308
+     * @return IShare[]
309
+     */
310
+    public function getChildren(IShare $parent) {
311
+        $children = [];
312
+
313
+        $qb = $this->dbConnection->getQueryBuilder();
314
+        $qb->select('*')
315
+            ->from('share')
316
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
317
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
318
+            ->orderBy('id');
319
+
320
+        $cursor = $qb->execute();
321
+        while($data = $cursor->fetch()) {
322
+            $children[] = $this->createShareObject($data);
323
+        }
324
+        $cursor->closeCursor();
325
+
326
+        return $children;
327
+    }
328
+
329
+    /**
330
+     * add share to the database and return the ID
331
+     *
332
+     * @param int $itemSource
333
+     * @param string $itemType
334
+     * @param string $shareWith
335
+     * @param string $sharedBy
336
+     * @param string $uidOwner
337
+     * @param int $permissions
338
+     * @param string $token
339
+     * @return int
340
+     */
341
+    protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
342
+        $qb = $this->dbConnection->getQueryBuilder();
343
+        $qb->insert('share')
344
+            ->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
345
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
346
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
347
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
348
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
349
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
350
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
351
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
352
+            ->setValue('token', $qb->createNamedParameter($token))
353
+            ->setValue('stime', $qb->createNamedParameter(time()));
354
+
355
+        /*
356 356
 		 * Added to fix https://github.com/owncloud/core/issues/22215
357 357
 		 * Can be removed once we get rid of ajax/share.php
358 358
 		 */
359
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
360
-
361
-		$qb->execute();
362
-		$id = $qb->getLastInsertId();
363
-
364
-		return (int)$id;
365
-	}
366
-
367
-	/**
368
-	 * Update a share
369
-	 *
370
-	 * @param IShare $share
371
-	 * @return IShare The share object
372
-	 */
373
-	public function update(IShare $share) {
374
-		/*
359
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
360
+
361
+        $qb->execute();
362
+        $id = $qb->getLastInsertId();
363
+
364
+        return (int)$id;
365
+    }
366
+
367
+    /**
368
+     * Update a share
369
+     *
370
+     * @param IShare $share
371
+     * @return IShare The share object
372
+     */
373
+    public function update(IShare $share) {
374
+        /*
375 375
 		 * We allow updating the permissions of mail shares
376 376
 		 */
377
-		$qb = $this->dbConnection->getQueryBuilder();
378
-			$qb->update('share')
379
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
380
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
381
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
382
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
383
-				->execute();
384
-
385
-		return $share;
386
-	}
387
-
388
-	/**
389
-	 * @inheritdoc
390
-	 */
391
-	public function move(IShare $share, $recipient) {
392
-		/**
393
-		 * nothing to do here, mail shares are only outgoing shares
394
-		 */
395
-		return $share;
396
-	}
397
-
398
-	/**
399
-	 * Delete a share (owner unShares the file)
400
-	 *
401
-	 * @param IShare $share
402
-	 */
403
-	public function delete(IShare $share) {
404
-		$this->removeShareFromTable($share->getId());
405
-	}
406
-
407
-	/**
408
-	 * @inheritdoc
409
-	 */
410
-	public function deleteFromSelf(IShare $share, $recipient) {
411
-		// nothing to do here, mail shares are only outgoing shares
412
-		return;
413
-	}
414
-
415
-	/**
416
-	 * @inheritdoc
417
-	 */
418
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
419
-		$qb = $this->dbConnection->getQueryBuilder();
420
-		$qb->select('*')
421
-			->from('share');
422
-
423
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
424
-
425
-		/**
426
-		 * Reshares for this user are shares where they are the owner.
427
-		 */
428
-		if ($reshares === false) {
429
-			//Special case for old shares created via the web UI
430
-			$or1 = $qb->expr()->andX(
431
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
432
-				$qb->expr()->isNull('uid_initiator')
433
-			);
434
-
435
-			$qb->andWhere(
436
-				$qb->expr()->orX(
437
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
438
-					$or1
439
-				)
440
-			);
441
-		} else {
442
-			$qb->andWhere(
443
-				$qb->expr()->orX(
444
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
445
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
446
-				)
447
-			);
448
-		}
449
-
450
-		if ($node !== null) {
451
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
452
-		}
453
-
454
-		if ($limit !== -1) {
455
-			$qb->setMaxResults($limit);
456
-		}
457
-
458
-		$qb->setFirstResult($offset);
459
-		$qb->orderBy('id');
460
-
461
-		$cursor = $qb->execute();
462
-		$shares = [];
463
-		while($data = $cursor->fetch()) {
464
-			$shares[] = $this->createShareObject($data);
465
-		}
466
-		$cursor->closeCursor();
467
-
468
-		return $shares;
469
-	}
470
-
471
-	/**
472
-	 * @inheritdoc
473
-	 */
474
-	public function getShareById($id, $recipientId = null) {
475
-		$qb = $this->dbConnection->getQueryBuilder();
476
-
477
-		$qb->select('*')
478
-			->from('share')
479
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
480
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
481
-
482
-		$cursor = $qb->execute();
483
-		$data = $cursor->fetch();
484
-		$cursor->closeCursor();
485
-
486
-		if ($data === false) {
487
-			throw new ShareNotFound();
488
-		}
489
-
490
-		try {
491
-			$share = $this->createShareObject($data);
492
-		} catch (InvalidShare $e) {
493
-			throw new ShareNotFound();
494
-		}
495
-
496
-		return $share;
497
-	}
498
-
499
-	/**
500
-	 * Get shares for a given path
501
-	 *
502
-	 * @param \OCP\Files\Node $path
503
-	 * @return IShare[]
504
-	 */
505
-	public function getSharesByPath(Node $path) {
506
-		$qb = $this->dbConnection->getQueryBuilder();
507
-
508
-		$cursor = $qb->select('*')
509
-			->from('share')
510
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
511
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
512
-			->execute();
513
-
514
-		$shares = [];
515
-		while($data = $cursor->fetch()) {
516
-			$shares[] = $this->createShareObject($data);
517
-		}
518
-		$cursor->closeCursor();
519
-
520
-		return $shares;
521
-	}
522
-
523
-	/**
524
-	 * @inheritdoc
525
-	 */
526
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
527
-		/** @var IShare[] $shares */
528
-		$shares = [];
529
-
530
-		//Get shares directly with this user
531
-		$qb = $this->dbConnection->getQueryBuilder();
532
-		$qb->select('*')
533
-			->from('share');
534
-
535
-		// Order by id
536
-		$qb->orderBy('id');
537
-
538
-		// Set limit and offset
539
-		if ($limit !== -1) {
540
-			$qb->setMaxResults($limit);
541
-		}
542
-		$qb->setFirstResult($offset);
543
-
544
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
545
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
546
-
547
-		// Filter by node if provided
548
-		if ($node !== null) {
549
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
550
-		}
551
-
552
-		$cursor = $qb->execute();
553
-
554
-		while($data = $cursor->fetch()) {
555
-			$shares[] = $this->createShareObject($data);
556
-		}
557
-		$cursor->closeCursor();
558
-
559
-
560
-		return $shares;
561
-	}
562
-
563
-	/**
564
-	 * Get a share by token
565
-	 *
566
-	 * @param string $token
567
-	 * @return IShare
568
-	 * @throws ShareNotFound
569
-	 */
570
-	public function getShareByToken($token) {
571
-		$qb = $this->dbConnection->getQueryBuilder();
572
-
573
-		$cursor = $qb->select('*')
574
-			->from('share')
575
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
576
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
577
-			->execute();
578
-
579
-		$data = $cursor->fetch();
580
-
581
-		if ($data === false) {
582
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
583
-		}
584
-
585
-		try {
586
-			$share = $this->createShareObject($data);
587
-		} catch (InvalidShare $e) {
588
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
589
-		}
590
-
591
-		return $share;
592
-	}
593
-
594
-	/**
595
-	 * remove share from table
596
-	 *
597
-	 * @param string $shareId
598
-	 */
599
-	protected function removeShareFromTable($shareId) {
600
-		$qb = $this->dbConnection->getQueryBuilder();
601
-		$qb->delete('share')
602
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
603
-		$qb->execute();
604
-	}
605
-
606
-	/**
607
-	 * Create a share object from an database row
608
-	 *
609
-	 * @param array $data
610
-	 * @return IShare
611
-	 * @throws InvalidShare
612
-	 * @throws ShareNotFound
613
-	 */
614
-	protected function createShareObject($data) {
615
-
616
-		$share = new Share($this->rootFolder, $this->userManager);
617
-		$share->setId((int)$data['id'])
618
-			->setShareType((int)$data['share_type'])
619
-			->setPermissions((int)$data['permissions'])
620
-			->setTarget($data['file_target'])
621
-			->setMailSend((bool)$data['mail_send'])
622
-			->setToken($data['token']);
623
-
624
-		$shareTime = new \DateTime();
625
-		$shareTime->setTimestamp((int)$data['stime']);
626
-		$share->setShareTime($shareTime);
627
-		$share->setSharedWith($data['share_with']);
628
-
629
-		if ($data['uid_initiator'] !== null) {
630
-			$share->setShareOwner($data['uid_owner']);
631
-			$share->setSharedBy($data['uid_initiator']);
632
-		} else {
633
-			//OLD SHARE
634
-			$share->setSharedBy($data['uid_owner']);
635
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
636
-
637
-			$owner = $path->getOwner();
638
-			$share->setShareOwner($owner->getUID());
639
-		}
640
-
641
-		$share->setNodeId((int)$data['file_source']);
642
-		$share->setNodeType($data['item_type']);
643
-
644
-		$share->setProviderId($this->identifier());
645
-
646
-		return $share;
647
-	}
648
-
649
-	/**
650
-	 * Get the node with file $id for $user
651
-	 *
652
-	 * @param string $userId
653
-	 * @param int $id
654
-	 * @return \OCP\Files\File|\OCP\Files\Folder
655
-	 * @throws InvalidShare
656
-	 */
657
-	private function getNode($userId, $id) {
658
-		try {
659
-			$userFolder = $this->rootFolder->getUserFolder($userId);
660
-		} catch (NotFoundException $e) {
661
-			throw new InvalidShare();
662
-		}
663
-
664
-		$nodes = $userFolder->getById($id);
665
-
666
-		if (empty($nodes)) {
667
-			throw new InvalidShare();
668
-		}
669
-
670
-		return $nodes[0];
671
-	}
672
-
673
-	/**
674
-	 * A user is deleted from the system
675
-	 * So clean up the relevant shares.
676
-	 *
677
-	 * @param string $uid
678
-	 * @param int $shareType
679
-	 */
680
-	public function userDeleted($uid, $shareType) {
681
-		$qb = $this->dbConnection->getQueryBuilder();
682
-
683
-		$qb->delete('share')
684
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
685
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
686
-			->execute();
687
-	}
688
-
689
-	/**
690
-	 * This provider does not support group shares
691
-	 *
692
-	 * @param string $gid
693
-	 */
694
-	public function groupDeleted($gid) {
695
-		return;
696
-	}
697
-
698
-	/**
699
-	 * This provider does not support group shares
700
-	 *
701
-	 * @param string $uid
702
-	 * @param string $gid
703
-	 */
704
-	public function userDeletedFromGroup($uid, $gid) {
705
-		return;
706
-	}
707
-
708
-	/**
709
-	 * get database row of a give share
710
-	 *
711
-	 * @param $id
712
-	 * @return array
713
-	 * @throws ShareNotFound
714
-	 */
715
-	protected function getRawShare($id) {
716
-
717
-		// Now fetch the inserted share and create a complete share object
718
-		$qb = $this->dbConnection->getQueryBuilder();
719
-		$qb->select('*')
720
-			->from('share')
721
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
722
-
723
-		$cursor = $qb->execute();
724
-		$data = $cursor->fetch();
725
-		$cursor->closeCursor();
726
-
727
-		if ($data === false) {
728
-			throw new ShareNotFound;
729
-		}
730
-
731
-		return $data;
732
-	}
733
-
734
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
735
-		$qb = $this->dbConnection->getQueryBuilder();
736
-		$qb->select('*')
737
-			->from('share', 's')
738
-			->andWhere($qb->expr()->orX(
739
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
740
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
741
-			))
742
-			->andWhere(
743
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
744
-			);
745
-
746
-		/**
747
-		 * Reshares for this user are shares where they are the owner.
748
-		 */
749
-		if ($reshares === false) {
750
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
751
-		} else {
752
-			$qb->andWhere(
753
-				$qb->expr()->orX(
754
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
755
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
756
-				)
757
-			);
758
-		}
759
-
760
-		$qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
761
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
762
-
763
-		$qb->orderBy('id');
764
-
765
-		$cursor = $qb->execute();
766
-		$shares = [];
767
-		while ($data = $cursor->fetch()) {
768
-			$shares[$data['fileid']][] = $this->createShareObject($data);
769
-		}
770
-		$cursor->closeCursor();
771
-
772
-		return $shares;
773
-	}
377
+        $qb = $this->dbConnection->getQueryBuilder();
378
+            $qb->update('share')
379
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
380
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
381
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
382
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
383
+                ->execute();
384
+
385
+        return $share;
386
+    }
387
+
388
+    /**
389
+     * @inheritdoc
390
+     */
391
+    public function move(IShare $share, $recipient) {
392
+        /**
393
+         * nothing to do here, mail shares are only outgoing shares
394
+         */
395
+        return $share;
396
+    }
397
+
398
+    /**
399
+     * Delete a share (owner unShares the file)
400
+     *
401
+     * @param IShare $share
402
+     */
403
+    public function delete(IShare $share) {
404
+        $this->removeShareFromTable($share->getId());
405
+    }
406
+
407
+    /**
408
+     * @inheritdoc
409
+     */
410
+    public function deleteFromSelf(IShare $share, $recipient) {
411
+        // nothing to do here, mail shares are only outgoing shares
412
+        return;
413
+    }
414
+
415
+    /**
416
+     * @inheritdoc
417
+     */
418
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
419
+        $qb = $this->dbConnection->getQueryBuilder();
420
+        $qb->select('*')
421
+            ->from('share');
422
+
423
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
424
+
425
+        /**
426
+         * Reshares for this user are shares where they are the owner.
427
+         */
428
+        if ($reshares === false) {
429
+            //Special case for old shares created via the web UI
430
+            $or1 = $qb->expr()->andX(
431
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
432
+                $qb->expr()->isNull('uid_initiator')
433
+            );
434
+
435
+            $qb->andWhere(
436
+                $qb->expr()->orX(
437
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
438
+                    $or1
439
+                )
440
+            );
441
+        } else {
442
+            $qb->andWhere(
443
+                $qb->expr()->orX(
444
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
445
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
446
+                )
447
+            );
448
+        }
449
+
450
+        if ($node !== null) {
451
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
452
+        }
453
+
454
+        if ($limit !== -1) {
455
+            $qb->setMaxResults($limit);
456
+        }
457
+
458
+        $qb->setFirstResult($offset);
459
+        $qb->orderBy('id');
460
+
461
+        $cursor = $qb->execute();
462
+        $shares = [];
463
+        while($data = $cursor->fetch()) {
464
+            $shares[] = $this->createShareObject($data);
465
+        }
466
+        $cursor->closeCursor();
467
+
468
+        return $shares;
469
+    }
470
+
471
+    /**
472
+     * @inheritdoc
473
+     */
474
+    public function getShareById($id, $recipientId = null) {
475
+        $qb = $this->dbConnection->getQueryBuilder();
476
+
477
+        $qb->select('*')
478
+            ->from('share')
479
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
480
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
481
+
482
+        $cursor = $qb->execute();
483
+        $data = $cursor->fetch();
484
+        $cursor->closeCursor();
485
+
486
+        if ($data === false) {
487
+            throw new ShareNotFound();
488
+        }
489
+
490
+        try {
491
+            $share = $this->createShareObject($data);
492
+        } catch (InvalidShare $e) {
493
+            throw new ShareNotFound();
494
+        }
495
+
496
+        return $share;
497
+    }
498
+
499
+    /**
500
+     * Get shares for a given path
501
+     *
502
+     * @param \OCP\Files\Node $path
503
+     * @return IShare[]
504
+     */
505
+    public function getSharesByPath(Node $path) {
506
+        $qb = $this->dbConnection->getQueryBuilder();
507
+
508
+        $cursor = $qb->select('*')
509
+            ->from('share')
510
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
511
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
512
+            ->execute();
513
+
514
+        $shares = [];
515
+        while($data = $cursor->fetch()) {
516
+            $shares[] = $this->createShareObject($data);
517
+        }
518
+        $cursor->closeCursor();
519
+
520
+        return $shares;
521
+    }
522
+
523
+    /**
524
+     * @inheritdoc
525
+     */
526
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
527
+        /** @var IShare[] $shares */
528
+        $shares = [];
529
+
530
+        //Get shares directly with this user
531
+        $qb = $this->dbConnection->getQueryBuilder();
532
+        $qb->select('*')
533
+            ->from('share');
534
+
535
+        // Order by id
536
+        $qb->orderBy('id');
537
+
538
+        // Set limit and offset
539
+        if ($limit !== -1) {
540
+            $qb->setMaxResults($limit);
541
+        }
542
+        $qb->setFirstResult($offset);
543
+
544
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
545
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
546
+
547
+        // Filter by node if provided
548
+        if ($node !== null) {
549
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
550
+        }
551
+
552
+        $cursor = $qb->execute();
553
+
554
+        while($data = $cursor->fetch()) {
555
+            $shares[] = $this->createShareObject($data);
556
+        }
557
+        $cursor->closeCursor();
558
+
559
+
560
+        return $shares;
561
+    }
562
+
563
+    /**
564
+     * Get a share by token
565
+     *
566
+     * @param string $token
567
+     * @return IShare
568
+     * @throws ShareNotFound
569
+     */
570
+    public function getShareByToken($token) {
571
+        $qb = $this->dbConnection->getQueryBuilder();
572
+
573
+        $cursor = $qb->select('*')
574
+            ->from('share')
575
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
576
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
577
+            ->execute();
578
+
579
+        $data = $cursor->fetch();
580
+
581
+        if ($data === false) {
582
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
583
+        }
584
+
585
+        try {
586
+            $share = $this->createShareObject($data);
587
+        } catch (InvalidShare $e) {
588
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
589
+        }
590
+
591
+        return $share;
592
+    }
593
+
594
+    /**
595
+     * remove share from table
596
+     *
597
+     * @param string $shareId
598
+     */
599
+    protected function removeShareFromTable($shareId) {
600
+        $qb = $this->dbConnection->getQueryBuilder();
601
+        $qb->delete('share')
602
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
603
+        $qb->execute();
604
+    }
605
+
606
+    /**
607
+     * Create a share object from an database row
608
+     *
609
+     * @param array $data
610
+     * @return IShare
611
+     * @throws InvalidShare
612
+     * @throws ShareNotFound
613
+     */
614
+    protected function createShareObject($data) {
615
+
616
+        $share = new Share($this->rootFolder, $this->userManager);
617
+        $share->setId((int)$data['id'])
618
+            ->setShareType((int)$data['share_type'])
619
+            ->setPermissions((int)$data['permissions'])
620
+            ->setTarget($data['file_target'])
621
+            ->setMailSend((bool)$data['mail_send'])
622
+            ->setToken($data['token']);
623
+
624
+        $shareTime = new \DateTime();
625
+        $shareTime->setTimestamp((int)$data['stime']);
626
+        $share->setShareTime($shareTime);
627
+        $share->setSharedWith($data['share_with']);
628
+
629
+        if ($data['uid_initiator'] !== null) {
630
+            $share->setShareOwner($data['uid_owner']);
631
+            $share->setSharedBy($data['uid_initiator']);
632
+        } else {
633
+            //OLD SHARE
634
+            $share->setSharedBy($data['uid_owner']);
635
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
636
+
637
+            $owner = $path->getOwner();
638
+            $share->setShareOwner($owner->getUID());
639
+        }
640
+
641
+        $share->setNodeId((int)$data['file_source']);
642
+        $share->setNodeType($data['item_type']);
643
+
644
+        $share->setProviderId($this->identifier());
645
+
646
+        return $share;
647
+    }
648
+
649
+    /**
650
+     * Get the node with file $id for $user
651
+     *
652
+     * @param string $userId
653
+     * @param int $id
654
+     * @return \OCP\Files\File|\OCP\Files\Folder
655
+     * @throws InvalidShare
656
+     */
657
+    private function getNode($userId, $id) {
658
+        try {
659
+            $userFolder = $this->rootFolder->getUserFolder($userId);
660
+        } catch (NotFoundException $e) {
661
+            throw new InvalidShare();
662
+        }
663
+
664
+        $nodes = $userFolder->getById($id);
665
+
666
+        if (empty($nodes)) {
667
+            throw new InvalidShare();
668
+        }
669
+
670
+        return $nodes[0];
671
+    }
672
+
673
+    /**
674
+     * A user is deleted from the system
675
+     * So clean up the relevant shares.
676
+     *
677
+     * @param string $uid
678
+     * @param int $shareType
679
+     */
680
+    public function userDeleted($uid, $shareType) {
681
+        $qb = $this->dbConnection->getQueryBuilder();
682
+
683
+        $qb->delete('share')
684
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
685
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
686
+            ->execute();
687
+    }
688
+
689
+    /**
690
+     * This provider does not support group shares
691
+     *
692
+     * @param string $gid
693
+     */
694
+    public function groupDeleted($gid) {
695
+        return;
696
+    }
697
+
698
+    /**
699
+     * This provider does not support group shares
700
+     *
701
+     * @param string $uid
702
+     * @param string $gid
703
+     */
704
+    public function userDeletedFromGroup($uid, $gid) {
705
+        return;
706
+    }
707
+
708
+    /**
709
+     * get database row of a give share
710
+     *
711
+     * @param $id
712
+     * @return array
713
+     * @throws ShareNotFound
714
+     */
715
+    protected function getRawShare($id) {
716
+
717
+        // Now fetch the inserted share and create a complete share object
718
+        $qb = $this->dbConnection->getQueryBuilder();
719
+        $qb->select('*')
720
+            ->from('share')
721
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
722
+
723
+        $cursor = $qb->execute();
724
+        $data = $cursor->fetch();
725
+        $cursor->closeCursor();
726
+
727
+        if ($data === false) {
728
+            throw new ShareNotFound;
729
+        }
730
+
731
+        return $data;
732
+    }
733
+
734
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
735
+        $qb = $this->dbConnection->getQueryBuilder();
736
+        $qb->select('*')
737
+            ->from('share', 's')
738
+            ->andWhere($qb->expr()->orX(
739
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
740
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
741
+            ))
742
+            ->andWhere(
743
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
744
+            );
745
+
746
+        /**
747
+         * Reshares for this user are shares where they are the owner.
748
+         */
749
+        if ($reshares === false) {
750
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
751
+        } else {
752
+            $qb->andWhere(
753
+                $qb->expr()->orX(
754
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
755
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
756
+                )
757
+            );
758
+        }
759
+
760
+        $qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
761
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
762
+
763
+        $qb->orderBy('id');
764
+
765
+        $cursor = $qb->execute();
766
+        $shares = [];
767
+        while ($data = $cursor->fetch()) {
768
+            $shares[$data['fileid']][] = $this->createShareObject($data);
769
+        }
770
+        $cursor->closeCursor();
771
+
772
+        return $shares;
773
+    }
774 774
 
775 775
 }
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -226,11 +226,11 @@  discard block
 block discarded – undo
226 226
 				$share->getShareOwner(),
227 227
 				$share->getSharedBy(), $share->getSharedWith());
228 228
 		} catch (HintException $hintException) {
229
-			$this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
229
+			$this->logger->error('Failed to send share by mail: '.$hintException->getMessage());
230 230
 			$this->removeShareFromTable($shareId);
231 231
 			throw $hintException;
232 232
 		} catch (\Exception $e) {
233
-			$this->logger->error('Failed to send share by mail: ' . $e->getMessage());
233
+			$this->logger->error('Failed to send share by mail: '.$e->getMessage());
234 234
 			$this->removeShareFromTable($shareId);
235 235
 			throw new HintException('Failed to send share by mail',
236 236
 				$this->l->t('Failed to send share by E-mail'));
@@ -246,9 +246,9 @@  discard block
 block discarded – undo
246 246
 		$ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
247 247
 		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
248 248
 		if ($owner === $initiator) {
249
-			$subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
249
+			$subject = (string) $this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
250 250
 		} else {
251
-			$subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
251
+			$subject = (string) $this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
252 252
 		}
253 253
 
254 254
 		$message = $this->mailer->createMessage();
@@ -275,11 +275,11 @@  discard block
 block discarded – undo
275 275
 	protected function createMailBody($template, $filename, $link, $owner, $initiator) {
276 276
 
277 277
 		$mailBodyTemplate = new Template('sharebymail', $template, '');
278
-		$mailBodyTemplate->assign ('filename', $filename);
279
-		$mailBodyTemplate->assign ('link', $link);
280
-		$mailBodyTemplate->assign ('owner', $owner);
281
-		$mailBodyTemplate->assign ('initiator', $initiator);
282
-		$mailBodyTemplate->assign ('onBehalfOf', $initiator !== $owner);
278
+		$mailBodyTemplate->assign('filename', $filename);
279
+		$mailBodyTemplate->assign('link', $link);
280
+		$mailBodyTemplate->assign('owner', $owner);
281
+		$mailBodyTemplate->assign('initiator', $initiator);
282
+		$mailBodyTemplate->assign('onBehalfOf', $initiator !== $owner);
283 283
 		$mailBody = $mailBodyTemplate->fetchPage();
284 284
 
285 285
 		if (is_string($mailBody)) {
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
 	 */
298 298
 	protected function generateToken() {
299 299
 		$token = $this->secureRandom->generate(
300
-			15, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
300
+			15, ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
301 301
 		return $token;
302 302
 	}
303 303
 
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
 			->orderBy('id');
319 319
 
320 320
 		$cursor = $qb->execute();
321
-		while($data = $cursor->fetch()) {
321
+		while ($data = $cursor->fetch()) {
322 322
 			$children[] = $this->createShareObject($data);
323 323
 		}
324 324
 		$cursor->closeCursor();
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
 		$qb->execute();
362 362
 		$id = $qb->getLastInsertId();
363 363
 
364
-		return (int)$id;
364
+		return (int) $id;
365 365
 	}
366 366
 
367 367
 	/**
@@ -460,7 +460,7 @@  discard block
 block discarded – undo
460 460
 
461 461
 		$cursor = $qb->execute();
462 462
 		$shares = [];
463
-		while($data = $cursor->fetch()) {
463
+		while ($data = $cursor->fetch()) {
464 464
 			$shares[] = $this->createShareObject($data);
465 465
 		}
466 466
 		$cursor->closeCursor();
@@ -512,7 +512,7 @@  discard block
 block discarded – undo
512 512
 			->execute();
513 513
 
514 514
 		$shares = [];
515
-		while($data = $cursor->fetch()) {
515
+		while ($data = $cursor->fetch()) {
516 516
 			$shares[] = $this->createShareObject($data);
517 517
 		}
518 518
 		$cursor->closeCursor();
@@ -551,7 +551,7 @@  discard block
 block discarded – undo
551 551
 
552 552
 		$cursor = $qb->execute();
553 553
 
554
-		while($data = $cursor->fetch()) {
554
+		while ($data = $cursor->fetch()) {
555 555
 			$shares[] = $this->createShareObject($data);
556 556
 		}
557 557
 		$cursor->closeCursor();
@@ -614,15 +614,15 @@  discard block
 block discarded – undo
614 614
 	protected function createShareObject($data) {
615 615
 
616 616
 		$share = new Share($this->rootFolder, $this->userManager);
617
-		$share->setId((int)$data['id'])
618
-			->setShareType((int)$data['share_type'])
619
-			->setPermissions((int)$data['permissions'])
617
+		$share->setId((int) $data['id'])
618
+			->setShareType((int) $data['share_type'])
619
+			->setPermissions((int) $data['permissions'])
620 620
 			->setTarget($data['file_target'])
621
-			->setMailSend((bool)$data['mail_send'])
621
+			->setMailSend((bool) $data['mail_send'])
622 622
 			->setToken($data['token']);
623 623
 
624 624
 		$shareTime = new \DateTime();
625
-		$shareTime->setTimestamp((int)$data['stime']);
625
+		$shareTime->setTimestamp((int) $data['stime']);
626 626
 		$share->setShareTime($shareTime);
627 627
 		$share->setSharedWith($data['share_with']);
628 628
 
@@ -632,13 +632,13 @@  discard block
 block discarded – undo
632 632
 		} else {
633 633
 			//OLD SHARE
634 634
 			$share->setSharedBy($data['uid_owner']);
635
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
635
+			$path = $this->getNode($share->getSharedBy(), (int) $data['file_source']);
636 636
 
637 637
 			$owner = $path->getOwner();
638 638
 			$share->setShareOwner($owner->getUID());
639 639
 		}
640 640
 
641
-		$share->setNodeId((int)$data['file_source']);
641
+		$share->setNodeId((int) $data['file_source']);
642 642
 		$share->setNodeType($data['item_type']);
643 643
 
644 644
 		$share->setProviderId($this->identifier());
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
 			);
758 758
 		}
759 759
 
760
-		$qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
760
+		$qb->innerJoin('s', 'filecache', 'f', 's.file_source = f.fileid');
761 761
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
762 762
 
763 763
 		$qb->orderBy('id');
Please login to merge, or discard this patch.
apps/user_ldap/lib/Helper.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -124,6 +124,9 @@
 block discarded – undo
124 124
 		return $nextPrefix;
125 125
 	}
126 126
 
127
+	/**
128
+	 * @param string $value
129
+	 */
127 130
 	private function getServersConfig($value) {
128 131
 		$regex = '/' . $value . '$/S';
129 132
 
Please login to merge, or discard this patch.
Indentation   +258 added lines, -258 removed lines patch added patch discarded remove patch
@@ -34,126 +34,126 @@  discard block
 block discarded – undo
34 34
 
35 35
 class Helper {
36 36
 
37
-	/** @var IConfig */
38
-	private $config;
39
-
40
-	/**
41
-	 * Helper constructor.
42
-	 *
43
-	 * @param IConfig $config
44
-	 */
45
-	public function __construct(IConfig $config) {
46
-		$this->config = $config;
47
-	}
48
-
49
-	/**
50
-	 * returns prefixes for each saved LDAP/AD server configuration.
51
-	 * @param bool $activeConfigurations optional, whether only active configuration shall be
52
-	 * retrieved, defaults to false
53
-	 * @return array with a list of the available prefixes
54
-	 *
55
-	 * Configuration prefixes are used to set up configurations for n LDAP or
56
-	 * AD servers. Since configuration is stored in the database, table
57
-	 * appconfig under appid user_ldap, the common identifiers in column
58
-	 * 'configkey' have a prefix. The prefix for the very first server
59
-	 * configuration is empty.
60
-	 * Configkey Examples:
61
-	 * Server 1: ldap_login_filter
62
-	 * Server 2: s1_ldap_login_filter
63
-	 * Server 3: s2_ldap_login_filter
64
-	 *
65
-	 * The prefix needs to be passed to the constructor of Connection class,
66
-	 * except the default (first) server shall be connected to.
67
-	 *
68
-	 */
69
-	public function getServerConfigurationPrefixes($activeConfigurations = false) {
70
-		$referenceConfigkey = 'ldap_configuration_active';
71
-
72
-		$keys = $this->getServersConfig($referenceConfigkey);
73
-
74
-		$prefixes = [];
75
-		foreach ($keys as $key) {
76
-			if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') {
77
-				continue;
78
-			}
79
-
80
-			$len = strlen($key) - strlen($referenceConfigkey);
81
-			$prefixes[] = substr($key, 0, $len);
82
-		}
83
-
84
-		return $prefixes;
85
-	}
86
-
87
-	/**
88
-	 *
89
-	 * determines the host for every configured connection
90
-	 * @return array an array with configprefix as keys
91
-	 *
92
-	 */
93
-	public function getServerConfigurationHosts() {
94
-		$referenceConfigkey = 'ldap_host';
95
-
96
-		$keys = $this->getServersConfig($referenceConfigkey);
97
-
98
-		$result = array();
99
-		foreach($keys as $key) {
100
-			$len = strlen($key) - strlen($referenceConfigkey);
101
-			$prefix = substr($key, 0, $len);
102
-			$result[$prefix] = $this->config->getAppValue('user_ldap', $key);
103
-		}
104
-
105
-		return $result;
106
-	}
107
-
108
-	/**
109
-	 * return the next available configuration prefix
110
-	 *
111
-	 * @return string
112
-	 */
113
-	public function getNextServerConfigurationPrefix() {
114
-		$serverConnections = $this->getServerConfigurationPrefixes();
115
-
116
-		if(count($serverConnections) === 0) {
117
-			return 's01';
118
-		}
119
-
120
-		sort($serverConnections);
121
-		$lastKey = array_pop($serverConnections);
122
-		$lastNumber = intval(str_replace('s', '', $lastKey));
123
-		$nextPrefix = 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
124
-		return $nextPrefix;
125
-	}
126
-
127
-	private function getServersConfig($value) {
128
-		$regex = '/' . $value . '$/S';
129
-
130
-		$keys = $this->config->getAppKeys('user_ldap');
131
-		$result = [];
132
-		foreach ($keys as $key) {
133
-			if (preg_match($regex, $key) === 1) {
134
-				$result[] = $key;
135
-			}
136
-		}
137
-
138
-		return $result;
139
-	}
140
-
141
-	/**
142
-	 * deletes a given saved LDAP/AD server configuration.
143
-	 * @param string $prefix the configuration prefix of the config to delete
144
-	 * @return bool true on success, false otherwise
145
-	 */
146
-	public function deleteServerConfiguration($prefix) {
147
-		if(!in_array($prefix, self::getServerConfigurationPrefixes())) {
148
-			return false;
149
-		}
150
-
151
-		$saveOtherConfigurations = '';
152
-		if(empty($prefix)) {
153
-			$saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
154
-		}
155
-
156
-		$query = \OCP\DB::prepare('
37
+    /** @var IConfig */
38
+    private $config;
39
+
40
+    /**
41
+     * Helper constructor.
42
+     *
43
+     * @param IConfig $config
44
+     */
45
+    public function __construct(IConfig $config) {
46
+        $this->config = $config;
47
+    }
48
+
49
+    /**
50
+     * returns prefixes for each saved LDAP/AD server configuration.
51
+     * @param bool $activeConfigurations optional, whether only active configuration shall be
52
+     * retrieved, defaults to false
53
+     * @return array with a list of the available prefixes
54
+     *
55
+     * Configuration prefixes are used to set up configurations for n LDAP or
56
+     * AD servers. Since configuration is stored in the database, table
57
+     * appconfig under appid user_ldap, the common identifiers in column
58
+     * 'configkey' have a prefix. The prefix for the very first server
59
+     * configuration is empty.
60
+     * Configkey Examples:
61
+     * Server 1: ldap_login_filter
62
+     * Server 2: s1_ldap_login_filter
63
+     * Server 3: s2_ldap_login_filter
64
+     *
65
+     * The prefix needs to be passed to the constructor of Connection class,
66
+     * except the default (first) server shall be connected to.
67
+     *
68
+     */
69
+    public function getServerConfigurationPrefixes($activeConfigurations = false) {
70
+        $referenceConfigkey = 'ldap_configuration_active';
71
+
72
+        $keys = $this->getServersConfig($referenceConfigkey);
73
+
74
+        $prefixes = [];
75
+        foreach ($keys as $key) {
76
+            if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') {
77
+                continue;
78
+            }
79
+
80
+            $len = strlen($key) - strlen($referenceConfigkey);
81
+            $prefixes[] = substr($key, 0, $len);
82
+        }
83
+
84
+        return $prefixes;
85
+    }
86
+
87
+    /**
88
+     *
89
+     * determines the host for every configured connection
90
+     * @return array an array with configprefix as keys
91
+     *
92
+     */
93
+    public function getServerConfigurationHosts() {
94
+        $referenceConfigkey = 'ldap_host';
95
+
96
+        $keys = $this->getServersConfig($referenceConfigkey);
97
+
98
+        $result = array();
99
+        foreach($keys as $key) {
100
+            $len = strlen($key) - strlen($referenceConfigkey);
101
+            $prefix = substr($key, 0, $len);
102
+            $result[$prefix] = $this->config->getAppValue('user_ldap', $key);
103
+        }
104
+
105
+        return $result;
106
+    }
107
+
108
+    /**
109
+     * return the next available configuration prefix
110
+     *
111
+     * @return string
112
+     */
113
+    public function getNextServerConfigurationPrefix() {
114
+        $serverConnections = $this->getServerConfigurationPrefixes();
115
+
116
+        if(count($serverConnections) === 0) {
117
+            return 's01';
118
+        }
119
+
120
+        sort($serverConnections);
121
+        $lastKey = array_pop($serverConnections);
122
+        $lastNumber = intval(str_replace('s', '', $lastKey));
123
+        $nextPrefix = 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
124
+        return $nextPrefix;
125
+    }
126
+
127
+    private function getServersConfig($value) {
128
+        $regex = '/' . $value . '$/S';
129
+
130
+        $keys = $this->config->getAppKeys('user_ldap');
131
+        $result = [];
132
+        foreach ($keys as $key) {
133
+            if (preg_match($regex, $key) === 1) {
134
+                $result[] = $key;
135
+            }
136
+        }
137
+
138
+        return $result;
139
+    }
140
+
141
+    /**
142
+     * deletes a given saved LDAP/AD server configuration.
143
+     * @param string $prefix the configuration prefix of the config to delete
144
+     * @return bool true on success, false otherwise
145
+     */
146
+    public function deleteServerConfiguration($prefix) {
147
+        if(!in_array($prefix, self::getServerConfigurationPrefixes())) {
148
+            return false;
149
+        }
150
+
151
+        $saveOtherConfigurations = '';
152
+        if(empty($prefix)) {
153
+            $saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
154
+        }
155
+
156
+        $query = \OCP\DB::prepare('
157 157
 			DELETE
158 158
 			FROM `*PREFIX*appconfig`
159 159
 			WHERE `configkey` LIKE ?
@@ -161,145 +161,145 @@  discard block
 block discarded – undo
161 161
 				AND `appid` = \'user_ldap\'
162 162
 				AND `configkey` NOT IN (\'enabled\', \'installed_version\', \'types\', \'bgjUpdateGroupsLastRun\')
163 163
 		');
164
-		$delRows = $query->execute(array($prefix.'%'));
165
-
166
-		if(\OCP\DB::isError($delRows)) {
167
-			return false;
168
-		}
169
-
170
-		if($delRows === 0) {
171
-			return false;
172
-		}
173
-
174
-		return true;
175
-	}
176
-
177
-	/**
178
-	 * checks whether there is one or more disabled LDAP configurations
179
-	 * @throws \Exception
180
-	 * @return bool
181
-	 */
182
-	public function haveDisabledConfigurations() {
183
-		$all = $this->getServerConfigurationPrefixes(false);
184
-		$active = $this->getServerConfigurationPrefixes(true);
185
-
186
-		if(!is_array($all) || !is_array($active)) {
187
-			throw new \Exception('Unexpected Return Value');
188
-		}
189
-
190
-		return count($all) !== count($active) || count($all) === 0;
191
-	}
192
-
193
-	/**
194
-	 * extracts the domain from a given URL
195
-	 * @param string $url the URL
196
-	 * @return string|false domain as string on success, false otherwise
197
-	 */
198
-	public function getDomainFromURL($url) {
199
-		$uinfo = parse_url($url);
200
-		if(!is_array($uinfo)) {
201
-			return false;
202
-		}
203
-
204
-		$domain = false;
205
-		if(isset($uinfo['host'])) {
206
-			$domain = $uinfo['host'];
207
-		} else if(isset($uinfo['path'])) {
208
-			$domain = $uinfo['path'];
209
-		}
210
-
211
-		return $domain;
212
-	}
164
+        $delRows = $query->execute(array($prefix.'%'));
165
+
166
+        if(\OCP\DB::isError($delRows)) {
167
+            return false;
168
+        }
169
+
170
+        if($delRows === 0) {
171
+            return false;
172
+        }
173
+
174
+        return true;
175
+    }
176
+
177
+    /**
178
+     * checks whether there is one or more disabled LDAP configurations
179
+     * @throws \Exception
180
+     * @return bool
181
+     */
182
+    public function haveDisabledConfigurations() {
183
+        $all = $this->getServerConfigurationPrefixes(false);
184
+        $active = $this->getServerConfigurationPrefixes(true);
185
+
186
+        if(!is_array($all) || !is_array($active)) {
187
+            throw new \Exception('Unexpected Return Value');
188
+        }
189
+
190
+        return count($all) !== count($active) || count($all) === 0;
191
+    }
192
+
193
+    /**
194
+     * extracts the domain from a given URL
195
+     * @param string $url the URL
196
+     * @return string|false domain as string on success, false otherwise
197
+     */
198
+    public function getDomainFromURL($url) {
199
+        $uinfo = parse_url($url);
200
+        if(!is_array($uinfo)) {
201
+            return false;
202
+        }
203
+
204
+        $domain = false;
205
+        if(isset($uinfo['host'])) {
206
+            $domain = $uinfo['host'];
207
+        } else if(isset($uinfo['path'])) {
208
+            $domain = $uinfo['path'];
209
+        }
210
+
211
+        return $domain;
212
+    }
213 213
 	
214
-	/**
215
-	 *
216
-	 * Set the LDAPProvider in the config
217
-	 *
218
-	 */
219
-	public function setLDAPProvider() {
220
-		$current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
221
-		if(is_null($current)) {
222
-			\OC::$server->getConfig()->setSystemValue('ldapProviderFactory', '\\OCA\\User_LDAP\\LDAPProviderFactory');
223
-		}
224
-	}
214
+    /**
215
+     *
216
+     * Set the LDAPProvider in the config
217
+     *
218
+     */
219
+    public function setLDAPProvider() {
220
+        $current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
221
+        if(is_null($current)) {
222
+            \OC::$server->getConfig()->setSystemValue('ldapProviderFactory', '\\OCA\\User_LDAP\\LDAPProviderFactory');
223
+        }
224
+    }
225 225
 	
226
-	/**
227
-	 * sanitizes a DN received from the LDAP server
228
-	 * @param array $dn the DN in question
229
-	 * @return array the sanitized DN
230
-	 */
231
-	public function sanitizeDN($dn) {
232
-		//treating multiple base DNs
233
-		if(is_array($dn)) {
234
-			$result = array();
235
-			foreach($dn as $singleDN) {
236
-				$result[] = $this->sanitizeDN($singleDN);
237
-			}
238
-			return $result;
239
-		}
240
-
241
-		//OID sometimes gives back DNs with whitespace after the comma
242
-		// a la "uid=foo, cn=bar, dn=..." We need to tackle this!
243
-		$dn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
244
-
245
-		//make comparisons and everything work
246
-		$dn = mb_strtolower($dn, 'UTF-8');
247
-
248
-		//escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
249
-		//to use the DN in search filters, \ needs to be escaped to \5c additionally
250
-		//to use them in bases, we convert them back to simple backslashes in readAttribute()
251
-		$replacements = array(
252
-			'\,' => '\5c2C',
253
-			'\=' => '\5c3D',
254
-			'\+' => '\5c2B',
255
-			'\<' => '\5c3C',
256
-			'\>' => '\5c3E',
257
-			'\;' => '\5c3B',
258
-			'\"' => '\5c22',
259
-			'\#' => '\5c23',
260
-			'('  => '\28',
261
-			')'  => '\29',
262
-			'*'  => '\2A',
263
-		);
264
-		$dn = str_replace(array_keys($replacements), array_values($replacements), $dn);
265
-
266
-		return $dn;
267
-	}
226
+    /**
227
+     * sanitizes a DN received from the LDAP server
228
+     * @param array $dn the DN in question
229
+     * @return array the sanitized DN
230
+     */
231
+    public function sanitizeDN($dn) {
232
+        //treating multiple base DNs
233
+        if(is_array($dn)) {
234
+            $result = array();
235
+            foreach($dn as $singleDN) {
236
+                $result[] = $this->sanitizeDN($singleDN);
237
+            }
238
+            return $result;
239
+        }
240
+
241
+        //OID sometimes gives back DNs with whitespace after the comma
242
+        // a la "uid=foo, cn=bar, dn=..." We need to tackle this!
243
+        $dn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
244
+
245
+        //make comparisons and everything work
246
+        $dn = mb_strtolower($dn, 'UTF-8');
247
+
248
+        //escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
249
+        //to use the DN in search filters, \ needs to be escaped to \5c additionally
250
+        //to use them in bases, we convert them back to simple backslashes in readAttribute()
251
+        $replacements = array(
252
+            '\,' => '\5c2C',
253
+            '\=' => '\5c3D',
254
+            '\+' => '\5c2B',
255
+            '\<' => '\5c3C',
256
+            '\>' => '\5c3E',
257
+            '\;' => '\5c3B',
258
+            '\"' => '\5c22',
259
+            '\#' => '\5c23',
260
+            '('  => '\28',
261
+            ')'  => '\29',
262
+            '*'  => '\2A',
263
+        );
264
+        $dn = str_replace(array_keys($replacements), array_values($replacements), $dn);
265
+
266
+        return $dn;
267
+    }
268 268
 	
269
-	/**
270
-	 * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters
271
-	 * @param string $dn the DN
272
-	 * @return string
273
-	 */
274
-	public function DNasBaseParameter($dn) {
275
-		return str_ireplace('\\5c', '\\', $dn);
276
-	}
277
-
278
-	/**
279
-	 * listens to a hook thrown by server2server sharing and replaces the given
280
-	 * login name by a username, if it matches an LDAP user.
281
-	 *
282
-	 * @param array $param
283
-	 * @throws \Exception
284
-	 */
285
-	public static function loginName2UserName($param) {
286
-		if(!isset($param['uid'])) {
287
-			throw new \Exception('key uid is expected to be set in $param');
288
-		}
289
-
290
-		//ain't it ironic?
291
-		$helper = new Helper(\OC::$server->getConfig());
292
-
293
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
294
-		$ldapWrapper = new LDAP();
295
-		$ocConfig = \OC::$server->getConfig();
296
-
297
-		$userBackend  = new User_Proxy(
298
-			$configPrefixes, $ldapWrapper, $ocConfig
299
-		);
300
-		$uid = $userBackend->loginName2UserName($param['uid'] );
301
-		if($uid !== false) {
302
-			$param['uid'] = $uid;
303
-		}
304
-	}
269
+    /**
270
+     * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters
271
+     * @param string $dn the DN
272
+     * @return string
273
+     */
274
+    public function DNasBaseParameter($dn) {
275
+        return str_ireplace('\\5c', '\\', $dn);
276
+    }
277
+
278
+    /**
279
+     * listens to a hook thrown by server2server sharing and replaces the given
280
+     * login name by a username, if it matches an LDAP user.
281
+     *
282
+     * @param array $param
283
+     * @throws \Exception
284
+     */
285
+    public static function loginName2UserName($param) {
286
+        if(!isset($param['uid'])) {
287
+            throw new \Exception('key uid is expected to be set in $param');
288
+        }
289
+
290
+        //ain't it ironic?
291
+        $helper = new Helper(\OC::$server->getConfig());
292
+
293
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
294
+        $ldapWrapper = new LDAP();
295
+        $ocConfig = \OC::$server->getConfig();
296
+
297
+        $userBackend  = new User_Proxy(
298
+            $configPrefixes, $ldapWrapper, $ocConfig
299
+        );
300
+        $uid = $userBackend->loginName2UserName($param['uid'] );
301
+        if($uid !== false) {
302
+            $param['uid'] = $uid;
303
+        }
304
+    }
305 305
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
 		$keys = $this->getServersConfig($referenceConfigkey);
97 97
 
98 98
 		$result = array();
99
-		foreach($keys as $key) {
99
+		foreach ($keys as $key) {
100 100
 			$len = strlen($key) - strlen($referenceConfigkey);
101 101
 			$prefix = substr($key, 0, $len);
102 102
 			$result[$prefix] = $this->config->getAppValue('user_ldap', $key);
@@ -113,19 +113,19 @@  discard block
 block discarded – undo
113 113
 	public function getNextServerConfigurationPrefix() {
114 114
 		$serverConnections = $this->getServerConfigurationPrefixes();
115 115
 
116
-		if(count($serverConnections) === 0) {
116
+		if (count($serverConnections) === 0) {
117 117
 			return 's01';
118 118
 		}
119 119
 
120 120
 		sort($serverConnections);
121 121
 		$lastKey = array_pop($serverConnections);
122 122
 		$lastNumber = intval(str_replace('s', '', $lastKey));
123
-		$nextPrefix = 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
123
+		$nextPrefix = 's'.str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
124 124
 		return $nextPrefix;
125 125
 	}
126 126
 
127 127
 	private function getServersConfig($value) {
128
-		$regex = '/' . $value . '$/S';
128
+		$regex = '/'.$value.'$/S';
129 129
 
130 130
 		$keys = $this->config->getAppKeys('user_ldap');
131 131
 		$result = [];
@@ -144,12 +144,12 @@  discard block
 block discarded – undo
144 144
 	 * @return bool true on success, false otherwise
145 145
 	 */
146 146
 	public function deleteServerConfiguration($prefix) {
147
-		if(!in_array($prefix, self::getServerConfigurationPrefixes())) {
147
+		if (!in_array($prefix, self::getServerConfigurationPrefixes())) {
148 148
 			return false;
149 149
 		}
150 150
 
151 151
 		$saveOtherConfigurations = '';
152
-		if(empty($prefix)) {
152
+		if (empty($prefix)) {
153 153
 			$saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
154 154
 		}
155 155
 
@@ -163,11 +163,11 @@  discard block
 block discarded – undo
163 163
 		');
164 164
 		$delRows = $query->execute(array($prefix.'%'));
165 165
 
166
-		if(\OCP\DB::isError($delRows)) {
166
+		if (\OCP\DB::isError($delRows)) {
167 167
 			return false;
168 168
 		}
169 169
 
170
-		if($delRows === 0) {
170
+		if ($delRows === 0) {
171 171
 			return false;
172 172
 		}
173 173
 
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 		$all = $this->getServerConfigurationPrefixes(false);
184 184
 		$active = $this->getServerConfigurationPrefixes(true);
185 185
 
186
-		if(!is_array($all) || !is_array($active)) {
186
+		if (!is_array($all) || !is_array($active)) {
187 187
 			throw new \Exception('Unexpected Return Value');
188 188
 		}
189 189
 
@@ -197,14 +197,14 @@  discard block
 block discarded – undo
197 197
 	 */
198 198
 	public function getDomainFromURL($url) {
199 199
 		$uinfo = parse_url($url);
200
-		if(!is_array($uinfo)) {
200
+		if (!is_array($uinfo)) {
201 201
 			return false;
202 202
 		}
203 203
 
204 204
 		$domain = false;
205
-		if(isset($uinfo['host'])) {
205
+		if (isset($uinfo['host'])) {
206 206
 			$domain = $uinfo['host'];
207
-		} else if(isset($uinfo['path'])) {
207
+		} else if (isset($uinfo['path'])) {
208 208
 			$domain = $uinfo['path'];
209 209
 		}
210 210
 
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 	 */
219 219
 	public function setLDAPProvider() {
220 220
 		$current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
221
-		if(is_null($current)) {
221
+		if (is_null($current)) {
222 222
 			\OC::$server->getConfig()->setSystemValue('ldapProviderFactory', '\\OCA\\User_LDAP\\LDAPProviderFactory');
223 223
 		}
224 224
 	}
@@ -230,9 +230,9 @@  discard block
 block discarded – undo
230 230
 	 */
231 231
 	public function sanitizeDN($dn) {
232 232
 		//treating multiple base DNs
233
-		if(is_array($dn)) {
233
+		if (is_array($dn)) {
234 234
 			$result = array();
235
-			foreach($dn as $singleDN) {
235
+			foreach ($dn as $singleDN) {
236 236
 				$result[] = $this->sanitizeDN($singleDN);
237 237
 			}
238 238
 			return $result;
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
 	 * @throws \Exception
284 284
 	 */
285 285
 	public static function loginName2UserName($param) {
286
-		if(!isset($param['uid'])) {
286
+		if (!isset($param['uid'])) {
287 287
 			throw new \Exception('key uid is expected to be set in $param');
288 288
 		}
289 289
 
@@ -294,11 +294,11 @@  discard block
 block discarded – undo
294 294
 		$ldapWrapper = new LDAP();
295 295
 		$ocConfig = \OC::$server->getConfig();
296 296
 
297
-		$userBackend  = new User_Proxy(
297
+		$userBackend = new User_Proxy(
298 298
 			$configPrefixes, $ldapWrapper, $ocConfig
299 299
 		);
300
-		$uid = $userBackend->loginName2UserName($param['uid'] );
301
-		if($uid !== false) {
300
+		$uid = $userBackend->loginName2UserName($param['uid']);
301
+		if ($uid !== false) {
302 302
 			$param['uid'] = $uid;
303 303
 		}
304 304
 	}
Please login to merge, or discard this patch.