Completed
Pull Request — master (#9293)
by Blizzz
38:09 queued 17:25
created
lib/private/Files/Cache/Scanner.php 2 patches
Indentation   +497 added lines, -497 removed lines patch added patch discarded remove patch
@@ -53,501 +53,501 @@
 block discarded – undo
53 53
  * @package OC\Files\Cache
54 54
  */
55 55
 class Scanner extends BasicEmitter implements IScanner {
56
-	/**
57
-	 * @var \OC\Files\Storage\Storage $storage
58
-	 */
59
-	protected $storage;
60
-
61
-	/**
62
-	 * @var string $storageId
63
-	 */
64
-	protected $storageId;
65
-
66
-	/**
67
-	 * @var \OC\Files\Cache\Cache $cache
68
-	 */
69
-	protected $cache;
70
-
71
-	/**
72
-	 * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache
73
-	 */
74
-	protected $cacheActive;
75
-
76
-	/**
77
-	 * @var bool $useTransactions whether to use transactions
78
-	 */
79
-	protected $useTransactions = true;
80
-
81
-	/**
82
-	 * @var \OCP\Lock\ILockingProvider
83
-	 */
84
-	protected $lockingProvider;
85
-
86
-	public function __construct(\OC\Files\Storage\Storage $storage) {
87
-		$this->storage = $storage;
88
-		$this->storageId = $this->storage->getId();
89
-		$this->cache = $storage->getCache();
90
-		$this->cacheActive = !\OC::$server->getConfig()->getSystemValue('filesystem_cache_readonly', false);
91
-		$this->lockingProvider = \OC::$server->getLockingProvider();
92
-	}
93
-
94
-	/**
95
-	 * Whether to wrap the scanning of a folder in a database transaction
96
-	 * On default transactions are used
97
-	 *
98
-	 * @param bool $useTransactions
99
-	 */
100
-	public function setUseTransactions($useTransactions) {
101
-		$this->useTransactions = $useTransactions;
102
-	}
103
-
104
-	/**
105
-	 * get all the metadata of a file or folder
106
-	 * *
107
-	 *
108
-	 * @param string $path
109
-	 * @return array an array of metadata of the file
110
-	 */
111
-	protected function getData($path) {
112
-		$data = $this->storage->getMetaData($path);
113
-		if (is_null($data)) {
114
-			\OCP\Util::writeLog(Scanner::class, "!!! Path '$path' is not accessible or present !!!", ILogger::DEBUG);
115
-		}
116
-		return $data;
117
-	}
118
-
119
-	/**
120
-	 * scan a single file and store it in the cache
121
-	 *
122
-	 * @param string $file
123
-	 * @param int $reuseExisting
124
-	 * @param int $parentId
125
-	 * @param array | null $cacheData existing data in the cache for the file to be scanned
126
-	 * @param bool $lock set to false to disable getting an additional read lock during scanning
127
-	 * @return array an array of metadata of the scanned file
128
-	 * @throws \OC\ServerNotAvailableException
129
-	 * @throws \OCP\Lock\LockedException
130
-	 */
131
-	public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) {
132
-		if ($file !== '') {
133
-			try {
134
-				$this->storage->verifyPath(dirname($file), basename($file));
135
-			} catch (\Exception $e) {
136
-				return null;
137
-			}
138
-		}
139
-		// only proceed if $file is not a partial file nor a blacklisted file
140
-		if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) {
141
-
142
-			//acquire a lock
143
-			if ($lock) {
144
-				if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
145
-					$this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
146
-				}
147
-			}
148
-
149
-			try {
150
-				$data = $this->getData($file);
151
-			} catch (ForbiddenException $e) {
152
-				if ($lock) {
153
-					if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
154
-						$this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
155
-					}
156
-				}
157
-
158
-				return null;
159
-			}
160
-
161
-			try {
162
-				if ($data) {
163
-
164
-					// pre-emit only if it was a file. By that we avoid counting/treating folders as files
165
-					if ($data['mimetype'] !== 'httpd/unix-directory') {
166
-						$this->emit('\OC\Files\Cache\Scanner', 'scanFile', array($file, $this->storageId));
167
-						\OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', array('path' => $file, 'storage' => $this->storageId));
168
-					}
169
-
170
-					$parent = dirname($file);
171
-					if ($parent === '.' or $parent === '/') {
172
-						$parent = '';
173
-					}
174
-					if ($parentId === -1) {
175
-						$parentId = $this->cache->getParentId($file);
176
-					}
177
-
178
-					// scan the parent if it's not in the cache (id -1) and the current file is not the root folder
179
-					if ($file and $parentId === -1) {
180
-						$parentData = $this->scanFile($parent);
181
-						if (!$parentData) {
182
-							return null;
183
-						}
184
-						$parentId = $parentData['fileid'];
185
-					}
186
-					if ($parent) {
187
-						$data['parent'] = $parentId;
188
-					}
189
-					if (is_null($cacheData)) {
190
-						/** @var CacheEntry $cacheData */
191
-						$cacheData = $this->cache->get($file);
192
-					}
193
-					if ($cacheData and $reuseExisting and isset($cacheData['fileid'])) {
194
-						// prevent empty etag
195
-						if (empty($cacheData['etag'])) {
196
-							$etag = $data['etag'];
197
-						} else {
198
-							$etag = $cacheData['etag'];
199
-						}
200
-						$fileId = $cacheData['fileid'];
201
-						$data['fileid'] = $fileId;
202
-						// only reuse data if the file hasn't explicitly changed
203
-						if (isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime']) {
204
-							$data['mtime'] = $cacheData['mtime'];
205
-							if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) {
206
-								$data['size'] = $cacheData['size'];
207
-							}
208
-							if ($reuseExisting & self::REUSE_ETAG) {
209
-								$data['etag'] = $etag;
210
-							}
211
-						}
212
-						// Only update metadata that has changed
213
-						$newData = array_diff_assoc($data, $cacheData->getData());
214
-					} else {
215
-						$newData = $data;
216
-						$fileId = -1;
217
-					}
218
-					if (!empty($newData)) {
219
-						// Reset the checksum if the data has changed
220
-						$newData['checksum'] = '';
221
-						$data['fileid'] = $this->addToCache($file, $newData, $fileId);
222
-					}
223
-					if (isset($cacheData['size'])) {
224
-						$data['oldSize'] = $cacheData['size'];
225
-					} else {
226
-						$data['oldSize'] = 0;
227
-					}
228
-
229
-					if (isset($cacheData['encrypted'])) {
230
-						$data['encrypted'] = $cacheData['encrypted'];
231
-					}
232
-
233
-					// post-emit only if it was a file. By that we avoid counting/treating folders as files
234
-					if ($data['mimetype'] !== 'httpd/unix-directory') {
235
-						$this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId));
236
-						\OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId));
237
-					}
238
-
239
-				} else {
240
-					$this->removeFromCache($file);
241
-				}
242
-			} catch (\Exception $e) {
243
-				if ($lock) {
244
-					if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
245
-						$this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
246
-					}
247
-				}
248
-				throw $e;
249
-			}
250
-
251
-			//release the acquired lock
252
-			if ($lock) {
253
-				if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
254
-					$this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
255
-				}
256
-			}
257
-
258
-			if ($data && !isset($data['encrypted'])) {
259
-				$data['encrypted'] = false;
260
-			}
261
-			return $data;
262
-		}
263
-
264
-		return null;
265
-	}
266
-
267
-	protected function removeFromCache($path) {
268
-		\OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $path));
269
-		$this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', array($path));
270
-		if ($this->cacheActive) {
271
-			$this->cache->remove($path);
272
-		}
273
-	}
274
-
275
-	/**
276
-	 * @param string $path
277
-	 * @param array $data
278
-	 * @param int $fileId
279
-	 * @return int the id of the added file
280
-	 */
281
-	protected function addToCache($path, $data, $fileId = -1) {
282
-		if (isset($data['scan_permissions'])) {
283
-			$data['permissions'] = $data['scan_permissions'];
284
-		}
285
-		\OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data));
286
-		$this->emit('\OC\Files\Cache\Scanner', 'addToCache', array($path, $this->storageId, $data));
287
-		if ($this->cacheActive) {
288
-			if ($fileId !== -1) {
289
-				$this->cache->update($fileId, $data);
290
-				return $fileId;
291
-			} else {
292
-				return $this->cache->put($path, $data);
293
-			}
294
-		} else {
295
-			return -1;
296
-		}
297
-	}
298
-
299
-	/**
300
-	 * @param string $path
301
-	 * @param array $data
302
-	 * @param int $fileId
303
-	 */
304
-	protected function updateCache($path, $data, $fileId = -1) {
305
-		\OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data));
306
-		$this->emit('\OC\Files\Cache\Scanner', 'updateCache', array($path, $this->storageId, $data));
307
-		if ($this->cacheActive) {
308
-			if ($fileId !== -1) {
309
-				$this->cache->update($fileId, $data);
310
-			} else {
311
-				$this->cache->put($path, $data);
312
-			}
313
-		}
314
-	}
315
-
316
-	/**
317
-	 * scan a folder and all it's children
318
-	 *
319
-	 * @param string $path
320
-	 * @param bool $recursive
321
-	 * @param int $reuse
322
-	 * @param bool $lock set to false to disable getting an additional read lock during scanning
323
-	 * @return array an array of the meta data of the scanned file or folder
324
-	 */
325
-	public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
326
-		if ($reuse === -1) {
327
-			$reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
328
-		}
329
-		if ($lock) {
330
-			if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
331
-				$this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
332
-				$this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
333
-			}
334
-		}
335
-		$data = $this->scanFile($path, $reuse, -1, null, $lock);
336
-		if ($data and $data['mimetype'] === 'httpd/unix-directory') {
337
-			$size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock);
338
-			$data['size'] = $size;
339
-		}
340
-		if ($lock) {
341
-			if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
342
-				$this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
343
-				$this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
344
-			}
345
-		}
346
-		return $data;
347
-	}
348
-
349
-	/**
350
-	 * Get the children currently in the cache
351
-	 *
352
-	 * @param int $folderId
353
-	 * @return array[]
354
-	 */
355
-	protected function getExistingChildren($folderId) {
356
-		$existingChildren = array();
357
-		$children = $this->cache->getFolderContentsById($folderId);
358
-		foreach ($children as $child) {
359
-			$existingChildren[$child['name']] = $child;
360
-		}
361
-		return $existingChildren;
362
-	}
363
-
364
-	/**
365
-	 * Get the children from the storage
366
-	 *
367
-	 * @param string $folder
368
-	 * @return string[]
369
-	 */
370
-	protected function getNewChildren($folder) {
371
-		$children = array();
372
-		if ($dh = $this->storage->opendir($folder)) {
373
-			if (is_resource($dh)) {
374
-				while (($file = readdir($dh)) !== false) {
375
-					if (!Filesystem::isIgnoredDir($file)) {
376
-						$children[] = trim(\OC\Files\Filesystem::normalizePath($file), '/');
377
-					}
378
-				}
379
-			}
380
-		}
381
-		return $children;
382
-	}
383
-
384
-	/**
385
-	 * scan all the files and folders in a folder
386
-	 *
387
-	 * @param string $path
388
-	 * @param bool $recursive
389
-	 * @param int $reuse
390
-	 * @param int $folderId id for the folder to be scanned
391
-	 * @param bool $lock set to false to disable getting an additional read lock during scanning
392
-	 * @return int the size of the scanned folder or -1 if the size is unknown at this stage
393
-	 */
394
-	protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) {
395
-		if ($reuse === -1) {
396
-			$reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
397
-		}
398
-		$this->emit('\OC\Files\Cache\Scanner', 'scanFolder', array($path, $this->storageId));
399
-		$size = 0;
400
-		if (!is_null($folderId)) {
401
-			$folderId = $this->cache->getId($path);
402
-		}
403
-		$childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size);
404
-
405
-		foreach ($childQueue as $child => $childId) {
406
-			$childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock);
407
-			if ($childSize === -1) {
408
-				$size = -1;
409
-			} else if ($size !== -1) {
410
-				$size += $childSize;
411
-			}
412
-		}
413
-		if ($this->cacheActive) {
414
-			$this->cache->update($folderId, array('size' => $size));
415
-		}
416
-		$this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId));
417
-		return $size;
418
-	}
419
-
420
-	private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) {
421
-		// we put this in it's own function so it cleans up the memory before we start recursing
422
-		$existingChildren = $this->getExistingChildren($folderId);
423
-		$newChildren = $this->getNewChildren($path);
424
-
425
-		if ($this->useTransactions) {
426
-			\OC::$server->getDatabaseConnection()->beginTransaction();
427
-		}
428
-
429
-		$exceptionOccurred = false;
430
-		$childQueue = [];
431
-		foreach ($newChildren as $file) {
432
-			$child = $path ? $path . '/' . $file : $file;
433
-			try {
434
-				$existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null;
435
-				$data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock);
436
-				if ($data) {
437
-					if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) {
438
-						$childQueue[$child] = $data['fileid'];
439
-					} else if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) {
440
-						// only recurse into folders which aren't fully scanned
441
-						$childQueue[$child] = $data['fileid'];
442
-					} else if ($data['size'] === -1) {
443
-						$size = -1;
444
-					} else if ($size !== -1) {
445
-						$size += $data['size'];
446
-					}
447
-				}
448
-			} catch (\Doctrine\DBAL\DBALException $ex) {
449
-				// might happen if inserting duplicate while a scanning
450
-				// process is running in parallel
451
-				// log and ignore
452
-				if ($this->useTransactions) {
453
-					\OC::$server->getDatabaseConnection()->rollback();
454
-					\OC::$server->getDatabaseConnection()->beginTransaction();
455
-				}
456
-				\OC::$server->getLogger()->logException($ex, [
457
-					'message' => 'Exception while scanning file "' . $child . '"',
458
-					'level' => ILogger::DEBUG,
459
-					'app' => 'core',
460
-				]);
461
-				$exceptionOccurred = true;
462
-			} catch (\OCP\Lock\LockedException $e) {
463
-				if ($this->useTransactions) {
464
-					\OC::$server->getDatabaseConnection()->rollback();
465
-				}
466
-				throw $e;
467
-			}
468
-		}
469
-		$removedChildren = \array_diff(array_keys($existingChildren), $newChildren);
470
-		foreach ($removedChildren as $childName) {
471
-			$child = $path ? $path . '/' . $childName : $childName;
472
-			$this->removeFromCache($child);
473
-		}
474
-		if ($this->useTransactions) {
475
-			\OC::$server->getDatabaseConnection()->commit();
476
-		}
477
-		if ($exceptionOccurred) {
478
-			// It might happen that the parallel scan process has already
479
-			// inserted mimetypes but those weren't available yet inside the transaction
480
-			// To make sure to have the updated mime types in such cases,
481
-			// we reload them here
482
-			\OC::$server->getMimeTypeLoader()->reset();
483
-		}
484
-		return $childQueue;
485
-	}
486
-
487
-	/**
488
-	 * check if the file should be ignored when scanning
489
-	 * NOTE: files with a '.part' extension are ignored as well!
490
-	 *       prevents unfinished put requests to be scanned
491
-	 *
492
-	 * @param string $file
493
-	 * @return boolean
494
-	 */
495
-	public static function isPartialFile($file) {
496
-		if (pathinfo($file, PATHINFO_EXTENSION) === 'part') {
497
-			return true;
498
-		}
499
-		if (strpos($file, '.part/') !== false) {
500
-			return true;
501
-		}
502
-
503
-		return false;
504
-	}
505
-
506
-	/**
507
-	 * walk over any folders that are not fully scanned yet and scan them
508
-	 */
509
-	public function backgroundScan() {
510
-		if (!$this->cache->inCache('')) {
511
-			$this->runBackgroundScanJob(function () {
512
-				$this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
513
-			}, '');
514
-		} else {
515
-			$lastPath = null;
516
-			while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
517
-				$this->runBackgroundScanJob(function () use ($path) {
518
-					$this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
519
-				}, $path);
520
-				// FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
521
-				// to make this possible
522
-				$lastPath = $path;
523
-			}
524
-		}
525
-	}
526
-
527
-	private function runBackgroundScanJob(callable $callback, $path) {
528
-		try {
529
-			$callback();
530
-			\OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path));
531
-			if ($this->cacheActive && $this->cache instanceof Cache) {
532
-				$this->cache->correctFolderSize($path);
533
-			}
534
-		} catch (\OCP\Files\StorageInvalidException $e) {
535
-			// skip unavailable storages
536
-		} catch (\OCP\Files\StorageNotAvailableException $e) {
537
-			// skip unavailable storages
538
-		} catch (\OCP\Files\ForbiddenException $e) {
539
-			// skip forbidden storages
540
-		} catch (\OCP\Lock\LockedException $e) {
541
-			// skip unavailable storages
542
-		}
543
-	}
544
-
545
-	/**
546
-	 * Set whether the cache is affected by scan operations
547
-	 *
548
-	 * @param boolean $active The active state of the cache
549
-	 */
550
-	public function setCacheActive($active) {
551
-		$this->cacheActive = $active;
552
-	}
56
+    /**
57
+     * @var \OC\Files\Storage\Storage $storage
58
+     */
59
+    protected $storage;
60
+
61
+    /**
62
+     * @var string $storageId
63
+     */
64
+    protected $storageId;
65
+
66
+    /**
67
+     * @var \OC\Files\Cache\Cache $cache
68
+     */
69
+    protected $cache;
70
+
71
+    /**
72
+     * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache
73
+     */
74
+    protected $cacheActive;
75
+
76
+    /**
77
+     * @var bool $useTransactions whether to use transactions
78
+     */
79
+    protected $useTransactions = true;
80
+
81
+    /**
82
+     * @var \OCP\Lock\ILockingProvider
83
+     */
84
+    protected $lockingProvider;
85
+
86
+    public function __construct(\OC\Files\Storage\Storage $storage) {
87
+        $this->storage = $storage;
88
+        $this->storageId = $this->storage->getId();
89
+        $this->cache = $storage->getCache();
90
+        $this->cacheActive = !\OC::$server->getConfig()->getSystemValue('filesystem_cache_readonly', false);
91
+        $this->lockingProvider = \OC::$server->getLockingProvider();
92
+    }
93
+
94
+    /**
95
+     * Whether to wrap the scanning of a folder in a database transaction
96
+     * On default transactions are used
97
+     *
98
+     * @param bool $useTransactions
99
+     */
100
+    public function setUseTransactions($useTransactions) {
101
+        $this->useTransactions = $useTransactions;
102
+    }
103
+
104
+    /**
105
+     * get all the metadata of a file or folder
106
+     * *
107
+     *
108
+     * @param string $path
109
+     * @return array an array of metadata of the file
110
+     */
111
+    protected function getData($path) {
112
+        $data = $this->storage->getMetaData($path);
113
+        if (is_null($data)) {
114
+            \OCP\Util::writeLog(Scanner::class, "!!! Path '$path' is not accessible or present !!!", ILogger::DEBUG);
115
+        }
116
+        return $data;
117
+    }
118
+
119
+    /**
120
+     * scan a single file and store it in the cache
121
+     *
122
+     * @param string $file
123
+     * @param int $reuseExisting
124
+     * @param int $parentId
125
+     * @param array | null $cacheData existing data in the cache for the file to be scanned
126
+     * @param bool $lock set to false to disable getting an additional read lock during scanning
127
+     * @return array an array of metadata of the scanned file
128
+     * @throws \OC\ServerNotAvailableException
129
+     * @throws \OCP\Lock\LockedException
130
+     */
131
+    public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) {
132
+        if ($file !== '') {
133
+            try {
134
+                $this->storage->verifyPath(dirname($file), basename($file));
135
+            } catch (\Exception $e) {
136
+                return null;
137
+            }
138
+        }
139
+        // only proceed if $file is not a partial file nor a blacklisted file
140
+        if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) {
141
+
142
+            //acquire a lock
143
+            if ($lock) {
144
+                if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
145
+                    $this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
146
+                }
147
+            }
148
+
149
+            try {
150
+                $data = $this->getData($file);
151
+            } catch (ForbiddenException $e) {
152
+                if ($lock) {
153
+                    if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
154
+                        $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
155
+                    }
156
+                }
157
+
158
+                return null;
159
+            }
160
+
161
+            try {
162
+                if ($data) {
163
+
164
+                    // pre-emit only if it was a file. By that we avoid counting/treating folders as files
165
+                    if ($data['mimetype'] !== 'httpd/unix-directory') {
166
+                        $this->emit('\OC\Files\Cache\Scanner', 'scanFile', array($file, $this->storageId));
167
+                        \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', array('path' => $file, 'storage' => $this->storageId));
168
+                    }
169
+
170
+                    $parent = dirname($file);
171
+                    if ($parent === '.' or $parent === '/') {
172
+                        $parent = '';
173
+                    }
174
+                    if ($parentId === -1) {
175
+                        $parentId = $this->cache->getParentId($file);
176
+                    }
177
+
178
+                    // scan the parent if it's not in the cache (id -1) and the current file is not the root folder
179
+                    if ($file and $parentId === -1) {
180
+                        $parentData = $this->scanFile($parent);
181
+                        if (!$parentData) {
182
+                            return null;
183
+                        }
184
+                        $parentId = $parentData['fileid'];
185
+                    }
186
+                    if ($parent) {
187
+                        $data['parent'] = $parentId;
188
+                    }
189
+                    if (is_null($cacheData)) {
190
+                        /** @var CacheEntry $cacheData */
191
+                        $cacheData = $this->cache->get($file);
192
+                    }
193
+                    if ($cacheData and $reuseExisting and isset($cacheData['fileid'])) {
194
+                        // prevent empty etag
195
+                        if (empty($cacheData['etag'])) {
196
+                            $etag = $data['etag'];
197
+                        } else {
198
+                            $etag = $cacheData['etag'];
199
+                        }
200
+                        $fileId = $cacheData['fileid'];
201
+                        $data['fileid'] = $fileId;
202
+                        // only reuse data if the file hasn't explicitly changed
203
+                        if (isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime']) {
204
+                            $data['mtime'] = $cacheData['mtime'];
205
+                            if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) {
206
+                                $data['size'] = $cacheData['size'];
207
+                            }
208
+                            if ($reuseExisting & self::REUSE_ETAG) {
209
+                                $data['etag'] = $etag;
210
+                            }
211
+                        }
212
+                        // Only update metadata that has changed
213
+                        $newData = array_diff_assoc($data, $cacheData->getData());
214
+                    } else {
215
+                        $newData = $data;
216
+                        $fileId = -1;
217
+                    }
218
+                    if (!empty($newData)) {
219
+                        // Reset the checksum if the data has changed
220
+                        $newData['checksum'] = '';
221
+                        $data['fileid'] = $this->addToCache($file, $newData, $fileId);
222
+                    }
223
+                    if (isset($cacheData['size'])) {
224
+                        $data['oldSize'] = $cacheData['size'];
225
+                    } else {
226
+                        $data['oldSize'] = 0;
227
+                    }
228
+
229
+                    if (isset($cacheData['encrypted'])) {
230
+                        $data['encrypted'] = $cacheData['encrypted'];
231
+                    }
232
+
233
+                    // post-emit only if it was a file. By that we avoid counting/treating folders as files
234
+                    if ($data['mimetype'] !== 'httpd/unix-directory') {
235
+                        $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', array($file, $this->storageId));
236
+                        \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', array('path' => $file, 'storage' => $this->storageId));
237
+                    }
238
+
239
+                } else {
240
+                    $this->removeFromCache($file);
241
+                }
242
+            } catch (\Exception $e) {
243
+                if ($lock) {
244
+                    if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
245
+                        $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
246
+                    }
247
+                }
248
+                throw $e;
249
+            }
250
+
251
+            //release the acquired lock
252
+            if ($lock) {
253
+                if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
254
+                    $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
255
+                }
256
+            }
257
+
258
+            if ($data && !isset($data['encrypted'])) {
259
+                $data['encrypted'] = false;
260
+            }
261
+            return $data;
262
+        }
263
+
264
+        return null;
265
+    }
266
+
267
+    protected function removeFromCache($path) {
268
+        \OC_Hook::emit('Scanner', 'removeFromCache', array('file' => $path));
269
+        $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', array($path));
270
+        if ($this->cacheActive) {
271
+            $this->cache->remove($path);
272
+        }
273
+    }
274
+
275
+    /**
276
+     * @param string $path
277
+     * @param array $data
278
+     * @param int $fileId
279
+     * @return int the id of the added file
280
+     */
281
+    protected function addToCache($path, $data, $fileId = -1) {
282
+        if (isset($data['scan_permissions'])) {
283
+            $data['permissions'] = $data['scan_permissions'];
284
+        }
285
+        \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data));
286
+        $this->emit('\OC\Files\Cache\Scanner', 'addToCache', array($path, $this->storageId, $data));
287
+        if ($this->cacheActive) {
288
+            if ($fileId !== -1) {
289
+                $this->cache->update($fileId, $data);
290
+                return $fileId;
291
+            } else {
292
+                return $this->cache->put($path, $data);
293
+            }
294
+        } else {
295
+            return -1;
296
+        }
297
+    }
298
+
299
+    /**
300
+     * @param string $path
301
+     * @param array $data
302
+     * @param int $fileId
303
+     */
304
+    protected function updateCache($path, $data, $fileId = -1) {
305
+        \OC_Hook::emit('Scanner', 'addToCache', array('file' => $path, 'data' => $data));
306
+        $this->emit('\OC\Files\Cache\Scanner', 'updateCache', array($path, $this->storageId, $data));
307
+        if ($this->cacheActive) {
308
+            if ($fileId !== -1) {
309
+                $this->cache->update($fileId, $data);
310
+            } else {
311
+                $this->cache->put($path, $data);
312
+            }
313
+        }
314
+    }
315
+
316
+    /**
317
+     * scan a folder and all it's children
318
+     *
319
+     * @param string $path
320
+     * @param bool $recursive
321
+     * @param int $reuse
322
+     * @param bool $lock set to false to disable getting an additional read lock during scanning
323
+     * @return array an array of the meta data of the scanned file or folder
324
+     */
325
+    public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
326
+        if ($reuse === -1) {
327
+            $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
328
+        }
329
+        if ($lock) {
330
+            if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
331
+                $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
332
+                $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
333
+            }
334
+        }
335
+        $data = $this->scanFile($path, $reuse, -1, null, $lock);
336
+        if ($data and $data['mimetype'] === 'httpd/unix-directory') {
337
+            $size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock);
338
+            $data['size'] = $size;
339
+        }
340
+        if ($lock) {
341
+            if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
342
+                $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
343
+                $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
344
+            }
345
+        }
346
+        return $data;
347
+    }
348
+
349
+    /**
350
+     * Get the children currently in the cache
351
+     *
352
+     * @param int $folderId
353
+     * @return array[]
354
+     */
355
+    protected function getExistingChildren($folderId) {
356
+        $existingChildren = array();
357
+        $children = $this->cache->getFolderContentsById($folderId);
358
+        foreach ($children as $child) {
359
+            $existingChildren[$child['name']] = $child;
360
+        }
361
+        return $existingChildren;
362
+    }
363
+
364
+    /**
365
+     * Get the children from the storage
366
+     *
367
+     * @param string $folder
368
+     * @return string[]
369
+     */
370
+    protected function getNewChildren($folder) {
371
+        $children = array();
372
+        if ($dh = $this->storage->opendir($folder)) {
373
+            if (is_resource($dh)) {
374
+                while (($file = readdir($dh)) !== false) {
375
+                    if (!Filesystem::isIgnoredDir($file)) {
376
+                        $children[] = trim(\OC\Files\Filesystem::normalizePath($file), '/');
377
+                    }
378
+                }
379
+            }
380
+        }
381
+        return $children;
382
+    }
383
+
384
+    /**
385
+     * scan all the files and folders in a folder
386
+     *
387
+     * @param string $path
388
+     * @param bool $recursive
389
+     * @param int $reuse
390
+     * @param int $folderId id for the folder to be scanned
391
+     * @param bool $lock set to false to disable getting an additional read lock during scanning
392
+     * @return int the size of the scanned folder or -1 if the size is unknown at this stage
393
+     */
394
+    protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) {
395
+        if ($reuse === -1) {
396
+            $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
397
+        }
398
+        $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', array($path, $this->storageId));
399
+        $size = 0;
400
+        if (!is_null($folderId)) {
401
+            $folderId = $this->cache->getId($path);
402
+        }
403
+        $childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size);
404
+
405
+        foreach ($childQueue as $child => $childId) {
406
+            $childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock);
407
+            if ($childSize === -1) {
408
+                $size = -1;
409
+            } else if ($size !== -1) {
410
+                $size += $childSize;
411
+            }
412
+        }
413
+        if ($this->cacheActive) {
414
+            $this->cache->update($folderId, array('size' => $size));
415
+        }
416
+        $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', array($path, $this->storageId));
417
+        return $size;
418
+    }
419
+
420
+    private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) {
421
+        // we put this in it's own function so it cleans up the memory before we start recursing
422
+        $existingChildren = $this->getExistingChildren($folderId);
423
+        $newChildren = $this->getNewChildren($path);
424
+
425
+        if ($this->useTransactions) {
426
+            \OC::$server->getDatabaseConnection()->beginTransaction();
427
+        }
428
+
429
+        $exceptionOccurred = false;
430
+        $childQueue = [];
431
+        foreach ($newChildren as $file) {
432
+            $child = $path ? $path . '/' . $file : $file;
433
+            try {
434
+                $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null;
435
+                $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock);
436
+                if ($data) {
437
+                    if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) {
438
+                        $childQueue[$child] = $data['fileid'];
439
+                    } else if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) {
440
+                        // only recurse into folders which aren't fully scanned
441
+                        $childQueue[$child] = $data['fileid'];
442
+                    } else if ($data['size'] === -1) {
443
+                        $size = -1;
444
+                    } else if ($size !== -1) {
445
+                        $size += $data['size'];
446
+                    }
447
+                }
448
+            } catch (\Doctrine\DBAL\DBALException $ex) {
449
+                // might happen if inserting duplicate while a scanning
450
+                // process is running in parallel
451
+                // log and ignore
452
+                if ($this->useTransactions) {
453
+                    \OC::$server->getDatabaseConnection()->rollback();
454
+                    \OC::$server->getDatabaseConnection()->beginTransaction();
455
+                }
456
+                \OC::$server->getLogger()->logException($ex, [
457
+                    'message' => 'Exception while scanning file "' . $child . '"',
458
+                    'level' => ILogger::DEBUG,
459
+                    'app' => 'core',
460
+                ]);
461
+                $exceptionOccurred = true;
462
+            } catch (\OCP\Lock\LockedException $e) {
463
+                if ($this->useTransactions) {
464
+                    \OC::$server->getDatabaseConnection()->rollback();
465
+                }
466
+                throw $e;
467
+            }
468
+        }
469
+        $removedChildren = \array_diff(array_keys($existingChildren), $newChildren);
470
+        foreach ($removedChildren as $childName) {
471
+            $child = $path ? $path . '/' . $childName : $childName;
472
+            $this->removeFromCache($child);
473
+        }
474
+        if ($this->useTransactions) {
475
+            \OC::$server->getDatabaseConnection()->commit();
476
+        }
477
+        if ($exceptionOccurred) {
478
+            // It might happen that the parallel scan process has already
479
+            // inserted mimetypes but those weren't available yet inside the transaction
480
+            // To make sure to have the updated mime types in such cases,
481
+            // we reload them here
482
+            \OC::$server->getMimeTypeLoader()->reset();
483
+        }
484
+        return $childQueue;
485
+    }
486
+
487
+    /**
488
+     * check if the file should be ignored when scanning
489
+     * NOTE: files with a '.part' extension are ignored as well!
490
+     *       prevents unfinished put requests to be scanned
491
+     *
492
+     * @param string $file
493
+     * @return boolean
494
+     */
495
+    public static function isPartialFile($file) {
496
+        if (pathinfo($file, PATHINFO_EXTENSION) === 'part') {
497
+            return true;
498
+        }
499
+        if (strpos($file, '.part/') !== false) {
500
+            return true;
501
+        }
502
+
503
+        return false;
504
+    }
505
+
506
+    /**
507
+     * walk over any folders that are not fully scanned yet and scan them
508
+     */
509
+    public function backgroundScan() {
510
+        if (!$this->cache->inCache('')) {
511
+            $this->runBackgroundScanJob(function () {
512
+                $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
513
+            }, '');
514
+        } else {
515
+            $lastPath = null;
516
+            while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
517
+                $this->runBackgroundScanJob(function () use ($path) {
518
+                    $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
519
+                }, $path);
520
+                // FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
521
+                // to make this possible
522
+                $lastPath = $path;
523
+            }
524
+        }
525
+    }
526
+
527
+    private function runBackgroundScanJob(callable $callback, $path) {
528
+        try {
529
+            $callback();
530
+            \OC_Hook::emit('Scanner', 'correctFolderSize', array('path' => $path));
531
+            if ($this->cacheActive && $this->cache instanceof Cache) {
532
+                $this->cache->correctFolderSize($path);
533
+            }
534
+        } catch (\OCP\Files\StorageInvalidException $e) {
535
+            // skip unavailable storages
536
+        } catch (\OCP\Files\StorageNotAvailableException $e) {
537
+            // skip unavailable storages
538
+        } catch (\OCP\Files\ForbiddenException $e) {
539
+            // skip forbidden storages
540
+        } catch (\OCP\Lock\LockedException $e) {
541
+            // skip unavailable storages
542
+        }
543
+    }
544
+
545
+    /**
546
+     * Set whether the cache is affected by scan operations
547
+     *
548
+     * @param boolean $active The active state of the cache
549
+     */
550
+    public function setCacheActive($active) {
551
+        $this->cacheActive = $active;
552
+    }
553 553
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
 		}
329 329
 		if ($lock) {
330 330
 			if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
331
-				$this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
331
+				$this->storage->acquireLock('scanner::'.$path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
332 332
 				$this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
333 333
 			}
334 334
 		}
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
 		if ($lock) {
341 341
 			if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
342 342
 				$this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
343
-				$this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
343
+				$this->storage->releaseLock('scanner::'.$path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
344 344
 			}
345 345
 		}
346 346
 		return $data;
@@ -429,7 +429,7 @@  discard block
 block discarded – undo
429 429
 		$exceptionOccurred = false;
430 430
 		$childQueue = [];
431 431
 		foreach ($newChildren as $file) {
432
-			$child = $path ? $path . '/' . $file : $file;
432
+			$child = $path ? $path.'/'.$file : $file;
433 433
 			try {
434 434
 				$existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null;
435 435
 				$data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock);
@@ -454,7 +454,7 @@  discard block
 block discarded – undo
454 454
 					\OC::$server->getDatabaseConnection()->beginTransaction();
455 455
 				}
456 456
 				\OC::$server->getLogger()->logException($ex, [
457
-					'message' => 'Exception while scanning file "' . $child . '"',
457
+					'message' => 'Exception while scanning file "'.$child.'"',
458 458
 					'level' => ILogger::DEBUG,
459 459
 					'app' => 'core',
460 460
 				]);
@@ -468,7 +468,7 @@  discard block
 block discarded – undo
468 468
 		}
469 469
 		$removedChildren = \array_diff(array_keys($existingChildren), $newChildren);
470 470
 		foreach ($removedChildren as $childName) {
471
-			$child = $path ? $path . '/' . $childName : $childName;
471
+			$child = $path ? $path.'/'.$childName : $childName;
472 472
 			$this->removeFromCache($child);
473 473
 		}
474 474
 		if ($this->useTransactions) {
@@ -508,13 +508,13 @@  discard block
 block discarded – undo
508 508
 	 */
509 509
 	public function backgroundScan() {
510 510
 		if (!$this->cache->inCache('')) {
511
-			$this->runBackgroundScanJob(function () {
511
+			$this->runBackgroundScanJob(function() {
512 512
 				$this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
513 513
 			}, '');
514 514
 		} else {
515 515
 			$lastPath = null;
516 516
 			while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
517
-				$this->runBackgroundScanJob(function () use ($path) {
517
+				$this->runBackgroundScanJob(function() use ($path) {
518 518
 					$this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
519 519
 				}, $path);
520 520
 				// FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
Please login to merge, or discard this patch.
lib/private/Log/Rotate.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -33,23 +33,23 @@
 block discarded – undo
33 33
  * location and manage that with your own tools.
34 34
  */
35 35
 class Rotate extends \OC\BackgroundJob\Job {
36
-	private $max_log_size;
37
-	public function run($dummy) {
38
-		$systemConfig = \OC::$server->getSystemConfig();
39
-		$logFile = $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', \OC::$SERVERROOT . '/data') . '/nextcloud.log');
40
-		$this->max_log_size = \OC::$server->getConfig()->getSystemValue('log_rotate_size', 100 * 1024 * 1024);
41
-		if ($this->max_log_size) {
42
-			$filesize = @filesize($logFile);
43
-			if ($filesize >= $this->max_log_size) {
44
-				$this->rotate($logFile);
45
-			}
46
-		}
47
-	}
36
+    private $max_log_size;
37
+    public function run($dummy) {
38
+        $systemConfig = \OC::$server->getSystemConfig();
39
+        $logFile = $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', \OC::$SERVERROOT . '/data') . '/nextcloud.log');
40
+        $this->max_log_size = \OC::$server->getConfig()->getSystemValue('log_rotate_size', 100 * 1024 * 1024);
41
+        if ($this->max_log_size) {
42
+            $filesize = @filesize($logFile);
43
+            if ($filesize >= $this->max_log_size) {
44
+                $this->rotate($logFile);
45
+            }
46
+        }
47
+    }
48 48
 
49
-	protected function rotate($logfile) {
50
-		$rotatedLogfile = $logfile.'.1';
51
-		rename($logfile, $rotatedLogfile);
52
-		$msg = 'Log file "'.$logfile.'" was over '.$this->max_log_size.' bytes, moved to "'.$rotatedLogfile.'"';
53
-		\OCP\Util::writeLog(Rotate::class, $msg, ILogger::WARN);
54
-	}
49
+    protected function rotate($logfile) {
50
+        $rotatedLogfile = $logfile.'.1';
51
+        rename($logfile, $rotatedLogfile);
52
+        $msg = 'Log file "'.$logfile.'" was over '.$this->max_log_size.' bytes, moved to "'.$rotatedLogfile.'"';
53
+        \OCP\Util::writeLog(Rotate::class, $msg, ILogger::WARN);
54
+    }
55 55
 }
Please login to merge, or discard this patch.
lib/private/Log/LogFactory.php 2 patches
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -31,54 +31,54 @@
 block discarded – undo
31 31
 use OCP\Log\IWriter;
32 32
 
33 33
 class LogFactory implements ILogFactory {
34
-	/** @var IServerContainer */
35
-	private $c;
34
+    /** @var IServerContainer */
35
+    private $c;
36 36
 
37
-	public function __construct(IServerContainer $c) {
38
-		$this->c = $c;
39
-	}
37
+    public function __construct(IServerContainer $c) {
38
+        $this->c = $c;
39
+    }
40 40
 
41
-	/**
42
-	 * @param $type
43
-	 * @return \OC\Log\Errorlog|File|\stdClass
44
-	 * @throws \OCP\AppFramework\QueryException
45
-	 */
46
-	public function get(string $type):IWriter {
47
-		switch (strtolower($type)) {
48
-			case 'errorlog':
49
-				return new Errorlog();
50
-			case 'syslog':
51
-				return $this->c->resolve(Syslog::class);
52
-			case 'file':
53
-				return $this->buildLogFile();
41
+    /**
42
+     * @param $type
43
+     * @return \OC\Log\Errorlog|File|\stdClass
44
+     * @throws \OCP\AppFramework\QueryException
45
+     */
46
+    public function get(string $type):IWriter {
47
+        switch (strtolower($type)) {
48
+            case 'errorlog':
49
+                return new Errorlog();
50
+            case 'syslog':
51
+                return $this->c->resolve(Syslog::class);
52
+            case 'file':
53
+                return $this->buildLogFile();
54 54
 
55
-			// Backwards compatibility for old and fallback for unknown log types
56
-			case 'owncloud':
57
-			case 'nextcloud':
58
-			default:
59
-				return $this->buildLogFile();
60
-		}
61
-	}
55
+            // Backwards compatibility for old and fallback for unknown log types
56
+            case 'owncloud':
57
+            case 'nextcloud':
58
+            default:
59
+                return $this->buildLogFile();
60
+        }
61
+    }
62 62
 
63
-	public function getCustomLogger(string $path):ILogger {
64
-		$systemConfig = null;
65
-		$iconfig = $this->c->getConfig();
66
-		if($iconfig instanceof AllConfig) {
67
-			// Log is bound to SystemConfig, but fetches it from \OC::$server if not supplied
68
-			$systemConfig = $iconfig->getSystemConfig();
69
-		}
70
-		$log = $this->buildLogFile($path);
71
-		return new Log($log, $systemConfig);
72
-	}
63
+    public function getCustomLogger(string $path):ILogger {
64
+        $systemConfig = null;
65
+        $iconfig = $this->c->getConfig();
66
+        if($iconfig instanceof AllConfig) {
67
+            // Log is bound to SystemConfig, but fetches it from \OC::$server if not supplied
68
+            $systemConfig = $iconfig->getSystemConfig();
69
+        }
70
+        $log = $this->buildLogFile($path);
71
+        return new Log($log, $systemConfig);
72
+    }
73 73
 
74
-	protected function buildLogFile(string $logFile = ''):File {
75
-		$config = $this->c->getConfig();
76
-		$defaultLogFile = $config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/nextcloud.log';
77
-		if($logFile === '') {
78
-			$logFile = $config->getSystemValue('logfile', $defaultLogFile);
79
-		}
80
-		$fallback = $defaultLogFile !== $logFile ? $defaultLogFile : '';
74
+    protected function buildLogFile(string $logFile = ''):File {
75
+        $config = $this->c->getConfig();
76
+        $defaultLogFile = $config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/nextcloud.log';
77
+        if($logFile === '') {
78
+            $logFile = $config->getSystemValue('logfile', $defaultLogFile);
79
+        }
80
+        $fallback = $defaultLogFile !== $logFile ? $defaultLogFile : '';
81 81
 
82
-		return new File($logFile, $fallback, $config);
83
-	}
82
+        return new File($logFile, $fallback, $config);
83
+    }
84 84
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
 	public function getCustomLogger(string $path):ILogger {
64 64
 		$systemConfig = null;
65 65
 		$iconfig = $this->c->getConfig();
66
-		if($iconfig instanceof AllConfig) {
66
+		if ($iconfig instanceof AllConfig) {
67 67
 			// Log is bound to SystemConfig, but fetches it from \OC::$server if not supplied
68 68
 			$systemConfig = $iconfig->getSystemConfig();
69 69
 		}
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
 	protected function buildLogFile(string $logFile = ''):File {
75 75
 		$config = $this->c->getConfig();
76 76
 		$defaultLogFile = $config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/nextcloud.log';
77
-		if($logFile === '') {
77
+		if ($logFile === '') {
78 78
 			$logFile = $config->getSystemValue('logfile', $defaultLogFile);
79 79
 		}
80 80
 		$fallback = $defaultLogFile !== $logFile ? $defaultLogFile : '';
Please login to merge, or discard this patch.
lib/private/Log/Syslog.php 1 patch
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -30,30 +30,30 @@
 block discarded – undo
30 30
 use OCP\Log\IWriter;
31 31
 
32 32
 class Syslog implements IWriter {
33
-	protected $levels = [
34
-		ILogger::DEBUG => LOG_DEBUG,
35
-		ILogger::INFO => LOG_INFO,
36
-		ILogger::WARN => LOG_WARNING,
37
-		ILogger::ERROR => LOG_ERR,
38
-		ILogger::FATAL => LOG_CRIT,
39
-	];
33
+    protected $levels = [
34
+        ILogger::DEBUG => LOG_DEBUG,
35
+        ILogger::INFO => LOG_INFO,
36
+        ILogger::WARN => LOG_WARNING,
37
+        ILogger::ERROR => LOG_ERR,
38
+        ILogger::FATAL => LOG_CRIT,
39
+    ];
40 40
 
41
-	public function __construct(IConfig $config) {
42
-		openlog($config->getSystemValue('syslog_tag', 'ownCloud'), LOG_PID | LOG_CONS, LOG_USER);
43
-	}
41
+    public function __construct(IConfig $config) {
42
+        openlog($config->getSystemValue('syslog_tag', 'ownCloud'), LOG_PID | LOG_CONS, LOG_USER);
43
+    }
44 44
 
45
-	public function __destruct() {
46
-		closelog();
47
-	}
45
+    public function __destruct() {
46
+        closelog();
47
+    }
48 48
 
49
-	/**
50
-	 * write a message in the log
51
-	 * @param string $app
52
-	 * @param string $message
53
-	 * @param int $level
54
-	 */
55
-	public function write(string $app, $message, int $level) {
56
-		$syslog_level = $this->levels[$level];
57
-		syslog($syslog_level, '{'.$app.'} '.$message);
58
-	}
49
+    /**
50
+     * write a message in the log
51
+     * @param string $app
52
+     * @param string $message
53
+     * @param int $level
54
+     */
55
+    public function write(string $app, $message, int $level) {
56
+        $syslog_level = $this->levels[$level];
57
+        syslog($syslog_level, '{'.$app.'} '.$message);
58
+    }
59 59
 }
Please login to merge, or discard this patch.
lib/private/Share/Share.php 2 patches
Indentation   +2067 added lines, -2067 removed lines patch added patch discarded remove patch
@@ -53,2081 +53,2081 @@
 block discarded – undo
53 53
  */
54 54
 class Share extends Constants {
55 55
 
56
-	/** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
57
-	 * Construct permissions for share() and setPermissions with Or (|) e.g.
58
-	 * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
59
-	 *
60
-	 * Check if permission is granted with And (&) e.g. Check if delete is
61
-	 * granted: if ($permissions & PERMISSION_DELETE)
62
-	 *
63
-	 * Remove permissions with And (&) and Not (~) e.g. Remove the update
64
-	 * permission: $permissions &= ~PERMISSION_UPDATE
65
-	 *
66
-	 * Apps are required to handle permissions on their own, this class only
67
-	 * stores and manages the permissions of shares
68
-	 * @see lib/public/constants.php
69
-	 */
70
-
71
-	/**
72
-	 * Register a sharing backend class that implements OCP\Share_Backend for an item type
73
-	 * @param string $itemType Item type
74
-	 * @param string $class Backend class
75
-	 * @param string $collectionOf (optional) Depends on item type
76
-	 * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
77
-	 * @return boolean true if backend is registered or false if error
78
-	 */
79
-	public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
80
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') {
81
-			if (!isset(self::$backendTypes[$itemType])) {
82
-				self::$backendTypes[$itemType] = array(
83
-					'class' => $class,
84
-					'collectionOf' => $collectionOf,
85
-					'supportedFileExtensions' => $supportedFileExtensions
86
-				);
87
-				if(count(self::$backendTypes) === 1) {
88
-					Util::addScript('core', 'merged-share-backend');
89
-					\OC_Util::addStyle('core', 'share');
90
-				}
91
-				return true;
92
-			}
93
-			\OCP\Util::writeLog('OCP\Share',
94
-				'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
95
-				.' is already registered for '.$itemType,
96
-				ILogger::WARN);
97
-		}
98
-		return false;
99
-	}
100
-
101
-	/**
102
-	 * Get the items of item type shared with the current user
103
-	 * @param string $itemType
104
-	 * @param int $format (optional) Format type must be defined by the backend
105
-	 * @param mixed $parameters (optional)
106
-	 * @param int $limit Number of items to return (optional) Returns all by default
107
-	 * @param boolean $includeCollections (optional)
108
-	 * @return mixed Return depends on format
109
-	 */
110
-	public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE,
111
-											  $parameters = null, $limit = -1, $includeCollections = false) {
112
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
113
-			$parameters, $limit, $includeCollections);
114
-	}
115
-
116
-	/**
117
-	 * Get the items of item type shared with a user
118
-	 * @param string $itemType
119
-	 * @param string $user id for which user we want the shares
120
-	 * @param int $format (optional) Format type must be defined by the backend
121
-	 * @param mixed $parameters (optional)
122
-	 * @param int $limit Number of items to return (optional) Returns all by default
123
-	 * @param boolean $includeCollections (optional)
124
-	 * @return mixed Return depends on format
125
-	 */
126
-	public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
127
-												  $parameters = null, $limit = -1, $includeCollections = false) {
128
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
129
-			$parameters, $limit, $includeCollections);
130
-	}
131
-
132
-	/**
133
-	 * Get the item of item type shared with a given user by source
134
-	 * @param string $itemType
135
-	 * @param string $itemSource
136
-	 * @param string $user User to whom the item was shared
137
-	 * @param string $owner Owner of the share
138
-	 * @param int $shareType only look for a specific share type
139
-	 * @return array Return list of items with file_target, permissions and expiration
140
-	 */
141
-	public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
142
-		$shares = array();
143
-		$fileDependent = false;
144
-
145
-		$where = 'WHERE';
146
-		$fileDependentWhere = '';
147
-		if ($itemType === 'file' || $itemType === 'folder') {
148
-			$fileDependent = true;
149
-			$column = 'file_source';
150
-			$fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
151
-			$fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
152
-		} else {
153
-			$column = 'item_source';
154
-		}
155
-
156
-		$select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
157
-
158
-		$where .= ' `' . $column . '` = ? AND `item_type` = ? ';
159
-		$arguments = array($itemSource, $itemType);
160
-		// for link shares $user === null
161
-		if ($user !== null) {
162
-			$where .= ' AND `share_with` = ? ';
163
-			$arguments[] = $user;
164
-		}
165
-
166
-		if ($shareType !== null) {
167
-			$where .= ' AND `share_type` = ? ';
168
-			$arguments[] = $shareType;
169
-		}
170
-
171
-		if ($owner !== null) {
172
-			$where .= ' AND `uid_owner` = ? ';
173
-			$arguments[] = $owner;
174
-		}
175
-
176
-		$query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
177
-
178
-		$result = \OC_DB::executeAudited($query, $arguments);
179
-
180
-		while ($row = $result->fetchRow()) {
181
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
182
-				continue;
183
-			}
184
-			if ($fileDependent && (int)$row['file_parent'] === -1) {
185
-				// if it is a mount point we need to get the path from the mount manager
186
-				$mountManager = \OC\Files\Filesystem::getMountManager();
187
-				$mountPoint = $mountManager->findByStorageId($row['storage_id']);
188
-				if (!empty($mountPoint)) {
189
-					$path = $mountPoint[0]->getMountPoint();
190
-					$path = trim($path, '/');
191
-					$path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
192
-					$row['path'] = $path;
193
-				} else {
194
-					\OC::$server->getLogger()->warning(
195
-						'Could not resolve mount point for ' . $row['storage_id'],
196
-						['app' => 'OCP\Share']
197
-					);
198
-				}
199
-			}
200
-			$shares[] = $row;
201
-		}
202
-
203
-		//if didn't found a result than let's look for a group share.
204
-		if(empty($shares) && $user !== null) {
205
-			$userObject = \OC::$server->getUserManager()->get($user);
206
-			$groups = [];
207
-			if ($userObject) {
208
-				$groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
209
-			}
210
-
211
-			if (!empty($groups)) {
212
-				$where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
213
-				$arguments = array($itemSource, $itemType, $groups);
214
-				$types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY);
215
-
216
-				if ($owner !== null) {
217
-					$where .= ' AND `uid_owner` = ?';
218
-					$arguments[] = $owner;
219
-					$types[] = null;
220
-				}
221
-
222
-				// TODO: inject connection, hopefully one day in the future when this
223
-				// class isn't static anymore...
224
-				$conn = \OC::$server->getDatabaseConnection();
225
-				$result = $conn->executeQuery(
226
-					'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
227
-					$arguments,
228
-					$types
229
-				);
230
-
231
-				while ($row = $result->fetch()) {
232
-					$shares[] = $row;
233
-				}
234
-			}
235
-		}
236
-
237
-		return $shares;
238
-
239
-	}
240
-
241
-	/**
242
-	 * Get the item of item type shared with the current user by source
243
-	 * @param string $itemType
244
-	 * @param string $itemSource
245
-	 * @param int $format (optional) Format type must be defined by the backend
246
-	 * @param mixed $parameters
247
-	 * @param boolean $includeCollections
248
-	 * @param string $shareWith (optional) define against which user should be checked, default: current user
249
-	 * @return array
250
-	 */
251
-	public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
252
-													 $parameters = null, $includeCollections = false, $shareWith = null) {
253
-		$shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
254
-		return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
255
-			$parameters, 1, $includeCollections, true);
256
-	}
257
-
258
-	/**
259
-	 * Based on the given token the share information will be returned - password protected shares will be verified
260
-	 * @param string $token
261
-	 * @param bool $checkPasswordProtection
262
-	 * @return array|boolean false will be returned in case the token is unknown or unauthorized
263
-	 */
264
-	public static function getShareByToken($token, $checkPasswordProtection = true) {
265
-		$query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
266
-		$result = $query->execute(array($token));
267
-		if ($result === false) {
268
-			\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, ILogger::ERROR);
269
-		}
270
-		$row = $result->fetchRow();
271
-		if ($row === false) {
272
-			return false;
273
-		}
274
-		if (is_array($row) and self::expireItem($row)) {
275
-			return false;
276
-		}
277
-
278
-		// password protected shares need to be authenticated
279
-		if ($checkPasswordProtection && !\OC\Share\Share::checkPasswordProtectedShare($row)) {
280
-			return false;
281
-		}
282
-
283
-		return $row;
284
-	}
285
-
286
-	/**
287
-	 * Get the shared items of item type owned by the current user
288
-	 * @param string $itemType
289
-	 * @param int $format (optional) Format type must be defined by the backend
290
-	 * @param mixed $parameters
291
-	 * @param int $limit Number of items to return (optional) Returns all by default
292
-	 * @param boolean $includeCollections
293
-	 * @return mixed Return depends on format
294
-	 */
295
-	public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
296
-										  $limit = -1, $includeCollections = false) {
297
-		return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
298
-			$parameters, $limit, $includeCollections);
299
-	}
300
-
301
-	/**
302
-	 * Get the shared item of item type owned by the current user
303
-	 * @param string $itemType
304
-	 * @param string $itemSource
305
-	 * @param int $format (optional) Format type must be defined by the backend
306
-	 * @param mixed $parameters
307
-	 * @param boolean $includeCollections
308
-	 * @return mixed Return depends on format
309
-	 */
310
-	public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
311
-										 $parameters = null, $includeCollections = false) {
312
-		return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
313
-			$parameters, -1, $includeCollections);
314
-	}
315
-
316
-	/**
317
-	 * Share an item with a user, group, or via private link
318
-	 * @param string $itemType
319
-	 * @param string $itemSource
320
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
321
-	 * @param string $shareWith User or group the item is being shared with
322
-	 * @param int $permissions CRUDS
323
-	 * @param string $itemSourceName
324
-	 * @param \DateTime|null $expirationDate
325
-	 * @param bool|null $passwordChanged
326
-	 * @return boolean|string Returns true on success or false on failure, Returns token on success for links
327
-	 * @throws \OC\HintException when the share type is remote and the shareWith is invalid
328
-	 * @throws \Exception
329
-	 * @since 5.0.0 - parameter $itemSourceName was added in 6.0.0, parameter $expirationDate was added in 7.0.0, parameter $passwordChanged added in 9.0.0
330
-	 */
331
-	public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null, $passwordChanged = null) {
332
-
333
-		$backend = self::getBackend($itemType);
334
-		$l = \OC::$server->getL10N('lib');
335
-
336
-		if ($backend->isShareTypeAllowed($shareType) === false) {
337
-			$message = 'Sharing %s failed, because the backend does not allow shares from type %i';
338
-			$message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
339
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareType), ILogger::DEBUG);
340
-			throw new \Exception($message_t);
341
-		}
342
-
343
-		$uidOwner = \OC_User::getUser();
344
-		$shareWithinGroupOnly = self::shareWithGroupMembersOnly();
345
-
346
-		if (is_null($itemSourceName)) {
347
-			$itemSourceName = $itemSource;
348
-		}
349
-		$itemName = $itemSourceName;
350
-
351
-		// check if file can be shared
352
-		if ($itemType === 'file' or $itemType === 'folder') {
353
-			$path = \OC\Files\Filesystem::getPath($itemSource);
354
-			$itemName = $path;
355
-
356
-			// verify that the file exists before we try to share it
357
-			if (!$path) {
358
-				$message = 'Sharing %s failed, because the file does not exist';
359
-				$message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
360
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), ILogger::DEBUG);
361
-				throw new \Exception($message_t);
362
-			}
363
-			// verify that the user has share permission
364
-			if (!\OC\Files\Filesystem::isSharable($path) || \OCP\Util::isSharingDisabledForUser()) {
365
-				$message = 'You are not allowed to share %s';
366
-				$message_t = $l->t('You are not allowed to share %s', [$path]);
367
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $path), ILogger::DEBUG);
368
-				throw new \Exception($message_t);
369
-			}
370
-		}
371
-
372
-		//verify that we don't share a folder which already contains a share mount point
373
-		if ($itemType === 'folder') {
374
-			$path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
375
-			$mountManager = \OC\Files\Filesystem::getMountManager();
376
-			$mounts = $mountManager->findIn($path);
377
-			foreach ($mounts as $mount) {
378
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
379
-					$message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
380
-					\OCP\Util::writeLog('OCP\Share', $message, ILogger::DEBUG);
381
-					throw new \Exception($message);
382
-				}
383
-
384
-			}
385
-		}
386
-
387
-		// single file shares should never have delete permissions
388
-		if ($itemType === 'file') {
389
-			$permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
390
-		}
391
-
392
-		//Validate expirationDate
393
-		if ($expirationDate !== null) {
394
-			try {
395
-				/*
56
+    /** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
57
+     * Construct permissions for share() and setPermissions with Or (|) e.g.
58
+     * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
59
+     *
60
+     * Check if permission is granted with And (&) e.g. Check if delete is
61
+     * granted: if ($permissions & PERMISSION_DELETE)
62
+     *
63
+     * Remove permissions with And (&) and Not (~) e.g. Remove the update
64
+     * permission: $permissions &= ~PERMISSION_UPDATE
65
+     *
66
+     * Apps are required to handle permissions on their own, this class only
67
+     * stores and manages the permissions of shares
68
+     * @see lib/public/constants.php
69
+     */
70
+
71
+    /**
72
+     * Register a sharing backend class that implements OCP\Share_Backend for an item type
73
+     * @param string $itemType Item type
74
+     * @param string $class Backend class
75
+     * @param string $collectionOf (optional) Depends on item type
76
+     * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
77
+     * @return boolean true if backend is registered or false if error
78
+     */
79
+    public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
80
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') {
81
+            if (!isset(self::$backendTypes[$itemType])) {
82
+                self::$backendTypes[$itemType] = array(
83
+                    'class' => $class,
84
+                    'collectionOf' => $collectionOf,
85
+                    'supportedFileExtensions' => $supportedFileExtensions
86
+                );
87
+                if(count(self::$backendTypes) === 1) {
88
+                    Util::addScript('core', 'merged-share-backend');
89
+                    \OC_Util::addStyle('core', 'share');
90
+                }
91
+                return true;
92
+            }
93
+            \OCP\Util::writeLog('OCP\Share',
94
+                'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
95
+                .' is already registered for '.$itemType,
96
+                ILogger::WARN);
97
+        }
98
+        return false;
99
+    }
100
+
101
+    /**
102
+     * Get the items of item type shared with the current user
103
+     * @param string $itemType
104
+     * @param int $format (optional) Format type must be defined by the backend
105
+     * @param mixed $parameters (optional)
106
+     * @param int $limit Number of items to return (optional) Returns all by default
107
+     * @param boolean $includeCollections (optional)
108
+     * @return mixed Return depends on format
109
+     */
110
+    public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE,
111
+                                                $parameters = null, $limit = -1, $includeCollections = false) {
112
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
113
+            $parameters, $limit, $includeCollections);
114
+    }
115
+
116
+    /**
117
+     * Get the items of item type shared with a user
118
+     * @param string $itemType
119
+     * @param string $user id for which user we want the shares
120
+     * @param int $format (optional) Format type must be defined by the backend
121
+     * @param mixed $parameters (optional)
122
+     * @param int $limit Number of items to return (optional) Returns all by default
123
+     * @param boolean $includeCollections (optional)
124
+     * @return mixed Return depends on format
125
+     */
126
+    public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
127
+                                                    $parameters = null, $limit = -1, $includeCollections = false) {
128
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
129
+            $parameters, $limit, $includeCollections);
130
+    }
131
+
132
+    /**
133
+     * Get the item of item type shared with a given user by source
134
+     * @param string $itemType
135
+     * @param string $itemSource
136
+     * @param string $user User to whom the item was shared
137
+     * @param string $owner Owner of the share
138
+     * @param int $shareType only look for a specific share type
139
+     * @return array Return list of items with file_target, permissions and expiration
140
+     */
141
+    public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
142
+        $shares = array();
143
+        $fileDependent = false;
144
+
145
+        $where = 'WHERE';
146
+        $fileDependentWhere = '';
147
+        if ($itemType === 'file' || $itemType === 'folder') {
148
+            $fileDependent = true;
149
+            $column = 'file_source';
150
+            $fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
151
+            $fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
152
+        } else {
153
+            $column = 'item_source';
154
+        }
155
+
156
+        $select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
157
+
158
+        $where .= ' `' . $column . '` = ? AND `item_type` = ? ';
159
+        $arguments = array($itemSource, $itemType);
160
+        // for link shares $user === null
161
+        if ($user !== null) {
162
+            $where .= ' AND `share_with` = ? ';
163
+            $arguments[] = $user;
164
+        }
165
+
166
+        if ($shareType !== null) {
167
+            $where .= ' AND `share_type` = ? ';
168
+            $arguments[] = $shareType;
169
+        }
170
+
171
+        if ($owner !== null) {
172
+            $where .= ' AND `uid_owner` = ? ';
173
+            $arguments[] = $owner;
174
+        }
175
+
176
+        $query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
177
+
178
+        $result = \OC_DB::executeAudited($query, $arguments);
179
+
180
+        while ($row = $result->fetchRow()) {
181
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
182
+                continue;
183
+            }
184
+            if ($fileDependent && (int)$row['file_parent'] === -1) {
185
+                // if it is a mount point we need to get the path from the mount manager
186
+                $mountManager = \OC\Files\Filesystem::getMountManager();
187
+                $mountPoint = $mountManager->findByStorageId($row['storage_id']);
188
+                if (!empty($mountPoint)) {
189
+                    $path = $mountPoint[0]->getMountPoint();
190
+                    $path = trim($path, '/');
191
+                    $path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
192
+                    $row['path'] = $path;
193
+                } else {
194
+                    \OC::$server->getLogger()->warning(
195
+                        'Could not resolve mount point for ' . $row['storage_id'],
196
+                        ['app' => 'OCP\Share']
197
+                    );
198
+                }
199
+            }
200
+            $shares[] = $row;
201
+        }
202
+
203
+        //if didn't found a result than let's look for a group share.
204
+        if(empty($shares) && $user !== null) {
205
+            $userObject = \OC::$server->getUserManager()->get($user);
206
+            $groups = [];
207
+            if ($userObject) {
208
+                $groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
209
+            }
210
+
211
+            if (!empty($groups)) {
212
+                $where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
213
+                $arguments = array($itemSource, $itemType, $groups);
214
+                $types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY);
215
+
216
+                if ($owner !== null) {
217
+                    $where .= ' AND `uid_owner` = ?';
218
+                    $arguments[] = $owner;
219
+                    $types[] = null;
220
+                }
221
+
222
+                // TODO: inject connection, hopefully one day in the future when this
223
+                // class isn't static anymore...
224
+                $conn = \OC::$server->getDatabaseConnection();
225
+                $result = $conn->executeQuery(
226
+                    'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
227
+                    $arguments,
228
+                    $types
229
+                );
230
+
231
+                while ($row = $result->fetch()) {
232
+                    $shares[] = $row;
233
+                }
234
+            }
235
+        }
236
+
237
+        return $shares;
238
+
239
+    }
240
+
241
+    /**
242
+     * Get the item of item type shared with the current user by source
243
+     * @param string $itemType
244
+     * @param string $itemSource
245
+     * @param int $format (optional) Format type must be defined by the backend
246
+     * @param mixed $parameters
247
+     * @param boolean $includeCollections
248
+     * @param string $shareWith (optional) define against which user should be checked, default: current user
249
+     * @return array
250
+     */
251
+    public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
252
+                                                        $parameters = null, $includeCollections = false, $shareWith = null) {
253
+        $shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
254
+        return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
255
+            $parameters, 1, $includeCollections, true);
256
+    }
257
+
258
+    /**
259
+     * Based on the given token the share information will be returned - password protected shares will be verified
260
+     * @param string $token
261
+     * @param bool $checkPasswordProtection
262
+     * @return array|boolean false will be returned in case the token is unknown or unauthorized
263
+     */
264
+    public static function getShareByToken($token, $checkPasswordProtection = true) {
265
+        $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
266
+        $result = $query->execute(array($token));
267
+        if ($result === false) {
268
+            \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, ILogger::ERROR);
269
+        }
270
+        $row = $result->fetchRow();
271
+        if ($row === false) {
272
+            return false;
273
+        }
274
+        if (is_array($row) and self::expireItem($row)) {
275
+            return false;
276
+        }
277
+
278
+        // password protected shares need to be authenticated
279
+        if ($checkPasswordProtection && !\OC\Share\Share::checkPasswordProtectedShare($row)) {
280
+            return false;
281
+        }
282
+
283
+        return $row;
284
+    }
285
+
286
+    /**
287
+     * Get the shared items of item type owned by the current user
288
+     * @param string $itemType
289
+     * @param int $format (optional) Format type must be defined by the backend
290
+     * @param mixed $parameters
291
+     * @param int $limit Number of items to return (optional) Returns all by default
292
+     * @param boolean $includeCollections
293
+     * @return mixed Return depends on format
294
+     */
295
+    public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
296
+                                            $limit = -1, $includeCollections = false) {
297
+        return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
298
+            $parameters, $limit, $includeCollections);
299
+    }
300
+
301
+    /**
302
+     * Get the shared item of item type owned by the current user
303
+     * @param string $itemType
304
+     * @param string $itemSource
305
+     * @param int $format (optional) Format type must be defined by the backend
306
+     * @param mixed $parameters
307
+     * @param boolean $includeCollections
308
+     * @return mixed Return depends on format
309
+     */
310
+    public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
311
+                                            $parameters = null, $includeCollections = false) {
312
+        return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
313
+            $parameters, -1, $includeCollections);
314
+    }
315
+
316
+    /**
317
+     * Share an item with a user, group, or via private link
318
+     * @param string $itemType
319
+     * @param string $itemSource
320
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
321
+     * @param string $shareWith User or group the item is being shared with
322
+     * @param int $permissions CRUDS
323
+     * @param string $itemSourceName
324
+     * @param \DateTime|null $expirationDate
325
+     * @param bool|null $passwordChanged
326
+     * @return boolean|string Returns true on success or false on failure, Returns token on success for links
327
+     * @throws \OC\HintException when the share type is remote and the shareWith is invalid
328
+     * @throws \Exception
329
+     * @since 5.0.0 - parameter $itemSourceName was added in 6.0.0, parameter $expirationDate was added in 7.0.0, parameter $passwordChanged added in 9.0.0
330
+     */
331
+    public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null, $passwordChanged = null) {
332
+
333
+        $backend = self::getBackend($itemType);
334
+        $l = \OC::$server->getL10N('lib');
335
+
336
+        if ($backend->isShareTypeAllowed($shareType) === false) {
337
+            $message = 'Sharing %s failed, because the backend does not allow shares from type %i';
338
+            $message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
339
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareType), ILogger::DEBUG);
340
+            throw new \Exception($message_t);
341
+        }
342
+
343
+        $uidOwner = \OC_User::getUser();
344
+        $shareWithinGroupOnly = self::shareWithGroupMembersOnly();
345
+
346
+        if (is_null($itemSourceName)) {
347
+            $itemSourceName = $itemSource;
348
+        }
349
+        $itemName = $itemSourceName;
350
+
351
+        // check if file can be shared
352
+        if ($itemType === 'file' or $itemType === 'folder') {
353
+            $path = \OC\Files\Filesystem::getPath($itemSource);
354
+            $itemName = $path;
355
+
356
+            // verify that the file exists before we try to share it
357
+            if (!$path) {
358
+                $message = 'Sharing %s failed, because the file does not exist';
359
+                $message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
360
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), ILogger::DEBUG);
361
+                throw new \Exception($message_t);
362
+            }
363
+            // verify that the user has share permission
364
+            if (!\OC\Files\Filesystem::isSharable($path) || \OCP\Util::isSharingDisabledForUser()) {
365
+                $message = 'You are not allowed to share %s';
366
+                $message_t = $l->t('You are not allowed to share %s', [$path]);
367
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $path), ILogger::DEBUG);
368
+                throw new \Exception($message_t);
369
+            }
370
+        }
371
+
372
+        //verify that we don't share a folder which already contains a share mount point
373
+        if ($itemType === 'folder') {
374
+            $path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
375
+            $mountManager = \OC\Files\Filesystem::getMountManager();
376
+            $mounts = $mountManager->findIn($path);
377
+            foreach ($mounts as $mount) {
378
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
379
+                    $message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
380
+                    \OCP\Util::writeLog('OCP\Share', $message, ILogger::DEBUG);
381
+                    throw new \Exception($message);
382
+                }
383
+
384
+            }
385
+        }
386
+
387
+        // single file shares should never have delete permissions
388
+        if ($itemType === 'file') {
389
+            $permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
390
+        }
391
+
392
+        //Validate expirationDate
393
+        if ($expirationDate !== null) {
394
+            try {
395
+                /*
396 396
 				 * Reuse the validateExpireDate.
397 397
 				 * We have to pass time() since the second arg is the time
398 398
 				 * the file was shared, since it is not shared yet we just use
399 399
 				 * the current time.
400 400
 				 */
401
-				$expirationDate = self::validateExpireDate($expirationDate->format('Y-m-d'), time(), $itemType, $itemSource);
402
-			} catch (\Exception $e) {
403
-				throw new \OC\HintException($e->getMessage(), $e->getMessage(), 404);
404
-			}
405
-		}
406
-
407
-		// Verify share type and sharing conditions are met
408
-		if ($shareType === self::SHARE_TYPE_USER) {
409
-			if ($shareWith == $uidOwner) {
410
-				$message = 'Sharing %s failed, because you can not share with yourself';
411
-				$message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]);
412
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), ILogger::DEBUG);
413
-				throw new \Exception($message_t);
414
-			}
415
-			if (!\OC::$server->getUserManager()->userExists($shareWith)) {
416
-				$message = 'Sharing %s failed, because the user %s does not exist';
417
-				$message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
418
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
419
-				throw new \Exception($message_t);
420
-			}
421
-			if ($shareWithinGroupOnly) {
422
-				$userManager = \OC::$server->getUserManager();
423
-				$groupManager = \OC::$server->getGroupManager();
424
-				$userOwner = $userManager->get($uidOwner);
425
-				$userShareWith = $userManager->get($shareWith);
426
-				$groupsOwner = [];
427
-				$groupsShareWith = [];
428
-				if ($userOwner) {
429
-					$groupsOwner = $groupManager->getUserGroupIds($userOwner);
430
-				}
431
-				if ($userShareWith) {
432
-					$groupsShareWith = $groupManager->getUserGroupIds($userShareWith);
433
-				}
434
-				$inGroup = array_intersect($groupsOwner, $groupsShareWith);
435
-				if (empty($inGroup)) {
436
-					$message = 'Sharing %s failed, because the user '
437
-						.'%s is not a member of any groups that %s is a member of';
438
-					$message_t = $l->t('Sharing %s failed, because the user %s is not a member of any groups that %s is a member of', array($itemName, $shareWith, $uidOwner));
439
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemName, $shareWith, $uidOwner), ILogger::DEBUG);
440
-					throw new \Exception($message_t);
441
-				}
442
-			}
443
-			// Check if the item source is already shared with the user, either from the same owner or a different user
444
-			if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
445
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
446
-				// Only allow the same share to occur again if it is the same
447
-				// owner and is not a user share, this use case is for increasing
448
-				// permissions for a specific user
449
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
450
-					$message = 'Sharing %s failed, because this item is already shared with %s';
451
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
452
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
453
-					throw new \Exception($message_t);
454
-				}
455
-			}
456
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
457
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
458
-				// Only allow the same share to occur again if it is the same
459
-				// owner and is not a user share, this use case is for increasing
460
-				// permissions for a specific user
461
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
462
-					$message = 'Sharing %s failed, because this item is already shared with user %s';
463
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', array($itemSourceName, $shareWith));
464
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::ERROR);
465
-					throw new \Exception($message_t);
466
-				}
467
-			}
468
-		} else if ($shareType === self::SHARE_TYPE_GROUP) {
469
-			if (!\OC::$server->getGroupManager()->groupExists($shareWith)) {
470
-				$message = 'Sharing %s failed, because the group %s does not exist';
471
-				$message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
472
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
473
-				throw new \Exception($message_t);
474
-			}
475
-			if ($shareWithinGroupOnly) {
476
-				$group = \OC::$server->getGroupManager()->get($shareWith);
477
-				$user = \OC::$server->getUserManager()->get($uidOwner);
478
-				if (!$group || !$user || !$group->inGroup($user)) {
479
-					$message = 'Sharing %s failed, because '
480
-						. '%s is not a member of the group %s';
481
-					$message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
482
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), ILogger::DEBUG);
483
-					throw new \Exception($message_t);
484
-				}
485
-			}
486
-			// Check if the item source is already shared with the group, either from the same owner or a different user
487
-			// The check for each user in the group is done inside the put() function
488
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
489
-				null, self::FORMAT_NONE, null, 1, true, true)) {
490
-
491
-				if ($checkExists['share_with'] === $shareWith && $checkExists['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
492
-					$message = 'Sharing %s failed, because this item is already shared with %s';
493
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
494
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
495
-					throw new \Exception($message_t);
496
-				}
497
-			}
498
-			// Convert share with into an array with the keys group and users
499
-			$group = $shareWith;
500
-			$shareWith = array();
501
-			$shareWith['group'] = $group;
502
-
503
-
504
-			$groupObject = \OC::$server->getGroupManager()->get($group);
505
-			$userIds = [];
506
-			if ($groupObject) {
507
-				$users = $groupObject->searchUsers('', -1, 0);
508
-				foreach ($users as $user) {
509
-					$userIds[] = $user->getUID();
510
-				}
511
-			}
512
-
513
-			$shareWith['users'] = array_diff($userIds, array($uidOwner));
514
-		} else if ($shareType === self::SHARE_TYPE_LINK) {
515
-			$updateExistingShare = false;
516
-			if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
517
-
518
-				// IF the password is changed via the old ajax endpoint verify it before deleting the old share
519
-				if ($passwordChanged === true) {
520
-					self::verifyPassword($shareWith);
521
-				}
522
-
523
-				// when updating a link share
524
-				// FIXME Don't delete link if we update it
525
-				if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
526
-					$uidOwner, self::FORMAT_NONE, null, 1)) {
527
-					// remember old token
528
-					$oldToken = $checkExists['token'];
529
-					$oldPermissions = $checkExists['permissions'];
530
-					//delete the old share
531
-					Helper::delete($checkExists['id']);
532
-					$updateExistingShare = true;
533
-				}
534
-
535
-				if ($passwordChanged === null) {
536
-					// Generate hash of password - same method as user passwords
537
-					if (is_string($shareWith) && $shareWith !== '') {
538
-						self::verifyPassword($shareWith);
539
-						$shareWith = \OC::$server->getHasher()->hash($shareWith);
540
-					} else {
541
-						// reuse the already set password, but only if we change permissions
542
-						// otherwise the user disabled the password protection
543
-						if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
544
-							$shareWith = $checkExists['share_with'];
545
-						}
546
-					}
547
-				} else {
548
-					if ($passwordChanged === true) {
549
-						if (is_string($shareWith) && $shareWith !== '') {
550
-							self::verifyPassword($shareWith);
551
-							$shareWith = \OC::$server->getHasher()->hash($shareWith);
552
-						}
553
-					} else if ($updateExistingShare) {
554
-						$shareWith = $checkExists['share_with'];
555
-					}
556
-				}
557
-
558
-				if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
559
-					$message = 'You need to provide a password to create a public link, only protected links are allowed';
560
-					$message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
561
-					\OCP\Util::writeLog('OCP\Share', $message, ILogger::DEBUG);
562
-					throw new \Exception($message_t);
563
-				}
564
-
565
-				if ($updateExistingShare === false &&
566
-					self::isDefaultExpireDateEnabled() &&
567
-					empty($expirationDate)) {
568
-					$expirationDate = Helper::calcExpireDate();
569
-				}
570
-
571
-				// Generate token
572
-				if (isset($oldToken)) {
573
-					$token = $oldToken;
574
-				} else {
575
-					$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH,
576
-						\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
577
-					);
578
-				}
579
-				$result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
580
-					null, $token, $itemSourceName, $expirationDate);
581
-				if ($result) {
582
-					return $token;
583
-				} else {
584
-					return false;
585
-				}
586
-			}
587
-			$message = 'Sharing %s failed, because sharing with links is not allowed';
588
-			$message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
589
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), ILogger::DEBUG);
590
-			throw new \Exception($message_t);
591
-		} else if ($shareType === self::SHARE_TYPE_REMOTE) {
592
-
593
-			/*
401
+                $expirationDate = self::validateExpireDate($expirationDate->format('Y-m-d'), time(), $itemType, $itemSource);
402
+            } catch (\Exception $e) {
403
+                throw new \OC\HintException($e->getMessage(), $e->getMessage(), 404);
404
+            }
405
+        }
406
+
407
+        // Verify share type and sharing conditions are met
408
+        if ($shareType === self::SHARE_TYPE_USER) {
409
+            if ($shareWith == $uidOwner) {
410
+                $message = 'Sharing %s failed, because you can not share with yourself';
411
+                $message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]);
412
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), ILogger::DEBUG);
413
+                throw new \Exception($message_t);
414
+            }
415
+            if (!\OC::$server->getUserManager()->userExists($shareWith)) {
416
+                $message = 'Sharing %s failed, because the user %s does not exist';
417
+                $message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
418
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
419
+                throw new \Exception($message_t);
420
+            }
421
+            if ($shareWithinGroupOnly) {
422
+                $userManager = \OC::$server->getUserManager();
423
+                $groupManager = \OC::$server->getGroupManager();
424
+                $userOwner = $userManager->get($uidOwner);
425
+                $userShareWith = $userManager->get($shareWith);
426
+                $groupsOwner = [];
427
+                $groupsShareWith = [];
428
+                if ($userOwner) {
429
+                    $groupsOwner = $groupManager->getUserGroupIds($userOwner);
430
+                }
431
+                if ($userShareWith) {
432
+                    $groupsShareWith = $groupManager->getUserGroupIds($userShareWith);
433
+                }
434
+                $inGroup = array_intersect($groupsOwner, $groupsShareWith);
435
+                if (empty($inGroup)) {
436
+                    $message = 'Sharing %s failed, because the user '
437
+                        .'%s is not a member of any groups that %s is a member of';
438
+                    $message_t = $l->t('Sharing %s failed, because the user %s is not a member of any groups that %s is a member of', array($itemName, $shareWith, $uidOwner));
439
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemName, $shareWith, $uidOwner), ILogger::DEBUG);
440
+                    throw new \Exception($message_t);
441
+                }
442
+            }
443
+            // Check if the item source is already shared with the user, either from the same owner or a different user
444
+            if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
445
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
446
+                // Only allow the same share to occur again if it is the same
447
+                // owner and is not a user share, this use case is for increasing
448
+                // permissions for a specific user
449
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
450
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
451
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
452
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
453
+                    throw new \Exception($message_t);
454
+                }
455
+            }
456
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
457
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
458
+                // Only allow the same share to occur again if it is the same
459
+                // owner and is not a user share, this use case is for increasing
460
+                // permissions for a specific user
461
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
462
+                    $message = 'Sharing %s failed, because this item is already shared with user %s';
463
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', array($itemSourceName, $shareWith));
464
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::ERROR);
465
+                    throw new \Exception($message_t);
466
+                }
467
+            }
468
+        } else if ($shareType === self::SHARE_TYPE_GROUP) {
469
+            if (!\OC::$server->getGroupManager()->groupExists($shareWith)) {
470
+                $message = 'Sharing %s failed, because the group %s does not exist';
471
+                $message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
472
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
473
+                throw new \Exception($message_t);
474
+            }
475
+            if ($shareWithinGroupOnly) {
476
+                $group = \OC::$server->getGroupManager()->get($shareWith);
477
+                $user = \OC::$server->getUserManager()->get($uidOwner);
478
+                if (!$group || !$user || !$group->inGroup($user)) {
479
+                    $message = 'Sharing %s failed, because '
480
+                        . '%s is not a member of the group %s';
481
+                    $message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
482
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), ILogger::DEBUG);
483
+                    throw new \Exception($message_t);
484
+                }
485
+            }
486
+            // Check if the item source is already shared with the group, either from the same owner or a different user
487
+            // The check for each user in the group is done inside the put() function
488
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
489
+                null, self::FORMAT_NONE, null, 1, true, true)) {
490
+
491
+                if ($checkExists['share_with'] === $shareWith && $checkExists['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
492
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
493
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
494
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
495
+                    throw new \Exception($message_t);
496
+                }
497
+            }
498
+            // Convert share with into an array with the keys group and users
499
+            $group = $shareWith;
500
+            $shareWith = array();
501
+            $shareWith['group'] = $group;
502
+
503
+
504
+            $groupObject = \OC::$server->getGroupManager()->get($group);
505
+            $userIds = [];
506
+            if ($groupObject) {
507
+                $users = $groupObject->searchUsers('', -1, 0);
508
+                foreach ($users as $user) {
509
+                    $userIds[] = $user->getUID();
510
+                }
511
+            }
512
+
513
+            $shareWith['users'] = array_diff($userIds, array($uidOwner));
514
+        } else if ($shareType === self::SHARE_TYPE_LINK) {
515
+            $updateExistingShare = false;
516
+            if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
517
+
518
+                // IF the password is changed via the old ajax endpoint verify it before deleting the old share
519
+                if ($passwordChanged === true) {
520
+                    self::verifyPassword($shareWith);
521
+                }
522
+
523
+                // when updating a link share
524
+                // FIXME Don't delete link if we update it
525
+                if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
526
+                    $uidOwner, self::FORMAT_NONE, null, 1)) {
527
+                    // remember old token
528
+                    $oldToken = $checkExists['token'];
529
+                    $oldPermissions = $checkExists['permissions'];
530
+                    //delete the old share
531
+                    Helper::delete($checkExists['id']);
532
+                    $updateExistingShare = true;
533
+                }
534
+
535
+                if ($passwordChanged === null) {
536
+                    // Generate hash of password - same method as user passwords
537
+                    if (is_string($shareWith) && $shareWith !== '') {
538
+                        self::verifyPassword($shareWith);
539
+                        $shareWith = \OC::$server->getHasher()->hash($shareWith);
540
+                    } else {
541
+                        // reuse the already set password, but only if we change permissions
542
+                        // otherwise the user disabled the password protection
543
+                        if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
544
+                            $shareWith = $checkExists['share_with'];
545
+                        }
546
+                    }
547
+                } else {
548
+                    if ($passwordChanged === true) {
549
+                        if (is_string($shareWith) && $shareWith !== '') {
550
+                            self::verifyPassword($shareWith);
551
+                            $shareWith = \OC::$server->getHasher()->hash($shareWith);
552
+                        }
553
+                    } else if ($updateExistingShare) {
554
+                        $shareWith = $checkExists['share_with'];
555
+                    }
556
+                }
557
+
558
+                if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
559
+                    $message = 'You need to provide a password to create a public link, only protected links are allowed';
560
+                    $message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
561
+                    \OCP\Util::writeLog('OCP\Share', $message, ILogger::DEBUG);
562
+                    throw new \Exception($message_t);
563
+                }
564
+
565
+                if ($updateExistingShare === false &&
566
+                    self::isDefaultExpireDateEnabled() &&
567
+                    empty($expirationDate)) {
568
+                    $expirationDate = Helper::calcExpireDate();
569
+                }
570
+
571
+                // Generate token
572
+                if (isset($oldToken)) {
573
+                    $token = $oldToken;
574
+                } else {
575
+                    $token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH,
576
+                        \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
577
+                    );
578
+                }
579
+                $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
580
+                    null, $token, $itemSourceName, $expirationDate);
581
+                if ($result) {
582
+                    return $token;
583
+                } else {
584
+                    return false;
585
+                }
586
+            }
587
+            $message = 'Sharing %s failed, because sharing with links is not allowed';
588
+            $message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
589
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), ILogger::DEBUG);
590
+            throw new \Exception($message_t);
591
+        } else if ($shareType === self::SHARE_TYPE_REMOTE) {
592
+
593
+            /*
594 594
 			 * Check if file is not already shared with the remote user
595 595
 			 */
596
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_REMOTE,
597
-				$shareWith, $uidOwner, self::FORMAT_NONE, null, 1, true, true)) {
598
-					$message = 'Sharing %s failed, because this item is already shared with %s';
599
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
600
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
601
-					throw new \Exception($message_t);
602
-			}
603
-
604
-			// don't allow federated shares if source and target server are the same
605
-			list($user, $remote) = Helper::splitUserRemote($shareWith);
606
-			$currentServer = self::removeProtocolFromUrl(\OC::$server->getURLGenerator()->getAbsoluteURL('/'));
607
-			$currentUser = \OC::$server->getUserSession()->getUser()->getUID();
608
-			if (Helper::isSameUserOnSameServer($user, $remote, $currentUser, $currentServer)) {
609
-				$message = 'Not allowed to create a federated share with the same user.';
610
-				$message_t = $l->t('Not allowed to create a federated share with the same user');
611
-				\OCP\Util::writeLog('OCP\Share', $message, ILogger::DEBUG);
612
-				throw new \Exception($message_t);
613
-			}
614
-
615
-			$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
616
-				\OCP\Security\ISecureRandom::CHAR_DIGITS);
617
-
618
-			$shareWith = $user . '@' . $remote;
619
-			$shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
620
-
621
-			$send = false;
622
-			if ($shareId) {
623
-				$send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
624
-			}
625
-
626
-			if ($send === false) {
627
-				$currentUser = \OC::$server->getUserSession()->getUser()->getUID();
628
-				self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
629
-				$message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
630
-				throw new \Exception($message_t);
631
-			}
632
-
633
-			return $send;
634
-		} else {
635
-			// Future share types need to include their own conditions
636
-			$message = 'Share type %s is not valid for %s';
637
-			$message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
638
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $shareType, $itemSource), ILogger::DEBUG);
639
-			throw new \Exception($message_t);
640
-		}
641
-
642
-		// Put the item into the database
643
-		$result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
644
-
645
-		return $result ? true : false;
646
-	}
647
-
648
-	/**
649
-	 * Unshare an item from a user, group, or delete a private link
650
-	 * @param string $itemType
651
-	 * @param string $itemSource
652
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
653
-	 * @param string $shareWith User or group the item is being shared with
654
-	 * @param string $owner owner of the share, if null the current user is used
655
-	 * @return boolean true on success or false on failure
656
-	 */
657
-	public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
658
-
659
-		// check if it is a valid itemType
660
-		self::getBackend($itemType);
661
-
662
-		$items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
663
-
664
-		$toDelete = array();
665
-		$newParent = null;
666
-		$currentUser = $owner ? $owner : \OC_User::getUser();
667
-		foreach ($items as $item) {
668
-			// delete the item with the expected share_type and owner
669
-			if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
670
-				$toDelete = $item;
671
-				// if there is more then one result we don't have to delete the children
672
-				// but update their parent. For group shares the new parent should always be
673
-				// the original group share and not the db entry with the unique name
674
-			} else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
675
-				$newParent = $item['parent'];
676
-			} else {
677
-				$newParent = $item['id'];
678
-			}
679
-		}
680
-
681
-		if (!empty($toDelete)) {
682
-			self::unshareItem($toDelete, $newParent);
683
-			return true;
684
-		}
685
-		return false;
686
-	}
687
-
688
-	/**
689
-	 * sent status if users got informed by mail about share
690
-	 * @param string $itemType
691
-	 * @param string $itemSource
692
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
693
-	 * @param string $recipient with whom was the file shared
694
-	 * @param boolean $status
695
-	 */
696
-	public static function setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status) {
697
-		$status = $status ? 1 : 0;
698
-
699
-		$query = \OC_DB::prepare(
700
-			'UPDATE `*PREFIX*share`
596
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_REMOTE,
597
+                $shareWith, $uidOwner, self::FORMAT_NONE, null, 1, true, true)) {
598
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
599
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
600
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
601
+                    throw new \Exception($message_t);
602
+            }
603
+
604
+            // don't allow federated shares if source and target server are the same
605
+            list($user, $remote) = Helper::splitUserRemote($shareWith);
606
+            $currentServer = self::removeProtocolFromUrl(\OC::$server->getURLGenerator()->getAbsoluteURL('/'));
607
+            $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
608
+            if (Helper::isSameUserOnSameServer($user, $remote, $currentUser, $currentServer)) {
609
+                $message = 'Not allowed to create a federated share with the same user.';
610
+                $message_t = $l->t('Not allowed to create a federated share with the same user');
611
+                \OCP\Util::writeLog('OCP\Share', $message, ILogger::DEBUG);
612
+                throw new \Exception($message_t);
613
+            }
614
+
615
+            $token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
616
+                \OCP\Security\ISecureRandom::CHAR_DIGITS);
617
+
618
+            $shareWith = $user . '@' . $remote;
619
+            $shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
620
+
621
+            $send = false;
622
+            if ($shareId) {
623
+                $send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
624
+            }
625
+
626
+            if ($send === false) {
627
+                $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
628
+                self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
629
+                $message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
630
+                throw new \Exception($message_t);
631
+            }
632
+
633
+            return $send;
634
+        } else {
635
+            // Future share types need to include their own conditions
636
+            $message = 'Share type %s is not valid for %s';
637
+            $message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
638
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $shareType, $itemSource), ILogger::DEBUG);
639
+            throw new \Exception($message_t);
640
+        }
641
+
642
+        // Put the item into the database
643
+        $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
644
+
645
+        return $result ? true : false;
646
+    }
647
+
648
+    /**
649
+     * Unshare an item from a user, group, or delete a private link
650
+     * @param string $itemType
651
+     * @param string $itemSource
652
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
653
+     * @param string $shareWith User or group the item is being shared with
654
+     * @param string $owner owner of the share, if null the current user is used
655
+     * @return boolean true on success or false on failure
656
+     */
657
+    public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
658
+
659
+        // check if it is a valid itemType
660
+        self::getBackend($itemType);
661
+
662
+        $items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
663
+
664
+        $toDelete = array();
665
+        $newParent = null;
666
+        $currentUser = $owner ? $owner : \OC_User::getUser();
667
+        foreach ($items as $item) {
668
+            // delete the item with the expected share_type and owner
669
+            if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
670
+                $toDelete = $item;
671
+                // if there is more then one result we don't have to delete the children
672
+                // but update their parent. For group shares the new parent should always be
673
+                // the original group share and not the db entry with the unique name
674
+            } else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
675
+                $newParent = $item['parent'];
676
+            } else {
677
+                $newParent = $item['id'];
678
+            }
679
+        }
680
+
681
+        if (!empty($toDelete)) {
682
+            self::unshareItem($toDelete, $newParent);
683
+            return true;
684
+        }
685
+        return false;
686
+    }
687
+
688
+    /**
689
+     * sent status if users got informed by mail about share
690
+     * @param string $itemType
691
+     * @param string $itemSource
692
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
693
+     * @param string $recipient with whom was the file shared
694
+     * @param boolean $status
695
+     */
696
+    public static function setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status) {
697
+        $status = $status ? 1 : 0;
698
+
699
+        $query = \OC_DB::prepare(
700
+            'UPDATE `*PREFIX*share`
701 701
 					SET `mail_send` = ?
702 702
 					WHERE `item_type` = ? AND `item_source` = ? AND `share_type` = ? AND `share_with` = ?');
703 703
 
704
-		$result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
705
-
706
-		if($result === false) {
707
-			\OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', ILogger::ERROR);
708
-		}
709
-	}
710
-
711
-	/**
712
-	 * validate expiration date if it meets all constraints
713
-	 *
714
-	 * @param string $expireDate well formatted date string, e.g. "DD-MM-YYYY"
715
-	 * @param string $shareTime timestamp when the file was shared
716
-	 * @param string $itemType
717
-	 * @param string $itemSource
718
-	 * @return \DateTime validated date
719
-	 * @throws \Exception when the expire date is in the past or further in the future then the enforced date
720
-	 */
721
-	private static function validateExpireDate($expireDate, $shareTime, $itemType, $itemSource) {
722
-		$l = \OC::$server->getL10N('lib');
723
-		$date = new \DateTime($expireDate);
724
-		$today = new \DateTime('now');
725
-
726
-		// if the user doesn't provide a share time we need to get it from the database
727
-		// fall-back mode to keep API stable, because the $shareTime parameter was added later
728
-		$defaultExpireDateEnforced = \OCP\Util::isDefaultExpireDateEnforced();
729
-		if ($defaultExpireDateEnforced && $shareTime === null) {
730
-			$items = self::getItemShared($itemType, $itemSource);
731
-			$firstItem = reset($items);
732
-			$shareTime = (int)$firstItem['stime'];
733
-		}
734
-
735
-		if ($defaultExpireDateEnforced) {
736
-			// initialize max date with share time
737
-			$maxDate = new \DateTime();
738
-			$maxDate->setTimestamp($shareTime);
739
-			$maxDays = \OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
740
-			$maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
741
-			if ($date > $maxDate) {
742
-				$warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
743
-				$warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
744
-				\OCP\Util::writeLog('OCP\Share', $warning, ILogger::WARN);
745
-				throw new \Exception($warning_t);
746
-			}
747
-		}
748
-
749
-		if ($date < $today) {
750
-			$message = 'Cannot set expiration date. Expiration date is in the past';
751
-			$message_t = $l->t('Cannot set expiration date. Expiration date is in the past');
752
-			\OCP\Util::writeLog('OCP\Share', $message, ILogger::WARN);
753
-			throw new \Exception($message_t);
754
-		}
755
-
756
-		return $date;
757
-	}
758
-
759
-	/**
760
-	 * Checks whether a share has expired, calls unshareItem() if yes.
761
-	 * @param array $item Share data (usually database row)
762
-	 * @return boolean True if item was expired, false otherwise.
763
-	 */
764
-	protected static function expireItem(array $item) {
765
-
766
-		$result = false;
767
-
768
-		// only use default expiration date for link shares
769
-		if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
770
-
771
-			// calculate expiration date
772
-			if (!empty($item['expiration'])) {
773
-				$userDefinedExpire = new \DateTime($item['expiration']);
774
-				$expires = $userDefinedExpire->getTimestamp();
775
-			} else {
776
-				$expires = null;
777
-			}
778
-
779
-
780
-			// get default expiration settings
781
-			$defaultSettings = Helper::getDefaultExpireSetting();
782
-			$expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
783
-
784
-
785
-			if (is_int($expires)) {
786
-				$now = time();
787
-				if ($now > $expires) {
788
-					self::unshareItem($item);
789
-					$result = true;
790
-				}
791
-			}
792
-		}
793
-		return $result;
794
-	}
795
-
796
-	/**
797
-	 * Unshares a share given a share data array
798
-	 * @param array $item Share data (usually database row)
799
-	 * @param int $newParent parent ID
800
-	 * @return null
801
-	 */
802
-	protected static function unshareItem(array $item, $newParent = null) {
803
-
804
-		$shareType = (int)$item['share_type'];
805
-		$shareWith = null;
806
-		if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
807
-			$shareWith = $item['share_with'];
808
-		}
809
-
810
-		// Pass all the vars we have for now, they may be useful
811
-		$hookParams = array(
812
-			'id'            => $item['id'],
813
-			'itemType'      => $item['item_type'],
814
-			'itemSource'    => $item['item_source'],
815
-			'shareType'     => $shareType,
816
-			'shareWith'     => $shareWith,
817
-			'itemParent'    => $item['parent'],
818
-			'uidOwner'      => $item['uid_owner'],
819
-		);
820
-		if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
821
-			$hookParams['fileSource'] = $item['file_source'];
822
-			$hookParams['fileTarget'] = $item['file_target'];
823
-		}
824
-
825
-		\OC_Hook::emit(\OCP\Share::class, 'pre_unshare', $hookParams);
826
-		$deletedShares = Helper::delete($item['id'], false, null, $newParent);
827
-		$deletedShares[] = $hookParams;
828
-		$hookParams['deletedShares'] = $deletedShares;
829
-		\OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
830
-		if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
831
-			list(, $remote) = Helper::splitUserRemote($item['share_with']);
832
-			self::sendRemoteUnshare($remote, $item['id'], $item['token']);
833
-		}
834
-	}
835
-
836
-	/**
837
-	 * Get the backend class for the specified item type
838
-	 * @param string $itemType
839
-	 * @throws \Exception
840
-	 * @return \OCP\Share_Backend
841
-	 */
842
-	public static function getBackend($itemType) {
843
-		$l = \OC::$server->getL10N('lib');
844
-		if (isset(self::$backends[$itemType])) {
845
-			return self::$backends[$itemType];
846
-		} else if (isset(self::$backendTypes[$itemType]['class'])) {
847
-			$class = self::$backendTypes[$itemType]['class'];
848
-			if (class_exists($class)) {
849
-				self::$backends[$itemType] = new $class;
850
-				if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
851
-					$message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
852
-					$message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class));
853
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
854
-					throw new \Exception($message_t);
855
-				}
856
-				return self::$backends[$itemType];
857
-			} else {
858
-				$message = 'Sharing backend %s not found';
859
-				$message_t = $l->t('Sharing backend %s not found', array($class));
860
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
861
-				throw new \Exception($message_t);
862
-			}
863
-		}
864
-		$message = 'Sharing backend for %s not found';
865
-		$message_t = $l->t('Sharing backend for %s not found', array($itemType));
866
-		\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), ILogger::ERROR);
867
-		throw new \Exception($message_t);
868
-	}
869
-
870
-	/**
871
-	 * Check if resharing is allowed
872
-	 * @return boolean true if allowed or false
873
-	 *
874
-	 * Resharing is allowed by default if not configured
875
-	 */
876
-	public static function isResharingAllowed() {
877
-		if (!isset(self::$isResharingAllowed)) {
878
-			if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
879
-				self::$isResharingAllowed = true;
880
-			} else {
881
-				self::$isResharingAllowed = false;
882
-			}
883
-		}
884
-		return self::$isResharingAllowed;
885
-	}
886
-
887
-	/**
888
-	 * Get a list of collection item types for the specified item type
889
-	 * @param string $itemType
890
-	 * @return array
891
-	 */
892
-	private static function getCollectionItemTypes($itemType) {
893
-		$collectionTypes = array($itemType);
894
-		foreach (self::$backendTypes as $type => $backend) {
895
-			if (in_array($backend['collectionOf'], $collectionTypes)) {
896
-				$collectionTypes[] = $type;
897
-			}
898
-		}
899
-		// TODO Add option for collections to be collection of themselves, only 'folder' does it now...
900
-		if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
901
-			unset($collectionTypes[0]);
902
-		}
903
-		// Return array if collections were found or the item type is a
904
-		// collection itself - collections can be inside collections
905
-		if (count($collectionTypes) > 0) {
906
-			return $collectionTypes;
907
-		}
908
-		return false;
909
-	}
910
-
911
-	/**
912
-	 * Get the owners of items shared with a user.
913
-	 *
914
-	 * @param string $user The user the items are shared with.
915
-	 * @param string $type The type of the items shared with the user.
916
-	 * @param boolean $includeCollections Include collection item types (optional)
917
-	 * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
918
-	 * @return array
919
-	 */
920
-	public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
921
-		// First, we find out if $type is part of a collection (and if that collection is part of
922
-		// another one and so on).
923
-		$collectionTypes = array();
924
-		if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
925
-			$collectionTypes[] = $type;
926
-		}
927
-
928
-		// Of these collection types, along with our original $type, we make a
929
-		// list of the ones for which a sharing backend has been registered.
930
-		// FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
931
-		// with its $includeCollections parameter set to true. Unfortunately, this fails currently.
932
-		$allMaybeSharedItems = array();
933
-		foreach ($collectionTypes as $collectionType) {
934
-			if (isset(self::$backends[$collectionType])) {
935
-				$allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
936
-					$collectionType,
937
-					$user,
938
-					self::FORMAT_NONE
939
-				);
940
-			}
941
-		}
942
-
943
-		$owners = array();
944
-		if ($includeOwner) {
945
-			$owners[] = $user;
946
-		}
947
-
948
-		// We take a look at all shared items of the given $type (or of the collections it is part of)
949
-		// and find out their owners. Then, we gather the tags for the original $type from all owners,
950
-		// and return them as elements of a list that look like "Tag (owner)".
951
-		foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
952
-			foreach ($maybeSharedItems as $sharedItem) {
953
-				if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
954
-					$owners[] = $sharedItem['uid_owner'];
955
-				}
956
-			}
957
-		}
958
-
959
-		return $owners;
960
-	}
961
-
962
-	/**
963
-	 * Get shared items from the database
964
-	 * @param string $itemType
965
-	 * @param string $item Item source or target (optional)
966
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
967
-	 * @param string $shareWith User or group the item is being shared with
968
-	 * @param string $uidOwner User that is the owner of shared items (optional)
969
-	 * @param int $format Format to convert items to with formatItems() (optional)
970
-	 * @param mixed $parameters to pass to formatItems() (optional)
971
-	 * @param int $limit Number of items to return, -1 to return all matches (optional)
972
-	 * @param boolean $includeCollections Include collection item types (optional)
973
-	 * @param boolean $itemShareWithBySource (optional)
974
-	 * @param boolean $checkExpireDate
975
-	 * @return array
976
-	 *
977
-	 * See public functions getItem(s)... for parameter usage
978
-	 *
979
-	 */
980
-	public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
981
-									$uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
982
-									$includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
983
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') {
984
-			return array();
985
-		}
986
-		$backend = self::getBackend($itemType);
987
-		$collectionTypes = false;
988
-		// Get filesystem root to add it to the file target and remove from the
989
-		// file source, match file_source with the file cache
990
-		if ($itemType == 'file' || $itemType == 'folder') {
991
-			if(!is_null($uidOwner)) {
992
-				$root = \OC\Files\Filesystem::getRoot();
993
-			} else {
994
-				$root = '';
995
-			}
996
-			$where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
997
-			if (!isset($item)) {
998
-				$where .= ' AND `file_target` IS NOT NULL ';
999
-			}
1000
-			$where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
1001
-			$fileDependent = true;
1002
-			$queryArgs = array();
1003
-		} else {
1004
-			$fileDependent = false;
1005
-			$root = '';
1006
-			$collectionTypes = self::getCollectionItemTypes($itemType);
1007
-			if ($includeCollections && !isset($item) && $collectionTypes) {
1008
-				// If includeCollections is true, find collections of this item type, e.g. a music album contains songs
1009
-				if (!in_array($itemType, $collectionTypes)) {
1010
-					$itemTypes = array_merge(array($itemType), $collectionTypes);
1011
-				} else {
1012
-					$itemTypes = $collectionTypes;
1013
-				}
1014
-				$placeholders = implode(',', array_fill(0, count($itemTypes), '?'));
1015
-				$where = ' WHERE `item_type` IN ('.$placeholders.'))';
1016
-				$queryArgs = $itemTypes;
1017
-			} else {
1018
-				$where = ' WHERE `item_type` = ?';
1019
-				$queryArgs = array($itemType);
1020
-			}
1021
-		}
1022
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
1023
-			$where .= ' AND `share_type` != ?';
1024
-			$queryArgs[] = self::SHARE_TYPE_LINK;
1025
-		}
1026
-		if (isset($shareType)) {
1027
-			// Include all user and group items
1028
-			if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
1029
-				$where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
1030
-				$queryArgs[] = self::SHARE_TYPE_USER;
1031
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
1032
-				$queryArgs[] = $shareWith;
1033
-
1034
-				$user = \OC::$server->getUserManager()->get($shareWith);
1035
-				$groups = [];
1036
-				if ($user) {
1037
-					$groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
1038
-				}
1039
-				if (!empty($groups)) {
1040
-					$placeholders = implode(',', array_fill(0, count($groups), '?'));
1041
-					$where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
1042
-					$queryArgs[] = self::SHARE_TYPE_GROUP;
1043
-					$queryArgs = array_merge($queryArgs, $groups);
1044
-				}
1045
-				$where .= ')';
1046
-				// Don't include own group shares
1047
-				$where .= ' AND `uid_owner` != ?';
1048
-				$queryArgs[] = $shareWith;
1049
-			} else {
1050
-				$where .= ' AND `share_type` = ?';
1051
-				$queryArgs[] = $shareType;
1052
-				if (isset($shareWith)) {
1053
-					$where .= ' AND `share_with` = ?';
1054
-					$queryArgs[] = $shareWith;
1055
-				}
1056
-			}
1057
-		}
1058
-		if (isset($uidOwner)) {
1059
-			$where .= ' AND `uid_owner` = ?';
1060
-			$queryArgs[] = $uidOwner;
1061
-			if (!isset($shareType)) {
1062
-				// Prevent unique user targets for group shares from being selected
1063
-				$where .= ' AND `share_type` != ?';
1064
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
1065
-			}
1066
-			if ($fileDependent) {
1067
-				$column = 'file_source';
1068
-			} else {
1069
-				$column = 'item_source';
1070
-			}
1071
-		} else {
1072
-			if ($fileDependent) {
1073
-				$column = 'file_target';
1074
-			} else {
1075
-				$column = 'item_target';
1076
-			}
1077
-		}
1078
-		if (isset($item)) {
1079
-			$collectionTypes = self::getCollectionItemTypes($itemType);
1080
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1081
-				$where .= ' AND (';
1082
-			} else {
1083
-				$where .= ' AND';
1084
-			}
1085
-			// If looking for own shared items, check item_source else check item_target
1086
-			if (isset($uidOwner) || $itemShareWithBySource) {
1087
-				// If item type is a file, file source needs to be checked in case the item was converted
1088
-				if ($fileDependent) {
1089
-					$where .= ' `file_source` = ?';
1090
-					$column = 'file_source';
1091
-				} else {
1092
-					$where .= ' `item_source` = ?';
1093
-					$column = 'item_source';
1094
-				}
1095
-			} else {
1096
-				if ($fileDependent) {
1097
-					$where .= ' `file_target` = ?';
1098
-					$item = \OC\Files\Filesystem::normalizePath($item);
1099
-				} else {
1100
-					$where .= ' `item_target` = ?';
1101
-				}
1102
-			}
1103
-			$queryArgs[] = $item;
1104
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1105
-				$placeholders = implode(',', array_fill(0, count($collectionTypes), '?'));
1106
-				$where .= ' OR `item_type` IN ('.$placeholders.'))';
1107
-				$queryArgs = array_merge($queryArgs, $collectionTypes);
1108
-			}
1109
-		}
1110
-
1111
-		if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
1112
-			// Make sure the unique user target is returned if it exists,
1113
-			// unique targets should follow the group share in the database
1114
-			// If the limit is not 1, the filtering can be done later
1115
-			$where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
1116
-		} else {
1117
-			$where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
1118
-		}
1119
-
1120
-		if ($limit != -1 && !$includeCollections) {
1121
-			// The limit must be at least 3, because filtering needs to be done
1122
-			if ($limit < 3) {
1123
-				$queryLimit = 3;
1124
-			} else {
1125
-				$queryLimit = $limit;
1126
-			}
1127
-		} else {
1128
-			$queryLimit = null;
1129
-		}
1130
-		$select = self::createSelectStatement($format, $fileDependent, $uidOwner);
1131
-		$root = strlen($root);
1132
-		$query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
1133
-		$result = $query->execute($queryArgs);
1134
-		if ($result === false) {
1135
-			\OCP\Util::writeLog('OCP\Share',
1136
-				\OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
1137
-				ILogger::ERROR);
1138
-		}
1139
-		$items = array();
1140
-		$targets = array();
1141
-		$switchedItems = array();
1142
-		$mounts = array();
1143
-		while ($row = $result->fetchRow()) {
1144
-			self::transformDBResults($row);
1145
-			// Filter out duplicate group shares for users with unique targets
1146
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
1147
-				continue;
1148
-			}
1149
-			if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
1150
-				$row['share_type'] = self::SHARE_TYPE_GROUP;
1151
-				$row['unique_name'] = true; // remember that we use a unique name for this user
1152
-				$row['share_with'] = $items[$row['parent']]['share_with'];
1153
-				// if the group share was unshared from the user we keep the permission, otherwise
1154
-				// we take the permission from the parent because this is always the up-to-date
1155
-				// permission for the group share
1156
-				if ($row['permissions'] > 0) {
1157
-					$row['permissions'] = $items[$row['parent']]['permissions'];
1158
-				}
1159
-				// Remove the parent group share
1160
-				unset($items[$row['parent']]);
1161
-				if ($row['permissions'] == 0) {
1162
-					continue;
1163
-				}
1164
-			} else if (!isset($uidOwner)) {
1165
-				// Check if the same target already exists
1166
-				if (isset($targets[$row['id']])) {
1167
-					// Check if the same owner shared with the user twice
1168
-					// through a group and user share - this is allowed
1169
-					$id = $targets[$row['id']];
1170
-					if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
1171
-						// Switch to group share type to ensure resharing conditions aren't bypassed
1172
-						if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
1173
-							$items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
1174
-							$items[$id]['share_with'] = $row['share_with'];
1175
-						}
1176
-						// Switch ids if sharing permission is granted on only
1177
-						// one share to ensure correct parent is used if resharing
1178
-						if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1179
-							&& (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1180
-							$items[$row['id']] = $items[$id];
1181
-							$switchedItems[$id] = $row['id'];
1182
-							unset($items[$id]);
1183
-							$id = $row['id'];
1184
-						}
1185
-						$items[$id]['permissions'] |= (int)$row['permissions'];
1186
-
1187
-					}
1188
-					continue;
1189
-				} elseif (!empty($row['parent'])) {
1190
-					$targets[$row['parent']] = $row['id'];
1191
-				}
1192
-			}
1193
-			// Remove root from file source paths if retrieving own shared items
1194
-			if (isset($uidOwner) && isset($row['path'])) {
1195
-				if (isset($row['parent'])) {
1196
-					$query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
1197
-					$parentResult = $query->execute(array($row['parent']));
1198
-					if ($result === false) {
1199
-						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
1200
-							\OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
1201
-							ILogger::ERROR);
1202
-					} else {
1203
-						$parentRow = $parentResult->fetchRow();
1204
-						$tmpPath = $parentRow['file_target'];
1205
-						// find the right position where the row path continues from the target path
1206
-						$pos = strrpos($row['path'], $parentRow['file_target']);
1207
-						$subPath = substr($row['path'], $pos);
1208
-						$splitPath = explode('/', $subPath);
1209
-						foreach (array_slice($splitPath, 2) as $pathPart) {
1210
-							$tmpPath = $tmpPath . '/' . $pathPart;
1211
-						}
1212
-						$row['path'] = $tmpPath;
1213
-					}
1214
-				} else {
1215
-					if (!isset($mounts[$row['storage']])) {
1216
-						$mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
1217
-						if (is_array($mountPoints) && !empty($mountPoints)) {
1218
-							$mounts[$row['storage']] = current($mountPoints);
1219
-						}
1220
-					}
1221
-					if (!empty($mounts[$row['storage']])) {
1222
-						$path = $mounts[$row['storage']]->getMountPoint().$row['path'];
1223
-						$relPath = substr($path, $root); // path relative to data/user
1224
-						$row['path'] = rtrim($relPath, '/');
1225
-					}
1226
-				}
1227
-			}
1228
-
1229
-			if($checkExpireDate) {
1230
-				if (self::expireItem($row)) {
1231
-					continue;
1232
-				}
1233
-			}
1234
-			// Check if resharing is allowed, if not remove share permission
1235
-			if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
1236
-				$row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
1237
-			}
1238
-			// Add display names to result
1239
-			$row['share_with_displayname'] = $row['share_with'];
1240
-			if ( isset($row['share_with']) && $row['share_with'] != '' &&
1241
-				$row['share_type'] === self::SHARE_TYPE_USER) {
1242
-				$shareWithUser = \OC::$server->getUserManager()->get($row['share_with']);
1243
-				$row['share_with_displayname'] = $shareWithUser === null ? $row['share_with'] : $shareWithUser->getDisplayName();
1244
-			} else if(isset($row['share_with']) && $row['share_with'] != '' &&
1245
-				$row['share_type'] === self::SHARE_TYPE_REMOTE) {
1246
-				$addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
1247
-				foreach ($addressBookEntries as $entry) {
1248
-					foreach ($entry['CLOUD'] as $cloudID) {
1249
-						if ($cloudID === $row['share_with']) {
1250
-							$row['share_with_displayname'] = $entry['FN'];
1251
-						}
1252
-					}
1253
-				}
1254
-			}
1255
-			if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
1256
-				$ownerUser = \OC::$server->getUserManager()->get($row['uid_owner']);
1257
-				$row['displayname_owner'] = $ownerUser === null ? $row['uid_owner'] : $ownerUser->getDisplayName();
1258
-			}
1259
-
1260
-			if ($row['permissions'] > 0) {
1261
-				$items[$row['id']] = $row;
1262
-			}
1263
-
1264
-		}
1265
-
1266
-		// group items if we are looking for items shared with the current user
1267
-		if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
1268
-			$items = self::groupItems($items, $itemType);
1269
-		}
1270
-
1271
-		if (!empty($items)) {
1272
-			$collectionItems = array();
1273
-			foreach ($items as &$row) {
1274
-				// Return only the item instead of a 2-dimensional array
1275
-				if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
1276
-					if ($format == self::FORMAT_NONE) {
1277
-						return $row;
1278
-					} else {
1279
-						break;
1280
-					}
1281
-				}
1282
-				// Check if this is a collection of the requested item type
1283
-				if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
1284
-					if (($collectionBackend = self::getBackend($row['item_type']))
1285
-						&& $collectionBackend instanceof \OCP\Share_Backend_Collection) {
1286
-						// Collections can be inside collections, check if the item is a collection
1287
-						if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
1288
-							$collectionItems[] = $row;
1289
-						} else {
1290
-							$collection = array();
1291
-							$collection['item_type'] = $row['item_type'];
1292
-							if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1293
-								$collection['path'] = basename($row['path']);
1294
-							}
1295
-							$row['collection'] = $collection;
1296
-							// Fetch all of the children sources
1297
-							$children = $collectionBackend->getChildren($row[$column]);
1298
-							foreach ($children as $child) {
1299
-								$childItem = $row;
1300
-								$childItem['item_type'] = $itemType;
1301
-								if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
1302
-									$childItem['item_source'] = $child['source'];
1303
-									$childItem['item_target'] = $child['target'];
1304
-								}
1305
-								if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1306
-									if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1307
-										$childItem['file_source'] = $child['source'];
1308
-									} else { // TODO is this really needed if we already know that we use the file backend?
1309
-										$meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
1310
-										$childItem['file_source'] = $meta['fileid'];
1311
-									}
1312
-									$childItem['file_target'] =
1313
-										\OC\Files\Filesystem::normalizePath($child['file_path']);
1314
-								}
1315
-								if (isset($item)) {
1316
-									if ($childItem[$column] == $item) {
1317
-										// Return only the item instead of a 2-dimensional array
1318
-										if ($limit == 1) {
1319
-											if ($format == self::FORMAT_NONE) {
1320
-												return $childItem;
1321
-											} else {
1322
-												// Unset the items array and break out of both loops
1323
-												$items = array();
1324
-												$items[] = $childItem;
1325
-												break 2;
1326
-											}
1327
-										} else {
1328
-											$collectionItems[] = $childItem;
1329
-										}
1330
-									}
1331
-								} else {
1332
-									$collectionItems[] = $childItem;
1333
-								}
1334
-							}
1335
-						}
1336
-					}
1337
-					// Remove collection item
1338
-					$toRemove = $row['id'];
1339
-					if (array_key_exists($toRemove, $switchedItems)) {
1340
-						$toRemove = $switchedItems[$toRemove];
1341
-					}
1342
-					unset($items[$toRemove]);
1343
-				} elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
1344
-					// FIXME: Thats a dirty hack to improve file sharing performance,
1345
-					// see github issue #10588 for more details
1346
-					// Need to find a solution which works for all back-ends
1347
-					$collectionBackend = self::getBackend($row['item_type']);
1348
-					$sharedParents = $collectionBackend->getParents($row['item_source']);
1349
-					foreach ($sharedParents as $parent) {
1350
-						$collectionItems[] = $parent;
1351
-					}
1352
-				}
1353
-			}
1354
-			if (!empty($collectionItems)) {
1355
-				$collectionItems = array_unique($collectionItems, SORT_REGULAR);
1356
-				$items = array_merge($items, $collectionItems);
1357
-			}
1358
-
1359
-			// filter out invalid items, these can appear when subshare entries exist
1360
-			// for a group in which the requested user isn't a member any more
1361
-			$items = array_filter($items, function($item) {
1362
-				return $item['share_type'] !== self::$shareTypeGroupUserUnique;
1363
-			});
1364
-
1365
-			return self::formatResult($items, $column, $backend, $format, $parameters);
1366
-		} elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
1367
-			// FIXME: Thats a dirty hack to improve file sharing performance,
1368
-			// see github issue #10588 for more details
1369
-			// Need to find a solution which works for all back-ends
1370
-			$collectionItems = array();
1371
-			$collectionBackend = self::getBackend('folder');
1372
-			$sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
1373
-			foreach ($sharedParents as $parent) {
1374
-				$collectionItems[] = $parent;
1375
-			}
1376
-			if ($limit === 1) {
1377
-				return reset($collectionItems);
1378
-			}
1379
-			return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
1380
-		}
1381
-
1382
-		return array();
1383
-	}
1384
-
1385
-	/**
1386
-	 * group items with link to the same source
1387
-	 *
1388
-	 * @param array $items
1389
-	 * @param string $itemType
1390
-	 * @return array of grouped items
1391
-	 */
1392
-	protected static function groupItems($items, $itemType) {
1393
-
1394
-		$fileSharing = $itemType === 'file' || $itemType === 'folder';
1395
-
1396
-		$result = array();
1397
-
1398
-		foreach ($items as $item) {
1399
-			$grouped = false;
1400
-			foreach ($result as $key => $r) {
1401
-				// for file/folder shares we need to compare file_source, otherwise we compare item_source
1402
-				// only group shares if they already point to the same target, otherwise the file where shared
1403
-				// before grouping of shares was added. In this case we don't group them toi avoid confusions
1404
-				if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1405
-					(!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
1406
-					// add the first item to the list of grouped shares
1407
-					if (!isset($result[$key]['grouped'])) {
1408
-						$result[$key]['grouped'][] = $result[$key];
1409
-					}
1410
-					$result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
1411
-					$result[$key]['grouped'][] = $item;
1412
-					$grouped = true;
1413
-					break;
1414
-				}
1415
-			}
1416
-
1417
-			if (!$grouped) {
1418
-				$result[] = $item;
1419
-			}
1420
-
1421
-		}
1422
-
1423
-		return $result;
1424
-	}
1425
-
1426
-	/**
1427
-	 * Put shared item into the database
1428
-	 * @param string $itemType Item type
1429
-	 * @param string $itemSource Item source
1430
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1431
-	 * @param string $shareWith User or group the item is being shared with
1432
-	 * @param string $uidOwner User that is the owner of shared item
1433
-	 * @param int $permissions CRUDS permissions
1434
-	 * @param boolean|array $parentFolder Parent folder target (optional)
1435
-	 * @param string $token (optional)
1436
-	 * @param string $itemSourceName name of the source item (optional)
1437
-	 * @param \DateTime $expirationDate (optional)
1438
-	 * @throws \Exception
1439
-	 * @return mixed id of the new share or false
1440
-	 */
1441
-	private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1442
-								$permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) {
1443
-
1444
-		$queriesToExecute = array();
1445
-		$suggestedItemTarget = null;
1446
-		$groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
1447
-		$groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1448
-
1449
-		$result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
1450
-		if(!empty($result)) {
1451
-			$parent = $result['parent'];
1452
-			$itemSource = $result['itemSource'];
1453
-			$fileSource = $result['fileSource'];
1454
-			$suggestedItemTarget = $result['suggestedItemTarget'];
1455
-			$suggestedFileTarget = $result['suggestedFileTarget'];
1456
-			$filePath = $result['filePath'];
1457
-		}
1458
-
1459
-		$isGroupShare = false;
1460
-		if ($shareType == self::SHARE_TYPE_GROUP) {
1461
-			$isGroupShare = true;
1462
-			if (isset($shareWith['users'])) {
1463
-				$users = $shareWith['users'];
1464
-			} else {
1465
-				$group = \OC::$server->getGroupManager()->get($shareWith['group']);
1466
-				if ($group) {
1467
-					$users = $group->searchUsers('', -1, 0);
1468
-					$userIds = [];
1469
-					foreach ($users as $user) {
1470
-						$userIds[] = $user->getUID();
1471
-					}
1472
-					$users = $userIds;
1473
-				} else {
1474
-					$users = [];
1475
-				}
1476
-			}
1477
-			// remove current user from list
1478
-			if (in_array(\OCP\User::getUser(), $users)) {
1479
-				unset($users[array_search(\OCP\User::getUser(), $users)]);
1480
-			}
1481
-			$groupItemTarget = Helper::generateTarget($itemType, $itemSource,
1482
-				$shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget);
1483
-			$groupFileTarget = Helper::generateTarget($itemType, $itemSource,
1484
-				$shareType, $shareWith['group'], $uidOwner, $filePath);
1485
-
1486
-			// add group share to table and remember the id as parent
1487
-			$queriesToExecute['groupShare'] = array(
1488
-				'itemType'			=> $itemType,
1489
-				'itemSource'		=> $itemSource,
1490
-				'itemTarget'		=> $groupItemTarget,
1491
-				'shareType'			=> $shareType,
1492
-				'shareWith'			=> $shareWith['group'],
1493
-				'uidOwner'			=> $uidOwner,
1494
-				'permissions'		=> $permissions,
1495
-				'shareTime'			=> time(),
1496
-				'fileSource'		=> $fileSource,
1497
-				'fileTarget'		=> $groupFileTarget,
1498
-				'token'				=> $token,
1499
-				'parent'			=> $parent,
1500
-				'expiration'		=> $expirationDate,
1501
-			);
1502
-
1503
-		} else {
1504
-			$users = array($shareWith);
1505
-			$itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1506
-				$suggestedItemTarget);
1507
-		}
1508
-
1509
-		$run = true;
1510
-		$error = '';
1511
-		$preHookData = array(
1512
-			'itemType' => $itemType,
1513
-			'itemSource' => $itemSource,
1514
-			'shareType' => $shareType,
1515
-			'uidOwner' => $uidOwner,
1516
-			'permissions' => $permissions,
1517
-			'fileSource' => $fileSource,
1518
-			'expiration' => $expirationDate,
1519
-			'token' => $token,
1520
-			'run' => &$run,
1521
-			'error' => &$error
1522
-		);
1523
-
1524
-		$preHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget;
1525
-		$preHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith;
1526
-
1527
-		\OC_Hook::emit(\OCP\Share::class, 'pre_shared', $preHookData);
1528
-
1529
-		if ($run === false) {
1530
-			throw new \Exception($error);
1531
-		}
1532
-
1533
-		foreach ($users as $user) {
1534
-			$sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
1535
-			$sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
1536
-
1537
-			$userShareType = $isGroupShare ? self::$shareTypeGroupUserUnique : $shareType;
1538
-
1539
-			if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
1540
-				$fileTarget = $sourceExists['file_target'];
1541
-				$itemTarget = $sourceExists['item_target'];
1542
-
1543
-				// for group shares we don't need a additional entry if the target is the same
1544
-				if($isGroupShare && $groupItemTarget === $itemTarget) {
1545
-					continue;
1546
-				}
1547
-
1548
-			} elseif(!$sourceExists && !$isGroupShare)  {
1549
-
1550
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1551
-					$uidOwner, $suggestedItemTarget, $parent);
1552
-				if (isset($fileSource)) {
1553
-					if ($parentFolder) {
1554
-						if ($parentFolder === true) {
1555
-							$fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user,
1556
-								$uidOwner, $suggestedFileTarget, $parent);
1557
-							if ($fileTarget != $groupFileTarget) {
1558
-								$parentFolders[$user]['folder'] = $fileTarget;
1559
-							}
1560
-						} else if (isset($parentFolder[$user])) {
1561
-							$fileTarget = $parentFolder[$user]['folder'].$itemSource;
1562
-							$parent = $parentFolder[$user]['id'];
1563
-						}
1564
-					} else {
1565
-						$fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
1566
-							$user, $uidOwner, $suggestedFileTarget, $parent);
1567
-					}
1568
-				} else {
1569
-					$fileTarget = null;
1570
-				}
1571
-
1572
-			} else {
1573
-
1574
-				// group share which doesn't exists until now, check if we need a unique target for this user
1575
-
1576
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
1577
-					$uidOwner, $suggestedItemTarget, $parent);
1578
-
1579
-				// do we also need a file target
1580
-				if (isset($fileSource)) {
1581
-					$fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
1582
-						$uidOwner, $suggestedFileTarget, $parent);
1583
-				} else {
1584
-					$fileTarget = null;
1585
-				}
1586
-
1587
-				if (($itemTarget === $groupItemTarget) &&
1588
-					(!isset($fileSource) || $fileTarget === $groupFileTarget)) {
1589
-					continue;
1590
-				}
1591
-			}
1592
-
1593
-			$queriesToExecute[] = array(
1594
-				'itemType'			=> $itemType,
1595
-				'itemSource'		=> $itemSource,
1596
-				'itemTarget'		=> $itemTarget,
1597
-				'shareType'			=> $userShareType,
1598
-				'shareWith'			=> $user,
1599
-				'uidOwner'			=> $uidOwner,
1600
-				'permissions'		=> $permissions,
1601
-				'shareTime'			=> time(),
1602
-				'fileSource'		=> $fileSource,
1603
-				'fileTarget'		=> $fileTarget,
1604
-				'token'				=> $token,
1605
-				'parent'			=> $parent,
1606
-				'expiration'		=> $expirationDate,
1607
-			);
1608
-
1609
-		}
1610
-
1611
-		$id = false;
1612
-		if ($isGroupShare) {
1613
-			$id = self::insertShare($queriesToExecute['groupShare']);
1614
-			// Save this id, any extra rows for this group share will need to reference it
1615
-			$parent = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1616
-			unset($queriesToExecute['groupShare']);
1617
-		}
1618
-
1619
-		foreach ($queriesToExecute as $shareQuery) {
1620
-			$shareQuery['parent'] = $parent;
1621
-			$id = self::insertShare($shareQuery);
1622
-		}
1623
-
1624
-		$postHookData = array(
1625
-			'itemType' => $itemType,
1626
-			'itemSource' => $itemSource,
1627
-			'parent' => $parent,
1628
-			'shareType' => $shareType,
1629
-			'uidOwner' => $uidOwner,
1630
-			'permissions' => $permissions,
1631
-			'fileSource' => $fileSource,
1632
-			'id' => $parent,
1633
-			'token' => $token,
1634
-			'expirationDate' => $expirationDate,
1635
-		);
1636
-
1637
-		$postHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith;
1638
-		$postHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget;
1639
-		$postHookData['fileTarget'] = $isGroupShare ? $groupFileTarget : $fileTarget;
1640
-
1641
-		\OC_Hook::emit(\OCP\Share::class, 'post_shared', $postHookData);
1642
-
1643
-
1644
-		return $id ? $id : false;
1645
-	}
1646
-
1647
-	/**
1648
-	 * @param string $itemType
1649
-	 * @param string $itemSource
1650
-	 * @param int $shareType
1651
-	 * @param string $shareWith
1652
-	 * @param string $uidOwner
1653
-	 * @param int $permissions
1654
-	 * @param string|null $itemSourceName
1655
-	 * @param null|\DateTime $expirationDate
1656
-	 */
1657
-	private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
1658
-		$backend = self::getBackend($itemType);
1659
-
1660
-		$l = \OC::$server->getL10N('lib');
1661
-		$result = array();
1662
-
1663
-		$column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
1664
-
1665
-		$checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
1666
-		if ($checkReshare) {
1667
-			// Check if attempting to share back to owner
1668
-			if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
1669
-				$message = 'Sharing %s failed, because the user %s is the original sharer';
1670
-				$message_t = $l->t('Sharing failed, because the user %s is the original sharer', [$shareWith]);
1671
-
1672
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
1673
-				throw new \Exception($message_t);
1674
-			}
1675
-		}
1676
-
1677
-		if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1678
-			// Check if share permissions is granted
1679
-			if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1680
-				if (~(int)$checkReshare['permissions'] & $permissions) {
1681
-					$message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
1682
-					$message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
1683
-
1684
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner), ILogger::DEBUG);
1685
-					throw new \Exception($message_t);
1686
-				} else {
1687
-					// TODO Don't check if inside folder
1688
-					$result['parent'] = $checkReshare['id'];
1689
-
1690
-					$result['expirationDate'] = $expirationDate;
1691
-					// $checkReshare['expiration'] could be null and then is always less than any value
1692
-					if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1693
-						$result['expirationDate'] = $checkReshare['expiration'];
1694
-					}
1695
-
1696
-					// only suggest the same name as new target if it is a reshare of the
1697
-					// same file/folder and not the reshare of a child
1698
-					if ($checkReshare[$column] === $itemSource) {
1699
-						$result['filePath'] = $checkReshare['file_target'];
1700
-						$result['itemSource'] = $checkReshare['item_source'];
1701
-						$result['fileSource'] = $checkReshare['file_source'];
1702
-						$result['suggestedItemTarget'] = $checkReshare['item_target'];
1703
-						$result['suggestedFileTarget'] = $checkReshare['file_target'];
1704
-					} else {
1705
-						$result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
1706
-						$result['suggestedItemTarget'] = null;
1707
-						$result['suggestedFileTarget'] = null;
1708
-						$result['itemSource'] = $itemSource;
1709
-						$result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
1710
-					}
1711
-				}
1712
-			} else {
1713
-				$message = 'Sharing %s failed, because resharing is not allowed';
1714
-				$message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
1715
-
1716
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), ILogger::DEBUG);
1717
-				throw new \Exception($message_t);
1718
-			}
1719
-		} else {
1720
-			$result['parent'] = null;
1721
-			$result['suggestedItemTarget'] = null;
1722
-			$result['suggestedFileTarget'] = null;
1723
-			$result['itemSource'] = $itemSource;
1724
-			$result['expirationDate'] = $expirationDate;
1725
-			if (!$backend->isValidSource($itemSource, $uidOwner)) {
1726
-				$message = 'Sharing %s failed, because the sharing backend for '
1727
-					.'%s could not find its source';
1728
-				$message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
1729
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, $itemType), ILogger::DEBUG);
1730
-				throw new \Exception($message_t);
1731
-			}
1732
-			if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1733
-				$result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
1734
-				if ($itemType == 'file' || $itemType == 'folder') {
1735
-					$result['fileSource'] = $itemSource;
1736
-				} else {
1737
-					$meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
1738
-					$result['fileSource'] = $meta['fileid'];
1739
-				}
1740
-				if ($result['fileSource'] == -1) {
1741
-					$message = 'Sharing %s failed, because the file could not be found in the file cache';
1742
-					$message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
1743
-
1744
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), ILogger::DEBUG);
1745
-					throw new \Exception($message_t);
1746
-				}
1747
-			} else {
1748
-				$result['filePath'] = null;
1749
-				$result['fileSource'] = null;
1750
-			}
1751
-		}
1752
-
1753
-		return $result;
1754
-	}
1755
-
1756
-	/**
1757
-	 *
1758
-	 * @param array $shareData
1759
-	 * @return mixed false in case of a failure or the id of the new share
1760
-	 */
1761
-	private static function insertShare(array $shareData) {
1762
-
1763
-		$query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
1764
-			.' `item_type`, `item_source`, `item_target`, `share_type`,'
1765
-			.' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
1766
-			.' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
1767
-		$query->bindValue(1, $shareData['itemType']);
1768
-		$query->bindValue(2, $shareData['itemSource']);
1769
-		$query->bindValue(3, $shareData['itemTarget']);
1770
-		$query->bindValue(4, $shareData['shareType']);
1771
-		$query->bindValue(5, $shareData['shareWith']);
1772
-		$query->bindValue(6, $shareData['uidOwner']);
1773
-		$query->bindValue(7, $shareData['permissions']);
1774
-		$query->bindValue(8, $shareData['shareTime']);
1775
-		$query->bindValue(9, $shareData['fileSource']);
1776
-		$query->bindValue(10, $shareData['fileTarget']);
1777
-		$query->bindValue(11, $shareData['token']);
1778
-		$query->bindValue(12, $shareData['parent']);
1779
-		$query->bindValue(13, $shareData['expiration'], 'datetime');
1780
-		$result = $query->execute();
1781
-
1782
-		$id = false;
1783
-		if ($result) {
1784
-			$id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1785
-		}
1786
-
1787
-		return $id;
1788
-
1789
-	}
1790
-
1791
-	/**
1792
-	 * In case a password protected link is not yet authenticated this function will return false
1793
-	 *
1794
-	 * @param array $linkItem
1795
-	 * @return boolean
1796
-	 */
1797
-	public static function checkPasswordProtectedShare(array $linkItem) {
1798
-		if (!isset($linkItem['share_with'])) {
1799
-			return true;
1800
-		}
1801
-		if (!isset($linkItem['share_type'])) {
1802
-			return true;
1803
-		}
1804
-		if (!isset($linkItem['id'])) {
1805
-			return true;
1806
-		}
1807
-
1808
-		if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
1809
-			return true;
1810
-		}
1811
-
1812
-		if ( \OC::$server->getSession()->exists('public_link_authenticated')
1813
-			&& \OC::$server->getSession()->get('public_link_authenticated') === (string)$linkItem['id'] ) {
1814
-			return true;
1815
-		}
1816
-
1817
-		return false;
1818
-	}
1819
-
1820
-	/**
1821
-	 * construct select statement
1822
-	 * @param int $format
1823
-	 * @param boolean $fileDependent ist it a file/folder share or a generla share
1824
-	 * @param string $uidOwner
1825
-	 * @return string select statement
1826
-	 */
1827
-	private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
1828
-		$select = '*';
1829
-		if ($format == self::FORMAT_STATUSES) {
1830
-			if ($fileDependent) {
1831
-				$select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
1832
-					. '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
1833
-					. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1834
-					. '`uid_initiator`';
1835
-			} else {
1836
-				$select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
1837
-			}
1838
-		} else {
1839
-			if (isset($uidOwner)) {
1840
-				if ($fileDependent) {
1841
-					$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
1842
-						. ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
1843
-						. ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
1844
-						. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1845
-				} else {
1846
-					$select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
1847
-						. ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
1848
-				}
1849
-			} else {
1850
-				if ($fileDependent) {
1851
-					if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
1852
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
1853
-							. '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
1854
-							. '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1855
-							. '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
1856
-					} else {
1857
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
1858
-							. '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
1859
-							. '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
1860
-						    . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
1861
-							. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1862
-					}
1863
-				}
1864
-			}
1865
-		}
1866
-		return $select;
1867
-	}
1868
-
1869
-
1870
-	/**
1871
-	 * transform db results
1872
-	 * @param array $row result
1873
-	 */
1874
-	private static function transformDBResults(&$row) {
1875
-		if (isset($row['id'])) {
1876
-			$row['id'] = (int) $row['id'];
1877
-		}
1878
-		if (isset($row['share_type'])) {
1879
-			$row['share_type'] = (int) $row['share_type'];
1880
-		}
1881
-		if (isset($row['parent'])) {
1882
-			$row['parent'] = (int) $row['parent'];
1883
-		}
1884
-		if (isset($row['file_parent'])) {
1885
-			$row['file_parent'] = (int) $row['file_parent'];
1886
-		}
1887
-		if (isset($row['file_source'])) {
1888
-			$row['file_source'] = (int) $row['file_source'];
1889
-		}
1890
-		if (isset($row['permissions'])) {
1891
-			$row['permissions'] = (int) $row['permissions'];
1892
-		}
1893
-		if (isset($row['storage'])) {
1894
-			$row['storage'] = (int) $row['storage'];
1895
-		}
1896
-		if (isset($row['stime'])) {
1897
-			$row['stime'] = (int) $row['stime'];
1898
-		}
1899
-		if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
1900
-			// discard expiration date for non-link shares, which might have been
1901
-			// set by ancient bugs
1902
-			$row['expiration'] = null;
1903
-		}
1904
-	}
1905
-
1906
-	/**
1907
-	 * format result
1908
-	 * @param array $items result
1909
-	 * @param string $column is it a file share or a general share ('file_target' or 'item_target')
1910
-	 * @param \OCP\Share_Backend $backend sharing backend
1911
-	 * @param int $format
1912
-	 * @param array $parameters additional format parameters
1913
-	 * @return array format result
1914
-	 */
1915
-	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
1916
-		if ($format === self::FORMAT_NONE) {
1917
-			return $items;
1918
-		} else if ($format === self::FORMAT_STATUSES) {
1919
-			$statuses = array();
1920
-			foreach ($items as $item) {
1921
-				if ($item['share_type'] === self::SHARE_TYPE_LINK) {
1922
-					if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
1923
-						continue;
1924
-					}
1925
-					$statuses[$item[$column]]['link'] = true;
1926
-				} else if (!isset($statuses[$item[$column]])) {
1927
-					$statuses[$item[$column]]['link'] = false;
1928
-				}
1929
-				if (!empty($item['file_target'])) {
1930
-					$statuses[$item[$column]]['path'] = $item['path'];
1931
-				}
1932
-			}
1933
-			return $statuses;
1934
-		} else {
1935
-			return $backend->formatItems($items, $format, $parameters);
1936
-		}
1937
-	}
1938
-
1939
-	/**
1940
-	 * remove protocol from URL
1941
-	 *
1942
-	 * @param string $url
1943
-	 * @return string
1944
-	 */
1945
-	public static function removeProtocolFromUrl($url) {
1946
-		if (strpos($url, 'https://') === 0) {
1947
-			return substr($url, strlen('https://'));
1948
-		} else if (strpos($url, 'http://') === 0) {
1949
-			return substr($url, strlen('http://'));
1950
-		}
1951
-
1952
-		return $url;
1953
-	}
1954
-
1955
-	/**
1956
-	 * try http post first with https and then with http as a fallback
1957
-	 *
1958
-	 * @param string $remoteDomain
1959
-	 * @param string $urlSuffix
1960
-	 * @param array $fields post parameters
1961
-	 * @return array
1962
-	 */
1963
-	private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
1964
-		$protocol = 'https://';
1965
-		$result = [
1966
-			'success' => false,
1967
-			'result' => '',
1968
-		];
1969
-		$try = 0;
1970
-		$discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
1971
-		while ($result['success'] === false && $try < 2) {
1972
-			$federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
1973
-			$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
1974
-			$client = \OC::$server->getHTTPClientService()->newClient();
1975
-
1976
-			try {
1977
-				$response = $client->post(
1978
-					$protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
1979
-					[
1980
-						'body' => $fields,
1981
-						'connect_timeout' => 10,
1982
-					]
1983
-				);
1984
-
1985
-				$result = ['success' => true, 'result' => $response->getBody()];
1986
-			} catch (\Exception $e) {
1987
-				$result = ['success' => false, 'result' => $e->getMessage()];
1988
-			}
1989
-
1990
-			$try++;
1991
-			$protocol = 'http://';
1992
-		}
1993
-
1994
-		return $result;
1995
-	}
1996
-
1997
-	/**
1998
-	 * send server-to-server share to remote server
1999
-	 *
2000
-	 * @param string $token
2001
-	 * @param string $shareWith
2002
-	 * @param string $name
2003
-	 * @param int $remote_id
2004
-	 * @param string $owner
2005
-	 * @return bool
2006
-	 */
2007
-	private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) {
2008
-
2009
-		list($user, $remote) = Helper::splitUserRemote($shareWith);
2010
-
2011
-		if ($user && $remote) {
2012
-			$url = $remote;
2013
-
2014
-			$local = \OC::$server->getURLGenerator()->getAbsoluteURL('/');
2015
-
2016
-			$fields = array(
2017
-				'shareWith' => $user,
2018
-				'token' => $token,
2019
-				'name' => $name,
2020
-				'remoteId' => $remote_id,
2021
-				'owner' => $owner,
2022
-				'remote' => $local,
2023
-			);
2024
-
2025
-			$url = self::removeProtocolFromUrl($url);
2026
-			$result = self::tryHttpPostToShareEndpoint($url, '', $fields);
2027
-			$status = json_decode($result['result'], true);
2028
-
2029
-			if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
2030
-				\OC_Hook::emit(\OCP\Share::class, 'federated_share_added', ['server' => $remote]);
2031
-				return true;
2032
-			}
2033
-
2034
-		}
2035
-
2036
-		return false;
2037
-	}
2038
-
2039
-	/**
2040
-	 * send server-to-server unshare to remote server
2041
-	 *
2042
-	 * @param string $remote url
2043
-	 * @param int $id share id
2044
-	 * @param string $token
2045
-	 * @return bool
2046
-	 */
2047
-	private static function sendRemoteUnshare($remote, $id, $token) {
2048
-		$url = rtrim($remote, '/');
2049
-		$fields = array('token' => $token, 'format' => 'json');
2050
-		$url = self::removeProtocolFromUrl($url);
2051
-		$result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
2052
-		$status = json_decode($result['result'], true);
2053
-
2054
-		return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
2055
-	}
2056
-
2057
-	/**
2058
-	 * check if user can only share with group members
2059
-	 * @return bool
2060
-	 */
2061
-	public static function shareWithGroupMembersOnly() {
2062
-		$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_only_share_with_group_members', 'no');
2063
-		return $value === 'yes';
2064
-	}
2065
-
2066
-	/**
2067
-	 * @return bool
2068
-	 */
2069
-	public static function isDefaultExpireDateEnabled() {
2070
-		$defaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
2071
-		return $defaultExpireDateEnabled === 'yes';
2072
-	}
2073
-
2074
-	/**
2075
-	 * @return int
2076
-	 */
2077
-	public static function getExpireInterval() {
2078
-		return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
2079
-	}
2080
-
2081
-	/**
2082
-	 * Checks whether the given path is reachable for the given owner
2083
-	 *
2084
-	 * @param string $path path relative to files
2085
-	 * @param string $ownerStorageId storage id of the owner
2086
-	 *
2087
-	 * @return boolean true if file is reachable, false otherwise
2088
-	 */
2089
-	private static function isFileReachable($path, $ownerStorageId) {
2090
-		// if outside the home storage, file is always considered reachable
2091
-		if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
2092
-			substr($ownerStorageId, 0, 13) === 'object::user:'
2093
-		)) {
2094
-			return true;
2095
-		}
2096
-
2097
-		// if inside the home storage, the file has to be under "/files/"
2098
-		$path = ltrim($path, '/');
2099
-		if (substr($path, 0, 6) === 'files/') {
2100
-			return true;
2101
-		}
2102
-
2103
-		return false;
2104
-	}
2105
-
2106
-	/**
2107
-	 * @param IConfig $config
2108
-	 * @return bool
2109
-	 */
2110
-	public static function enforcePassword(IConfig $config) {
2111
-		$enforcePassword = $config->getAppValue('core', 'shareapi_enforce_links_password', 'no');
2112
-		return $enforcePassword === 'yes';
2113
-	}
2114
-
2115
-	/**
2116
-	 * @param string $password
2117
-	 * @throws \Exception
2118
-	 */
2119
-	private static function verifyPassword($password) {
2120
-
2121
-		$accepted = true;
2122
-		$message = '';
2123
-		\OCP\Util::emitHook('\OC\Share', 'verifyPassword', [
2124
-			'password' => $password,
2125
-			'accepted' => &$accepted,
2126
-			'message' => &$message
2127
-		]);
2128
-
2129
-		if (!$accepted) {
2130
-			throw new \Exception($message);
2131
-		}
2132
-	}
704
+        $result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
705
+
706
+        if($result === false) {
707
+            \OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', ILogger::ERROR);
708
+        }
709
+    }
710
+
711
+    /**
712
+     * validate expiration date if it meets all constraints
713
+     *
714
+     * @param string $expireDate well formatted date string, e.g. "DD-MM-YYYY"
715
+     * @param string $shareTime timestamp when the file was shared
716
+     * @param string $itemType
717
+     * @param string $itemSource
718
+     * @return \DateTime validated date
719
+     * @throws \Exception when the expire date is in the past or further in the future then the enforced date
720
+     */
721
+    private static function validateExpireDate($expireDate, $shareTime, $itemType, $itemSource) {
722
+        $l = \OC::$server->getL10N('lib');
723
+        $date = new \DateTime($expireDate);
724
+        $today = new \DateTime('now');
725
+
726
+        // if the user doesn't provide a share time we need to get it from the database
727
+        // fall-back mode to keep API stable, because the $shareTime parameter was added later
728
+        $defaultExpireDateEnforced = \OCP\Util::isDefaultExpireDateEnforced();
729
+        if ($defaultExpireDateEnforced && $shareTime === null) {
730
+            $items = self::getItemShared($itemType, $itemSource);
731
+            $firstItem = reset($items);
732
+            $shareTime = (int)$firstItem['stime'];
733
+        }
734
+
735
+        if ($defaultExpireDateEnforced) {
736
+            // initialize max date with share time
737
+            $maxDate = new \DateTime();
738
+            $maxDate->setTimestamp($shareTime);
739
+            $maxDays = \OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
740
+            $maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
741
+            if ($date > $maxDate) {
742
+                $warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
743
+                $warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
744
+                \OCP\Util::writeLog('OCP\Share', $warning, ILogger::WARN);
745
+                throw new \Exception($warning_t);
746
+            }
747
+        }
748
+
749
+        if ($date < $today) {
750
+            $message = 'Cannot set expiration date. Expiration date is in the past';
751
+            $message_t = $l->t('Cannot set expiration date. Expiration date is in the past');
752
+            \OCP\Util::writeLog('OCP\Share', $message, ILogger::WARN);
753
+            throw new \Exception($message_t);
754
+        }
755
+
756
+        return $date;
757
+    }
758
+
759
+    /**
760
+     * Checks whether a share has expired, calls unshareItem() if yes.
761
+     * @param array $item Share data (usually database row)
762
+     * @return boolean True if item was expired, false otherwise.
763
+     */
764
+    protected static function expireItem(array $item) {
765
+
766
+        $result = false;
767
+
768
+        // only use default expiration date for link shares
769
+        if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
770
+
771
+            // calculate expiration date
772
+            if (!empty($item['expiration'])) {
773
+                $userDefinedExpire = new \DateTime($item['expiration']);
774
+                $expires = $userDefinedExpire->getTimestamp();
775
+            } else {
776
+                $expires = null;
777
+            }
778
+
779
+
780
+            // get default expiration settings
781
+            $defaultSettings = Helper::getDefaultExpireSetting();
782
+            $expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
783
+
784
+
785
+            if (is_int($expires)) {
786
+                $now = time();
787
+                if ($now > $expires) {
788
+                    self::unshareItem($item);
789
+                    $result = true;
790
+                }
791
+            }
792
+        }
793
+        return $result;
794
+    }
795
+
796
+    /**
797
+     * Unshares a share given a share data array
798
+     * @param array $item Share data (usually database row)
799
+     * @param int $newParent parent ID
800
+     * @return null
801
+     */
802
+    protected static function unshareItem(array $item, $newParent = null) {
803
+
804
+        $shareType = (int)$item['share_type'];
805
+        $shareWith = null;
806
+        if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
807
+            $shareWith = $item['share_with'];
808
+        }
809
+
810
+        // Pass all the vars we have for now, they may be useful
811
+        $hookParams = array(
812
+            'id'            => $item['id'],
813
+            'itemType'      => $item['item_type'],
814
+            'itemSource'    => $item['item_source'],
815
+            'shareType'     => $shareType,
816
+            'shareWith'     => $shareWith,
817
+            'itemParent'    => $item['parent'],
818
+            'uidOwner'      => $item['uid_owner'],
819
+        );
820
+        if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
821
+            $hookParams['fileSource'] = $item['file_source'];
822
+            $hookParams['fileTarget'] = $item['file_target'];
823
+        }
824
+
825
+        \OC_Hook::emit(\OCP\Share::class, 'pre_unshare', $hookParams);
826
+        $deletedShares = Helper::delete($item['id'], false, null, $newParent);
827
+        $deletedShares[] = $hookParams;
828
+        $hookParams['deletedShares'] = $deletedShares;
829
+        \OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
830
+        if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
831
+            list(, $remote) = Helper::splitUserRemote($item['share_with']);
832
+            self::sendRemoteUnshare($remote, $item['id'], $item['token']);
833
+        }
834
+    }
835
+
836
+    /**
837
+     * Get the backend class for the specified item type
838
+     * @param string $itemType
839
+     * @throws \Exception
840
+     * @return \OCP\Share_Backend
841
+     */
842
+    public static function getBackend($itemType) {
843
+        $l = \OC::$server->getL10N('lib');
844
+        if (isset(self::$backends[$itemType])) {
845
+            return self::$backends[$itemType];
846
+        } else if (isset(self::$backendTypes[$itemType]['class'])) {
847
+            $class = self::$backendTypes[$itemType]['class'];
848
+            if (class_exists($class)) {
849
+                self::$backends[$itemType] = new $class;
850
+                if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
851
+                    $message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
852
+                    $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class));
853
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
854
+                    throw new \Exception($message_t);
855
+                }
856
+                return self::$backends[$itemType];
857
+            } else {
858
+                $message = 'Sharing backend %s not found';
859
+                $message_t = $l->t('Sharing backend %s not found', array($class));
860
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
861
+                throw new \Exception($message_t);
862
+            }
863
+        }
864
+        $message = 'Sharing backend for %s not found';
865
+        $message_t = $l->t('Sharing backend for %s not found', array($itemType));
866
+        \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), ILogger::ERROR);
867
+        throw new \Exception($message_t);
868
+    }
869
+
870
+    /**
871
+     * Check if resharing is allowed
872
+     * @return boolean true if allowed or false
873
+     *
874
+     * Resharing is allowed by default if not configured
875
+     */
876
+    public static function isResharingAllowed() {
877
+        if (!isset(self::$isResharingAllowed)) {
878
+            if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
879
+                self::$isResharingAllowed = true;
880
+            } else {
881
+                self::$isResharingAllowed = false;
882
+            }
883
+        }
884
+        return self::$isResharingAllowed;
885
+    }
886
+
887
+    /**
888
+     * Get a list of collection item types for the specified item type
889
+     * @param string $itemType
890
+     * @return array
891
+     */
892
+    private static function getCollectionItemTypes($itemType) {
893
+        $collectionTypes = array($itemType);
894
+        foreach (self::$backendTypes as $type => $backend) {
895
+            if (in_array($backend['collectionOf'], $collectionTypes)) {
896
+                $collectionTypes[] = $type;
897
+            }
898
+        }
899
+        // TODO Add option for collections to be collection of themselves, only 'folder' does it now...
900
+        if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
901
+            unset($collectionTypes[0]);
902
+        }
903
+        // Return array if collections were found or the item type is a
904
+        // collection itself - collections can be inside collections
905
+        if (count($collectionTypes) > 0) {
906
+            return $collectionTypes;
907
+        }
908
+        return false;
909
+    }
910
+
911
+    /**
912
+     * Get the owners of items shared with a user.
913
+     *
914
+     * @param string $user The user the items are shared with.
915
+     * @param string $type The type of the items shared with the user.
916
+     * @param boolean $includeCollections Include collection item types (optional)
917
+     * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
918
+     * @return array
919
+     */
920
+    public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
921
+        // First, we find out if $type is part of a collection (and if that collection is part of
922
+        // another one and so on).
923
+        $collectionTypes = array();
924
+        if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
925
+            $collectionTypes[] = $type;
926
+        }
927
+
928
+        // Of these collection types, along with our original $type, we make a
929
+        // list of the ones for which a sharing backend has been registered.
930
+        // FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
931
+        // with its $includeCollections parameter set to true. Unfortunately, this fails currently.
932
+        $allMaybeSharedItems = array();
933
+        foreach ($collectionTypes as $collectionType) {
934
+            if (isset(self::$backends[$collectionType])) {
935
+                $allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
936
+                    $collectionType,
937
+                    $user,
938
+                    self::FORMAT_NONE
939
+                );
940
+            }
941
+        }
942
+
943
+        $owners = array();
944
+        if ($includeOwner) {
945
+            $owners[] = $user;
946
+        }
947
+
948
+        // We take a look at all shared items of the given $type (or of the collections it is part of)
949
+        // and find out their owners. Then, we gather the tags for the original $type from all owners,
950
+        // and return them as elements of a list that look like "Tag (owner)".
951
+        foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
952
+            foreach ($maybeSharedItems as $sharedItem) {
953
+                if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
954
+                    $owners[] = $sharedItem['uid_owner'];
955
+                }
956
+            }
957
+        }
958
+
959
+        return $owners;
960
+    }
961
+
962
+    /**
963
+     * Get shared items from the database
964
+     * @param string $itemType
965
+     * @param string $item Item source or target (optional)
966
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
967
+     * @param string $shareWith User or group the item is being shared with
968
+     * @param string $uidOwner User that is the owner of shared items (optional)
969
+     * @param int $format Format to convert items to with formatItems() (optional)
970
+     * @param mixed $parameters to pass to formatItems() (optional)
971
+     * @param int $limit Number of items to return, -1 to return all matches (optional)
972
+     * @param boolean $includeCollections Include collection item types (optional)
973
+     * @param boolean $itemShareWithBySource (optional)
974
+     * @param boolean $checkExpireDate
975
+     * @return array
976
+     *
977
+     * See public functions getItem(s)... for parameter usage
978
+     *
979
+     */
980
+    public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
981
+                                    $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
982
+                                    $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
983
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') {
984
+            return array();
985
+        }
986
+        $backend = self::getBackend($itemType);
987
+        $collectionTypes = false;
988
+        // Get filesystem root to add it to the file target and remove from the
989
+        // file source, match file_source with the file cache
990
+        if ($itemType == 'file' || $itemType == 'folder') {
991
+            if(!is_null($uidOwner)) {
992
+                $root = \OC\Files\Filesystem::getRoot();
993
+            } else {
994
+                $root = '';
995
+            }
996
+            $where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
997
+            if (!isset($item)) {
998
+                $where .= ' AND `file_target` IS NOT NULL ';
999
+            }
1000
+            $where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
1001
+            $fileDependent = true;
1002
+            $queryArgs = array();
1003
+        } else {
1004
+            $fileDependent = false;
1005
+            $root = '';
1006
+            $collectionTypes = self::getCollectionItemTypes($itemType);
1007
+            if ($includeCollections && !isset($item) && $collectionTypes) {
1008
+                // If includeCollections is true, find collections of this item type, e.g. a music album contains songs
1009
+                if (!in_array($itemType, $collectionTypes)) {
1010
+                    $itemTypes = array_merge(array($itemType), $collectionTypes);
1011
+                } else {
1012
+                    $itemTypes = $collectionTypes;
1013
+                }
1014
+                $placeholders = implode(',', array_fill(0, count($itemTypes), '?'));
1015
+                $where = ' WHERE `item_type` IN ('.$placeholders.'))';
1016
+                $queryArgs = $itemTypes;
1017
+            } else {
1018
+                $where = ' WHERE `item_type` = ?';
1019
+                $queryArgs = array($itemType);
1020
+            }
1021
+        }
1022
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
1023
+            $where .= ' AND `share_type` != ?';
1024
+            $queryArgs[] = self::SHARE_TYPE_LINK;
1025
+        }
1026
+        if (isset($shareType)) {
1027
+            // Include all user and group items
1028
+            if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
1029
+                $where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
1030
+                $queryArgs[] = self::SHARE_TYPE_USER;
1031
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
1032
+                $queryArgs[] = $shareWith;
1033
+
1034
+                $user = \OC::$server->getUserManager()->get($shareWith);
1035
+                $groups = [];
1036
+                if ($user) {
1037
+                    $groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
1038
+                }
1039
+                if (!empty($groups)) {
1040
+                    $placeholders = implode(',', array_fill(0, count($groups), '?'));
1041
+                    $where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
1042
+                    $queryArgs[] = self::SHARE_TYPE_GROUP;
1043
+                    $queryArgs = array_merge($queryArgs, $groups);
1044
+                }
1045
+                $where .= ')';
1046
+                // Don't include own group shares
1047
+                $where .= ' AND `uid_owner` != ?';
1048
+                $queryArgs[] = $shareWith;
1049
+            } else {
1050
+                $where .= ' AND `share_type` = ?';
1051
+                $queryArgs[] = $shareType;
1052
+                if (isset($shareWith)) {
1053
+                    $where .= ' AND `share_with` = ?';
1054
+                    $queryArgs[] = $shareWith;
1055
+                }
1056
+            }
1057
+        }
1058
+        if (isset($uidOwner)) {
1059
+            $where .= ' AND `uid_owner` = ?';
1060
+            $queryArgs[] = $uidOwner;
1061
+            if (!isset($shareType)) {
1062
+                // Prevent unique user targets for group shares from being selected
1063
+                $where .= ' AND `share_type` != ?';
1064
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
1065
+            }
1066
+            if ($fileDependent) {
1067
+                $column = 'file_source';
1068
+            } else {
1069
+                $column = 'item_source';
1070
+            }
1071
+        } else {
1072
+            if ($fileDependent) {
1073
+                $column = 'file_target';
1074
+            } else {
1075
+                $column = 'item_target';
1076
+            }
1077
+        }
1078
+        if (isset($item)) {
1079
+            $collectionTypes = self::getCollectionItemTypes($itemType);
1080
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1081
+                $where .= ' AND (';
1082
+            } else {
1083
+                $where .= ' AND';
1084
+            }
1085
+            // If looking for own shared items, check item_source else check item_target
1086
+            if (isset($uidOwner) || $itemShareWithBySource) {
1087
+                // If item type is a file, file source needs to be checked in case the item was converted
1088
+                if ($fileDependent) {
1089
+                    $where .= ' `file_source` = ?';
1090
+                    $column = 'file_source';
1091
+                } else {
1092
+                    $where .= ' `item_source` = ?';
1093
+                    $column = 'item_source';
1094
+                }
1095
+            } else {
1096
+                if ($fileDependent) {
1097
+                    $where .= ' `file_target` = ?';
1098
+                    $item = \OC\Files\Filesystem::normalizePath($item);
1099
+                } else {
1100
+                    $where .= ' `item_target` = ?';
1101
+                }
1102
+            }
1103
+            $queryArgs[] = $item;
1104
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1105
+                $placeholders = implode(',', array_fill(0, count($collectionTypes), '?'));
1106
+                $where .= ' OR `item_type` IN ('.$placeholders.'))';
1107
+                $queryArgs = array_merge($queryArgs, $collectionTypes);
1108
+            }
1109
+        }
1110
+
1111
+        if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
1112
+            // Make sure the unique user target is returned if it exists,
1113
+            // unique targets should follow the group share in the database
1114
+            // If the limit is not 1, the filtering can be done later
1115
+            $where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
1116
+        } else {
1117
+            $where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
1118
+        }
1119
+
1120
+        if ($limit != -1 && !$includeCollections) {
1121
+            // The limit must be at least 3, because filtering needs to be done
1122
+            if ($limit < 3) {
1123
+                $queryLimit = 3;
1124
+            } else {
1125
+                $queryLimit = $limit;
1126
+            }
1127
+        } else {
1128
+            $queryLimit = null;
1129
+        }
1130
+        $select = self::createSelectStatement($format, $fileDependent, $uidOwner);
1131
+        $root = strlen($root);
1132
+        $query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
1133
+        $result = $query->execute($queryArgs);
1134
+        if ($result === false) {
1135
+            \OCP\Util::writeLog('OCP\Share',
1136
+                \OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
1137
+                ILogger::ERROR);
1138
+        }
1139
+        $items = array();
1140
+        $targets = array();
1141
+        $switchedItems = array();
1142
+        $mounts = array();
1143
+        while ($row = $result->fetchRow()) {
1144
+            self::transformDBResults($row);
1145
+            // Filter out duplicate group shares for users with unique targets
1146
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
1147
+                continue;
1148
+            }
1149
+            if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
1150
+                $row['share_type'] = self::SHARE_TYPE_GROUP;
1151
+                $row['unique_name'] = true; // remember that we use a unique name for this user
1152
+                $row['share_with'] = $items[$row['parent']]['share_with'];
1153
+                // if the group share was unshared from the user we keep the permission, otherwise
1154
+                // we take the permission from the parent because this is always the up-to-date
1155
+                // permission for the group share
1156
+                if ($row['permissions'] > 0) {
1157
+                    $row['permissions'] = $items[$row['parent']]['permissions'];
1158
+                }
1159
+                // Remove the parent group share
1160
+                unset($items[$row['parent']]);
1161
+                if ($row['permissions'] == 0) {
1162
+                    continue;
1163
+                }
1164
+            } else if (!isset($uidOwner)) {
1165
+                // Check if the same target already exists
1166
+                if (isset($targets[$row['id']])) {
1167
+                    // Check if the same owner shared with the user twice
1168
+                    // through a group and user share - this is allowed
1169
+                    $id = $targets[$row['id']];
1170
+                    if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
1171
+                        // Switch to group share type to ensure resharing conditions aren't bypassed
1172
+                        if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
1173
+                            $items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
1174
+                            $items[$id]['share_with'] = $row['share_with'];
1175
+                        }
1176
+                        // Switch ids if sharing permission is granted on only
1177
+                        // one share to ensure correct parent is used if resharing
1178
+                        if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1179
+                            && (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1180
+                            $items[$row['id']] = $items[$id];
1181
+                            $switchedItems[$id] = $row['id'];
1182
+                            unset($items[$id]);
1183
+                            $id = $row['id'];
1184
+                        }
1185
+                        $items[$id]['permissions'] |= (int)$row['permissions'];
1186
+
1187
+                    }
1188
+                    continue;
1189
+                } elseif (!empty($row['parent'])) {
1190
+                    $targets[$row['parent']] = $row['id'];
1191
+                }
1192
+            }
1193
+            // Remove root from file source paths if retrieving own shared items
1194
+            if (isset($uidOwner) && isset($row['path'])) {
1195
+                if (isset($row['parent'])) {
1196
+                    $query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
1197
+                    $parentResult = $query->execute(array($row['parent']));
1198
+                    if ($result === false) {
1199
+                        \OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
1200
+                            \OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
1201
+                            ILogger::ERROR);
1202
+                    } else {
1203
+                        $parentRow = $parentResult->fetchRow();
1204
+                        $tmpPath = $parentRow['file_target'];
1205
+                        // find the right position where the row path continues from the target path
1206
+                        $pos = strrpos($row['path'], $parentRow['file_target']);
1207
+                        $subPath = substr($row['path'], $pos);
1208
+                        $splitPath = explode('/', $subPath);
1209
+                        foreach (array_slice($splitPath, 2) as $pathPart) {
1210
+                            $tmpPath = $tmpPath . '/' . $pathPart;
1211
+                        }
1212
+                        $row['path'] = $tmpPath;
1213
+                    }
1214
+                } else {
1215
+                    if (!isset($mounts[$row['storage']])) {
1216
+                        $mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
1217
+                        if (is_array($mountPoints) && !empty($mountPoints)) {
1218
+                            $mounts[$row['storage']] = current($mountPoints);
1219
+                        }
1220
+                    }
1221
+                    if (!empty($mounts[$row['storage']])) {
1222
+                        $path = $mounts[$row['storage']]->getMountPoint().$row['path'];
1223
+                        $relPath = substr($path, $root); // path relative to data/user
1224
+                        $row['path'] = rtrim($relPath, '/');
1225
+                    }
1226
+                }
1227
+            }
1228
+
1229
+            if($checkExpireDate) {
1230
+                if (self::expireItem($row)) {
1231
+                    continue;
1232
+                }
1233
+            }
1234
+            // Check if resharing is allowed, if not remove share permission
1235
+            if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
1236
+                $row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
1237
+            }
1238
+            // Add display names to result
1239
+            $row['share_with_displayname'] = $row['share_with'];
1240
+            if ( isset($row['share_with']) && $row['share_with'] != '' &&
1241
+                $row['share_type'] === self::SHARE_TYPE_USER) {
1242
+                $shareWithUser = \OC::$server->getUserManager()->get($row['share_with']);
1243
+                $row['share_with_displayname'] = $shareWithUser === null ? $row['share_with'] : $shareWithUser->getDisplayName();
1244
+            } else if(isset($row['share_with']) && $row['share_with'] != '' &&
1245
+                $row['share_type'] === self::SHARE_TYPE_REMOTE) {
1246
+                $addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
1247
+                foreach ($addressBookEntries as $entry) {
1248
+                    foreach ($entry['CLOUD'] as $cloudID) {
1249
+                        if ($cloudID === $row['share_with']) {
1250
+                            $row['share_with_displayname'] = $entry['FN'];
1251
+                        }
1252
+                    }
1253
+                }
1254
+            }
1255
+            if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
1256
+                $ownerUser = \OC::$server->getUserManager()->get($row['uid_owner']);
1257
+                $row['displayname_owner'] = $ownerUser === null ? $row['uid_owner'] : $ownerUser->getDisplayName();
1258
+            }
1259
+
1260
+            if ($row['permissions'] > 0) {
1261
+                $items[$row['id']] = $row;
1262
+            }
1263
+
1264
+        }
1265
+
1266
+        // group items if we are looking for items shared with the current user
1267
+        if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
1268
+            $items = self::groupItems($items, $itemType);
1269
+        }
1270
+
1271
+        if (!empty($items)) {
1272
+            $collectionItems = array();
1273
+            foreach ($items as &$row) {
1274
+                // Return only the item instead of a 2-dimensional array
1275
+                if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
1276
+                    if ($format == self::FORMAT_NONE) {
1277
+                        return $row;
1278
+                    } else {
1279
+                        break;
1280
+                    }
1281
+                }
1282
+                // Check if this is a collection of the requested item type
1283
+                if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
1284
+                    if (($collectionBackend = self::getBackend($row['item_type']))
1285
+                        && $collectionBackend instanceof \OCP\Share_Backend_Collection) {
1286
+                        // Collections can be inside collections, check if the item is a collection
1287
+                        if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
1288
+                            $collectionItems[] = $row;
1289
+                        } else {
1290
+                            $collection = array();
1291
+                            $collection['item_type'] = $row['item_type'];
1292
+                            if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1293
+                                $collection['path'] = basename($row['path']);
1294
+                            }
1295
+                            $row['collection'] = $collection;
1296
+                            // Fetch all of the children sources
1297
+                            $children = $collectionBackend->getChildren($row[$column]);
1298
+                            foreach ($children as $child) {
1299
+                                $childItem = $row;
1300
+                                $childItem['item_type'] = $itemType;
1301
+                                if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
1302
+                                    $childItem['item_source'] = $child['source'];
1303
+                                    $childItem['item_target'] = $child['target'];
1304
+                                }
1305
+                                if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1306
+                                    if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1307
+                                        $childItem['file_source'] = $child['source'];
1308
+                                    } else { // TODO is this really needed if we already know that we use the file backend?
1309
+                                        $meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
1310
+                                        $childItem['file_source'] = $meta['fileid'];
1311
+                                    }
1312
+                                    $childItem['file_target'] =
1313
+                                        \OC\Files\Filesystem::normalizePath($child['file_path']);
1314
+                                }
1315
+                                if (isset($item)) {
1316
+                                    if ($childItem[$column] == $item) {
1317
+                                        // Return only the item instead of a 2-dimensional array
1318
+                                        if ($limit == 1) {
1319
+                                            if ($format == self::FORMAT_NONE) {
1320
+                                                return $childItem;
1321
+                                            } else {
1322
+                                                // Unset the items array and break out of both loops
1323
+                                                $items = array();
1324
+                                                $items[] = $childItem;
1325
+                                                break 2;
1326
+                                            }
1327
+                                        } else {
1328
+                                            $collectionItems[] = $childItem;
1329
+                                        }
1330
+                                    }
1331
+                                } else {
1332
+                                    $collectionItems[] = $childItem;
1333
+                                }
1334
+                            }
1335
+                        }
1336
+                    }
1337
+                    // Remove collection item
1338
+                    $toRemove = $row['id'];
1339
+                    if (array_key_exists($toRemove, $switchedItems)) {
1340
+                        $toRemove = $switchedItems[$toRemove];
1341
+                    }
1342
+                    unset($items[$toRemove]);
1343
+                } elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
1344
+                    // FIXME: Thats a dirty hack to improve file sharing performance,
1345
+                    // see github issue #10588 for more details
1346
+                    // Need to find a solution which works for all back-ends
1347
+                    $collectionBackend = self::getBackend($row['item_type']);
1348
+                    $sharedParents = $collectionBackend->getParents($row['item_source']);
1349
+                    foreach ($sharedParents as $parent) {
1350
+                        $collectionItems[] = $parent;
1351
+                    }
1352
+                }
1353
+            }
1354
+            if (!empty($collectionItems)) {
1355
+                $collectionItems = array_unique($collectionItems, SORT_REGULAR);
1356
+                $items = array_merge($items, $collectionItems);
1357
+            }
1358
+
1359
+            // filter out invalid items, these can appear when subshare entries exist
1360
+            // for a group in which the requested user isn't a member any more
1361
+            $items = array_filter($items, function($item) {
1362
+                return $item['share_type'] !== self::$shareTypeGroupUserUnique;
1363
+            });
1364
+
1365
+            return self::formatResult($items, $column, $backend, $format, $parameters);
1366
+        } elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
1367
+            // FIXME: Thats a dirty hack to improve file sharing performance,
1368
+            // see github issue #10588 for more details
1369
+            // Need to find a solution which works for all back-ends
1370
+            $collectionItems = array();
1371
+            $collectionBackend = self::getBackend('folder');
1372
+            $sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
1373
+            foreach ($sharedParents as $parent) {
1374
+                $collectionItems[] = $parent;
1375
+            }
1376
+            if ($limit === 1) {
1377
+                return reset($collectionItems);
1378
+            }
1379
+            return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
1380
+        }
1381
+
1382
+        return array();
1383
+    }
1384
+
1385
+    /**
1386
+     * group items with link to the same source
1387
+     *
1388
+     * @param array $items
1389
+     * @param string $itemType
1390
+     * @return array of grouped items
1391
+     */
1392
+    protected static function groupItems($items, $itemType) {
1393
+
1394
+        $fileSharing = $itemType === 'file' || $itemType === 'folder';
1395
+
1396
+        $result = array();
1397
+
1398
+        foreach ($items as $item) {
1399
+            $grouped = false;
1400
+            foreach ($result as $key => $r) {
1401
+                // for file/folder shares we need to compare file_source, otherwise we compare item_source
1402
+                // only group shares if they already point to the same target, otherwise the file where shared
1403
+                // before grouping of shares was added. In this case we don't group them toi avoid confusions
1404
+                if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1405
+                    (!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
1406
+                    // add the first item to the list of grouped shares
1407
+                    if (!isset($result[$key]['grouped'])) {
1408
+                        $result[$key]['grouped'][] = $result[$key];
1409
+                    }
1410
+                    $result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
1411
+                    $result[$key]['grouped'][] = $item;
1412
+                    $grouped = true;
1413
+                    break;
1414
+                }
1415
+            }
1416
+
1417
+            if (!$grouped) {
1418
+                $result[] = $item;
1419
+            }
1420
+
1421
+        }
1422
+
1423
+        return $result;
1424
+    }
1425
+
1426
+    /**
1427
+     * Put shared item into the database
1428
+     * @param string $itemType Item type
1429
+     * @param string $itemSource Item source
1430
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1431
+     * @param string $shareWith User or group the item is being shared with
1432
+     * @param string $uidOwner User that is the owner of shared item
1433
+     * @param int $permissions CRUDS permissions
1434
+     * @param boolean|array $parentFolder Parent folder target (optional)
1435
+     * @param string $token (optional)
1436
+     * @param string $itemSourceName name of the source item (optional)
1437
+     * @param \DateTime $expirationDate (optional)
1438
+     * @throws \Exception
1439
+     * @return mixed id of the new share or false
1440
+     */
1441
+    private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1442
+                                $permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) {
1443
+
1444
+        $queriesToExecute = array();
1445
+        $suggestedItemTarget = null;
1446
+        $groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
1447
+        $groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1448
+
1449
+        $result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
1450
+        if(!empty($result)) {
1451
+            $parent = $result['parent'];
1452
+            $itemSource = $result['itemSource'];
1453
+            $fileSource = $result['fileSource'];
1454
+            $suggestedItemTarget = $result['suggestedItemTarget'];
1455
+            $suggestedFileTarget = $result['suggestedFileTarget'];
1456
+            $filePath = $result['filePath'];
1457
+        }
1458
+
1459
+        $isGroupShare = false;
1460
+        if ($shareType == self::SHARE_TYPE_GROUP) {
1461
+            $isGroupShare = true;
1462
+            if (isset($shareWith['users'])) {
1463
+                $users = $shareWith['users'];
1464
+            } else {
1465
+                $group = \OC::$server->getGroupManager()->get($shareWith['group']);
1466
+                if ($group) {
1467
+                    $users = $group->searchUsers('', -1, 0);
1468
+                    $userIds = [];
1469
+                    foreach ($users as $user) {
1470
+                        $userIds[] = $user->getUID();
1471
+                    }
1472
+                    $users = $userIds;
1473
+                } else {
1474
+                    $users = [];
1475
+                }
1476
+            }
1477
+            // remove current user from list
1478
+            if (in_array(\OCP\User::getUser(), $users)) {
1479
+                unset($users[array_search(\OCP\User::getUser(), $users)]);
1480
+            }
1481
+            $groupItemTarget = Helper::generateTarget($itemType, $itemSource,
1482
+                $shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget);
1483
+            $groupFileTarget = Helper::generateTarget($itemType, $itemSource,
1484
+                $shareType, $shareWith['group'], $uidOwner, $filePath);
1485
+
1486
+            // add group share to table and remember the id as parent
1487
+            $queriesToExecute['groupShare'] = array(
1488
+                'itemType'			=> $itemType,
1489
+                'itemSource'		=> $itemSource,
1490
+                'itemTarget'		=> $groupItemTarget,
1491
+                'shareType'			=> $shareType,
1492
+                'shareWith'			=> $shareWith['group'],
1493
+                'uidOwner'			=> $uidOwner,
1494
+                'permissions'		=> $permissions,
1495
+                'shareTime'			=> time(),
1496
+                'fileSource'		=> $fileSource,
1497
+                'fileTarget'		=> $groupFileTarget,
1498
+                'token'				=> $token,
1499
+                'parent'			=> $parent,
1500
+                'expiration'		=> $expirationDate,
1501
+            );
1502
+
1503
+        } else {
1504
+            $users = array($shareWith);
1505
+            $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1506
+                $suggestedItemTarget);
1507
+        }
1508
+
1509
+        $run = true;
1510
+        $error = '';
1511
+        $preHookData = array(
1512
+            'itemType' => $itemType,
1513
+            'itemSource' => $itemSource,
1514
+            'shareType' => $shareType,
1515
+            'uidOwner' => $uidOwner,
1516
+            'permissions' => $permissions,
1517
+            'fileSource' => $fileSource,
1518
+            'expiration' => $expirationDate,
1519
+            'token' => $token,
1520
+            'run' => &$run,
1521
+            'error' => &$error
1522
+        );
1523
+
1524
+        $preHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget;
1525
+        $preHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith;
1526
+
1527
+        \OC_Hook::emit(\OCP\Share::class, 'pre_shared', $preHookData);
1528
+
1529
+        if ($run === false) {
1530
+            throw new \Exception($error);
1531
+        }
1532
+
1533
+        foreach ($users as $user) {
1534
+            $sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
1535
+            $sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
1536
+
1537
+            $userShareType = $isGroupShare ? self::$shareTypeGroupUserUnique : $shareType;
1538
+
1539
+            if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
1540
+                $fileTarget = $sourceExists['file_target'];
1541
+                $itemTarget = $sourceExists['item_target'];
1542
+
1543
+                // for group shares we don't need a additional entry if the target is the same
1544
+                if($isGroupShare && $groupItemTarget === $itemTarget) {
1545
+                    continue;
1546
+                }
1547
+
1548
+            } elseif(!$sourceExists && !$isGroupShare)  {
1549
+
1550
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1551
+                    $uidOwner, $suggestedItemTarget, $parent);
1552
+                if (isset($fileSource)) {
1553
+                    if ($parentFolder) {
1554
+                        if ($parentFolder === true) {
1555
+                            $fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user,
1556
+                                $uidOwner, $suggestedFileTarget, $parent);
1557
+                            if ($fileTarget != $groupFileTarget) {
1558
+                                $parentFolders[$user]['folder'] = $fileTarget;
1559
+                            }
1560
+                        } else if (isset($parentFolder[$user])) {
1561
+                            $fileTarget = $parentFolder[$user]['folder'].$itemSource;
1562
+                            $parent = $parentFolder[$user]['id'];
1563
+                        }
1564
+                    } else {
1565
+                        $fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
1566
+                            $user, $uidOwner, $suggestedFileTarget, $parent);
1567
+                    }
1568
+                } else {
1569
+                    $fileTarget = null;
1570
+                }
1571
+
1572
+            } else {
1573
+
1574
+                // group share which doesn't exists until now, check if we need a unique target for this user
1575
+
1576
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
1577
+                    $uidOwner, $suggestedItemTarget, $parent);
1578
+
1579
+                // do we also need a file target
1580
+                if (isset($fileSource)) {
1581
+                    $fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
1582
+                        $uidOwner, $suggestedFileTarget, $parent);
1583
+                } else {
1584
+                    $fileTarget = null;
1585
+                }
1586
+
1587
+                if (($itemTarget === $groupItemTarget) &&
1588
+                    (!isset($fileSource) || $fileTarget === $groupFileTarget)) {
1589
+                    continue;
1590
+                }
1591
+            }
1592
+
1593
+            $queriesToExecute[] = array(
1594
+                'itemType'			=> $itemType,
1595
+                'itemSource'		=> $itemSource,
1596
+                'itemTarget'		=> $itemTarget,
1597
+                'shareType'			=> $userShareType,
1598
+                'shareWith'			=> $user,
1599
+                'uidOwner'			=> $uidOwner,
1600
+                'permissions'		=> $permissions,
1601
+                'shareTime'			=> time(),
1602
+                'fileSource'		=> $fileSource,
1603
+                'fileTarget'		=> $fileTarget,
1604
+                'token'				=> $token,
1605
+                'parent'			=> $parent,
1606
+                'expiration'		=> $expirationDate,
1607
+            );
1608
+
1609
+        }
1610
+
1611
+        $id = false;
1612
+        if ($isGroupShare) {
1613
+            $id = self::insertShare($queriesToExecute['groupShare']);
1614
+            // Save this id, any extra rows for this group share will need to reference it
1615
+            $parent = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1616
+            unset($queriesToExecute['groupShare']);
1617
+        }
1618
+
1619
+        foreach ($queriesToExecute as $shareQuery) {
1620
+            $shareQuery['parent'] = $parent;
1621
+            $id = self::insertShare($shareQuery);
1622
+        }
1623
+
1624
+        $postHookData = array(
1625
+            'itemType' => $itemType,
1626
+            'itemSource' => $itemSource,
1627
+            'parent' => $parent,
1628
+            'shareType' => $shareType,
1629
+            'uidOwner' => $uidOwner,
1630
+            'permissions' => $permissions,
1631
+            'fileSource' => $fileSource,
1632
+            'id' => $parent,
1633
+            'token' => $token,
1634
+            'expirationDate' => $expirationDate,
1635
+        );
1636
+
1637
+        $postHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith;
1638
+        $postHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget;
1639
+        $postHookData['fileTarget'] = $isGroupShare ? $groupFileTarget : $fileTarget;
1640
+
1641
+        \OC_Hook::emit(\OCP\Share::class, 'post_shared', $postHookData);
1642
+
1643
+
1644
+        return $id ? $id : false;
1645
+    }
1646
+
1647
+    /**
1648
+     * @param string $itemType
1649
+     * @param string $itemSource
1650
+     * @param int $shareType
1651
+     * @param string $shareWith
1652
+     * @param string $uidOwner
1653
+     * @param int $permissions
1654
+     * @param string|null $itemSourceName
1655
+     * @param null|\DateTime $expirationDate
1656
+     */
1657
+    private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
1658
+        $backend = self::getBackend($itemType);
1659
+
1660
+        $l = \OC::$server->getL10N('lib');
1661
+        $result = array();
1662
+
1663
+        $column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
1664
+
1665
+        $checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
1666
+        if ($checkReshare) {
1667
+            // Check if attempting to share back to owner
1668
+            if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
1669
+                $message = 'Sharing %s failed, because the user %s is the original sharer';
1670
+                $message_t = $l->t('Sharing failed, because the user %s is the original sharer', [$shareWith]);
1671
+
1672
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
1673
+                throw new \Exception($message_t);
1674
+            }
1675
+        }
1676
+
1677
+        if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1678
+            // Check if share permissions is granted
1679
+            if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1680
+                if (~(int)$checkReshare['permissions'] & $permissions) {
1681
+                    $message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
1682
+                    $message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
1683
+
1684
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner), ILogger::DEBUG);
1685
+                    throw new \Exception($message_t);
1686
+                } else {
1687
+                    // TODO Don't check if inside folder
1688
+                    $result['parent'] = $checkReshare['id'];
1689
+
1690
+                    $result['expirationDate'] = $expirationDate;
1691
+                    // $checkReshare['expiration'] could be null and then is always less than any value
1692
+                    if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1693
+                        $result['expirationDate'] = $checkReshare['expiration'];
1694
+                    }
1695
+
1696
+                    // only suggest the same name as new target if it is a reshare of the
1697
+                    // same file/folder and not the reshare of a child
1698
+                    if ($checkReshare[$column] === $itemSource) {
1699
+                        $result['filePath'] = $checkReshare['file_target'];
1700
+                        $result['itemSource'] = $checkReshare['item_source'];
1701
+                        $result['fileSource'] = $checkReshare['file_source'];
1702
+                        $result['suggestedItemTarget'] = $checkReshare['item_target'];
1703
+                        $result['suggestedFileTarget'] = $checkReshare['file_target'];
1704
+                    } else {
1705
+                        $result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
1706
+                        $result['suggestedItemTarget'] = null;
1707
+                        $result['suggestedFileTarget'] = null;
1708
+                        $result['itemSource'] = $itemSource;
1709
+                        $result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
1710
+                    }
1711
+                }
1712
+            } else {
1713
+                $message = 'Sharing %s failed, because resharing is not allowed';
1714
+                $message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
1715
+
1716
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), ILogger::DEBUG);
1717
+                throw new \Exception($message_t);
1718
+            }
1719
+        } else {
1720
+            $result['parent'] = null;
1721
+            $result['suggestedItemTarget'] = null;
1722
+            $result['suggestedFileTarget'] = null;
1723
+            $result['itemSource'] = $itemSource;
1724
+            $result['expirationDate'] = $expirationDate;
1725
+            if (!$backend->isValidSource($itemSource, $uidOwner)) {
1726
+                $message = 'Sharing %s failed, because the sharing backend for '
1727
+                    .'%s could not find its source';
1728
+                $message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
1729
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, $itemType), ILogger::DEBUG);
1730
+                throw new \Exception($message_t);
1731
+            }
1732
+            if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1733
+                $result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
1734
+                if ($itemType == 'file' || $itemType == 'folder') {
1735
+                    $result['fileSource'] = $itemSource;
1736
+                } else {
1737
+                    $meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
1738
+                    $result['fileSource'] = $meta['fileid'];
1739
+                }
1740
+                if ($result['fileSource'] == -1) {
1741
+                    $message = 'Sharing %s failed, because the file could not be found in the file cache';
1742
+                    $message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
1743
+
1744
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), ILogger::DEBUG);
1745
+                    throw new \Exception($message_t);
1746
+                }
1747
+            } else {
1748
+                $result['filePath'] = null;
1749
+                $result['fileSource'] = null;
1750
+            }
1751
+        }
1752
+
1753
+        return $result;
1754
+    }
1755
+
1756
+    /**
1757
+     *
1758
+     * @param array $shareData
1759
+     * @return mixed false in case of a failure or the id of the new share
1760
+     */
1761
+    private static function insertShare(array $shareData) {
1762
+
1763
+        $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
1764
+            .' `item_type`, `item_source`, `item_target`, `share_type`,'
1765
+            .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
1766
+            .' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
1767
+        $query->bindValue(1, $shareData['itemType']);
1768
+        $query->bindValue(2, $shareData['itemSource']);
1769
+        $query->bindValue(3, $shareData['itemTarget']);
1770
+        $query->bindValue(4, $shareData['shareType']);
1771
+        $query->bindValue(5, $shareData['shareWith']);
1772
+        $query->bindValue(6, $shareData['uidOwner']);
1773
+        $query->bindValue(7, $shareData['permissions']);
1774
+        $query->bindValue(8, $shareData['shareTime']);
1775
+        $query->bindValue(9, $shareData['fileSource']);
1776
+        $query->bindValue(10, $shareData['fileTarget']);
1777
+        $query->bindValue(11, $shareData['token']);
1778
+        $query->bindValue(12, $shareData['parent']);
1779
+        $query->bindValue(13, $shareData['expiration'], 'datetime');
1780
+        $result = $query->execute();
1781
+
1782
+        $id = false;
1783
+        if ($result) {
1784
+            $id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1785
+        }
1786
+
1787
+        return $id;
1788
+
1789
+    }
1790
+
1791
+    /**
1792
+     * In case a password protected link is not yet authenticated this function will return false
1793
+     *
1794
+     * @param array $linkItem
1795
+     * @return boolean
1796
+     */
1797
+    public static function checkPasswordProtectedShare(array $linkItem) {
1798
+        if (!isset($linkItem['share_with'])) {
1799
+            return true;
1800
+        }
1801
+        if (!isset($linkItem['share_type'])) {
1802
+            return true;
1803
+        }
1804
+        if (!isset($linkItem['id'])) {
1805
+            return true;
1806
+        }
1807
+
1808
+        if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
1809
+            return true;
1810
+        }
1811
+
1812
+        if ( \OC::$server->getSession()->exists('public_link_authenticated')
1813
+            && \OC::$server->getSession()->get('public_link_authenticated') === (string)$linkItem['id'] ) {
1814
+            return true;
1815
+        }
1816
+
1817
+        return false;
1818
+    }
1819
+
1820
+    /**
1821
+     * construct select statement
1822
+     * @param int $format
1823
+     * @param boolean $fileDependent ist it a file/folder share or a generla share
1824
+     * @param string $uidOwner
1825
+     * @return string select statement
1826
+     */
1827
+    private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
1828
+        $select = '*';
1829
+        if ($format == self::FORMAT_STATUSES) {
1830
+            if ($fileDependent) {
1831
+                $select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
1832
+                    . '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
1833
+                    . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1834
+                    . '`uid_initiator`';
1835
+            } else {
1836
+                $select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
1837
+            }
1838
+        } else {
1839
+            if (isset($uidOwner)) {
1840
+                if ($fileDependent) {
1841
+                    $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
1842
+                        . ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
1843
+                        . ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
1844
+                        . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1845
+                } else {
1846
+                    $select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
1847
+                        . ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
1848
+                }
1849
+            } else {
1850
+                if ($fileDependent) {
1851
+                    if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
1852
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
1853
+                            . '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
1854
+                            . '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1855
+                            . '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
1856
+                    } else {
1857
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
1858
+                            . '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
1859
+                            . '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
1860
+                            . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
1861
+                            . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1862
+                    }
1863
+                }
1864
+            }
1865
+        }
1866
+        return $select;
1867
+    }
1868
+
1869
+
1870
+    /**
1871
+     * transform db results
1872
+     * @param array $row result
1873
+     */
1874
+    private static function transformDBResults(&$row) {
1875
+        if (isset($row['id'])) {
1876
+            $row['id'] = (int) $row['id'];
1877
+        }
1878
+        if (isset($row['share_type'])) {
1879
+            $row['share_type'] = (int) $row['share_type'];
1880
+        }
1881
+        if (isset($row['parent'])) {
1882
+            $row['parent'] = (int) $row['parent'];
1883
+        }
1884
+        if (isset($row['file_parent'])) {
1885
+            $row['file_parent'] = (int) $row['file_parent'];
1886
+        }
1887
+        if (isset($row['file_source'])) {
1888
+            $row['file_source'] = (int) $row['file_source'];
1889
+        }
1890
+        if (isset($row['permissions'])) {
1891
+            $row['permissions'] = (int) $row['permissions'];
1892
+        }
1893
+        if (isset($row['storage'])) {
1894
+            $row['storage'] = (int) $row['storage'];
1895
+        }
1896
+        if (isset($row['stime'])) {
1897
+            $row['stime'] = (int) $row['stime'];
1898
+        }
1899
+        if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
1900
+            // discard expiration date for non-link shares, which might have been
1901
+            // set by ancient bugs
1902
+            $row['expiration'] = null;
1903
+        }
1904
+    }
1905
+
1906
+    /**
1907
+     * format result
1908
+     * @param array $items result
1909
+     * @param string $column is it a file share or a general share ('file_target' or 'item_target')
1910
+     * @param \OCP\Share_Backend $backend sharing backend
1911
+     * @param int $format
1912
+     * @param array $parameters additional format parameters
1913
+     * @return array format result
1914
+     */
1915
+    private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
1916
+        if ($format === self::FORMAT_NONE) {
1917
+            return $items;
1918
+        } else if ($format === self::FORMAT_STATUSES) {
1919
+            $statuses = array();
1920
+            foreach ($items as $item) {
1921
+                if ($item['share_type'] === self::SHARE_TYPE_LINK) {
1922
+                    if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
1923
+                        continue;
1924
+                    }
1925
+                    $statuses[$item[$column]]['link'] = true;
1926
+                } else if (!isset($statuses[$item[$column]])) {
1927
+                    $statuses[$item[$column]]['link'] = false;
1928
+                }
1929
+                if (!empty($item['file_target'])) {
1930
+                    $statuses[$item[$column]]['path'] = $item['path'];
1931
+                }
1932
+            }
1933
+            return $statuses;
1934
+        } else {
1935
+            return $backend->formatItems($items, $format, $parameters);
1936
+        }
1937
+    }
1938
+
1939
+    /**
1940
+     * remove protocol from URL
1941
+     *
1942
+     * @param string $url
1943
+     * @return string
1944
+     */
1945
+    public static function removeProtocolFromUrl($url) {
1946
+        if (strpos($url, 'https://') === 0) {
1947
+            return substr($url, strlen('https://'));
1948
+        } else if (strpos($url, 'http://') === 0) {
1949
+            return substr($url, strlen('http://'));
1950
+        }
1951
+
1952
+        return $url;
1953
+    }
1954
+
1955
+    /**
1956
+     * try http post first with https and then with http as a fallback
1957
+     *
1958
+     * @param string $remoteDomain
1959
+     * @param string $urlSuffix
1960
+     * @param array $fields post parameters
1961
+     * @return array
1962
+     */
1963
+    private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
1964
+        $protocol = 'https://';
1965
+        $result = [
1966
+            'success' => false,
1967
+            'result' => '',
1968
+        ];
1969
+        $try = 0;
1970
+        $discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
1971
+        while ($result['success'] === false && $try < 2) {
1972
+            $federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
1973
+            $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
1974
+            $client = \OC::$server->getHTTPClientService()->newClient();
1975
+
1976
+            try {
1977
+                $response = $client->post(
1978
+                    $protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
1979
+                    [
1980
+                        'body' => $fields,
1981
+                        'connect_timeout' => 10,
1982
+                    ]
1983
+                );
1984
+
1985
+                $result = ['success' => true, 'result' => $response->getBody()];
1986
+            } catch (\Exception $e) {
1987
+                $result = ['success' => false, 'result' => $e->getMessage()];
1988
+            }
1989
+
1990
+            $try++;
1991
+            $protocol = 'http://';
1992
+        }
1993
+
1994
+        return $result;
1995
+    }
1996
+
1997
+    /**
1998
+     * send server-to-server share to remote server
1999
+     *
2000
+     * @param string $token
2001
+     * @param string $shareWith
2002
+     * @param string $name
2003
+     * @param int $remote_id
2004
+     * @param string $owner
2005
+     * @return bool
2006
+     */
2007
+    private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) {
2008
+
2009
+        list($user, $remote) = Helper::splitUserRemote($shareWith);
2010
+
2011
+        if ($user && $remote) {
2012
+            $url = $remote;
2013
+
2014
+            $local = \OC::$server->getURLGenerator()->getAbsoluteURL('/');
2015
+
2016
+            $fields = array(
2017
+                'shareWith' => $user,
2018
+                'token' => $token,
2019
+                'name' => $name,
2020
+                'remoteId' => $remote_id,
2021
+                'owner' => $owner,
2022
+                'remote' => $local,
2023
+            );
2024
+
2025
+            $url = self::removeProtocolFromUrl($url);
2026
+            $result = self::tryHttpPostToShareEndpoint($url, '', $fields);
2027
+            $status = json_decode($result['result'], true);
2028
+
2029
+            if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
2030
+                \OC_Hook::emit(\OCP\Share::class, 'federated_share_added', ['server' => $remote]);
2031
+                return true;
2032
+            }
2033
+
2034
+        }
2035
+
2036
+        return false;
2037
+    }
2038
+
2039
+    /**
2040
+     * send server-to-server unshare to remote server
2041
+     *
2042
+     * @param string $remote url
2043
+     * @param int $id share id
2044
+     * @param string $token
2045
+     * @return bool
2046
+     */
2047
+    private static function sendRemoteUnshare($remote, $id, $token) {
2048
+        $url = rtrim($remote, '/');
2049
+        $fields = array('token' => $token, 'format' => 'json');
2050
+        $url = self::removeProtocolFromUrl($url);
2051
+        $result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
2052
+        $status = json_decode($result['result'], true);
2053
+
2054
+        return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
2055
+    }
2056
+
2057
+    /**
2058
+     * check if user can only share with group members
2059
+     * @return bool
2060
+     */
2061
+    public static function shareWithGroupMembersOnly() {
2062
+        $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_only_share_with_group_members', 'no');
2063
+        return $value === 'yes';
2064
+    }
2065
+
2066
+    /**
2067
+     * @return bool
2068
+     */
2069
+    public static function isDefaultExpireDateEnabled() {
2070
+        $defaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
2071
+        return $defaultExpireDateEnabled === 'yes';
2072
+    }
2073
+
2074
+    /**
2075
+     * @return int
2076
+     */
2077
+    public static function getExpireInterval() {
2078
+        return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
2079
+    }
2080
+
2081
+    /**
2082
+     * Checks whether the given path is reachable for the given owner
2083
+     *
2084
+     * @param string $path path relative to files
2085
+     * @param string $ownerStorageId storage id of the owner
2086
+     *
2087
+     * @return boolean true if file is reachable, false otherwise
2088
+     */
2089
+    private static function isFileReachable($path, $ownerStorageId) {
2090
+        // if outside the home storage, file is always considered reachable
2091
+        if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
2092
+            substr($ownerStorageId, 0, 13) === 'object::user:'
2093
+        )) {
2094
+            return true;
2095
+        }
2096
+
2097
+        // if inside the home storage, the file has to be under "/files/"
2098
+        $path = ltrim($path, '/');
2099
+        if (substr($path, 0, 6) === 'files/') {
2100
+            return true;
2101
+        }
2102
+
2103
+        return false;
2104
+    }
2105
+
2106
+    /**
2107
+     * @param IConfig $config
2108
+     * @return bool
2109
+     */
2110
+    public static function enforcePassword(IConfig $config) {
2111
+        $enforcePassword = $config->getAppValue('core', 'shareapi_enforce_links_password', 'no');
2112
+        return $enforcePassword === 'yes';
2113
+    }
2114
+
2115
+    /**
2116
+     * @param string $password
2117
+     * @throws \Exception
2118
+     */
2119
+    private static function verifyPassword($password) {
2120
+
2121
+        $accepted = true;
2122
+        $message = '';
2123
+        \OCP\Util::emitHook('\OC\Share', 'verifyPassword', [
2124
+            'password' => $password,
2125
+            'accepted' => &$accepted,
2126
+            'message' => &$message
2127
+        ]);
2128
+
2129
+        if (!$accepted) {
2130
+            throw new \Exception($message);
2131
+        }
2132
+    }
2133 2133
 }
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
 					'collectionOf' => $collectionOf,
85 85
 					'supportedFileExtensions' => $supportedFileExtensions
86 86
 				);
87
-				if(count(self::$backendTypes) === 1) {
87
+				if (count(self::$backendTypes) === 1) {
88 88
 					Util::addScript('core', 'merged-share-backend');
89 89
 					\OC_Util::addStyle('core', 'share');
90 90
 				}
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 
156 156
 		$select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
157 157
 
158
-		$where .= ' `' . $column . '` = ? AND `item_type` = ? ';
158
+		$where .= ' `'.$column.'` = ? AND `item_type` = ? ';
159 159
 		$arguments = array($itemSource, $itemType);
160 160
 		// for link shares $user === null
161 161
 		if ($user !== null) {
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 			$arguments[] = $owner;
174 174
 		}
175 175
 
176
-		$query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
176
+		$query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$fileDependentWhere.$where);
177 177
 
178 178
 		$result = \OC_DB::executeAudited($query, $arguments);
179 179
 
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
 			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
182 182
 				continue;
183 183
 			}
184
-			if ($fileDependent && (int)$row['file_parent'] === -1) {
184
+			if ($fileDependent && (int) $row['file_parent'] === -1) {
185 185
 				// if it is a mount point we need to get the path from the mount manager
186 186
 				$mountManager = \OC\Files\Filesystem::getMountManager();
187 187
 				$mountPoint = $mountManager->findByStorageId($row['storage_id']);
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
 					$row['path'] = $path;
193 193
 				} else {
194 194
 					\OC::$server->getLogger()->warning(
195
-						'Could not resolve mount point for ' . $row['storage_id'],
195
+						'Could not resolve mount point for '.$row['storage_id'],
196 196
 						['app' => 'OCP\Share']
197 197
 					);
198 198
 				}
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
 		}
202 202
 
203 203
 		//if didn't found a result than let's look for a group share.
204
-		if(empty($shares) && $user !== null) {
204
+		if (empty($shares) && $user !== null) {
205 205
 			$userObject = \OC::$server->getUserManager()->get($user);
206 206
 			$groups = [];
207 207
 			if ($userObject) {
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
 			}
210 210
 
211 211
 			if (!empty($groups)) {
212
-				$where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
212
+				$where = $fileDependentWhere.' WHERE `'.$column.'` = ? AND `item_type` = ? AND `share_with` in (?)';
213 213
 				$arguments = array($itemSource, $itemType, $groups);
214 214
 				$types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY);
215 215
 
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 				// class isn't static anymore...
224 224
 				$conn = \OC::$server->getDatabaseConnection();
225 225
 				$result = $conn->executeQuery(
226
-					'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
226
+					'SELECT '.$select.' FROM `*PREFIX*share` '.$where,
227 227
 					$arguments,
228 228
 					$types
229 229
 				);
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
 		$query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
266 266
 		$result = $query->execute(array($token));
267 267
 		if ($result === false) {
268
-			\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, ILogger::ERROR);
268
+			\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage().', token='.$token, ILogger::ERROR);
269 269
 		}
270 270
 		$row = $result->fetchRow();
271 271
 		if ($row === false) {
@@ -371,12 +371,12 @@  discard block
 block discarded – undo
371 371
 
372 372
 		//verify that we don't share a folder which already contains a share mount point
373 373
 		if ($itemType === 'folder') {
374
-			$path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
374
+			$path = '/'.$uidOwner.'/files'.\OC\Files\Filesystem::getPath($itemSource).'/';
375 375
 			$mountManager = \OC\Files\Filesystem::getMountManager();
376 376
 			$mounts = $mountManager->findIn($path);
377 377
 			foreach ($mounts as $mount) {
378 378
 				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
379
-					$message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
379
+					$message = 'Sharing "'.$itemSourceName.'" failed, because it contains files shared with you!';
380 380
 					\OCP\Util::writeLog('OCP\Share', $message, ILogger::DEBUG);
381 381
 					throw new \Exception($message);
382 382
 				}
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
 
387 387
 		// single file shares should never have delete permissions
388 388
 		if ($itemType === 'file') {
389
-			$permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
389
+			$permissions = (int) $permissions & ~\OCP\Constants::PERMISSION_DELETE;
390 390
 		}
391 391
 
392 392
 		//Validate expirationDate
@@ -540,7 +540,7 @@  discard block
 block discarded – undo
540 540
 					} else {
541 541
 						// reuse the already set password, but only if we change permissions
542 542
 						// otherwise the user disabled the password protection
543
-						if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
543
+						if ($checkExists && (int) $permissions !== (int) $oldPermissions) {
544 544
 							$shareWith = $checkExists['share_with'];
545 545
 						}
546 546
 					}
@@ -612,10 +612,10 @@  discard block
 block discarded – undo
612 612
 				throw new \Exception($message_t);
613 613
 			}
614 614
 
615
-			$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
615
+			$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_UPPER.
616 616
 				\OCP\Security\ISecureRandom::CHAR_DIGITS);
617 617
 
618
-			$shareWith = $user . '@' . $remote;
618
+			$shareWith = $user.'@'.$remote;
619 619
 			$shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
620 620
 
621 621
 			$send = false;
@@ -666,12 +666,12 @@  discard block
 block discarded – undo
666 666
 		$currentUser = $owner ? $owner : \OC_User::getUser();
667 667
 		foreach ($items as $item) {
668 668
 			// delete the item with the expected share_type and owner
669
-			if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
669
+			if ((int) $item['share_type'] === (int) $shareType && $item['uid_owner'] === $currentUser) {
670 670
 				$toDelete = $item;
671 671
 				// if there is more then one result we don't have to delete the children
672 672
 				// but update their parent. For group shares the new parent should always be
673 673
 				// the original group share and not the db entry with the unique name
674
-			} else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
674
+			} else if ((int) $item['share_type'] === self::$shareTypeGroupUserUnique) {
675 675
 				$newParent = $item['parent'];
676 676
 			} else {
677 677
 				$newParent = $item['id'];
@@ -703,7 +703,7 @@  discard block
 block discarded – undo
703 703
 
704 704
 		$result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
705 705
 
706
-		if($result === false) {
706
+		if ($result === false) {
707 707
 			\OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', ILogger::ERROR);
708 708
 		}
709 709
 	}
@@ -729,7 +729,7 @@  discard block
 block discarded – undo
729 729
 		if ($defaultExpireDateEnforced && $shareTime === null) {
730 730
 			$items = self::getItemShared($itemType, $itemSource);
731 731
 			$firstItem = reset($items);
732
-			$shareTime = (int)$firstItem['stime'];
732
+			$shareTime = (int) $firstItem['stime'];
733 733
 		}
734 734
 
735 735
 		if ($defaultExpireDateEnforced) {
@@ -737,9 +737,9 @@  discard block
 block discarded – undo
737 737
 			$maxDate = new \DateTime();
738 738
 			$maxDate->setTimestamp($shareTime);
739 739
 			$maxDays = \OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
740
-			$maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
740
+			$maxDate->add(new \DateInterval('P'.$maxDays.'D'));
741 741
 			if ($date > $maxDate) {
742
-				$warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
742
+				$warning = 'Cannot set expiration date. Shares cannot expire later than '.$maxDays.' after they have been shared';
743 743
 				$warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
744 744
 				\OCP\Util::writeLog('OCP\Share', $warning, ILogger::WARN);
745 745
 				throw new \Exception($warning_t);
@@ -801,7 +801,7 @@  discard block
 block discarded – undo
801 801
 	 */
802 802
 	protected static function unshareItem(array $item, $newParent = null) {
803 803
 
804
-		$shareType = (int)$item['share_type'];
804
+		$shareType = (int) $item['share_type'];
805 805
 		$shareWith = null;
806 806
 		if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
807 807
 			$shareWith = $item['share_with'];
@@ -817,7 +817,7 @@  discard block
 block discarded – undo
817 817
 			'itemParent'    => $item['parent'],
818 818
 			'uidOwner'      => $item['uid_owner'],
819 819
 		);
820
-		if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
820
+		if ($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
821 821
 			$hookParams['fileSource'] = $item['file_source'];
822 822
 			$hookParams['fileTarget'] = $item['file_target'];
823 823
 		}
@@ -827,7 +827,7 @@  discard block
 block discarded – undo
827 827
 		$deletedShares[] = $hookParams;
828 828
 		$hookParams['deletedShares'] = $deletedShares;
829 829
 		\OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
830
-		if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
830
+		if ((int) $item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
831 831
 			list(, $remote) = Helper::splitUserRemote($item['share_with']);
832 832
 			self::sendRemoteUnshare($remote, $item['id'], $item['token']);
833 833
 		}
@@ -988,7 +988,7 @@  discard block
 block discarded – undo
988 988
 		// Get filesystem root to add it to the file target and remove from the
989 989
 		// file source, match file_source with the file cache
990 990
 		if ($itemType == 'file' || $itemType == 'folder') {
991
-			if(!is_null($uidOwner)) {
991
+			if (!is_null($uidOwner)) {
992 992
 				$root = \OC\Files\Filesystem::getRoot();
993 993
 			} else {
994 994
 				$root = '';
@@ -1133,7 +1133,7 @@  discard block
 block discarded – undo
1133 1133
 		$result = $query->execute($queryArgs);
1134 1134
 		if ($result === false) {
1135 1135
 			\OCP\Util::writeLog('OCP\Share',
1136
-				\OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
1136
+				\OC_DB::getErrorMessage().', select='.$select.' where=',
1137 1137
 				ILogger::ERROR);
1138 1138
 		}
1139 1139
 		$items = array();
@@ -1175,14 +1175,14 @@  discard block
 block discarded – undo
1175 1175
 						}
1176 1176
 						// Switch ids if sharing permission is granted on only
1177 1177
 						// one share to ensure correct parent is used if resharing
1178
-						if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1179
-							&& (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1178
+						if (~(int) $items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1179
+							&& (int) $row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1180 1180
 							$items[$row['id']] = $items[$id];
1181 1181
 							$switchedItems[$id] = $row['id'];
1182 1182
 							unset($items[$id]);
1183 1183
 							$id = $row['id'];
1184 1184
 						}
1185
-						$items[$id]['permissions'] |= (int)$row['permissions'];
1185
+						$items[$id]['permissions'] |= (int) $row['permissions'];
1186 1186
 
1187 1187
 					}
1188 1188
 					continue;
@@ -1196,8 +1196,8 @@  discard block
 block discarded – undo
1196 1196
 					$query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
1197 1197
 					$parentResult = $query->execute(array($row['parent']));
1198 1198
 					if ($result === false) {
1199
-						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
1200
-							\OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
1199
+						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: '.
1200
+							\OC_DB::getErrorMessage().', select='.$select.' where='.$where,
1201 1201
 							ILogger::ERROR);
1202 1202
 					} else {
1203 1203
 						$parentRow = $parentResult->fetchRow();
@@ -1207,7 +1207,7 @@  discard block
 block discarded – undo
1207 1207
 						$subPath = substr($row['path'], $pos);
1208 1208
 						$splitPath = explode('/', $subPath);
1209 1209
 						foreach (array_slice($splitPath, 2) as $pathPart) {
1210
-							$tmpPath = $tmpPath . '/' . $pathPart;
1210
+							$tmpPath = $tmpPath.'/'.$pathPart;
1211 1211
 						}
1212 1212
 						$row['path'] = $tmpPath;
1213 1213
 					}
@@ -1226,7 +1226,7 @@  discard block
 block discarded – undo
1226 1226
 				}
1227 1227
 			}
1228 1228
 
1229
-			if($checkExpireDate) {
1229
+			if ($checkExpireDate) {
1230 1230
 				if (self::expireItem($row)) {
1231 1231
 					continue;
1232 1232
 				}
@@ -1237,11 +1237,11 @@  discard block
 block discarded – undo
1237 1237
 			}
1238 1238
 			// Add display names to result
1239 1239
 			$row['share_with_displayname'] = $row['share_with'];
1240
-			if ( isset($row['share_with']) && $row['share_with'] != '' &&
1240
+			if (isset($row['share_with']) && $row['share_with'] != '' &&
1241 1241
 				$row['share_type'] === self::SHARE_TYPE_USER) {
1242 1242
 				$shareWithUser = \OC::$server->getUserManager()->get($row['share_with']);
1243 1243
 				$row['share_with_displayname'] = $shareWithUser === null ? $row['share_with'] : $shareWithUser->getDisplayName();
1244
-			} else if(isset($row['share_with']) && $row['share_with'] != '' &&
1244
+			} else if (isset($row['share_with']) && $row['share_with'] != '' &&
1245 1245
 				$row['share_type'] === self::SHARE_TYPE_REMOTE) {
1246 1246
 				$addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
1247 1247
 				foreach ($addressBookEntries as $entry) {
@@ -1252,7 +1252,7 @@  discard block
 block discarded – undo
1252 1252
 					}
1253 1253
 				}
1254 1254
 			}
1255
-			if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
1255
+			if (isset($row['uid_owner']) && $row['uid_owner'] != '') {
1256 1256
 				$ownerUser = \OC::$server->getUserManager()->get($row['uid_owner']);
1257 1257
 				$row['displayname_owner'] = $ownerUser === null ? $row['uid_owner'] : $ownerUser->getDisplayName();
1258 1258
 			}
@@ -1401,7 +1401,7 @@  discard block
 block discarded – undo
1401 1401
 				// for file/folder shares we need to compare file_source, otherwise we compare item_source
1402 1402
 				// only group shares if they already point to the same target, otherwise the file where shared
1403 1403
 				// before grouping of shares was added. In this case we don't group them toi avoid confusions
1404
-				if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1404
+				if (($fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1405 1405
 					(!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
1406 1406
 					// add the first item to the list of grouped shares
1407 1407
 					if (!isset($result[$key]['grouped'])) {
@@ -1447,7 +1447,7 @@  discard block
 block discarded – undo
1447 1447
 		$groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1448 1448
 
1449 1449
 		$result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
1450
-		if(!empty($result)) {
1450
+		if (!empty($result)) {
1451 1451
 			$parent = $result['parent'];
1452 1452
 			$itemSource = $result['itemSource'];
1453 1453
 			$fileSource = $result['fileSource'];
@@ -1541,11 +1541,11 @@  discard block
 block discarded – undo
1541 1541
 				$itemTarget = $sourceExists['item_target'];
1542 1542
 
1543 1543
 				// for group shares we don't need a additional entry if the target is the same
1544
-				if($isGroupShare && $groupItemTarget === $itemTarget) {
1544
+				if ($isGroupShare && $groupItemTarget === $itemTarget) {
1545 1545
 					continue;
1546 1546
 				}
1547 1547
 
1548
-			} elseif(!$sourceExists && !$isGroupShare)  {
1548
+			} elseif (!$sourceExists && !$isGroupShare) {
1549 1549
 
1550 1550
 				$itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1551 1551
 					$uidOwner, $suggestedItemTarget, $parent);
@@ -1676,8 +1676,8 @@  discard block
 block discarded – undo
1676 1676
 
1677 1677
 		if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1678 1678
 			// Check if share permissions is granted
1679
-			if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1680
-				if (~(int)$checkReshare['permissions'] & $permissions) {
1679
+			if (self::isResharingAllowed() && (int) $checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1680
+				if (~(int) $checkReshare['permissions'] & $permissions) {
1681 1681
 					$message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
1682 1682
 					$message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
1683 1683
 
@@ -1689,7 +1689,7 @@  discard block
 block discarded – undo
1689 1689
 
1690 1690
 					$result['expirationDate'] = $expirationDate;
1691 1691
 					// $checkReshare['expiration'] could be null and then is always less than any value
1692
-					if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1692
+					if (isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1693 1693
 						$result['expirationDate'] = $checkReshare['expiration'];
1694 1694
 					}
1695 1695
 
@@ -1781,7 +1781,7 @@  discard block
 block discarded – undo
1781 1781
 
1782 1782
 		$id = false;
1783 1783
 		if ($result) {
1784
-			$id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1784
+			$id = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1785 1785
 		}
1786 1786
 
1787 1787
 		return $id;
@@ -1809,8 +1809,8 @@  discard block
 block discarded – undo
1809 1809
 			return true;
1810 1810
 		}
1811 1811
 
1812
-		if ( \OC::$server->getSession()->exists('public_link_authenticated')
1813
-			&& \OC::$server->getSession()->get('public_link_authenticated') === (string)$linkItem['id'] ) {
1812
+		if (\OC::$server->getSession()->exists('public_link_authenticated')
1813
+			&& \OC::$server->getSession()->get('public_link_authenticated') === (string) $linkItem['id']) {
1814 1814
 			return true;
1815 1815
 		}
1816 1816
 
@@ -1912,7 +1912,7 @@  discard block
 block discarded – undo
1912 1912
 	 * @param array $parameters additional format parameters
1913 1913
 	 * @return array format result
1914 1914
 	 */
1915
-	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
1915
+	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE, $parameters = null) {
1916 1916
 		if ($format === self::FORMAT_NONE) {
1917 1917
 			return $items;
1918 1918
 		} else if ($format === self::FORMAT_STATUSES) {
@@ -1969,13 +1969,13 @@  discard block
 block discarded – undo
1969 1969
 		$try = 0;
1970 1970
 		$discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
1971 1971
 		while ($result['success'] === false && $try < 2) {
1972
-			$federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
1972
+			$federationEndpoints = $discoveryService->discover($protocol.$remoteDomain, 'FEDERATED_SHARING');
1973 1973
 			$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
1974 1974
 			$client = \OC::$server->getHTTPClientService()->newClient();
1975 1975
 
1976 1976
 			try {
1977 1977
 				$response = $client->post(
1978
-					$protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
1978
+					$protocol.$remoteDomain.$endpoint.$urlSuffix.'?format='.self::RESPONSE_FORMAT,
1979 1979
 					[
1980 1980
 						'body' => $fields,
1981 1981
 						'connect_timeout' => 10,
@@ -2075,7 +2075,7 @@  discard block
 block discarded – undo
2075 2075
 	 * @return int
2076 2076
 	 */
2077 2077
 	public static function getExpireInterval() {
2078
-		return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
2078
+		return (int) \OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
2079 2079
 	}
2080 2080
 
2081 2081
 	/**
Please login to merge, or discard this patch.
lib/private/AppFramework/DependencyInjection/DIContainer.php 2 patches
Indentation   +380 added lines, -380 removed lines patch added patch discarded remove patch
@@ -68,384 +68,384 @@
 block discarded – undo
68 68
 
69 69
 class DIContainer extends SimpleContainer implements IAppContainer {
70 70
 
71
-	/**
72
-	 * @var array
73
-	 */
74
-	private $middleWares = array();
75
-
76
-	/** @var ServerContainer */
77
-	private $server;
78
-
79
-	/**
80
-	 * Put your class dependencies in here
81
-	 * @param string $appName the name of the app
82
-	 * @param array $urlParams
83
-	 * @param ServerContainer|null $server
84
-	 */
85
-	public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
86
-		parent::__construct();
87
-		$this['AppName'] = $appName;
88
-		$this['urlParams'] = $urlParams;
89
-
90
-		/** @var \OC\ServerContainer $server */
91
-		if ($server === null) {
92
-			$server = \OC::$server;
93
-		}
94
-		$this->server = $server;
95
-		$this->server->registerAppContainer($appName, $this);
96
-
97
-		// aliases
98
-		$this->registerAlias('appName', 'AppName');
99
-		$this->registerAlias('webRoot', 'WebRoot');
100
-		$this->registerAlias('userId', 'UserId');
101
-
102
-		/**
103
-		 * Core services
104
-		 */
105
-		$this->registerService(IOutput::class, function($c){
106
-			return new Output($this->getServer()->getWebRoot());
107
-		});
108
-
109
-		$this->registerService(Folder::class, function() {
110
-			return $this->getServer()->getUserFolder();
111
-		});
112
-
113
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
114
-			return $this->getServer()->getAppDataDir($c->query('AppName'));
115
-		});
116
-
117
-		$this->registerService(IL10N::class, function($c) {
118
-			return $this->getServer()->getL10N($c->query('AppName'));
119
-		});
120
-
121
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
122
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
123
-
124
-		$this->registerService(IRequest::class, function() {
125
-			return $this->getServer()->query(IRequest::class);
126
-		});
127
-		$this->registerAlias('Request', IRequest::class);
128
-
129
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
130
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
131
-
132
-		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
133
-
134
-		$this->registerService(IServerContainer::class, function ($c) {
135
-			return $this->getServer();
136
-		});
137
-		$this->registerAlias('ServerContainer', IServerContainer::class);
138
-
139
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
140
-			return $c->query(Manager::class);
141
-		});
142
-
143
-		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
144
-			return $c;
145
-		});
146
-
147
-		// commonly used attributes
148
-		$this->registerService('UserId', function ($c) {
149
-			return $c->query(IUserSession::class)->getSession()->get('user_id');
150
-		});
151
-
152
-		$this->registerService('WebRoot', function ($c) {
153
-			return $c->query('ServerContainer')->getWebRoot();
154
-		});
155
-
156
-		$this->registerService('OC_Defaults', function ($c) {
157
-			return $c->getServer()->getThemingDefaults();
158
-		});
159
-
160
-		$this->registerService(IManager::class, function ($c) {
161
-			return $this->getServer()->getEncryptionManager();
162
-		});
163
-
164
-		$this->registerService(IConfig::class, function ($c) {
165
-			return $c->query(OC\GlobalScale\Config::class);
166
-		});
167
-
168
-		$this->registerService(IValidator::class, function($c) {
169
-			return $c->query(Validator::class);
170
-		});
171
-
172
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
173
-			return new \OC\Security\IdentityProof\Manager(
174
-				$this->getServer()->query(\OC\Files\AppData\Factory::class),
175
-				$this->getServer()->getCrypto(),
176
-				$this->getServer()->getConfig()
177
-			);
178
-		});
179
-
180
-		$this->registerService('Protocol', function($c){
181
-			/** @var \OC\Server $server */
182
-			$server = $c->query('ServerContainer');
183
-			$protocol = $server->getRequest()->getHttpProtocol();
184
-			return new Http($_SERVER, $protocol);
185
-		});
186
-
187
-		$this->registerService('Dispatcher', function($c) {
188
-			return new Dispatcher(
189
-				$c['Protocol'],
190
-				$c['MiddlewareDispatcher'],
191
-				$c['ControllerMethodReflector'],
192
-				$c['Request']
193
-			);
194
-		});
195
-
196
-		/**
197
-		 * App Framework default arguments
198
-		 */
199
-		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
200
-		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
201
-		$this->registerParameter('corsMaxAge', 1728000);
202
-
203
-		/**
204
-		 * Middleware
205
-		 */
206
-		$app = $this;
207
-		$this->registerService('SecurityMiddleware', function($c) use ($app){
208
-			/** @var \OC\Server $server */
209
-			$server = $app->getServer();
210
-
211
-			return new SecurityMiddleware(
212
-				$c['Request'],
213
-				$c['ControllerMethodReflector'],
214
-				$server->getNavigationManager(),
215
-				$server->getURLGenerator(),
216
-				$server->getLogger(),
217
-				$c['AppName'],
218
-				$server->getUserSession()->isLoggedIn(),
219
-				$server->getGroupManager()->isAdmin($this->getUserId()),
220
-				$server->getContentSecurityPolicyManager(),
221
-				$server->getCsrfTokenManager(),
222
-				$server->getContentSecurityPolicyNonceManager(),
223
-				$server->getAppManager(),
224
-				$server->getL10N('lib')
225
-			);
226
-		});
227
-
228
-		$this->registerService(OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware::class, function ($c) use ($app) {
229
-			/** @var \OC\Server $server */
230
-			$server = $app->getServer();
231
-
232
-			return new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
233
-				$c['ControllerMethodReflector'],
234
-				$server->getSession(),
235
-				$server->getUserSession(),
236
-				$server->query(ITimeFactory::class)
237
-			);
238
-		});
239
-
240
-		$this->registerService('BruteForceMiddleware', function($c) use ($app) {
241
-			/** @var \OC\Server $server */
242
-			$server = $app->getServer();
243
-
244
-			return new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
245
-				$c['ControllerMethodReflector'],
246
-				$server->getBruteForceThrottler(),
247
-				$server->getRequest()
248
-			);
249
-		});
250
-
251
-		$this->registerService('RateLimitingMiddleware', function($c) use ($app) {
252
-			/** @var \OC\Server $server */
253
-			$server = $app->getServer();
254
-
255
-			return new RateLimitingMiddleware(
256
-				$server->getRequest(),
257
-				$server->getUserSession(),
258
-				$c['ControllerMethodReflector'],
259
-				$c->query(OC\Security\RateLimiting\Limiter::class)
260
-			);
261
-		});
262
-
263
-		$this->registerService('CORSMiddleware', function($c) {
264
-			return new CORSMiddleware(
265
-				$c['Request'],
266
-				$c['ControllerMethodReflector'],
267
-				$c->query(IUserSession::class),
268
-				$c->getServer()->getBruteForceThrottler()
269
-			);
270
-		});
271
-
272
-		$this->registerService('SessionMiddleware', function($c) use ($app) {
273
-			return new SessionMiddleware(
274
-				$c['Request'],
275
-				$c['ControllerMethodReflector'],
276
-				$app->getServer()->getSession()
277
-			);
278
-		});
279
-
280
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
281
-			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
282
-			$userSession = $app->getServer()->getUserSession();
283
-			$session = $app->getServer()->getSession();
284
-			$urlGenerator = $app->getServer()->getURLGenerator();
285
-			$reflector = $c['ControllerMethodReflector'];
286
-			$request = $app->getServer()->getRequest();
287
-			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
288
-		});
289
-
290
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
291
-			return new OCSMiddleware(
292
-				$c['Request']
293
-			);
294
-		});
295
-
296
-		$this->registerService(OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class, function (SimpleContainer $c) {
297
-			return new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
298
-				$c['Request'],
299
-				$c['ControllerMethodReflector']
300
-			);
301
-		});
302
-
303
-		$middleWares = &$this->middleWares;
304
-		$this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
305
-			$dispatcher = new MiddlewareDispatcher();
306
-			$dispatcher->registerMiddleware($c[OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class]);
307
-			$dispatcher->registerMiddleware($c['CORSMiddleware']);
308
-			$dispatcher->registerMiddleware($c['OCSMiddleware']);
309
-			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
310
-			$dispatcher->registerMiddleware($c[OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware::class]);
311
-			$dispatcher->registerMiddleware($c['TwoFactorMiddleware']);
312
-			$dispatcher->registerMiddleware($c['BruteForceMiddleware']);
313
-			$dispatcher->registerMiddleware($c['RateLimitingMiddleware']);
314
-
315
-			foreach($middleWares as $middleWare) {
316
-				$dispatcher->registerMiddleware($c[$middleWare]);
317
-			}
318
-
319
-			$dispatcher->registerMiddleware($c['SessionMiddleware']);
320
-			return $dispatcher;
321
-		});
322
-
323
-	}
324
-
325
-	/**
326
-	 * @return \OCP\IServerContainer
327
-	 */
328
-	public function getServer()
329
-	{
330
-		return $this->server;
331
-	}
332
-
333
-	/**
334
-	 * @param string $middleWare
335
-	 * @return boolean|null
336
-	 */
337
-	public function registerMiddleWare($middleWare) {
338
-		$this->middleWares[] = $middleWare;
339
-	}
340
-
341
-	/**
342
-	 * used to return the appname of the set application
343
-	 * @return string the name of your application
344
-	 */
345
-	public function getAppName() {
346
-		return $this->query('AppName');
347
-	}
348
-
349
-	/**
350
-	 * @deprecated use IUserSession->isLoggedIn()
351
-	 * @return boolean
352
-	 */
353
-	public function isLoggedIn() {
354
-		return \OC::$server->getUserSession()->isLoggedIn();
355
-	}
356
-
357
-	/**
358
-	 * @deprecated use IGroupManager->isAdmin($userId)
359
-	 * @return boolean
360
-	 */
361
-	public function isAdminUser() {
362
-		$uid = $this->getUserId();
363
-		return \OC_User::isAdminUser($uid);
364
-	}
365
-
366
-	private function getUserId() {
367
-		return $this->getServer()->getSession()->get('user_id');
368
-	}
369
-
370
-	/**
371
-	 * @deprecated use the ILogger instead
372
-	 * @param string $message
373
-	 * @param string $level
374
-	 * @return mixed
375
-	 */
376
-	public function log($message, $level) {
377
-		switch($level){
378
-			case 'debug':
379
-				$level = ILogger::DEBUG;
380
-				break;
381
-			case 'info':
382
-				$level = ILogger::INFO;
383
-				break;
384
-			case 'warn':
385
-				$level = ILogger::WARN;
386
-				break;
387
-			case 'fatal':
388
-				$level = ILogger::FATAL;
389
-				break;
390
-			default:
391
-				$level = ILogger::ERROR;
392
-				break;
393
-		}
394
-		\OCP\Util::writeLog($this->getAppName(), $message, $level);
395
-	}
396
-
397
-	/**
398
-	 * Register a capability
399
-	 *
400
-	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
401
-	 */
402
-	public function registerCapability($serviceName) {
403
-		$this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
404
-			return $this->query($serviceName);
405
-		});
406
-	}
407
-
408
-	/**
409
-	 * @param string $name
410
-	 * @return mixed
411
-	 * @throws QueryException if the query could not be resolved
412
-	 */
413
-	public function query($name) {
414
-		try {
415
-			return $this->queryNoFallback($name);
416
-		} catch (QueryException $firstException) {
417
-			try {
418
-				return $this->getServer()->query($name);
419
-			} catch (QueryException $secondException) {
420
-				if ($firstException->getCode() === 1) {
421
-					throw $secondException;
422
-				}
423
-				throw $firstException;
424
-			}
425
-		}
426
-	}
427
-
428
-	/**
429
-	 * @param string $name
430
-	 * @return mixed
431
-	 * @throws QueryException if the query could not be resolved
432
-	 */
433
-	public function queryNoFallback($name) {
434
-		$name = $this->sanitizeName($name);
435
-
436
-		if ($this->offsetExists($name)) {
437
-			return parent::query($name);
438
-		} else {
439
-			if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
440
-				return parent::query($name);
441
-			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
442
-				return parent::query($name);
443
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
444
-				return parent::query($name);
445
-			}
446
-		}
447
-
448
-		throw new QueryException('Could not resolve ' . $name . '!' .
449
-			' Class can not be instantiated', 1);
450
-	}
71
+    /**
72
+     * @var array
73
+     */
74
+    private $middleWares = array();
75
+
76
+    /** @var ServerContainer */
77
+    private $server;
78
+
79
+    /**
80
+     * Put your class dependencies in here
81
+     * @param string $appName the name of the app
82
+     * @param array $urlParams
83
+     * @param ServerContainer|null $server
84
+     */
85
+    public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
86
+        parent::__construct();
87
+        $this['AppName'] = $appName;
88
+        $this['urlParams'] = $urlParams;
89
+
90
+        /** @var \OC\ServerContainer $server */
91
+        if ($server === null) {
92
+            $server = \OC::$server;
93
+        }
94
+        $this->server = $server;
95
+        $this->server->registerAppContainer($appName, $this);
96
+
97
+        // aliases
98
+        $this->registerAlias('appName', 'AppName');
99
+        $this->registerAlias('webRoot', 'WebRoot');
100
+        $this->registerAlias('userId', 'UserId');
101
+
102
+        /**
103
+         * Core services
104
+         */
105
+        $this->registerService(IOutput::class, function($c){
106
+            return new Output($this->getServer()->getWebRoot());
107
+        });
108
+
109
+        $this->registerService(Folder::class, function() {
110
+            return $this->getServer()->getUserFolder();
111
+        });
112
+
113
+        $this->registerService(IAppData::class, function (SimpleContainer $c) {
114
+            return $this->getServer()->getAppDataDir($c->query('AppName'));
115
+        });
116
+
117
+        $this->registerService(IL10N::class, function($c) {
118
+            return $this->getServer()->getL10N($c->query('AppName'));
119
+        });
120
+
121
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
122
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
123
+
124
+        $this->registerService(IRequest::class, function() {
125
+            return $this->getServer()->query(IRequest::class);
126
+        });
127
+        $this->registerAlias('Request', IRequest::class);
128
+
129
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
130
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
131
+
132
+        $this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
133
+
134
+        $this->registerService(IServerContainer::class, function ($c) {
135
+            return $this->getServer();
136
+        });
137
+        $this->registerAlias('ServerContainer', IServerContainer::class);
138
+
139
+        $this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
140
+            return $c->query(Manager::class);
141
+        });
142
+
143
+        $this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
144
+            return $c;
145
+        });
146
+
147
+        // commonly used attributes
148
+        $this->registerService('UserId', function ($c) {
149
+            return $c->query(IUserSession::class)->getSession()->get('user_id');
150
+        });
151
+
152
+        $this->registerService('WebRoot', function ($c) {
153
+            return $c->query('ServerContainer')->getWebRoot();
154
+        });
155
+
156
+        $this->registerService('OC_Defaults', function ($c) {
157
+            return $c->getServer()->getThemingDefaults();
158
+        });
159
+
160
+        $this->registerService(IManager::class, function ($c) {
161
+            return $this->getServer()->getEncryptionManager();
162
+        });
163
+
164
+        $this->registerService(IConfig::class, function ($c) {
165
+            return $c->query(OC\GlobalScale\Config::class);
166
+        });
167
+
168
+        $this->registerService(IValidator::class, function($c) {
169
+            return $c->query(Validator::class);
170
+        });
171
+
172
+        $this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
173
+            return new \OC\Security\IdentityProof\Manager(
174
+                $this->getServer()->query(\OC\Files\AppData\Factory::class),
175
+                $this->getServer()->getCrypto(),
176
+                $this->getServer()->getConfig()
177
+            );
178
+        });
179
+
180
+        $this->registerService('Protocol', function($c){
181
+            /** @var \OC\Server $server */
182
+            $server = $c->query('ServerContainer');
183
+            $protocol = $server->getRequest()->getHttpProtocol();
184
+            return new Http($_SERVER, $protocol);
185
+        });
186
+
187
+        $this->registerService('Dispatcher', function($c) {
188
+            return new Dispatcher(
189
+                $c['Protocol'],
190
+                $c['MiddlewareDispatcher'],
191
+                $c['ControllerMethodReflector'],
192
+                $c['Request']
193
+            );
194
+        });
195
+
196
+        /**
197
+         * App Framework default arguments
198
+         */
199
+        $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
200
+        $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
201
+        $this->registerParameter('corsMaxAge', 1728000);
202
+
203
+        /**
204
+         * Middleware
205
+         */
206
+        $app = $this;
207
+        $this->registerService('SecurityMiddleware', function($c) use ($app){
208
+            /** @var \OC\Server $server */
209
+            $server = $app->getServer();
210
+
211
+            return new SecurityMiddleware(
212
+                $c['Request'],
213
+                $c['ControllerMethodReflector'],
214
+                $server->getNavigationManager(),
215
+                $server->getURLGenerator(),
216
+                $server->getLogger(),
217
+                $c['AppName'],
218
+                $server->getUserSession()->isLoggedIn(),
219
+                $server->getGroupManager()->isAdmin($this->getUserId()),
220
+                $server->getContentSecurityPolicyManager(),
221
+                $server->getCsrfTokenManager(),
222
+                $server->getContentSecurityPolicyNonceManager(),
223
+                $server->getAppManager(),
224
+                $server->getL10N('lib')
225
+            );
226
+        });
227
+
228
+        $this->registerService(OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware::class, function ($c) use ($app) {
229
+            /** @var \OC\Server $server */
230
+            $server = $app->getServer();
231
+
232
+            return new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
233
+                $c['ControllerMethodReflector'],
234
+                $server->getSession(),
235
+                $server->getUserSession(),
236
+                $server->query(ITimeFactory::class)
237
+            );
238
+        });
239
+
240
+        $this->registerService('BruteForceMiddleware', function($c) use ($app) {
241
+            /** @var \OC\Server $server */
242
+            $server = $app->getServer();
243
+
244
+            return new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
245
+                $c['ControllerMethodReflector'],
246
+                $server->getBruteForceThrottler(),
247
+                $server->getRequest()
248
+            );
249
+        });
250
+
251
+        $this->registerService('RateLimitingMiddleware', function($c) use ($app) {
252
+            /** @var \OC\Server $server */
253
+            $server = $app->getServer();
254
+
255
+            return new RateLimitingMiddleware(
256
+                $server->getRequest(),
257
+                $server->getUserSession(),
258
+                $c['ControllerMethodReflector'],
259
+                $c->query(OC\Security\RateLimiting\Limiter::class)
260
+            );
261
+        });
262
+
263
+        $this->registerService('CORSMiddleware', function($c) {
264
+            return new CORSMiddleware(
265
+                $c['Request'],
266
+                $c['ControllerMethodReflector'],
267
+                $c->query(IUserSession::class),
268
+                $c->getServer()->getBruteForceThrottler()
269
+            );
270
+        });
271
+
272
+        $this->registerService('SessionMiddleware', function($c) use ($app) {
273
+            return new SessionMiddleware(
274
+                $c['Request'],
275
+                $c['ControllerMethodReflector'],
276
+                $app->getServer()->getSession()
277
+            );
278
+        });
279
+
280
+        $this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
281
+            $twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
282
+            $userSession = $app->getServer()->getUserSession();
283
+            $session = $app->getServer()->getSession();
284
+            $urlGenerator = $app->getServer()->getURLGenerator();
285
+            $reflector = $c['ControllerMethodReflector'];
286
+            $request = $app->getServer()->getRequest();
287
+            return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
288
+        });
289
+
290
+        $this->registerService('OCSMiddleware', function (SimpleContainer $c) {
291
+            return new OCSMiddleware(
292
+                $c['Request']
293
+            );
294
+        });
295
+
296
+        $this->registerService(OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class, function (SimpleContainer $c) {
297
+            return new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
298
+                $c['Request'],
299
+                $c['ControllerMethodReflector']
300
+            );
301
+        });
302
+
303
+        $middleWares = &$this->middleWares;
304
+        $this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
305
+            $dispatcher = new MiddlewareDispatcher();
306
+            $dispatcher->registerMiddleware($c[OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class]);
307
+            $dispatcher->registerMiddleware($c['CORSMiddleware']);
308
+            $dispatcher->registerMiddleware($c['OCSMiddleware']);
309
+            $dispatcher->registerMiddleware($c['SecurityMiddleware']);
310
+            $dispatcher->registerMiddleware($c[OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware::class]);
311
+            $dispatcher->registerMiddleware($c['TwoFactorMiddleware']);
312
+            $dispatcher->registerMiddleware($c['BruteForceMiddleware']);
313
+            $dispatcher->registerMiddleware($c['RateLimitingMiddleware']);
314
+
315
+            foreach($middleWares as $middleWare) {
316
+                $dispatcher->registerMiddleware($c[$middleWare]);
317
+            }
318
+
319
+            $dispatcher->registerMiddleware($c['SessionMiddleware']);
320
+            return $dispatcher;
321
+        });
322
+
323
+    }
324
+
325
+    /**
326
+     * @return \OCP\IServerContainer
327
+     */
328
+    public function getServer()
329
+    {
330
+        return $this->server;
331
+    }
332
+
333
+    /**
334
+     * @param string $middleWare
335
+     * @return boolean|null
336
+     */
337
+    public function registerMiddleWare($middleWare) {
338
+        $this->middleWares[] = $middleWare;
339
+    }
340
+
341
+    /**
342
+     * used to return the appname of the set application
343
+     * @return string the name of your application
344
+     */
345
+    public function getAppName() {
346
+        return $this->query('AppName');
347
+    }
348
+
349
+    /**
350
+     * @deprecated use IUserSession->isLoggedIn()
351
+     * @return boolean
352
+     */
353
+    public function isLoggedIn() {
354
+        return \OC::$server->getUserSession()->isLoggedIn();
355
+    }
356
+
357
+    /**
358
+     * @deprecated use IGroupManager->isAdmin($userId)
359
+     * @return boolean
360
+     */
361
+    public function isAdminUser() {
362
+        $uid = $this->getUserId();
363
+        return \OC_User::isAdminUser($uid);
364
+    }
365
+
366
+    private function getUserId() {
367
+        return $this->getServer()->getSession()->get('user_id');
368
+    }
369
+
370
+    /**
371
+     * @deprecated use the ILogger instead
372
+     * @param string $message
373
+     * @param string $level
374
+     * @return mixed
375
+     */
376
+    public function log($message, $level) {
377
+        switch($level){
378
+            case 'debug':
379
+                $level = ILogger::DEBUG;
380
+                break;
381
+            case 'info':
382
+                $level = ILogger::INFO;
383
+                break;
384
+            case 'warn':
385
+                $level = ILogger::WARN;
386
+                break;
387
+            case 'fatal':
388
+                $level = ILogger::FATAL;
389
+                break;
390
+            default:
391
+                $level = ILogger::ERROR;
392
+                break;
393
+        }
394
+        \OCP\Util::writeLog($this->getAppName(), $message, $level);
395
+    }
396
+
397
+    /**
398
+     * Register a capability
399
+     *
400
+     * @param string $serviceName e.g. 'OCA\Files\Capabilities'
401
+     */
402
+    public function registerCapability($serviceName) {
403
+        $this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
404
+            return $this->query($serviceName);
405
+        });
406
+    }
407
+
408
+    /**
409
+     * @param string $name
410
+     * @return mixed
411
+     * @throws QueryException if the query could not be resolved
412
+     */
413
+    public function query($name) {
414
+        try {
415
+            return $this->queryNoFallback($name);
416
+        } catch (QueryException $firstException) {
417
+            try {
418
+                return $this->getServer()->query($name);
419
+            } catch (QueryException $secondException) {
420
+                if ($firstException->getCode() === 1) {
421
+                    throw $secondException;
422
+                }
423
+                throw $firstException;
424
+            }
425
+        }
426
+    }
427
+
428
+    /**
429
+     * @param string $name
430
+     * @return mixed
431
+     * @throws QueryException if the query could not be resolved
432
+     */
433
+    public function queryNoFallback($name) {
434
+        $name = $this->sanitizeName($name);
435
+
436
+        if ($this->offsetExists($name)) {
437
+            return parent::query($name);
438
+        } else {
439
+            if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
440
+                return parent::query($name);
441
+            } else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
442
+                return parent::query($name);
443
+            } else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
444
+                return parent::query($name);
445
+            }
446
+        }
447
+
448
+        throw new QueryException('Could not resolve ' . $name . '!' .
449
+            ' Class can not be instantiated', 1);
450
+    }
451 451
 }
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
 	 * @param array $urlParams
83 83
 	 * @param ServerContainer|null $server
84 84
 	 */
85
-	public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
85
+	public function __construct($appName, $urlParams = array(), ServerContainer $server = null) {
86 86
 		parent::__construct();
87 87
 		$this['AppName'] = $appName;
88 88
 		$this['urlParams'] = $urlParams;
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 		/**
103 103
 		 * Core services
104 104
 		 */
105
-		$this->registerService(IOutput::class, function($c){
105
+		$this->registerService(IOutput::class, function($c) {
106 106
 			return new Output($this->getServer()->getWebRoot());
107 107
 		});
108 108
 
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 			return $this->getServer()->getUserFolder();
111 111
 		});
112 112
 
113
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
113
+		$this->registerService(IAppData::class, function(SimpleContainer $c) {
114 114
 			return $this->getServer()->getAppDataDir($c->query('AppName'));
115 115
 		});
116 116
 
@@ -131,37 +131,37 @@  discard block
 block discarded – undo
131 131
 
132 132
 		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
133 133
 
134
-		$this->registerService(IServerContainer::class, function ($c) {
134
+		$this->registerService(IServerContainer::class, function($c) {
135 135
 			return $this->getServer();
136 136
 		});
137 137
 		$this->registerAlias('ServerContainer', IServerContainer::class);
138 138
 
139
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
139
+		$this->registerService(\OCP\WorkflowEngine\IManager::class, function($c) {
140 140
 			return $c->query(Manager::class);
141 141
 		});
142 142
 
143
-		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
143
+		$this->registerService(\OCP\AppFramework\IAppContainer::class, function($c) {
144 144
 			return $c;
145 145
 		});
146 146
 
147 147
 		// commonly used attributes
148
-		$this->registerService('UserId', function ($c) {
148
+		$this->registerService('UserId', function($c) {
149 149
 			return $c->query(IUserSession::class)->getSession()->get('user_id');
150 150
 		});
151 151
 
152
-		$this->registerService('WebRoot', function ($c) {
152
+		$this->registerService('WebRoot', function($c) {
153 153
 			return $c->query('ServerContainer')->getWebRoot();
154 154
 		});
155 155
 
156
-		$this->registerService('OC_Defaults', function ($c) {
156
+		$this->registerService('OC_Defaults', function($c) {
157 157
 			return $c->getServer()->getThemingDefaults();
158 158
 		});
159 159
 
160
-		$this->registerService(IManager::class, function ($c) {
160
+		$this->registerService(IManager::class, function($c) {
161 161
 			return $this->getServer()->getEncryptionManager();
162 162
 		});
163 163
 
164
-		$this->registerService(IConfig::class, function ($c) {
164
+		$this->registerService(IConfig::class, function($c) {
165 165
 			return $c->query(OC\GlobalScale\Config::class);
166 166
 		});
167 167
 
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
 			return $c->query(Validator::class);
170 170
 		});
171 171
 
172
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
172
+		$this->registerService(\OC\Security\IdentityProof\Manager::class, function($c) {
173 173
 			return new \OC\Security\IdentityProof\Manager(
174 174
 				$this->getServer()->query(\OC\Files\AppData\Factory::class),
175 175
 				$this->getServer()->getCrypto(),
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 			);
178 178
 		});
179 179
 
180
-		$this->registerService('Protocol', function($c){
180
+		$this->registerService('Protocol', function($c) {
181 181
 			/** @var \OC\Server $server */
182 182
 			$server = $c->query('ServerContainer');
183 183
 			$protocol = $server->getRequest()->getHttpProtocol();
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
 			);
226 226
 		});
227 227
 
228
-		$this->registerService(OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware::class, function ($c) use ($app) {
228
+		$this->registerService(OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware::class, function($c) use ($app) {
229 229
 			/** @var \OC\Server $server */
230 230
 			$server = $app->getServer();
231 231
 
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
 			);
278 278
 		});
279 279
 
280
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
280
+		$this->registerService('TwoFactorMiddleware', function(SimpleContainer $c) use ($app) {
281 281
 			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
282 282
 			$userSession = $app->getServer()->getUserSession();
283 283
 			$session = $app->getServer()->getSession();
@@ -287,13 +287,13 @@  discard block
 block discarded – undo
287 287
 			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
288 288
 		});
289 289
 
290
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
290
+		$this->registerService('OCSMiddleware', function(SimpleContainer $c) {
291 291
 			return new OCSMiddleware(
292 292
 				$c['Request']
293 293
 			);
294 294
 		});
295 295
 
296
-		$this->registerService(OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class, function (SimpleContainer $c) {
296
+		$this->registerService(OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class, function(SimpleContainer $c) {
297 297
 			return new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
298 298
 				$c['Request'],
299 299
 				$c['ControllerMethodReflector']
@@ -312,7 +312,7 @@  discard block
 block discarded – undo
312 312
 			$dispatcher->registerMiddleware($c['BruteForceMiddleware']);
313 313
 			$dispatcher->registerMiddleware($c['RateLimitingMiddleware']);
314 314
 
315
-			foreach($middleWares as $middleWare) {
315
+			foreach ($middleWares as $middleWare) {
316 316
 				$dispatcher->registerMiddleware($c[$middleWare]);
317 317
 			}
318 318
 
@@ -374,7 +374,7 @@  discard block
 block discarded – undo
374 374
 	 * @return mixed
375 375
 	 */
376 376
 	public function log($message, $level) {
377
-		switch($level){
377
+		switch ($level) {
378 378
 			case 'debug':
379 379
 				$level = ILogger::DEBUG;
380 380
 				break;
@@ -440,12 +440,12 @@  discard block
 block discarded – undo
440 440
 				return parent::query($name);
441 441
 			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
442 442
 				return parent::query($name);
443
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
443
+			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']).'\\') === 0) {
444 444
 				return parent::query($name);
445 445
 			}
446 446
 		}
447 447
 
448
-		throw new QueryException('Could not resolve ' . $name . '!' .
448
+		throw new QueryException('Could not resolve '.$name.'!'.
449 449
 			' Class can not be instantiated', 1);
450 450
 	}
451 451
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php 1 patch
Indentation   +173 added lines, -173 removed lines patch added patch discarded remove patch
@@ -66,98 +66,98 @@  discard block
 block discarded – undo
66 66
  * check fails
67 67
  */
68 68
 class SecurityMiddleware extends Middleware {
69
-	/** @var INavigationManager */
70
-	private $navigationManager;
71
-	/** @var IRequest */
72
-	private $request;
73
-	/** @var ControllerMethodReflector */
74
-	private $reflector;
75
-	/** @var string */
76
-	private $appName;
77
-	/** @var IURLGenerator */
78
-	private $urlGenerator;
79
-	/** @var ILogger */
80
-	private $logger;
81
-	/** @var bool */
82
-	private $isLoggedIn;
83
-	/** @var bool */
84
-	private $isAdminUser;
85
-	/** @var ContentSecurityPolicyManager */
86
-	private $contentSecurityPolicyManager;
87
-	/** @var CsrfTokenManager */
88
-	private $csrfTokenManager;
89
-	/** @var ContentSecurityPolicyNonceManager */
90
-	private $cspNonceManager;
91
-	/** @var IAppManager */
92
-	private $appManager;
93
-	/** @var IL10N */
94
-	private $l10n;
69
+    /** @var INavigationManager */
70
+    private $navigationManager;
71
+    /** @var IRequest */
72
+    private $request;
73
+    /** @var ControllerMethodReflector */
74
+    private $reflector;
75
+    /** @var string */
76
+    private $appName;
77
+    /** @var IURLGenerator */
78
+    private $urlGenerator;
79
+    /** @var ILogger */
80
+    private $logger;
81
+    /** @var bool */
82
+    private $isLoggedIn;
83
+    /** @var bool */
84
+    private $isAdminUser;
85
+    /** @var ContentSecurityPolicyManager */
86
+    private $contentSecurityPolicyManager;
87
+    /** @var CsrfTokenManager */
88
+    private $csrfTokenManager;
89
+    /** @var ContentSecurityPolicyNonceManager */
90
+    private $cspNonceManager;
91
+    /** @var IAppManager */
92
+    private $appManager;
93
+    /** @var IL10N */
94
+    private $l10n;
95 95
 
96
-	public function __construct(IRequest $request,
97
-								ControllerMethodReflector $reflector,
98
-								INavigationManager $navigationManager,
99
-								IURLGenerator $urlGenerator,
100
-								ILogger $logger,
101
-								string $appName,
102
-								bool $isLoggedIn,
103
-								bool $isAdminUser,
104
-								ContentSecurityPolicyManager $contentSecurityPolicyManager,
105
-								CsrfTokenManager $csrfTokenManager,
106
-								ContentSecurityPolicyNonceManager $cspNonceManager,
107
-								IAppManager $appManager,
108
-								IL10N $l10n
109
-	) {
110
-		$this->navigationManager = $navigationManager;
111
-		$this->request = $request;
112
-		$this->reflector = $reflector;
113
-		$this->appName = $appName;
114
-		$this->urlGenerator = $urlGenerator;
115
-		$this->logger = $logger;
116
-		$this->isLoggedIn = $isLoggedIn;
117
-		$this->isAdminUser = $isAdminUser;
118
-		$this->contentSecurityPolicyManager = $contentSecurityPolicyManager;
119
-		$this->csrfTokenManager = $csrfTokenManager;
120
-		$this->cspNonceManager = $cspNonceManager;
121
-		$this->appManager = $appManager;
122
-		$this->l10n = $l10n;
123
-	}
96
+    public function __construct(IRequest $request,
97
+                                ControllerMethodReflector $reflector,
98
+                                INavigationManager $navigationManager,
99
+                                IURLGenerator $urlGenerator,
100
+                                ILogger $logger,
101
+                                string $appName,
102
+                                bool $isLoggedIn,
103
+                                bool $isAdminUser,
104
+                                ContentSecurityPolicyManager $contentSecurityPolicyManager,
105
+                                CsrfTokenManager $csrfTokenManager,
106
+                                ContentSecurityPolicyNonceManager $cspNonceManager,
107
+                                IAppManager $appManager,
108
+                                IL10N $l10n
109
+    ) {
110
+        $this->navigationManager = $navigationManager;
111
+        $this->request = $request;
112
+        $this->reflector = $reflector;
113
+        $this->appName = $appName;
114
+        $this->urlGenerator = $urlGenerator;
115
+        $this->logger = $logger;
116
+        $this->isLoggedIn = $isLoggedIn;
117
+        $this->isAdminUser = $isAdminUser;
118
+        $this->contentSecurityPolicyManager = $contentSecurityPolicyManager;
119
+        $this->csrfTokenManager = $csrfTokenManager;
120
+        $this->cspNonceManager = $cspNonceManager;
121
+        $this->appManager = $appManager;
122
+        $this->l10n = $l10n;
123
+    }
124 124
 
125
-	/**
126
-	 * This runs all the security checks before a method call. The
127
-	 * security checks are determined by inspecting the controller method
128
-	 * annotations
129
-	 * @param Controller $controller the controller
130
-	 * @param string $methodName the name of the method
131
-	 * @throws SecurityException when a security check fails
132
-	 */
133
-	public function beforeController($controller, $methodName) {
125
+    /**
126
+     * This runs all the security checks before a method call. The
127
+     * security checks are determined by inspecting the controller method
128
+     * annotations
129
+     * @param Controller $controller the controller
130
+     * @param string $methodName the name of the method
131
+     * @throws SecurityException when a security check fails
132
+     */
133
+    public function beforeController($controller, $methodName) {
134 134
 
135
-		// this will set the current navigation entry of the app, use this only
136
-		// for normal HTML requests and not for AJAX requests
137
-		$this->navigationManager->setActiveEntry($this->appName);
135
+        // this will set the current navigation entry of the app, use this only
136
+        // for normal HTML requests and not for AJAX requests
137
+        $this->navigationManager->setActiveEntry($this->appName);
138 138
 
139
-		// security checks
140
-		$isPublicPage = $this->reflector->hasAnnotation('PublicPage');
141
-		if(!$isPublicPage) {
142
-			if(!$this->isLoggedIn) {
143
-				throw new NotLoggedInException();
144
-			}
139
+        // security checks
140
+        $isPublicPage = $this->reflector->hasAnnotation('PublicPage');
141
+        if(!$isPublicPage) {
142
+            if(!$this->isLoggedIn) {
143
+                throw new NotLoggedInException();
144
+            }
145 145
 
146
-			if(!$this->reflector->hasAnnotation('NoAdminRequired') && !$this->isAdminUser) {
147
-				throw new NotAdminException($this->l10n->t('Logged in user must be an admin'));
148
-			}
149
-		}
146
+            if(!$this->reflector->hasAnnotation('NoAdminRequired') && !$this->isAdminUser) {
147
+                throw new NotAdminException($this->l10n->t('Logged in user must be an admin'));
148
+            }
149
+        }
150 150
 
151
-		// Check for strict cookie requirement
152
-		if($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
153
-			if(!$this->request->passesStrictCookieCheck()) {
154
-				throw new StrictCookieMissingException();
155
-			}
156
-		}
157
-		// CSRF check - also registers the CSRF token since the session may be closed later
158
-		Util::callRegister();
159
-		if(!$this->reflector->hasAnnotation('NoCSRFRequired')) {
160
-			/*
151
+        // Check for strict cookie requirement
152
+        if($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
153
+            if(!$this->request->passesStrictCookieCheck()) {
154
+                throw new StrictCookieMissingException();
155
+            }
156
+        }
157
+        // CSRF check - also registers the CSRF token since the session may be closed later
158
+        Util::callRegister();
159
+        if(!$this->reflector->hasAnnotation('NoCSRFRequired')) {
160
+            /*
161 161
 			 * Only allow the CSRF check to fail on OCS Requests. This kind of
162 162
 			 * hacks around that we have no full token auth in place yet and we
163 163
 			 * do want to offer CSRF checks for web requests.
@@ -165,103 +165,103 @@  discard block
 block discarded – undo
165 165
 			 * Additionally we allow Bearer authenticated requests to pass on OCS routes.
166 166
 			 * This allows oauth apps (e.g. moodle) to use the OCS endpoints
167 167
 			 */
168
-			if(!$this->request->passesCSRFCheck() && !(
169
-					$controller instanceof OCSController && (
170
-						$this->request->getHeader('OCS-APIREQUEST') === 'true' ||
171
-						strpos($this->request->getHeader('Authorization'), 'Bearer ') === 0
172
-					)
173
-				)) {
174
-				throw new CrossSiteRequestForgeryException();
175
-			}
176
-		}
168
+            if(!$this->request->passesCSRFCheck() && !(
169
+                    $controller instanceof OCSController && (
170
+                        $this->request->getHeader('OCS-APIREQUEST') === 'true' ||
171
+                        strpos($this->request->getHeader('Authorization'), 'Bearer ') === 0
172
+                    )
173
+                )) {
174
+                throw new CrossSiteRequestForgeryException();
175
+            }
176
+        }
177 177
 
178
-		/**
179
-		 * Checks if app is enabled (also includes a check whether user is allowed to access the resource)
180
-		 * The getAppPath() check is here since components such as settings also use the AppFramework and
181
-		 * therefore won't pass this check.
182
-		 * If page is public, app does not need to be enabled for current user/visitor
183
-		 */
184
-		try {
185
-			$appPath = $this->appManager->getAppPath($this->appName);
186
-		} catch (AppPathNotFoundException $e) {
187
-			$appPath = false;
188
-		}
178
+        /**
179
+         * Checks if app is enabled (also includes a check whether user is allowed to access the resource)
180
+         * The getAppPath() check is here since components such as settings also use the AppFramework and
181
+         * therefore won't pass this check.
182
+         * If page is public, app does not need to be enabled for current user/visitor
183
+         */
184
+        try {
185
+            $appPath = $this->appManager->getAppPath($this->appName);
186
+        } catch (AppPathNotFoundException $e) {
187
+            $appPath = false;
188
+        }
189 189
 
190
-		if ($appPath !== false && !$isPublicPage && !$this->appManager->isEnabledForUser($this->appName)) {
191
-			throw new AppNotEnabledException();
192
-		}
193
-	}
190
+        if ($appPath !== false && !$isPublicPage && !$this->appManager->isEnabledForUser($this->appName)) {
191
+            throw new AppNotEnabledException();
192
+        }
193
+    }
194 194
 
195
-	/**
196
-	 * Performs the default CSP modifications that may be injected by other
197
-	 * applications
198
-	 *
199
-	 * @param Controller $controller
200
-	 * @param string $methodName
201
-	 * @param Response $response
202
-	 * @return Response
203
-	 */
204
-	public function afterController($controller, $methodName, Response $response): Response {
205
-		$policy = !is_null($response->getContentSecurityPolicy()) ? $response->getContentSecurityPolicy() : new ContentSecurityPolicy();
195
+    /**
196
+     * Performs the default CSP modifications that may be injected by other
197
+     * applications
198
+     *
199
+     * @param Controller $controller
200
+     * @param string $methodName
201
+     * @param Response $response
202
+     * @return Response
203
+     */
204
+    public function afterController($controller, $methodName, Response $response): Response {
205
+        $policy = !is_null($response->getContentSecurityPolicy()) ? $response->getContentSecurityPolicy() : new ContentSecurityPolicy();
206 206
 
207
-		if (get_class($policy) === EmptyContentSecurityPolicy::class) {
208
-			return $response;
209
-		}
207
+        if (get_class($policy) === EmptyContentSecurityPolicy::class) {
208
+            return $response;
209
+        }
210 210
 
211
-		$defaultPolicy = $this->contentSecurityPolicyManager->getDefaultPolicy();
212
-		$defaultPolicy = $this->contentSecurityPolicyManager->mergePolicies($defaultPolicy, $policy);
211
+        $defaultPolicy = $this->contentSecurityPolicyManager->getDefaultPolicy();
212
+        $defaultPolicy = $this->contentSecurityPolicyManager->mergePolicies($defaultPolicy, $policy);
213 213
 
214
-		if($this->cspNonceManager->browserSupportsCspV3()) {
215
-			$defaultPolicy->useJsNonce($this->csrfTokenManager->getToken()->getEncryptedValue());
216
-		}
214
+        if($this->cspNonceManager->browserSupportsCspV3()) {
215
+            $defaultPolicy->useJsNonce($this->csrfTokenManager->getToken()->getEncryptedValue());
216
+        }
217 217
 
218
-		$response->setContentSecurityPolicy($defaultPolicy);
218
+        $response->setContentSecurityPolicy($defaultPolicy);
219 219
 
220
-		return $response;
221
-	}
220
+        return $response;
221
+    }
222 222
 
223
-	/**
224
-	 * If an SecurityException is being caught, ajax requests return a JSON error
225
-	 * response and non ajax requests redirect to the index
226
-	 * @param Controller $controller the controller that is being called
227
-	 * @param string $methodName the name of the method that will be called on
228
-	 *                           the controller
229
-	 * @param \Exception $exception the thrown exception
230
-	 * @throws \Exception the passed in exception if it can't handle it
231
-	 * @return Response a Response object or null in case that the exception could not be handled
232
-	 */
233
-	public function afterException($controller, $methodName, \Exception $exception): Response {
234
-		if($exception instanceof SecurityException) {
235
-			if($exception instanceof StrictCookieMissingException) {
236
-				return new RedirectResponse(\OC::$WEBROOT);
237
- 			}
238
-			if (stripos($this->request->getHeader('Accept'),'html') === false) {
239
-				$response = new JSONResponse(
240
-					['message' => $exception->getMessage()],
241
-					$exception->getCode()
242
-				);
243
-			} else {
244
-				if($exception instanceof NotLoggedInException) {
245
-					$params = [];
246
-					if (isset($this->request->server['REQUEST_URI'])) {
247
-						$params['redirect_url'] = $this->request->server['REQUEST_URI'];
248
-					}
249
-					$url = $this->urlGenerator->linkToRoute('core.login.showLoginForm', $params);
250
-					$response = new RedirectResponse($url);
251
-				} else {
252
-					$response = new TemplateResponse('core', '403', ['file' => $exception->getMessage()], 'guest');
253
-					$response->setStatus($exception->getCode());
254
-				}
255
-			}
223
+    /**
224
+     * If an SecurityException is being caught, ajax requests return a JSON error
225
+     * response and non ajax requests redirect to the index
226
+     * @param Controller $controller the controller that is being called
227
+     * @param string $methodName the name of the method that will be called on
228
+     *                           the controller
229
+     * @param \Exception $exception the thrown exception
230
+     * @throws \Exception the passed in exception if it can't handle it
231
+     * @return Response a Response object or null in case that the exception could not be handled
232
+     */
233
+    public function afterException($controller, $methodName, \Exception $exception): Response {
234
+        if($exception instanceof SecurityException) {
235
+            if($exception instanceof StrictCookieMissingException) {
236
+                return new RedirectResponse(\OC::$WEBROOT);
237
+                }
238
+            if (stripos($this->request->getHeader('Accept'),'html') === false) {
239
+                $response = new JSONResponse(
240
+                    ['message' => $exception->getMessage()],
241
+                    $exception->getCode()
242
+                );
243
+            } else {
244
+                if($exception instanceof NotLoggedInException) {
245
+                    $params = [];
246
+                    if (isset($this->request->server['REQUEST_URI'])) {
247
+                        $params['redirect_url'] = $this->request->server['REQUEST_URI'];
248
+                    }
249
+                    $url = $this->urlGenerator->linkToRoute('core.login.showLoginForm', $params);
250
+                    $response = new RedirectResponse($url);
251
+                } else {
252
+                    $response = new TemplateResponse('core', '403', ['file' => $exception->getMessage()], 'guest');
253
+                    $response->setStatus($exception->getCode());
254
+                }
255
+            }
256 256
 
257
-			$this->logger->logException($exception, [
258
-				'level' => ILogger::DEBUG,
259
-				'app' => 'core',
260
-			]);
261
-			return $response;
262
-		}
257
+            $this->logger->logException($exception, [
258
+                'level' => ILogger::DEBUG,
259
+                'app' => 'core',
260
+            ]);
261
+            return $response;
262
+        }
263 263
 
264
-		throw $exception;
265
-	}
264
+        throw $exception;
265
+    }
266 266
 
267 267
 }
Please login to merge, or discard this patch.
lib/private/Archive/ZIP.php 3 patches
Indentation   +192 added lines, -192 removed lines patch added patch discarded remove patch
@@ -34,199 +34,199 @@
 block discarded – undo
34 34
 use OCP\ILogger;
35 35
 
36 36
 class ZIP extends Archive{
37
-	/**
38
-	 * @var \ZipArchive zip
39
-	 */
40
-	private $zip=null;
41
-	private $path;
37
+    /**
38
+     * @var \ZipArchive zip
39
+     */
40
+    private $zip=null;
41
+    private $path;
42 42
 
43
-	/**
44
-	 * @param string $source
45
-	 */
46
-	public function __construct($source) {
47
-		$this->path=$source;
48
-		$this->zip=new \ZipArchive();
49
-		if($this->zip->open($source, \ZipArchive::CREATE)) {
50
-		}else{
51
-			\OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, ILogger::WARN);
52
-		}
53
-	}
54
-	/**
55
-	 * add an empty folder to the archive
56
-	 * @param string $path
57
-	 * @return bool
58
-	 */
59
-	public function addFolder($path) {
60
-		return $this->zip->addEmptyDir($path);
61
-	}
62
-	/**
63
-	 * add a file to the archive
64
-	 * @param string $path
65
-	 * @param string $source either a local file or string data
66
-	 * @return bool
67
-	 */
68
-	public function addFile($path, $source='') {
69
-		if($source and $source[0]=='/' and file_exists($source)) {
70
-			$result=$this->zip->addFile($source, $path);
71
-		}else{
72
-			$result=$this->zip->addFromString($path, $source);
73
-		}
74
-		if($result) {
75
-			$this->zip->close();//close and reopen to save the zip
76
-			$this->zip->open($this->path);
77
-		}
78
-		return $result;
79
-	}
80
-	/**
81
-	 * rename a file or folder in the archive
82
-	 * @param string $source
83
-	 * @param string $dest
84
-	 * @return boolean|null
85
-	 */
86
-	public function rename($source, $dest) {
87
-		$source=$this->stripPath($source);
88
-		$dest=$this->stripPath($dest);
89
-		$this->zip->renameName($source, $dest);
90
-	}
91
-	/**
92
-	 * get the uncompressed size of a file in the archive
93
-	 * @param string $path
94
-	 * @return int
95
-	 */
96
-	public function filesize($path) {
97
-		$stat=$this->zip->statName($path);
98
-		return $stat['size'];
99
-	}
100
-	/**
101
-	 * get the last modified time of a file in the archive
102
-	 * @param string $path
103
-	 * @return int
104
-	 */
105
-	public function mtime($path) {
106
-		return filemtime($this->path);
107
-	}
108
-	/**
109
-	 * get the files in a folder
110
-	 * @param string $path
111
-	 * @return array
112
-	 */
113
-	public function getFolder($path) {
114
-		$files=$this->getFiles();
115
-		$folderContent=array();
116
-		$pathLength=strlen($path);
117
-		foreach($files as $file) {
118
-			if(substr($file, 0, $pathLength)==$path and $file!=$path) {
119
-				if(strrpos(substr($file, 0, -1), '/')<=$pathLength) {
120
-					$folderContent[]=substr($file, $pathLength);
121
-				}
122
-			}
123
-		}
124
-		return $folderContent;
125
-	}
126
-	/**
127
-	 * get all files in the archive
128
-	 * @return array
129
-	 */
130
-	public function getFiles() {
131
-		$fileCount=$this->zip->numFiles;
132
-		$files=array();
133
-		for($i=0;$i<$fileCount;$i++) {
134
-			$files[]=$this->zip->getNameIndex($i);
135
-		}
136
-		return $files;
137
-	}
138
-	/**
139
-	 * get the content of a file
140
-	 * @param string $path
141
-	 * @return string
142
-	 */
143
-	public function getFile($path) {
144
-		return $this->zip->getFromName($path);
145
-	}
146
-	/**
147
-	 * extract a single file from the archive
148
-	 * @param string $path
149
-	 * @param string $dest
150
-	 * @return boolean|null
151
-	 */
152
-	public function extractFile($path, $dest) {
153
-		$fp = $this->zip->getStream($path);
154
-		file_put_contents($dest, $fp);
155
-	}
156
-	/**
157
-	 * extract the archive
158
-	 * @param string $dest
159
-	 * @return bool
160
-	 */
161
-	public function extract($dest) {
162
-		return $this->zip->extractTo($dest);
163
-	}
164
-	/**
165
-	 * check if a file or folder exists in the archive
166
-	 * @param string $path
167
-	 * @return bool
168
-	 */
169
-	public function fileExists($path) {
170
-		return ($this->zip->locateName($path)!==false) or ($this->zip->locateName($path.'/')!==false);
171
-	}
172
-	/**
173
-	 * remove a file or folder from the archive
174
-	 * @param string $path
175
-	 * @return bool
176
-	 */
177
-	public function remove($path) {
178
-		if($this->fileExists($path.'/')) {
179
-			return $this->zip->deleteName($path.'/');
180
-		}else{
181
-			return $this->zip->deleteName($path);
182
-		}
183
-	}
184
-	/**
185
-	 * get a file handler
186
-	 * @param string $path
187
-	 * @param string $mode
188
-	 * @return resource
189
-	 */
190
-	public function getStream($path, $mode) {
191
-		if($mode=='r' or $mode=='rb') {
192
-			return $this->zip->getStream($path);
193
-		} else {
194
-			//since we can't directly get a writable stream,
195
-			//make a temp copy of the file and put it back
196
-			//in the archive when the stream is closed
197
-			if(strrpos($path, '.')!==false) {
198
-				$ext=substr($path, strrpos($path, '.'));
199
-			}else{
200
-				$ext='';
201
-			}
202
-			$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
203
-			if($this->fileExists($path)) {
204
-				$this->extractFile($path, $tmpFile);
205
-			}
206
-			$handle = fopen($tmpFile, $mode);
207
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
208
-				$this->writeBack($tmpFile, $path);
209
-			});
210
-		}
211
-	}
43
+    /**
44
+     * @param string $source
45
+     */
46
+    public function __construct($source) {
47
+        $this->path=$source;
48
+        $this->zip=new \ZipArchive();
49
+        if($this->zip->open($source, \ZipArchive::CREATE)) {
50
+        }else{
51
+            \OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, ILogger::WARN);
52
+        }
53
+    }
54
+    /**
55
+     * add an empty folder to the archive
56
+     * @param string $path
57
+     * @return bool
58
+     */
59
+    public function addFolder($path) {
60
+        return $this->zip->addEmptyDir($path);
61
+    }
62
+    /**
63
+     * add a file to the archive
64
+     * @param string $path
65
+     * @param string $source either a local file or string data
66
+     * @return bool
67
+     */
68
+    public function addFile($path, $source='') {
69
+        if($source and $source[0]=='/' and file_exists($source)) {
70
+            $result=$this->zip->addFile($source, $path);
71
+        }else{
72
+            $result=$this->zip->addFromString($path, $source);
73
+        }
74
+        if($result) {
75
+            $this->zip->close();//close and reopen to save the zip
76
+            $this->zip->open($this->path);
77
+        }
78
+        return $result;
79
+    }
80
+    /**
81
+     * rename a file or folder in the archive
82
+     * @param string $source
83
+     * @param string $dest
84
+     * @return boolean|null
85
+     */
86
+    public function rename($source, $dest) {
87
+        $source=$this->stripPath($source);
88
+        $dest=$this->stripPath($dest);
89
+        $this->zip->renameName($source, $dest);
90
+    }
91
+    /**
92
+     * get the uncompressed size of a file in the archive
93
+     * @param string $path
94
+     * @return int
95
+     */
96
+    public function filesize($path) {
97
+        $stat=$this->zip->statName($path);
98
+        return $stat['size'];
99
+    }
100
+    /**
101
+     * get the last modified time of a file in the archive
102
+     * @param string $path
103
+     * @return int
104
+     */
105
+    public function mtime($path) {
106
+        return filemtime($this->path);
107
+    }
108
+    /**
109
+     * get the files in a folder
110
+     * @param string $path
111
+     * @return array
112
+     */
113
+    public function getFolder($path) {
114
+        $files=$this->getFiles();
115
+        $folderContent=array();
116
+        $pathLength=strlen($path);
117
+        foreach($files as $file) {
118
+            if(substr($file, 0, $pathLength)==$path and $file!=$path) {
119
+                if(strrpos(substr($file, 0, -1), '/')<=$pathLength) {
120
+                    $folderContent[]=substr($file, $pathLength);
121
+                }
122
+            }
123
+        }
124
+        return $folderContent;
125
+    }
126
+    /**
127
+     * get all files in the archive
128
+     * @return array
129
+     */
130
+    public function getFiles() {
131
+        $fileCount=$this->zip->numFiles;
132
+        $files=array();
133
+        for($i=0;$i<$fileCount;$i++) {
134
+            $files[]=$this->zip->getNameIndex($i);
135
+        }
136
+        return $files;
137
+    }
138
+    /**
139
+     * get the content of a file
140
+     * @param string $path
141
+     * @return string
142
+     */
143
+    public function getFile($path) {
144
+        return $this->zip->getFromName($path);
145
+    }
146
+    /**
147
+     * extract a single file from the archive
148
+     * @param string $path
149
+     * @param string $dest
150
+     * @return boolean|null
151
+     */
152
+    public function extractFile($path, $dest) {
153
+        $fp = $this->zip->getStream($path);
154
+        file_put_contents($dest, $fp);
155
+    }
156
+    /**
157
+     * extract the archive
158
+     * @param string $dest
159
+     * @return bool
160
+     */
161
+    public function extract($dest) {
162
+        return $this->zip->extractTo($dest);
163
+    }
164
+    /**
165
+     * check if a file or folder exists in the archive
166
+     * @param string $path
167
+     * @return bool
168
+     */
169
+    public function fileExists($path) {
170
+        return ($this->zip->locateName($path)!==false) or ($this->zip->locateName($path.'/')!==false);
171
+    }
172
+    /**
173
+     * remove a file or folder from the archive
174
+     * @param string $path
175
+     * @return bool
176
+     */
177
+    public function remove($path) {
178
+        if($this->fileExists($path.'/')) {
179
+            return $this->zip->deleteName($path.'/');
180
+        }else{
181
+            return $this->zip->deleteName($path);
182
+        }
183
+    }
184
+    /**
185
+     * get a file handler
186
+     * @param string $path
187
+     * @param string $mode
188
+     * @return resource
189
+     */
190
+    public function getStream($path, $mode) {
191
+        if($mode=='r' or $mode=='rb') {
192
+            return $this->zip->getStream($path);
193
+        } else {
194
+            //since we can't directly get a writable stream,
195
+            //make a temp copy of the file and put it back
196
+            //in the archive when the stream is closed
197
+            if(strrpos($path, '.')!==false) {
198
+                $ext=substr($path, strrpos($path, '.'));
199
+            }else{
200
+                $ext='';
201
+            }
202
+            $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
203
+            if($this->fileExists($path)) {
204
+                $this->extractFile($path, $tmpFile);
205
+            }
206
+            $handle = fopen($tmpFile, $mode);
207
+            return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
208
+                $this->writeBack($tmpFile, $path);
209
+            });
210
+        }
211
+    }
212 212
 
213
-	/**
214
-	 * write back temporary files
215
-	 */
216
-	public function writeBack($tmpFile, $path) {
217
-		$this->addFile($path, $tmpFile);
218
-		unlink($tmpFile);
219
-	}
213
+    /**
214
+     * write back temporary files
215
+     */
216
+    public function writeBack($tmpFile, $path) {
217
+        $this->addFile($path, $tmpFile);
218
+        unlink($tmpFile);
219
+    }
220 220
 
221
-	/**
222
-	 * @param string $path
223
-	 * @return string
224
-	 */
225
-	private function stripPath($path) {
226
-		if(!$path || $path[0]=='/') {
227
-			return substr($path, 1);
228
-		}else{
229
-			return $path;
230
-		}
231
-	}
221
+    /**
222
+     * @param string $path
223
+     * @return string
224
+     */
225
+    private function stripPath($path) {
226
+        if(!$path || $path[0]=='/') {
227
+            return substr($path, 1);
228
+        }else{
229
+            return $path;
230
+        }
231
+    }
232 232
 }
Please login to merge, or discard this patch.
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -33,21 +33,21 @@  discard block
 block discarded – undo
33 33
 use Icewind\Streams\CallbackWrapper;
34 34
 use OCP\ILogger;
35 35
 
36
-class ZIP extends Archive{
36
+class ZIP extends Archive {
37 37
 	/**
38 38
 	 * @var \ZipArchive zip
39 39
 	 */
40
-	private $zip=null;
40
+	private $zip = null;
41 41
 	private $path;
42 42
 
43 43
 	/**
44 44
 	 * @param string $source
45 45
 	 */
46 46
 	public function __construct($source) {
47
-		$this->path=$source;
48
-		$this->zip=new \ZipArchive();
49
-		if($this->zip->open($source, \ZipArchive::CREATE)) {
50
-		}else{
47
+		$this->path = $source;
48
+		$this->zip = new \ZipArchive();
49
+		if ($this->zip->open($source, \ZipArchive::CREATE)) {
50
+		} else {
51 51
 			\OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, ILogger::WARN);
52 52
 		}
53 53
 	}
@@ -65,14 +65,14 @@  discard block
 block discarded – undo
65 65
 	 * @param string $source either a local file or string data
66 66
 	 * @return bool
67 67
 	 */
68
-	public function addFile($path, $source='') {
69
-		if($source and $source[0]=='/' and file_exists($source)) {
70
-			$result=$this->zip->addFile($source, $path);
71
-		}else{
72
-			$result=$this->zip->addFromString($path, $source);
68
+	public function addFile($path, $source = '') {
69
+		if ($source and $source[0] == '/' and file_exists($source)) {
70
+			$result = $this->zip->addFile($source, $path);
71
+		} else {
72
+			$result = $this->zip->addFromString($path, $source);
73 73
 		}
74
-		if($result) {
75
-			$this->zip->close();//close and reopen to save the zip
74
+		if ($result) {
75
+			$this->zip->close(); //close and reopen to save the zip
76 76
 			$this->zip->open($this->path);
77 77
 		}
78 78
 		return $result;
@@ -84,8 +84,8 @@  discard block
 block discarded – undo
84 84
 	 * @return boolean|null
85 85
 	 */
86 86
 	public function rename($source, $dest) {
87
-		$source=$this->stripPath($source);
88
-		$dest=$this->stripPath($dest);
87
+		$source = $this->stripPath($source);
88
+		$dest = $this->stripPath($dest);
89 89
 		$this->zip->renameName($source, $dest);
90 90
 	}
91 91
 	/**
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 	 * @return int
95 95
 	 */
96 96
 	public function filesize($path) {
97
-		$stat=$this->zip->statName($path);
97
+		$stat = $this->zip->statName($path);
98 98
 		return $stat['size'];
99 99
 	}
100 100
 	/**
@@ -111,13 +111,13 @@  discard block
 block discarded – undo
111 111
 	 * @return array
112 112
 	 */
113 113
 	public function getFolder($path) {
114
-		$files=$this->getFiles();
115
-		$folderContent=array();
116
-		$pathLength=strlen($path);
117
-		foreach($files as $file) {
118
-			if(substr($file, 0, $pathLength)==$path and $file!=$path) {
119
-				if(strrpos(substr($file, 0, -1), '/')<=$pathLength) {
120
-					$folderContent[]=substr($file, $pathLength);
114
+		$files = $this->getFiles();
115
+		$folderContent = array();
116
+		$pathLength = strlen($path);
117
+		foreach ($files as $file) {
118
+			if (substr($file, 0, $pathLength) == $path and $file != $path) {
119
+				if (strrpos(substr($file, 0, -1), '/') <= $pathLength) {
120
+					$folderContent[] = substr($file, $pathLength);
121 121
 				}
122 122
 			}
123 123
 		}
@@ -128,10 +128,10 @@  discard block
 block discarded – undo
128 128
 	 * @return array
129 129
 	 */
130 130
 	public function getFiles() {
131
-		$fileCount=$this->zip->numFiles;
132
-		$files=array();
133
-		for($i=0;$i<$fileCount;$i++) {
134
-			$files[]=$this->zip->getNameIndex($i);
131
+		$fileCount = $this->zip->numFiles;
132
+		$files = array();
133
+		for ($i = 0; $i < $fileCount; $i++) {
134
+			$files[] = $this->zip->getNameIndex($i);
135 135
 		}
136 136
 		return $files;
137 137
 	}
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 	 * @return bool
168 168
 	 */
169 169
 	public function fileExists($path) {
170
-		return ($this->zip->locateName($path)!==false) or ($this->zip->locateName($path.'/')!==false);
170
+		return ($this->zip->locateName($path) !== false) or ($this->zip->locateName($path.'/') !== false);
171 171
 	}
172 172
 	/**
173 173
 	 * remove a file or folder from the archive
@@ -175,9 +175,9 @@  discard block
 block discarded – undo
175 175
 	 * @return bool
176 176
 	 */
177 177
 	public function remove($path) {
178
-		if($this->fileExists($path.'/')) {
178
+		if ($this->fileExists($path.'/')) {
179 179
 			return $this->zip->deleteName($path.'/');
180
-		}else{
180
+		} else {
181 181
 			return $this->zip->deleteName($path);
182 182
 		}
183 183
 	}
@@ -188,23 +188,23 @@  discard block
 block discarded – undo
188 188
 	 * @return resource
189 189
 	 */
190 190
 	public function getStream($path, $mode) {
191
-		if($mode=='r' or $mode=='rb') {
191
+		if ($mode == 'r' or $mode == 'rb') {
192 192
 			return $this->zip->getStream($path);
193 193
 		} else {
194 194
 			//since we can't directly get a writable stream,
195 195
 			//make a temp copy of the file and put it back
196 196
 			//in the archive when the stream is closed
197
-			if(strrpos($path, '.')!==false) {
198
-				$ext=substr($path, strrpos($path, '.'));
199
-			}else{
200
-				$ext='';
197
+			if (strrpos($path, '.') !== false) {
198
+				$ext = substr($path, strrpos($path, '.'));
199
+			} else {
200
+				$ext = '';
201 201
 			}
202 202
 			$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
203
-			if($this->fileExists($path)) {
203
+			if ($this->fileExists($path)) {
204 204
 				$this->extractFile($path, $tmpFile);
205 205
 			}
206 206
 			$handle = fopen($tmpFile, $mode);
207
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
207
+			return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
208 208
 				$this->writeBack($tmpFile, $path);
209 209
 			});
210 210
 		}
@@ -223,9 +223,9 @@  discard block
 block discarded – undo
223 223
 	 * @return string
224 224
 	 */
225 225
 	private function stripPath($path) {
226
-		if(!$path || $path[0]=='/') {
226
+		if (!$path || $path[0] == '/') {
227 227
 			return substr($path, 1);
228
-		}else{
228
+		} else {
229 229
 			return $path;
230 230
 		}
231 231
 	}
Please login to merge, or discard this patch.
Braces   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
 		$this->path=$source;
48 48
 		$this->zip=new \ZipArchive();
49 49
 		if($this->zip->open($source, \ZipArchive::CREATE)) {
50
-		}else{
50
+		} else{
51 51
 			\OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, ILogger::WARN);
52 52
 		}
53 53
 	}
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 	public function addFile($path, $source='') {
69 69
 		if($source and $source[0]=='/' and file_exists($source)) {
70 70
 			$result=$this->zip->addFile($source, $path);
71
-		}else{
71
+		} else{
72 72
 			$result=$this->zip->addFromString($path, $source);
73 73
 		}
74 74
 		if($result) {
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 	public function remove($path) {
178 178
 		if($this->fileExists($path.'/')) {
179 179
 			return $this->zip->deleteName($path.'/');
180
-		}else{
180
+		} else{
181 181
 			return $this->zip->deleteName($path);
182 182
 		}
183 183
 	}
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
 			//in the archive when the stream is closed
197 197
 			if(strrpos($path, '.')!==false) {
198 198
 				$ext=substr($path, strrpos($path, '.'));
199
-			}else{
199
+			} else{
200 200
 				$ext='';
201 201
 			}
202 202
 			$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
 	private function stripPath($path) {
226 226
 		if(!$path || $path[0]=='/') {
227 227
 			return substr($path, 1);
228
-		}else{
228
+		} else{
229 229
 			return $path;
230 230
 		}
231 231
 	}
Please login to merge, or discard this patch.
lib/private/NaturalSort.php 1 patch
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -30,113 +30,113 @@
 block discarded – undo
30 30
 use OCP\ILogger;
31 31
 
32 32
 class NaturalSort {
33
-	private static $instance;
34
-	private $collator;
35
-	private $cache = array();
33
+    private static $instance;
34
+    private $collator;
35
+    private $cache = array();
36 36
 
37
-	/**
38
-	 * Instantiate a new \OC\NaturalSort instance.
39
-	 * @param object $injectedCollator
40
-	 */
41
-	public function __construct($injectedCollator = null) {
42
-		// inject an instance of \Collator('en_US') to force using the php5-intl Collator
43
-		// or inject an instance of \OC\NaturalSort_DefaultCollator to force using Owncloud's default collator
44
-		if (isset($injectedCollator)) {
45
-			$this->collator = $injectedCollator;
46
-			\OCP\Util::writeLog('core', 'forced use of '.get_class($injectedCollator), ILogger::DEBUG);
47
-		}
48
-	}
37
+    /**
38
+     * Instantiate a new \OC\NaturalSort instance.
39
+     * @param object $injectedCollator
40
+     */
41
+    public function __construct($injectedCollator = null) {
42
+        // inject an instance of \Collator('en_US') to force using the php5-intl Collator
43
+        // or inject an instance of \OC\NaturalSort_DefaultCollator to force using Owncloud's default collator
44
+        if (isset($injectedCollator)) {
45
+            $this->collator = $injectedCollator;
46
+            \OCP\Util::writeLog('core', 'forced use of '.get_class($injectedCollator), ILogger::DEBUG);
47
+        }
48
+    }
49 49
 
50
-	/**
51
-	 * Split the given string in chunks of numbers and strings
52
-	 * @param string $t string
53
-	 * @return array of strings and number chunks
54
-	 */
55
-	private function naturalSortChunkify($t) {
56
-		// Adapted and ported to PHP from
57
-		// http://my.opera.com/GreyWyvern/blog/show.dml/1671288
58
-		if (isset($this->cache[$t])) {
59
-			return $this->cache[$t];
60
-		}
61
-		$tz = array();
62
-		$x = 0;
63
-		$y = -1;
64
-		$n = null;
50
+    /**
51
+     * Split the given string in chunks of numbers and strings
52
+     * @param string $t string
53
+     * @return array of strings and number chunks
54
+     */
55
+    private function naturalSortChunkify($t) {
56
+        // Adapted and ported to PHP from
57
+        // http://my.opera.com/GreyWyvern/blog/show.dml/1671288
58
+        if (isset($this->cache[$t])) {
59
+            return $this->cache[$t];
60
+        }
61
+        $tz = array();
62
+        $x = 0;
63
+        $y = -1;
64
+        $n = null;
65 65
 
66
-		while (isset($t[$x])) {
67
-			$c = $t[$x];
68
-			// only include the dot in strings
69
-			$m = ((!$n && $c === '.') || ($c >= '0' && $c <= '9'));
70
-			if ($m !== $n) {
71
-				// next chunk
72
-				$y++;
73
-				$tz[$y] = '';
74
-				$n = $m;
75
-			}
76
-			$tz[$y] .= $c;
77
-			$x++;
78
-		}
79
-		$this->cache[$t] = $tz;
80
-		return $tz;
81
-	}
66
+        while (isset($t[$x])) {
67
+            $c = $t[$x];
68
+            // only include the dot in strings
69
+            $m = ((!$n && $c === '.') || ($c >= '0' && $c <= '9'));
70
+            if ($m !== $n) {
71
+                // next chunk
72
+                $y++;
73
+                $tz[$y] = '';
74
+                $n = $m;
75
+            }
76
+            $tz[$y] .= $c;
77
+            $x++;
78
+        }
79
+        $this->cache[$t] = $tz;
80
+        return $tz;
81
+    }
82 82
 
83
-	/**
84
-	 * Returns the string collator
85
-	 * @return \Collator string collator
86
-	 */
87
-	private function getCollator() {
88
-		if (!isset($this->collator)) {
89
-			// looks like the default is en_US_POSIX which yields wrong sorting with
90
-			// German umlauts, so using en_US instead
91
-			if (class_exists('Collator')) {
92
-				$this->collator = new \Collator('en_US');
93
-			}
94
-			else {
95
-				$this->collator = new \OC\NaturalSort_DefaultCollator();
96
-			}
97
-		}
98
-		return $this->collator;
99
-	}
83
+    /**
84
+     * Returns the string collator
85
+     * @return \Collator string collator
86
+     */
87
+    private function getCollator() {
88
+        if (!isset($this->collator)) {
89
+            // looks like the default is en_US_POSIX which yields wrong sorting with
90
+            // German umlauts, so using en_US instead
91
+            if (class_exists('Collator')) {
92
+                $this->collator = new \Collator('en_US');
93
+            }
94
+            else {
95
+                $this->collator = new \OC\NaturalSort_DefaultCollator();
96
+            }
97
+        }
98
+        return $this->collator;
99
+    }
100 100
 
101
-	/**
102
-	 * Compare two strings to provide a natural sort
103
-	 * @param string $a first string to compare
104
-	 * @param string $b second string to compare
105
-	 * @return int -1 if $b comes before $a, 1 if $a comes before $b
106
-	 * or 0 if the strings are identical
107
-	 */
108
-	public function compare($a, $b) {
109
-		// Needed because PHP doesn't sort correctly when numbers are enclosed in
110
-		// parenthesis, even with NUMERIC_COLLATION enabled.
111
-		// For example it gave ["test (2).txt", "test.txt"]
112
-		// instead of ["test.txt", "test (2).txt"]
113
-		$aa = self::naturalSortChunkify($a);
114
-		$bb = self::naturalSortChunkify($b);
101
+    /**
102
+     * Compare two strings to provide a natural sort
103
+     * @param string $a first string to compare
104
+     * @param string $b second string to compare
105
+     * @return int -1 if $b comes before $a, 1 if $a comes before $b
106
+     * or 0 if the strings are identical
107
+     */
108
+    public function compare($a, $b) {
109
+        // Needed because PHP doesn't sort correctly when numbers are enclosed in
110
+        // parenthesis, even with NUMERIC_COLLATION enabled.
111
+        // For example it gave ["test (2).txt", "test.txt"]
112
+        // instead of ["test.txt", "test (2).txt"]
113
+        $aa = self::naturalSortChunkify($a);
114
+        $bb = self::naturalSortChunkify($b);
115 115
 
116
-		for ($x = 0; isset($aa[$x]) && isset($bb[$x]); $x++) {
117
-			$aChunk = $aa[$x];
118
-			$bChunk = $bb[$x];
119
-			if ($aChunk !== $bChunk) {
120
-				// test first character (character comparison, not number comparison)
121
-				if ($aChunk[0] >= '0' && $aChunk[0] <= '9' && $bChunk[0] >= '0' && $bChunk[0] <= '9') {
122
-					$aNum = (int)$aChunk;
123
-					$bNum = (int)$bChunk;
124
-					return $aNum - $bNum;
125
-				}
126
-				return self::getCollator()->compare($aChunk, $bChunk);
127
-			}
128
-		}
129
-		return count($aa) - count($bb);
130
-	}
116
+        for ($x = 0; isset($aa[$x]) && isset($bb[$x]); $x++) {
117
+            $aChunk = $aa[$x];
118
+            $bChunk = $bb[$x];
119
+            if ($aChunk !== $bChunk) {
120
+                // test first character (character comparison, not number comparison)
121
+                if ($aChunk[0] >= '0' && $aChunk[0] <= '9' && $bChunk[0] >= '0' && $bChunk[0] <= '9') {
122
+                    $aNum = (int)$aChunk;
123
+                    $bNum = (int)$bChunk;
124
+                    return $aNum - $bNum;
125
+                }
126
+                return self::getCollator()->compare($aChunk, $bChunk);
127
+            }
128
+        }
129
+        return count($aa) - count($bb);
130
+    }
131 131
 
132
-	/**
133
-	 * Returns a singleton
134
-	 * @return \OC\NaturalSort instance
135
-	 */
136
-	public static function getInstance() {
137
-		if (!isset(self::$instance)) {
138
-			self::$instance = new \OC\NaturalSort();
139
-		}
140
-		return self::$instance;
141
-	}
132
+    /**
133
+     * Returns a singleton
134
+     * @return \OC\NaturalSort instance
135
+     */
136
+    public static function getInstance() {
137
+        if (!isset(self::$instance)) {
138
+            self::$instance = new \OC\NaturalSort();
139
+        }
140
+        return self::$instance;
141
+    }
142 142
 }
Please login to merge, or discard this patch.