Completed
Pull Request — master (#9293)
by Blizzz
20:13
created
lib/private/Files/Storage/Local.php 2 patches
Indentation   +414 added lines, -414 removed lines patch added patch discarded remove patch
@@ -48,418 +48,418 @@
 block discarded – undo
48 48
  * for local filestore, we only have to map the paths
49 49
  */
50 50
 class Local extends \OC\Files\Storage\Common {
51
-	protected $datadir;
52
-
53
-	protected $dataDirLength;
54
-
55
-	protected $allowSymlinks = false;
56
-
57
-	protected $realDataDir;
58
-
59
-	public function __construct($arguments) {
60
-		if (!isset($arguments['datadir']) || !is_string($arguments['datadir'])) {
61
-			throw new \InvalidArgumentException('No data directory set for local storage');
62
-		}
63
-		$this->datadir = str_replace('//', '/', $arguments['datadir']);
64
-		// some crazy code uses a local storage on root...
65
-		if ($this->datadir === '/') {
66
-			$this->realDataDir = $this->datadir;
67
-		} else {
68
-			$realPath = realpath($this->datadir) ?: $this->datadir;
69
-			$this->realDataDir = rtrim($realPath, '/') . '/';
70
-		}
71
-		if (substr($this->datadir, -1) !== '/') {
72
-			$this->datadir .= '/';
73
-		}
74
-		$this->dataDirLength = strlen($this->realDataDir);
75
-	}
76
-
77
-	public function __destruct() {
78
-	}
79
-
80
-	public function getId() {
81
-		return 'local::' . $this->datadir;
82
-	}
83
-
84
-	public function mkdir($path) {
85
-		return @mkdir($this->getSourcePath($path), 0777, true);
86
-	}
87
-
88
-	public function rmdir($path) {
89
-		if (!$this->isDeletable($path)) {
90
-			return false;
91
-		}
92
-		try {
93
-			$it = new \RecursiveIteratorIterator(
94
-				new \RecursiveDirectoryIterator($this->getSourcePath($path)),
95
-				\RecursiveIteratorIterator::CHILD_FIRST
96
-			);
97
-			/**
98
-			 * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
99
-			 * This bug is fixed in PHP 5.5.9 or before
100
-			 * See #8376
101
-			 */
102
-			$it->rewind();
103
-			while ($it->valid()) {
104
-				/**
105
-				 * @var \SplFileInfo $file
106
-				 */
107
-				$file = $it->current();
108
-				if (in_array($file->getBasename(), array('.', '..'))) {
109
-					$it->next();
110
-					continue;
111
-				} elseif ($file->isDir()) {
112
-					rmdir($file->getPathname());
113
-				} elseif ($file->isFile() || $file->isLink()) {
114
-					unlink($file->getPathname());
115
-				}
116
-				$it->next();
117
-			}
118
-			return rmdir($this->getSourcePath($path));
119
-		} catch (\UnexpectedValueException $e) {
120
-			return false;
121
-		}
122
-	}
123
-
124
-	public function opendir($path) {
125
-		return opendir($this->getSourcePath($path));
126
-	}
127
-
128
-	public function is_dir($path) {
129
-		if (substr($path, -1) == '/') {
130
-			$path = substr($path, 0, -1);
131
-		}
132
-		return is_dir($this->getSourcePath($path));
133
-	}
134
-
135
-	public function is_file($path) {
136
-		return is_file($this->getSourcePath($path));
137
-	}
138
-
139
-	public function stat($path) {
140
-		clearstatcache();
141
-		$fullPath = $this->getSourcePath($path);
142
-		$statResult = stat($fullPath);
143
-		if (PHP_INT_SIZE === 4 && !$this->is_dir($path)) {
144
-			$filesize = $this->filesize($path);
145
-			$statResult['size'] = $filesize;
146
-			$statResult[7] = $filesize;
147
-		}
148
-		return $statResult;
149
-	}
150
-
151
-	public function filetype($path) {
152
-		$filetype = filetype($this->getSourcePath($path));
153
-		if ($filetype == 'link') {
154
-			$filetype = filetype(realpath($this->getSourcePath($path)));
155
-		}
156
-		return $filetype;
157
-	}
158
-
159
-	public function filesize($path) {
160
-		if ($this->is_dir($path)) {
161
-			return 0;
162
-		}
163
-		$fullPath = $this->getSourcePath($path);
164
-		if (PHP_INT_SIZE === 4) {
165
-			$helper = new \OC\LargeFileHelper;
166
-			return $helper->getFileSize($fullPath);
167
-		}
168
-		return filesize($fullPath);
169
-	}
170
-
171
-	public function isReadable($path) {
172
-		return is_readable($this->getSourcePath($path));
173
-	}
174
-
175
-	public function isUpdatable($path) {
176
-		return is_writable($this->getSourcePath($path));
177
-	}
178
-
179
-	public function file_exists($path) {
180
-		return file_exists($this->getSourcePath($path));
181
-	}
182
-
183
-	public function filemtime($path) {
184
-		$fullPath = $this->getSourcePath($path);
185
-		clearstatcache(true, $fullPath);
186
-		if (!$this->file_exists($path)) {
187
-			return false;
188
-		}
189
-		if (PHP_INT_SIZE === 4) {
190
-			$helper = new \OC\LargeFileHelper();
191
-			return $helper->getFileMtime($fullPath);
192
-		}
193
-		return filemtime($fullPath);
194
-	}
195
-
196
-	public function touch($path, $mtime = null) {
197
-		// sets the modification time of the file to the given value.
198
-		// If mtime is nil the current time is set.
199
-		// note that the access time of the file always changes to the current time.
200
-		if ($this->file_exists($path) and !$this->isUpdatable($path)) {
201
-			return false;
202
-		}
203
-		if (!is_null($mtime)) {
204
-			$result = touch($this->getSourcePath($path), $mtime);
205
-		} else {
206
-			$result = touch($this->getSourcePath($path));
207
-		}
208
-		if ($result) {
209
-			clearstatcache(true, $this->getSourcePath($path));
210
-		}
211
-
212
-		return $result;
213
-	}
214
-
215
-	public function file_get_contents($path) {
216
-		return file_get_contents($this->getSourcePath($path));
217
-	}
218
-
219
-	public function file_put_contents($path, $data) {
220
-		return file_put_contents($this->getSourcePath($path), $data);
221
-	}
222
-
223
-	public function unlink($path) {
224
-		if ($this->is_dir($path)) {
225
-			return $this->rmdir($path);
226
-		} else if ($this->is_file($path)) {
227
-			return unlink($this->getSourcePath($path));
228
-		} else {
229
-			return false;
230
-		}
231
-
232
-	}
233
-
234
-	public function rename($path1, $path2) {
235
-		$srcParent = dirname($path1);
236
-		$dstParent = dirname($path2);
237
-
238
-		if (!$this->isUpdatable($srcParent)) {
239
-			\OCP\Util::writeLog('core', 'unable to rename, source directory is not writable : ' . $srcParent, ILogger::ERROR);
240
-			return false;
241
-		}
242
-
243
-		if (!$this->isUpdatable($dstParent)) {
244
-			\OCP\Util::writeLog('core', 'unable to rename, destination directory is not writable : ' . $dstParent, ILogger::ERROR);
245
-			return false;
246
-		}
247
-
248
-		if (!$this->file_exists($path1)) {
249
-			\OCP\Util::writeLog('core', 'unable to rename, file does not exists : ' . $path1, ILogger::ERROR);
250
-			return false;
251
-		}
252
-
253
-		if ($this->is_dir($path2)) {
254
-			$this->rmdir($path2);
255
-		} else if ($this->is_file($path2)) {
256
-			$this->unlink($path2);
257
-		}
258
-
259
-		if ($this->is_dir($path1)) {
260
-			// we can't move folders across devices, use copy instead
261
-			$stat1 = stat(dirname($this->getSourcePath($path1)));
262
-			$stat2 = stat(dirname($this->getSourcePath($path2)));
263
-			if ($stat1['dev'] !== $stat2['dev']) {
264
-				$result = $this->copy($path1, $path2);
265
-				if ($result) {
266
-					$result &= $this->rmdir($path1);
267
-				}
268
-				return $result;
269
-			}
270
-		}
271
-
272
-		return rename($this->getSourcePath($path1), $this->getSourcePath($path2));
273
-	}
274
-
275
-	public function copy($path1, $path2) {
276
-		if ($this->is_dir($path1)) {
277
-			return parent::copy($path1, $path2);
278
-		} else {
279
-			return copy($this->getSourcePath($path1), $this->getSourcePath($path2));
280
-		}
281
-	}
282
-
283
-	public function fopen($path, $mode) {
284
-		return fopen($this->getSourcePath($path), $mode);
285
-	}
286
-
287
-	public function hash($type, $path, $raw = false) {
288
-		return hash_file($type, $this->getSourcePath($path), $raw);
289
-	}
290
-
291
-	public function free_space($path) {
292
-		$sourcePath = $this->getSourcePath($path);
293
-		// using !is_dir because $sourcePath might be a part file or
294
-		// non-existing file, so we'd still want to use the parent dir
295
-		// in such cases
296
-		if (!is_dir($sourcePath)) {
297
-			// disk_free_space doesn't work on files
298
-			$sourcePath = dirname($sourcePath);
299
-		}
300
-		$space = @disk_free_space($sourcePath);
301
-		if ($space === false || is_null($space)) {
302
-			return \OCP\Files\FileInfo::SPACE_UNKNOWN;
303
-		}
304
-		return $space;
305
-	}
306
-
307
-	public function search($query) {
308
-		return $this->searchInDir($query);
309
-	}
310
-
311
-	public function getLocalFile($path) {
312
-		return $this->getSourcePath($path);
313
-	}
314
-
315
-	public function getLocalFolder($path) {
316
-		return $this->getSourcePath($path);
317
-	}
318
-
319
-	/**
320
-	 * @param string $query
321
-	 * @param string $dir
322
-	 * @return array
323
-	 */
324
-	protected function searchInDir($query, $dir = '') {
325
-		$files = array();
326
-		$physicalDir = $this->getSourcePath($dir);
327
-		foreach (scandir($physicalDir) as $item) {
328
-			if (\OC\Files\Filesystem::isIgnoredDir($item))
329
-				continue;
330
-			$physicalItem = $physicalDir . '/' . $item;
331
-
332
-			if (strstr(strtolower($item), strtolower($query)) !== false) {
333
-				$files[] = $dir . '/' . $item;
334
-			}
335
-			if (is_dir($physicalItem)) {
336
-				$files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
337
-			}
338
-		}
339
-		return $files;
340
-	}
341
-
342
-	/**
343
-	 * check if a file or folder has been updated since $time
344
-	 *
345
-	 * @param string $path
346
-	 * @param int $time
347
-	 * @return bool
348
-	 */
349
-	public function hasUpdated($path, $time) {
350
-		if ($this->file_exists($path)) {
351
-			return $this->filemtime($path) > $time;
352
-		} else {
353
-			return true;
354
-		}
355
-	}
356
-
357
-	/**
358
-	 * Get the source path (on disk) of a given path
359
-	 *
360
-	 * @param string $path
361
-	 * @return string
362
-	 * @throws ForbiddenException
363
-	 */
364
-	public function getSourcePath($path) {
365
-		$fullPath = $this->datadir . $path;
366
-		$currentPath = $path;
367
-		if ($this->allowSymlinks || $currentPath === '') {
368
-			return $fullPath;
369
-		}
370
-		$pathToResolve = $fullPath;
371
-		$realPath = realpath($pathToResolve);
372
-		while ($realPath === false) { // for non existing files check the parent directory
373
-			$currentPath = dirname($currentPath);
374
-			if ($currentPath === '' || $currentPath === '.') {
375
-				return $fullPath;
376
-			}
377
-			$realPath = realpath($this->datadir . $currentPath);
378
-		}
379
-		if ($realPath) {
380
-			$realPath = $realPath . '/';
381
-		}
382
-		if (substr($realPath, 0, $this->dataDirLength) === $this->realDataDir) {
383
-			return $fullPath;
384
-		}
385
-
386
-		\OCP\Util::writeLog('core', "Following symlinks is not allowed ('$fullPath' -> '$realPath' not inside '{$this->realDataDir}')", ILogger::ERROR);
387
-		throw new ForbiddenException('Following symlinks is not allowed', false);
388
-	}
389
-
390
-	/**
391
-	 * {@inheritdoc}
392
-	 */
393
-	public function isLocal() {
394
-		return true;
395
-	}
396
-
397
-	/**
398
-	 * get the ETag for a file or folder
399
-	 *
400
-	 * @param string $path
401
-	 * @return string
402
-	 */
403
-	public function getETag($path) {
404
-		if ($this->is_file($path)) {
405
-			$stat = $this->stat($path);
406
-			return md5(
407
-				$stat['mtime'] .
408
-				$stat['ino'] .
409
-				$stat['dev'] .
410
-				$stat['size']
411
-			);
412
-		} else {
413
-			return parent::getETag($path);
414
-		}
415
-	}
416
-
417
-	/**
418
-	 * @param IStorage $sourceStorage
419
-	 * @param string $sourceInternalPath
420
-	 * @param string $targetInternalPath
421
-	 * @param bool $preserveMtime
422
-	 * @return bool
423
-	 */
424
-	public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) {
425
-		if ($sourceStorage->instanceOfStorage(Local::class)) {
426
-			if ($sourceStorage->instanceOfStorage(Jail::class)) {
427
-				/**
428
-				 * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage
429
-				 */
430
-				$sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
431
-			}
432
-			/**
433
-			 * @var \OC\Files\Storage\Local $sourceStorage
434
-			 */
435
-			$rootStorage = new Local(['datadir' => '/']);
436
-			return $rootStorage->copy($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath));
437
-		} else {
438
-			return parent::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
439
-		}
440
-	}
441
-
442
-	/**
443
-	 * @param IStorage $sourceStorage
444
-	 * @param string $sourceInternalPath
445
-	 * @param string $targetInternalPath
446
-	 * @return bool
447
-	 */
448
-	public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
449
-		if ($sourceStorage->instanceOfStorage(Local::class)) {
450
-			if ($sourceStorage->instanceOfStorage(Jail::class)) {
451
-				/**
452
-				 * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage
453
-				 */
454
-				$sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
455
-			}
456
-			/**
457
-			 * @var \OC\Files\Storage\Local $sourceStorage
458
-			 */
459
-			$rootStorage = new Local(['datadir' => '/']);
460
-			return $rootStorage->rename($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath));
461
-		} else {
462
-			return parent::moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
463
-		}
464
-	}
51
+    protected $datadir;
52
+
53
+    protected $dataDirLength;
54
+
55
+    protected $allowSymlinks = false;
56
+
57
+    protected $realDataDir;
58
+
59
+    public function __construct($arguments) {
60
+        if (!isset($arguments['datadir']) || !is_string($arguments['datadir'])) {
61
+            throw new \InvalidArgumentException('No data directory set for local storage');
62
+        }
63
+        $this->datadir = str_replace('//', '/', $arguments['datadir']);
64
+        // some crazy code uses a local storage on root...
65
+        if ($this->datadir === '/') {
66
+            $this->realDataDir = $this->datadir;
67
+        } else {
68
+            $realPath = realpath($this->datadir) ?: $this->datadir;
69
+            $this->realDataDir = rtrim($realPath, '/') . '/';
70
+        }
71
+        if (substr($this->datadir, -1) !== '/') {
72
+            $this->datadir .= '/';
73
+        }
74
+        $this->dataDirLength = strlen($this->realDataDir);
75
+    }
76
+
77
+    public function __destruct() {
78
+    }
79
+
80
+    public function getId() {
81
+        return 'local::' . $this->datadir;
82
+    }
83
+
84
+    public function mkdir($path) {
85
+        return @mkdir($this->getSourcePath($path), 0777, true);
86
+    }
87
+
88
+    public function rmdir($path) {
89
+        if (!$this->isDeletable($path)) {
90
+            return false;
91
+        }
92
+        try {
93
+            $it = new \RecursiveIteratorIterator(
94
+                new \RecursiveDirectoryIterator($this->getSourcePath($path)),
95
+                \RecursiveIteratorIterator::CHILD_FIRST
96
+            );
97
+            /**
98
+             * RecursiveDirectoryIterator on an NFS path isn't iterable with foreach
99
+             * This bug is fixed in PHP 5.5.9 or before
100
+             * See #8376
101
+             */
102
+            $it->rewind();
103
+            while ($it->valid()) {
104
+                /**
105
+                 * @var \SplFileInfo $file
106
+                 */
107
+                $file = $it->current();
108
+                if (in_array($file->getBasename(), array('.', '..'))) {
109
+                    $it->next();
110
+                    continue;
111
+                } elseif ($file->isDir()) {
112
+                    rmdir($file->getPathname());
113
+                } elseif ($file->isFile() || $file->isLink()) {
114
+                    unlink($file->getPathname());
115
+                }
116
+                $it->next();
117
+            }
118
+            return rmdir($this->getSourcePath($path));
119
+        } catch (\UnexpectedValueException $e) {
120
+            return false;
121
+        }
122
+    }
123
+
124
+    public function opendir($path) {
125
+        return opendir($this->getSourcePath($path));
126
+    }
127
+
128
+    public function is_dir($path) {
129
+        if (substr($path, -1) == '/') {
130
+            $path = substr($path, 0, -1);
131
+        }
132
+        return is_dir($this->getSourcePath($path));
133
+    }
134
+
135
+    public function is_file($path) {
136
+        return is_file($this->getSourcePath($path));
137
+    }
138
+
139
+    public function stat($path) {
140
+        clearstatcache();
141
+        $fullPath = $this->getSourcePath($path);
142
+        $statResult = stat($fullPath);
143
+        if (PHP_INT_SIZE === 4 && !$this->is_dir($path)) {
144
+            $filesize = $this->filesize($path);
145
+            $statResult['size'] = $filesize;
146
+            $statResult[7] = $filesize;
147
+        }
148
+        return $statResult;
149
+    }
150
+
151
+    public function filetype($path) {
152
+        $filetype = filetype($this->getSourcePath($path));
153
+        if ($filetype == 'link') {
154
+            $filetype = filetype(realpath($this->getSourcePath($path)));
155
+        }
156
+        return $filetype;
157
+    }
158
+
159
+    public function filesize($path) {
160
+        if ($this->is_dir($path)) {
161
+            return 0;
162
+        }
163
+        $fullPath = $this->getSourcePath($path);
164
+        if (PHP_INT_SIZE === 4) {
165
+            $helper = new \OC\LargeFileHelper;
166
+            return $helper->getFileSize($fullPath);
167
+        }
168
+        return filesize($fullPath);
169
+    }
170
+
171
+    public function isReadable($path) {
172
+        return is_readable($this->getSourcePath($path));
173
+    }
174
+
175
+    public function isUpdatable($path) {
176
+        return is_writable($this->getSourcePath($path));
177
+    }
178
+
179
+    public function file_exists($path) {
180
+        return file_exists($this->getSourcePath($path));
181
+    }
182
+
183
+    public function filemtime($path) {
184
+        $fullPath = $this->getSourcePath($path);
185
+        clearstatcache(true, $fullPath);
186
+        if (!$this->file_exists($path)) {
187
+            return false;
188
+        }
189
+        if (PHP_INT_SIZE === 4) {
190
+            $helper = new \OC\LargeFileHelper();
191
+            return $helper->getFileMtime($fullPath);
192
+        }
193
+        return filemtime($fullPath);
194
+    }
195
+
196
+    public function touch($path, $mtime = null) {
197
+        // sets the modification time of the file to the given value.
198
+        // If mtime is nil the current time is set.
199
+        // note that the access time of the file always changes to the current time.
200
+        if ($this->file_exists($path) and !$this->isUpdatable($path)) {
201
+            return false;
202
+        }
203
+        if (!is_null($mtime)) {
204
+            $result = touch($this->getSourcePath($path), $mtime);
205
+        } else {
206
+            $result = touch($this->getSourcePath($path));
207
+        }
208
+        if ($result) {
209
+            clearstatcache(true, $this->getSourcePath($path));
210
+        }
211
+
212
+        return $result;
213
+    }
214
+
215
+    public function file_get_contents($path) {
216
+        return file_get_contents($this->getSourcePath($path));
217
+    }
218
+
219
+    public function file_put_contents($path, $data) {
220
+        return file_put_contents($this->getSourcePath($path), $data);
221
+    }
222
+
223
+    public function unlink($path) {
224
+        if ($this->is_dir($path)) {
225
+            return $this->rmdir($path);
226
+        } else if ($this->is_file($path)) {
227
+            return unlink($this->getSourcePath($path));
228
+        } else {
229
+            return false;
230
+        }
231
+
232
+    }
233
+
234
+    public function rename($path1, $path2) {
235
+        $srcParent = dirname($path1);
236
+        $dstParent = dirname($path2);
237
+
238
+        if (!$this->isUpdatable($srcParent)) {
239
+            \OCP\Util::writeLog('core', 'unable to rename, source directory is not writable : ' . $srcParent, ILogger::ERROR);
240
+            return false;
241
+        }
242
+
243
+        if (!$this->isUpdatable($dstParent)) {
244
+            \OCP\Util::writeLog('core', 'unable to rename, destination directory is not writable : ' . $dstParent, ILogger::ERROR);
245
+            return false;
246
+        }
247
+
248
+        if (!$this->file_exists($path1)) {
249
+            \OCP\Util::writeLog('core', 'unable to rename, file does not exists : ' . $path1, ILogger::ERROR);
250
+            return false;
251
+        }
252
+
253
+        if ($this->is_dir($path2)) {
254
+            $this->rmdir($path2);
255
+        } else if ($this->is_file($path2)) {
256
+            $this->unlink($path2);
257
+        }
258
+
259
+        if ($this->is_dir($path1)) {
260
+            // we can't move folders across devices, use copy instead
261
+            $stat1 = stat(dirname($this->getSourcePath($path1)));
262
+            $stat2 = stat(dirname($this->getSourcePath($path2)));
263
+            if ($stat1['dev'] !== $stat2['dev']) {
264
+                $result = $this->copy($path1, $path2);
265
+                if ($result) {
266
+                    $result &= $this->rmdir($path1);
267
+                }
268
+                return $result;
269
+            }
270
+        }
271
+
272
+        return rename($this->getSourcePath($path1), $this->getSourcePath($path2));
273
+    }
274
+
275
+    public function copy($path1, $path2) {
276
+        if ($this->is_dir($path1)) {
277
+            return parent::copy($path1, $path2);
278
+        } else {
279
+            return copy($this->getSourcePath($path1), $this->getSourcePath($path2));
280
+        }
281
+    }
282
+
283
+    public function fopen($path, $mode) {
284
+        return fopen($this->getSourcePath($path), $mode);
285
+    }
286
+
287
+    public function hash($type, $path, $raw = false) {
288
+        return hash_file($type, $this->getSourcePath($path), $raw);
289
+    }
290
+
291
+    public function free_space($path) {
292
+        $sourcePath = $this->getSourcePath($path);
293
+        // using !is_dir because $sourcePath might be a part file or
294
+        // non-existing file, so we'd still want to use the parent dir
295
+        // in such cases
296
+        if (!is_dir($sourcePath)) {
297
+            // disk_free_space doesn't work on files
298
+            $sourcePath = dirname($sourcePath);
299
+        }
300
+        $space = @disk_free_space($sourcePath);
301
+        if ($space === false || is_null($space)) {
302
+            return \OCP\Files\FileInfo::SPACE_UNKNOWN;
303
+        }
304
+        return $space;
305
+    }
306
+
307
+    public function search($query) {
308
+        return $this->searchInDir($query);
309
+    }
310
+
311
+    public function getLocalFile($path) {
312
+        return $this->getSourcePath($path);
313
+    }
314
+
315
+    public function getLocalFolder($path) {
316
+        return $this->getSourcePath($path);
317
+    }
318
+
319
+    /**
320
+     * @param string $query
321
+     * @param string $dir
322
+     * @return array
323
+     */
324
+    protected function searchInDir($query, $dir = '') {
325
+        $files = array();
326
+        $physicalDir = $this->getSourcePath($dir);
327
+        foreach (scandir($physicalDir) as $item) {
328
+            if (\OC\Files\Filesystem::isIgnoredDir($item))
329
+                continue;
330
+            $physicalItem = $physicalDir . '/' . $item;
331
+
332
+            if (strstr(strtolower($item), strtolower($query)) !== false) {
333
+                $files[] = $dir . '/' . $item;
334
+            }
335
+            if (is_dir($physicalItem)) {
336
+                $files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
337
+            }
338
+        }
339
+        return $files;
340
+    }
341
+
342
+    /**
343
+     * check if a file or folder has been updated since $time
344
+     *
345
+     * @param string $path
346
+     * @param int $time
347
+     * @return bool
348
+     */
349
+    public function hasUpdated($path, $time) {
350
+        if ($this->file_exists($path)) {
351
+            return $this->filemtime($path) > $time;
352
+        } else {
353
+            return true;
354
+        }
355
+    }
356
+
357
+    /**
358
+     * Get the source path (on disk) of a given path
359
+     *
360
+     * @param string $path
361
+     * @return string
362
+     * @throws ForbiddenException
363
+     */
364
+    public function getSourcePath($path) {
365
+        $fullPath = $this->datadir . $path;
366
+        $currentPath = $path;
367
+        if ($this->allowSymlinks || $currentPath === '') {
368
+            return $fullPath;
369
+        }
370
+        $pathToResolve = $fullPath;
371
+        $realPath = realpath($pathToResolve);
372
+        while ($realPath === false) { // for non existing files check the parent directory
373
+            $currentPath = dirname($currentPath);
374
+            if ($currentPath === '' || $currentPath === '.') {
375
+                return $fullPath;
376
+            }
377
+            $realPath = realpath($this->datadir . $currentPath);
378
+        }
379
+        if ($realPath) {
380
+            $realPath = $realPath . '/';
381
+        }
382
+        if (substr($realPath, 0, $this->dataDirLength) === $this->realDataDir) {
383
+            return $fullPath;
384
+        }
385
+
386
+        \OCP\Util::writeLog('core', "Following symlinks is not allowed ('$fullPath' -> '$realPath' not inside '{$this->realDataDir}')", ILogger::ERROR);
387
+        throw new ForbiddenException('Following symlinks is not allowed', false);
388
+    }
389
+
390
+    /**
391
+     * {@inheritdoc}
392
+     */
393
+    public function isLocal() {
394
+        return true;
395
+    }
396
+
397
+    /**
398
+     * get the ETag for a file or folder
399
+     *
400
+     * @param string $path
401
+     * @return string
402
+     */
403
+    public function getETag($path) {
404
+        if ($this->is_file($path)) {
405
+            $stat = $this->stat($path);
406
+            return md5(
407
+                $stat['mtime'] .
408
+                $stat['ino'] .
409
+                $stat['dev'] .
410
+                $stat['size']
411
+            );
412
+        } else {
413
+            return parent::getETag($path);
414
+        }
415
+    }
416
+
417
+    /**
418
+     * @param IStorage $sourceStorage
419
+     * @param string $sourceInternalPath
420
+     * @param string $targetInternalPath
421
+     * @param bool $preserveMtime
422
+     * @return bool
423
+     */
424
+    public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) {
425
+        if ($sourceStorage->instanceOfStorage(Local::class)) {
426
+            if ($sourceStorage->instanceOfStorage(Jail::class)) {
427
+                /**
428
+                 * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage
429
+                 */
430
+                $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
431
+            }
432
+            /**
433
+             * @var \OC\Files\Storage\Local $sourceStorage
434
+             */
435
+            $rootStorage = new Local(['datadir' => '/']);
436
+            return $rootStorage->copy($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath));
437
+        } else {
438
+            return parent::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
439
+        }
440
+    }
441
+
442
+    /**
443
+     * @param IStorage $sourceStorage
444
+     * @param string $sourceInternalPath
445
+     * @param string $targetInternalPath
446
+     * @return bool
447
+     */
448
+    public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
449
+        if ($sourceStorage->instanceOfStorage(Local::class)) {
450
+            if ($sourceStorage->instanceOfStorage(Jail::class)) {
451
+                /**
452
+                 * @var \OC\Files\Storage\Wrapper\Jail $sourceStorage
453
+                 */
454
+                $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
455
+            }
456
+            /**
457
+             * @var \OC\Files\Storage\Local $sourceStorage
458
+             */
459
+            $rootStorage = new Local(['datadir' => '/']);
460
+            return $rootStorage->rename($sourceStorage->getSourcePath($sourceInternalPath), $this->getSourcePath($targetInternalPath));
461
+        } else {
462
+            return parent::moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
463
+        }
464
+    }
465 465
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
 			$this->realDataDir = $this->datadir;
67 67
 		} else {
68 68
 			$realPath = realpath($this->datadir) ?: $this->datadir;
69
-			$this->realDataDir = rtrim($realPath, '/') . '/';
69
+			$this->realDataDir = rtrim($realPath, '/').'/';
70 70
 		}
71 71
 		if (substr($this->datadir, -1) !== '/') {
72 72
 			$this->datadir .= '/';
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
 	}
79 79
 
80 80
 	public function getId() {
81
-		return 'local::' . $this->datadir;
81
+		return 'local::'.$this->datadir;
82 82
 	}
83 83
 
84 84
 	public function mkdir($path) {
@@ -236,17 +236,17 @@  discard block
 block discarded – undo
236 236
 		$dstParent = dirname($path2);
237 237
 
238 238
 		if (!$this->isUpdatable($srcParent)) {
239
-			\OCP\Util::writeLog('core', 'unable to rename, source directory is not writable : ' . $srcParent, ILogger::ERROR);
239
+			\OCP\Util::writeLog('core', 'unable to rename, source directory is not writable : '.$srcParent, ILogger::ERROR);
240 240
 			return false;
241 241
 		}
242 242
 
243 243
 		if (!$this->isUpdatable($dstParent)) {
244
-			\OCP\Util::writeLog('core', 'unable to rename, destination directory is not writable : ' . $dstParent, ILogger::ERROR);
244
+			\OCP\Util::writeLog('core', 'unable to rename, destination directory is not writable : '.$dstParent, ILogger::ERROR);
245 245
 			return false;
246 246
 		}
247 247
 
248 248
 		if (!$this->file_exists($path1)) {
249
-			\OCP\Util::writeLog('core', 'unable to rename, file does not exists : ' . $path1, ILogger::ERROR);
249
+			\OCP\Util::writeLog('core', 'unable to rename, file does not exists : '.$path1, ILogger::ERROR);
250 250
 			return false;
251 251
 		}
252 252
 
@@ -327,13 +327,13 @@  discard block
 block discarded – undo
327 327
 		foreach (scandir($physicalDir) as $item) {
328 328
 			if (\OC\Files\Filesystem::isIgnoredDir($item))
329 329
 				continue;
330
-			$physicalItem = $physicalDir . '/' . $item;
330
+			$physicalItem = $physicalDir.'/'.$item;
331 331
 
332 332
 			if (strstr(strtolower($item), strtolower($query)) !== false) {
333
-				$files[] = $dir . '/' . $item;
333
+				$files[] = $dir.'/'.$item;
334 334
 			}
335 335
 			if (is_dir($physicalItem)) {
336
-				$files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
336
+				$files = array_merge($files, $this->searchInDir($query, $dir.'/'.$item));
337 337
 			}
338 338
 		}
339 339
 		return $files;
@@ -362,7 +362,7 @@  discard block
 block discarded – undo
362 362
 	 * @throws ForbiddenException
363 363
 	 */
364 364
 	public function getSourcePath($path) {
365
-		$fullPath = $this->datadir . $path;
365
+		$fullPath = $this->datadir.$path;
366 366
 		$currentPath = $path;
367 367
 		if ($this->allowSymlinks || $currentPath === '') {
368 368
 			return $fullPath;
@@ -374,10 +374,10 @@  discard block
 block discarded – undo
374 374
 			if ($currentPath === '' || $currentPath === '.') {
375 375
 				return $fullPath;
376 376
 			}
377
-			$realPath = realpath($this->datadir . $currentPath);
377
+			$realPath = realpath($this->datadir.$currentPath);
378 378
 		}
379 379
 		if ($realPath) {
380
-			$realPath = $realPath . '/';
380
+			$realPath = $realPath.'/';
381 381
 		}
382 382
 		if (substr($realPath, 0, $this->dataDirLength) === $this->realDataDir) {
383 383
 			return $fullPath;
@@ -404,9 +404,9 @@  discard block
 block discarded – undo
404 404
 		if ($this->is_file($path)) {
405 405
 			$stat = $this->stat($path);
406 406
 			return md5(
407
-				$stat['mtime'] .
408
-				$stat['ino'] .
409
-				$stat['dev'] .
407
+				$stat['mtime'].
408
+				$stat['ino'].
409
+				$stat['dev'].
410 410
 				$stat['size']
411 411
 			);
412 412
 		} else {
Please login to merge, or discard this patch.
lib/private/Files/Storage/Common.php 2 patches
Indentation   +736 added lines, -736 removed lines patch added patch discarded remove patch
@@ -71,744 +71,744 @@
 block discarded – undo
71 71
  */
72 72
 abstract class Common implements Storage, ILockingStorage {
73 73
 
74
-	use LocalTempFileTrait;
75
-
76
-	protected $cache;
77
-	protected $scanner;
78
-	protected $watcher;
79
-	protected $propagator;
80
-	protected $storageCache;
81
-	protected $updater;
82
-
83
-	protected $mountOptions = [];
84
-	protected $owner = null;
85
-
86
-	private $shouldLogLocks = null;
87
-	private $logger;
88
-
89
-	public function __construct($parameters) {
90
-	}
91
-
92
-	/**
93
-	 * Remove a file or folder
94
-	 *
95
-	 * @param string $path
96
-	 * @return bool
97
-	 */
98
-	protected function remove($path) {
99
-		if ($this->is_dir($path)) {
100
-			return $this->rmdir($path);
101
-		} else if ($this->is_file($path)) {
102
-			return $this->unlink($path);
103
-		} else {
104
-			return false;
105
-		}
106
-	}
107
-
108
-	public function is_dir($path) {
109
-		return $this->filetype($path) === 'dir';
110
-	}
111
-
112
-	public function is_file($path) {
113
-		return $this->filetype($path) === 'file';
114
-	}
115
-
116
-	public function filesize($path) {
117
-		if ($this->is_dir($path)) {
118
-			return 0; //by definition
119
-		} else {
120
-			$stat = $this->stat($path);
121
-			if (isset($stat['size'])) {
122
-				return $stat['size'];
123
-			} else {
124
-				return 0;
125
-			}
126
-		}
127
-	}
128
-
129
-	public function isReadable($path) {
130
-		// at least check whether it exists
131
-		// subclasses might want to implement this more thoroughly
132
-		return $this->file_exists($path);
133
-	}
134
-
135
-	public function isUpdatable($path) {
136
-		// at least check whether it exists
137
-		// subclasses might want to implement this more thoroughly
138
-		// a non-existing file/folder isn't updatable
139
-		return $this->file_exists($path);
140
-	}
141
-
142
-	public function isCreatable($path) {
143
-		if ($this->is_dir($path) && $this->isUpdatable($path)) {
144
-			return true;
145
-		}
146
-		return false;
147
-	}
148
-
149
-	public function isDeletable($path) {
150
-		if ($path === '' || $path === '/') {
151
-			return false;
152
-		}
153
-		$parent = dirname($path);
154
-		return $this->isUpdatable($parent) && $this->isUpdatable($path);
155
-	}
156
-
157
-	public function isSharable($path) {
158
-		return $this->isReadable($path);
159
-	}
160
-
161
-	public function getPermissions($path) {
162
-		$permissions = 0;
163
-		if ($this->isCreatable($path)) {
164
-			$permissions |= \OCP\Constants::PERMISSION_CREATE;
165
-		}
166
-		if ($this->isReadable($path)) {
167
-			$permissions |= \OCP\Constants::PERMISSION_READ;
168
-		}
169
-		if ($this->isUpdatable($path)) {
170
-			$permissions |= \OCP\Constants::PERMISSION_UPDATE;
171
-		}
172
-		if ($this->isDeletable($path)) {
173
-			$permissions |= \OCP\Constants::PERMISSION_DELETE;
174
-		}
175
-		if ($this->isSharable($path)) {
176
-			$permissions |= \OCP\Constants::PERMISSION_SHARE;
177
-		}
178
-		return $permissions;
179
-	}
180
-
181
-	public function filemtime($path) {
182
-		$stat = $this->stat($path);
183
-		if (isset($stat['mtime']) && $stat['mtime'] > 0) {
184
-			return $stat['mtime'];
185
-		} else {
186
-			return 0;
187
-		}
188
-	}
189
-
190
-	public function file_get_contents($path) {
191
-		$handle = $this->fopen($path, "r");
192
-		if (!$handle) {
193
-			return false;
194
-		}
195
-		$data = stream_get_contents($handle);
196
-		fclose($handle);
197
-		return $data;
198
-	}
199
-
200
-	public function file_put_contents($path, $data) {
201
-		$handle = $this->fopen($path, "w");
202
-		$this->removeCachedFile($path);
203
-		$count = fwrite($handle, $data);
204
-		fclose($handle);
205
-		return $count;
206
-	}
207
-
208
-	public function rename($path1, $path2) {
209
-		$this->remove($path2);
210
-
211
-		$this->removeCachedFile($path1);
212
-		return $this->copy($path1, $path2) and $this->remove($path1);
213
-	}
214
-
215
-	public function copy($path1, $path2) {
216
-		if ($this->is_dir($path1)) {
217
-			$this->remove($path2);
218
-			$dir = $this->opendir($path1);
219
-			$this->mkdir($path2);
220
-			while ($file = readdir($dir)) {
221
-				if (!Filesystem::isIgnoredDir($file)) {
222
-					if (!$this->copy($path1 . '/' . $file, $path2 . '/' . $file)) {
223
-						return false;
224
-					}
225
-				}
226
-			}
227
-			closedir($dir);
228
-			return true;
229
-		} else {
230
-			$source = $this->fopen($path1, 'r');
231
-			$target = $this->fopen($path2, 'w');
232
-			list(, $result) = \OC_Helper::streamCopy($source, $target);
233
-			if (!$result) {
234
-				\OC::$server->getLogger()->warning("Failed to write data while copying $path1 to $path2");
235
-			}
236
-			$this->removeCachedFile($path2);
237
-			return $result;
238
-		}
239
-	}
240
-
241
-	public function getMimeType($path) {
242
-		if ($this->is_dir($path)) {
243
-			return 'httpd/unix-directory';
244
-		} elseif ($this->file_exists($path)) {
245
-			return \OC::$server->getMimeTypeDetector()->detectPath($path);
246
-		} else {
247
-			return false;
248
-		}
249
-	}
250
-
251
-	public function hash($type, $path, $raw = false) {
252
-		$fh = $this->fopen($path, 'rb');
253
-		$ctx = hash_init($type);
254
-		hash_update_stream($ctx, $fh);
255
-		fclose($fh);
256
-		return hash_final($ctx, $raw);
257
-	}
258
-
259
-	public function search($query) {
260
-		return $this->searchInDir($query);
261
-	}
262
-
263
-	public function getLocalFile($path) {
264
-		return $this->getCachedFile($path);
265
-	}
266
-
267
-	/**
268
-	 * @param string $path
269
-	 * @param string $target
270
-	 */
271
-	private function addLocalFolder($path, $target) {
272
-		$dh = $this->opendir($path);
273
-		if (is_resource($dh)) {
274
-			while (($file = readdir($dh)) !== false) {
275
-				if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
276
-					if ($this->is_dir($path . '/' . $file)) {
277
-						mkdir($target . '/' . $file);
278
-						$this->addLocalFolder($path . '/' . $file, $target . '/' . $file);
279
-					} else {
280
-						$tmp = $this->toTmpFile($path . '/' . $file);
281
-						rename($tmp, $target . '/' . $file);
282
-					}
283
-				}
284
-			}
285
-		}
286
-	}
287
-
288
-	/**
289
-	 * @param string $query
290
-	 * @param string $dir
291
-	 * @return array
292
-	 */
293
-	protected function searchInDir($query, $dir = '') {
294
-		$files = array();
295
-		$dh = $this->opendir($dir);
296
-		if (is_resource($dh)) {
297
-			while (($item = readdir($dh)) !== false) {
298
-				if (\OC\Files\Filesystem::isIgnoredDir($item)) continue;
299
-				if (strstr(strtolower($item), strtolower($query)) !== false) {
300
-					$files[] = $dir . '/' . $item;
301
-				}
302
-				if ($this->is_dir($dir . '/' . $item)) {
303
-					$files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
304
-				}
305
-			}
306
-		}
307
-		closedir($dh);
308
-		return $files;
309
-	}
310
-
311
-	/**
312
-	 * check if a file or folder has been updated since $time
313
-	 *
314
-	 * The method is only used to check if the cache needs to be updated. Storage backends that don't support checking
315
-	 * the mtime should always return false here. As a result storage implementations that always return false expect
316
-	 * exclusive access to the backend and will not pick up files that have been added in a way that circumvents
317
-	 * ownClouds filesystem.
318
-	 *
319
-	 * @param string $path
320
-	 * @param int $time
321
-	 * @return bool
322
-	 */
323
-	public function hasUpdated($path, $time) {
324
-		return $this->filemtime($path) > $time;
325
-	}
326
-
327
-	public function getCache($path = '', $storage = null) {
328
-		if (!$storage) {
329
-			$storage = $this;
330
-		}
331
-		if (!isset($storage->cache)) {
332
-			$storage->cache = new Cache($storage);
333
-		}
334
-		return $storage->cache;
335
-	}
336
-
337
-	public function getScanner($path = '', $storage = null) {
338
-		if (!$storage) {
339
-			$storage = $this;
340
-		}
341
-		if (!isset($storage->scanner)) {
342
-			$storage->scanner = new Scanner($storage);
343
-		}
344
-		return $storage->scanner;
345
-	}
346
-
347
-	public function getWatcher($path = '', $storage = null) {
348
-		if (!$storage) {
349
-			$storage = $this;
350
-		}
351
-		if (!isset($this->watcher)) {
352
-			$this->watcher = new Watcher($storage);
353
-			$globalPolicy = \OC::$server->getConfig()->getSystemValue('filesystem_check_changes', Watcher::CHECK_NEVER);
354
-			$this->watcher->setPolicy((int)$this->getMountOption('filesystem_check_changes', $globalPolicy));
355
-		}
356
-		return $this->watcher;
357
-	}
358
-
359
-	/**
360
-	 * get a propagator instance for the cache
361
-	 *
362
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
363
-	 * @return \OC\Files\Cache\Propagator
364
-	 */
365
-	public function getPropagator($storage = null) {
366
-		if (!$storage) {
367
-			$storage = $this;
368
-		}
369
-		if (!isset($storage->propagator)) {
370
-			$storage->propagator = new Propagator($storage, \OC::$server->getDatabaseConnection());
371
-		}
372
-		return $storage->propagator;
373
-	}
374
-
375
-	public function getUpdater($storage = null) {
376
-		if (!$storage) {
377
-			$storage = $this;
378
-		}
379
-		if (!isset($storage->updater)) {
380
-			$storage->updater = new Updater($storage);
381
-		}
382
-		return $storage->updater;
383
-	}
384
-
385
-	public function getStorageCache($storage = null) {
386
-		if (!$storage) {
387
-			$storage = $this;
388
-		}
389
-		if (!isset($this->storageCache)) {
390
-			$this->storageCache = new \OC\Files\Cache\Storage($storage);
391
-		}
392
-		return $this->storageCache;
393
-	}
394
-
395
-	/**
396
-	 * get the owner of a path
397
-	 *
398
-	 * @param string $path The path to get the owner
399
-	 * @return string|false uid or false
400
-	 */
401
-	public function getOwner($path) {
402
-		if ($this->owner === null) {
403
-			$this->owner = \OC_User::getUser();
404
-		}
405
-
406
-		return $this->owner;
407
-	}
408
-
409
-	/**
410
-	 * get the ETag for a file or folder
411
-	 *
412
-	 * @param string $path
413
-	 * @return string
414
-	 */
415
-	public function getETag($path) {
416
-		return uniqid();
417
-	}
418
-
419
-	/**
420
-	 * clean a path, i.e. remove all redundant '.' and '..'
421
-	 * making sure that it can't point to higher than '/'
422
-	 *
423
-	 * @param string $path The path to clean
424
-	 * @return string cleaned path
425
-	 */
426
-	public function cleanPath($path) {
427
-		if (strlen($path) == 0 or $path[0] != '/') {
428
-			$path = '/' . $path;
429
-		}
430
-
431
-		$output = array();
432
-		foreach (explode('/', $path) as $chunk) {
433
-			if ($chunk == '..') {
434
-				array_pop($output);
435
-			} else if ($chunk == '.') {
436
-			} else {
437
-				$output[] = $chunk;
438
-			}
439
-		}
440
-		return implode('/', $output);
441
-	}
442
-
443
-	/**
444
-	 * Test a storage for availability
445
-	 *
446
-	 * @return bool
447
-	 */
448
-	public function test() {
449
-		try {
450
-			if ($this->stat('')) {
451
-				return true;
452
-			}
453
-			\OC::$server->getLogger()->info("External storage not available: stat() failed");
454
-			return false;
455
-		} catch (\Exception $e) {
456
-			\OC::$server->getLogger()->info("External storage not available: " . $e->getMessage());
457
-			\OC::$server->getLogger()->logException($e, ['level' => ILogger::DEBUG]);
458
-			return false;
459
-		}
460
-	}
461
-
462
-	/**
463
-	 * get the free space in the storage
464
-	 *
465
-	 * @param string $path
466
-	 * @return int|false
467
-	 */
468
-	public function free_space($path) {
469
-		return \OCP\Files\FileInfo::SPACE_UNKNOWN;
470
-	}
471
-
472
-	/**
473
-	 * {@inheritdoc}
474
-	 */
475
-	public function isLocal() {
476
-		// the common implementation returns a temporary file by
477
-		// default, which is not local
478
-		return false;
479
-	}
480
-
481
-	/**
482
-	 * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class
483
-	 *
484
-	 * @param string $class
485
-	 * @return bool
486
-	 */
487
-	public function instanceOfStorage($class) {
488
-		if (ltrim($class, '\\') === 'OC\Files\Storage\Shared') {
489
-			// FIXME Temporary fix to keep existing checks working
490
-			$class = '\OCA\Files_Sharing\SharedStorage';
491
-		}
492
-		return is_a($this, $class);
493
-	}
494
-
495
-	/**
496
-	 * A custom storage implementation can return an url for direct download of a give file.
497
-	 *
498
-	 * For now the returned array can hold the parameter url - in future more attributes might follow.
499
-	 *
500
-	 * @param string $path
501
-	 * @return array|false
502
-	 */
503
-	public function getDirectDownload($path) {
504
-		return [];
505
-	}
506
-
507
-	/**
508
-	 * @inheritdoc
509
-	 * @throws InvalidPathException
510
-	 */
511
-	public function verifyPath($path, $fileName) {
512
-
513
-		// verify empty and dot files
514
-		$trimmed = trim($fileName);
515
-		if ($trimmed === '') {
516
-			throw new EmptyFileNameException();
517
-		}
518
-
519
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
520
-			throw new InvalidDirectoryException();
521
-		}
522
-
523
-		if (!\OC::$server->getDatabaseConnection()->supports4ByteText()) {
524
-			// verify database - e.g. mysql only 3-byte chars
525
-			if (preg_match('%(?:
74
+    use LocalTempFileTrait;
75
+
76
+    protected $cache;
77
+    protected $scanner;
78
+    protected $watcher;
79
+    protected $propagator;
80
+    protected $storageCache;
81
+    protected $updater;
82
+
83
+    protected $mountOptions = [];
84
+    protected $owner = null;
85
+
86
+    private $shouldLogLocks = null;
87
+    private $logger;
88
+
89
+    public function __construct($parameters) {
90
+    }
91
+
92
+    /**
93
+     * Remove a file or folder
94
+     *
95
+     * @param string $path
96
+     * @return bool
97
+     */
98
+    protected function remove($path) {
99
+        if ($this->is_dir($path)) {
100
+            return $this->rmdir($path);
101
+        } else if ($this->is_file($path)) {
102
+            return $this->unlink($path);
103
+        } else {
104
+            return false;
105
+        }
106
+    }
107
+
108
+    public function is_dir($path) {
109
+        return $this->filetype($path) === 'dir';
110
+    }
111
+
112
+    public function is_file($path) {
113
+        return $this->filetype($path) === 'file';
114
+    }
115
+
116
+    public function filesize($path) {
117
+        if ($this->is_dir($path)) {
118
+            return 0; //by definition
119
+        } else {
120
+            $stat = $this->stat($path);
121
+            if (isset($stat['size'])) {
122
+                return $stat['size'];
123
+            } else {
124
+                return 0;
125
+            }
126
+        }
127
+    }
128
+
129
+    public function isReadable($path) {
130
+        // at least check whether it exists
131
+        // subclasses might want to implement this more thoroughly
132
+        return $this->file_exists($path);
133
+    }
134
+
135
+    public function isUpdatable($path) {
136
+        // at least check whether it exists
137
+        // subclasses might want to implement this more thoroughly
138
+        // a non-existing file/folder isn't updatable
139
+        return $this->file_exists($path);
140
+    }
141
+
142
+    public function isCreatable($path) {
143
+        if ($this->is_dir($path) && $this->isUpdatable($path)) {
144
+            return true;
145
+        }
146
+        return false;
147
+    }
148
+
149
+    public function isDeletable($path) {
150
+        if ($path === '' || $path === '/') {
151
+            return false;
152
+        }
153
+        $parent = dirname($path);
154
+        return $this->isUpdatable($parent) && $this->isUpdatable($path);
155
+    }
156
+
157
+    public function isSharable($path) {
158
+        return $this->isReadable($path);
159
+    }
160
+
161
+    public function getPermissions($path) {
162
+        $permissions = 0;
163
+        if ($this->isCreatable($path)) {
164
+            $permissions |= \OCP\Constants::PERMISSION_CREATE;
165
+        }
166
+        if ($this->isReadable($path)) {
167
+            $permissions |= \OCP\Constants::PERMISSION_READ;
168
+        }
169
+        if ($this->isUpdatable($path)) {
170
+            $permissions |= \OCP\Constants::PERMISSION_UPDATE;
171
+        }
172
+        if ($this->isDeletable($path)) {
173
+            $permissions |= \OCP\Constants::PERMISSION_DELETE;
174
+        }
175
+        if ($this->isSharable($path)) {
176
+            $permissions |= \OCP\Constants::PERMISSION_SHARE;
177
+        }
178
+        return $permissions;
179
+    }
180
+
181
+    public function filemtime($path) {
182
+        $stat = $this->stat($path);
183
+        if (isset($stat['mtime']) && $stat['mtime'] > 0) {
184
+            return $stat['mtime'];
185
+        } else {
186
+            return 0;
187
+        }
188
+    }
189
+
190
+    public function file_get_contents($path) {
191
+        $handle = $this->fopen($path, "r");
192
+        if (!$handle) {
193
+            return false;
194
+        }
195
+        $data = stream_get_contents($handle);
196
+        fclose($handle);
197
+        return $data;
198
+    }
199
+
200
+    public function file_put_contents($path, $data) {
201
+        $handle = $this->fopen($path, "w");
202
+        $this->removeCachedFile($path);
203
+        $count = fwrite($handle, $data);
204
+        fclose($handle);
205
+        return $count;
206
+    }
207
+
208
+    public function rename($path1, $path2) {
209
+        $this->remove($path2);
210
+
211
+        $this->removeCachedFile($path1);
212
+        return $this->copy($path1, $path2) and $this->remove($path1);
213
+    }
214
+
215
+    public function copy($path1, $path2) {
216
+        if ($this->is_dir($path1)) {
217
+            $this->remove($path2);
218
+            $dir = $this->opendir($path1);
219
+            $this->mkdir($path2);
220
+            while ($file = readdir($dir)) {
221
+                if (!Filesystem::isIgnoredDir($file)) {
222
+                    if (!$this->copy($path1 . '/' . $file, $path2 . '/' . $file)) {
223
+                        return false;
224
+                    }
225
+                }
226
+            }
227
+            closedir($dir);
228
+            return true;
229
+        } else {
230
+            $source = $this->fopen($path1, 'r');
231
+            $target = $this->fopen($path2, 'w');
232
+            list(, $result) = \OC_Helper::streamCopy($source, $target);
233
+            if (!$result) {
234
+                \OC::$server->getLogger()->warning("Failed to write data while copying $path1 to $path2");
235
+            }
236
+            $this->removeCachedFile($path2);
237
+            return $result;
238
+        }
239
+    }
240
+
241
+    public function getMimeType($path) {
242
+        if ($this->is_dir($path)) {
243
+            return 'httpd/unix-directory';
244
+        } elseif ($this->file_exists($path)) {
245
+            return \OC::$server->getMimeTypeDetector()->detectPath($path);
246
+        } else {
247
+            return false;
248
+        }
249
+    }
250
+
251
+    public function hash($type, $path, $raw = false) {
252
+        $fh = $this->fopen($path, 'rb');
253
+        $ctx = hash_init($type);
254
+        hash_update_stream($ctx, $fh);
255
+        fclose($fh);
256
+        return hash_final($ctx, $raw);
257
+    }
258
+
259
+    public function search($query) {
260
+        return $this->searchInDir($query);
261
+    }
262
+
263
+    public function getLocalFile($path) {
264
+        return $this->getCachedFile($path);
265
+    }
266
+
267
+    /**
268
+     * @param string $path
269
+     * @param string $target
270
+     */
271
+    private function addLocalFolder($path, $target) {
272
+        $dh = $this->opendir($path);
273
+        if (is_resource($dh)) {
274
+            while (($file = readdir($dh)) !== false) {
275
+                if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
276
+                    if ($this->is_dir($path . '/' . $file)) {
277
+                        mkdir($target . '/' . $file);
278
+                        $this->addLocalFolder($path . '/' . $file, $target . '/' . $file);
279
+                    } else {
280
+                        $tmp = $this->toTmpFile($path . '/' . $file);
281
+                        rename($tmp, $target . '/' . $file);
282
+                    }
283
+                }
284
+            }
285
+        }
286
+    }
287
+
288
+    /**
289
+     * @param string $query
290
+     * @param string $dir
291
+     * @return array
292
+     */
293
+    protected function searchInDir($query, $dir = '') {
294
+        $files = array();
295
+        $dh = $this->opendir($dir);
296
+        if (is_resource($dh)) {
297
+            while (($item = readdir($dh)) !== false) {
298
+                if (\OC\Files\Filesystem::isIgnoredDir($item)) continue;
299
+                if (strstr(strtolower($item), strtolower($query)) !== false) {
300
+                    $files[] = $dir . '/' . $item;
301
+                }
302
+                if ($this->is_dir($dir . '/' . $item)) {
303
+                    $files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
304
+                }
305
+            }
306
+        }
307
+        closedir($dh);
308
+        return $files;
309
+    }
310
+
311
+    /**
312
+     * check if a file or folder has been updated since $time
313
+     *
314
+     * The method is only used to check if the cache needs to be updated. Storage backends that don't support checking
315
+     * the mtime should always return false here. As a result storage implementations that always return false expect
316
+     * exclusive access to the backend and will not pick up files that have been added in a way that circumvents
317
+     * ownClouds filesystem.
318
+     *
319
+     * @param string $path
320
+     * @param int $time
321
+     * @return bool
322
+     */
323
+    public function hasUpdated($path, $time) {
324
+        return $this->filemtime($path) > $time;
325
+    }
326
+
327
+    public function getCache($path = '', $storage = null) {
328
+        if (!$storage) {
329
+            $storage = $this;
330
+        }
331
+        if (!isset($storage->cache)) {
332
+            $storage->cache = new Cache($storage);
333
+        }
334
+        return $storage->cache;
335
+    }
336
+
337
+    public function getScanner($path = '', $storage = null) {
338
+        if (!$storage) {
339
+            $storage = $this;
340
+        }
341
+        if (!isset($storage->scanner)) {
342
+            $storage->scanner = new Scanner($storage);
343
+        }
344
+        return $storage->scanner;
345
+    }
346
+
347
+    public function getWatcher($path = '', $storage = null) {
348
+        if (!$storage) {
349
+            $storage = $this;
350
+        }
351
+        if (!isset($this->watcher)) {
352
+            $this->watcher = new Watcher($storage);
353
+            $globalPolicy = \OC::$server->getConfig()->getSystemValue('filesystem_check_changes', Watcher::CHECK_NEVER);
354
+            $this->watcher->setPolicy((int)$this->getMountOption('filesystem_check_changes', $globalPolicy));
355
+        }
356
+        return $this->watcher;
357
+    }
358
+
359
+    /**
360
+     * get a propagator instance for the cache
361
+     *
362
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
363
+     * @return \OC\Files\Cache\Propagator
364
+     */
365
+    public function getPropagator($storage = null) {
366
+        if (!$storage) {
367
+            $storage = $this;
368
+        }
369
+        if (!isset($storage->propagator)) {
370
+            $storage->propagator = new Propagator($storage, \OC::$server->getDatabaseConnection());
371
+        }
372
+        return $storage->propagator;
373
+    }
374
+
375
+    public function getUpdater($storage = null) {
376
+        if (!$storage) {
377
+            $storage = $this;
378
+        }
379
+        if (!isset($storage->updater)) {
380
+            $storage->updater = new Updater($storage);
381
+        }
382
+        return $storage->updater;
383
+    }
384
+
385
+    public function getStorageCache($storage = null) {
386
+        if (!$storage) {
387
+            $storage = $this;
388
+        }
389
+        if (!isset($this->storageCache)) {
390
+            $this->storageCache = new \OC\Files\Cache\Storage($storage);
391
+        }
392
+        return $this->storageCache;
393
+    }
394
+
395
+    /**
396
+     * get the owner of a path
397
+     *
398
+     * @param string $path The path to get the owner
399
+     * @return string|false uid or false
400
+     */
401
+    public function getOwner($path) {
402
+        if ($this->owner === null) {
403
+            $this->owner = \OC_User::getUser();
404
+        }
405
+
406
+        return $this->owner;
407
+    }
408
+
409
+    /**
410
+     * get the ETag for a file or folder
411
+     *
412
+     * @param string $path
413
+     * @return string
414
+     */
415
+    public function getETag($path) {
416
+        return uniqid();
417
+    }
418
+
419
+    /**
420
+     * clean a path, i.e. remove all redundant '.' and '..'
421
+     * making sure that it can't point to higher than '/'
422
+     *
423
+     * @param string $path The path to clean
424
+     * @return string cleaned path
425
+     */
426
+    public function cleanPath($path) {
427
+        if (strlen($path) == 0 or $path[0] != '/') {
428
+            $path = '/' . $path;
429
+        }
430
+
431
+        $output = array();
432
+        foreach (explode('/', $path) as $chunk) {
433
+            if ($chunk == '..') {
434
+                array_pop($output);
435
+            } else if ($chunk == '.') {
436
+            } else {
437
+                $output[] = $chunk;
438
+            }
439
+        }
440
+        return implode('/', $output);
441
+    }
442
+
443
+    /**
444
+     * Test a storage for availability
445
+     *
446
+     * @return bool
447
+     */
448
+    public function test() {
449
+        try {
450
+            if ($this->stat('')) {
451
+                return true;
452
+            }
453
+            \OC::$server->getLogger()->info("External storage not available: stat() failed");
454
+            return false;
455
+        } catch (\Exception $e) {
456
+            \OC::$server->getLogger()->info("External storage not available: " . $e->getMessage());
457
+            \OC::$server->getLogger()->logException($e, ['level' => ILogger::DEBUG]);
458
+            return false;
459
+        }
460
+    }
461
+
462
+    /**
463
+     * get the free space in the storage
464
+     *
465
+     * @param string $path
466
+     * @return int|false
467
+     */
468
+    public function free_space($path) {
469
+        return \OCP\Files\FileInfo::SPACE_UNKNOWN;
470
+    }
471
+
472
+    /**
473
+     * {@inheritdoc}
474
+     */
475
+    public function isLocal() {
476
+        // the common implementation returns a temporary file by
477
+        // default, which is not local
478
+        return false;
479
+    }
480
+
481
+    /**
482
+     * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class
483
+     *
484
+     * @param string $class
485
+     * @return bool
486
+     */
487
+    public function instanceOfStorage($class) {
488
+        if (ltrim($class, '\\') === 'OC\Files\Storage\Shared') {
489
+            // FIXME Temporary fix to keep existing checks working
490
+            $class = '\OCA\Files_Sharing\SharedStorage';
491
+        }
492
+        return is_a($this, $class);
493
+    }
494
+
495
+    /**
496
+     * A custom storage implementation can return an url for direct download of a give file.
497
+     *
498
+     * For now the returned array can hold the parameter url - in future more attributes might follow.
499
+     *
500
+     * @param string $path
501
+     * @return array|false
502
+     */
503
+    public function getDirectDownload($path) {
504
+        return [];
505
+    }
506
+
507
+    /**
508
+     * @inheritdoc
509
+     * @throws InvalidPathException
510
+     */
511
+    public function verifyPath($path, $fileName) {
512
+
513
+        // verify empty and dot files
514
+        $trimmed = trim($fileName);
515
+        if ($trimmed === '') {
516
+            throw new EmptyFileNameException();
517
+        }
518
+
519
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
520
+            throw new InvalidDirectoryException();
521
+        }
522
+
523
+        if (!\OC::$server->getDatabaseConnection()->supports4ByteText()) {
524
+            // verify database - e.g. mysql only 3-byte chars
525
+            if (preg_match('%(?:
526 526
       \xF0[\x90-\xBF][\x80-\xBF]{2}      # planes 1-3
527 527
     | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
528 528
     | \xF4[\x80-\x8F][\x80-\xBF]{2}      # plane 16
529 529
 )%xs', $fileName)) {
530
-				throw new InvalidCharacterInPathException();
531
-			}
532
-		}
533
-
534
-		if (isset($fileName[255])) {
535
-			throw new FileNameTooLongException();
536
-		}
537
-
538
-		// NOTE: $path will remain unverified for now
539
-		$this->verifyPosixPath($fileName);
540
-	}
541
-
542
-	/**
543
-	 * @param string $fileName
544
-	 * @throws InvalidPathException
545
-	 */
546
-	protected function verifyPosixPath($fileName) {
547
-		$fileName = trim($fileName);
548
-		$this->scanForInvalidCharacters($fileName, "\\/");
549
-		$reservedNames = ['*'];
550
-		if (in_array($fileName, $reservedNames)) {
551
-			throw new ReservedWordException();
552
-		}
553
-	}
554
-
555
-	/**
556
-	 * @param string $fileName
557
-	 * @param string $invalidChars
558
-	 * @throws InvalidPathException
559
-	 */
560
-	private function scanForInvalidCharacters($fileName, $invalidChars) {
561
-		foreach (str_split($invalidChars) as $char) {
562
-			if (strpos($fileName, $char) !== false) {
563
-				throw new InvalidCharacterInPathException();
564
-			}
565
-		}
566
-
567
-		$sanitizedFileName = filter_var($fileName, FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW);
568
-		if ($sanitizedFileName !== $fileName) {
569
-			throw new InvalidCharacterInPathException();
570
-		}
571
-	}
572
-
573
-	/**
574
-	 * @param array $options
575
-	 */
576
-	public function setMountOptions(array $options) {
577
-		$this->mountOptions = $options;
578
-	}
579
-
580
-	/**
581
-	 * @param string $name
582
-	 * @param mixed $default
583
-	 * @return mixed
584
-	 */
585
-	public function getMountOption($name, $default = null) {
586
-		return isset($this->mountOptions[$name]) ? $this->mountOptions[$name] : $default;
587
-	}
588
-
589
-	/**
590
-	 * @param IStorage $sourceStorage
591
-	 * @param string $sourceInternalPath
592
-	 * @param string $targetInternalPath
593
-	 * @param bool $preserveMtime
594
-	 * @return bool
595
-	 */
596
-	public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) {
597
-		if ($sourceStorage === $this) {
598
-			return $this->copy($sourceInternalPath, $targetInternalPath);
599
-		}
600
-
601
-		if ($sourceStorage->is_dir($sourceInternalPath)) {
602
-			$dh = $sourceStorage->opendir($sourceInternalPath);
603
-			$result = $this->mkdir($targetInternalPath);
604
-			if (is_resource($dh)) {
605
-				while ($result and ($file = readdir($dh)) !== false) {
606
-					if (!Filesystem::isIgnoredDir($file)) {
607
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file);
608
-					}
609
-				}
610
-			}
611
-		} else {
612
-			$source = $sourceStorage->fopen($sourceInternalPath, 'r');
613
-			// TODO: call fopen in a way that we execute again all storage wrappers
614
-			// to avoid that we bypass storage wrappers which perform important actions
615
-			// for this operation. Same is true for all other operations which
616
-			// are not the same as the original one.Once this is fixed we also
617
-			// need to adjust the encryption wrapper.
618
-			$target = $this->fopen($targetInternalPath, 'w');
619
-			list(, $result) = \OC_Helper::streamCopy($source, $target);
620
-			if ($result and $preserveMtime) {
621
-				$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
622
-			}
623
-			fclose($source);
624
-			fclose($target);
625
-
626
-			if (!$result) {
627
-				// delete partially written target file
628
-				$this->unlink($targetInternalPath);
629
-				// delete cache entry that was created by fopen
630
-				$this->getCache()->remove($targetInternalPath);
631
-			}
632
-		}
633
-		return (bool)$result;
634
-	}
635
-
636
-	/**
637
-	 * @param IStorage $sourceStorage
638
-	 * @param string $sourceInternalPath
639
-	 * @param string $targetInternalPath
640
-	 * @return bool
641
-	 */
642
-	public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
643
-		if ($sourceStorage === $this) {
644
-			return $this->rename($sourceInternalPath, $targetInternalPath);
645
-		}
646
-
647
-		if (!$sourceStorage->isDeletable($sourceInternalPath)) {
648
-			return false;
649
-		}
650
-
651
-		$result = $this->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, true);
652
-		if ($result) {
653
-			if ($sourceStorage->is_dir($sourceInternalPath)) {
654
-				$result &= $sourceStorage->rmdir($sourceInternalPath);
655
-			} else {
656
-				$result &= $sourceStorage->unlink($sourceInternalPath);
657
-			}
658
-		}
659
-		return $result;
660
-	}
661
-
662
-	/**
663
-	 * @inheritdoc
664
-	 */
665
-	public function getMetaData($path) {
666
-		$permissions = $this->getPermissions($path);
667
-		if (!$permissions & \OCP\Constants::PERMISSION_READ) {
668
-			//can't read, nothing we can do
669
-			return null;
670
-		}
671
-
672
-		$data = [];
673
-		$data['mimetype'] = $this->getMimeType($path);
674
-		$data['mtime'] = $this->filemtime($path);
675
-		if ($data['mtime'] === false) {
676
-			$data['mtime'] = time();
677
-		}
678
-		if ($data['mimetype'] == 'httpd/unix-directory') {
679
-			$data['size'] = -1; //unknown
680
-		} else {
681
-			$data['size'] = $this->filesize($path);
682
-		}
683
-		$data['etag'] = $this->getETag($path);
684
-		$data['storage_mtime'] = $data['mtime'];
685
-		$data['permissions'] = $permissions;
686
-
687
-		return $data;
688
-	}
689
-
690
-	/**
691
-	 * @param string $path
692
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
693
-	 * @param \OCP\Lock\ILockingProvider $provider
694
-	 * @throws \OCP\Lock\LockedException
695
-	 */
696
-	public function acquireLock($path, $type, ILockingProvider $provider) {
697
-		$logger = $this->getLockLogger();
698
-		if ($logger) {
699
-			$typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
700
-			$logger->info(
701
-				sprintf(
702
-					'acquire %s lock on "%s" on storage "%s"',
703
-					$typeString,
704
-					$path,
705
-					$this->getId()
706
-				),
707
-				[
708
-					'app' => 'locking',
709
-				]
710
-			);
711
-		}
712
-		try {
713
-			$provider->acquireLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
714
-		} catch (LockedException $e) {
715
-			if ($logger) {
716
-				$logger->logException($e);
717
-			}
718
-			throw $e;
719
-		}
720
-	}
721
-
722
-	/**
723
-	 * @param string $path
724
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
725
-	 * @param \OCP\Lock\ILockingProvider $provider
726
-	 * @throws \OCP\Lock\LockedException
727
-	 */
728
-	public function releaseLock($path, $type, ILockingProvider $provider) {
729
-		$logger = $this->getLockLogger();
730
-		if ($logger) {
731
-			$typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
732
-			$logger->info(
733
-				sprintf(
734
-					'release %s lock on "%s" on storage "%s"',
735
-					$typeString,
736
-					$path,
737
-					$this->getId()
738
-				),
739
-				[
740
-					'app' => 'locking',
741
-				]
742
-			);
743
-		}
744
-		try {
745
-			$provider->releaseLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
746
-		} catch (LockedException $e) {
747
-			if ($logger) {
748
-				$logger->logException($e);
749
-			}
750
-			throw $e;
751
-		}
752
-	}
753
-
754
-	/**
755
-	 * @param string $path
756
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
757
-	 * @param \OCP\Lock\ILockingProvider $provider
758
-	 * @throws \OCP\Lock\LockedException
759
-	 */
760
-	public function changeLock($path, $type, ILockingProvider $provider) {
761
-		$logger = $this->getLockLogger();
762
-		if ($logger) {
763
-			$typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
764
-			$logger->info(
765
-				sprintf(
766
-					'change lock on "%s" to %s on storage "%s"',
767
-					$path,
768
-					$typeString,
769
-					$this->getId()
770
-				),
771
-				[
772
-					'app' => 'locking',
773
-				]
774
-			);
775
-		}
776
-		try {
777
-			$provider->changeLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
778
-		} catch (LockedException $e) {
779
-			if ($logger) {
780
-				$logger->logException($e);
781
-			}
782
-			throw $e;
783
-		}
784
-	}
785
-
786
-	private function getLockLogger() {
787
-		if (is_null($this->shouldLogLocks)) {
788
-			$this->shouldLogLocks = \OC::$server->getConfig()->getSystemValue('filelocking.debug', false);
789
-			$this->logger = $this->shouldLogLocks ? \OC::$server->getLogger() : null;
790
-		}
791
-		return $this->logger;
792
-	}
793
-
794
-	/**
795
-	 * @return array [ available, last_checked ]
796
-	 */
797
-	public function getAvailability() {
798
-		return $this->getStorageCache()->getAvailability();
799
-	}
800
-
801
-	/**
802
-	 * @param bool $isAvailable
803
-	 */
804
-	public function setAvailability($isAvailable) {
805
-		$this->getStorageCache()->setAvailability($isAvailable);
806
-	}
807
-
808
-	/**
809
-	 * @return bool
810
-	 */
811
-	public function needsPartFile() {
812
-		return true;
813
-	}
530
+                throw new InvalidCharacterInPathException();
531
+            }
532
+        }
533
+
534
+        if (isset($fileName[255])) {
535
+            throw new FileNameTooLongException();
536
+        }
537
+
538
+        // NOTE: $path will remain unverified for now
539
+        $this->verifyPosixPath($fileName);
540
+    }
541
+
542
+    /**
543
+     * @param string $fileName
544
+     * @throws InvalidPathException
545
+     */
546
+    protected function verifyPosixPath($fileName) {
547
+        $fileName = trim($fileName);
548
+        $this->scanForInvalidCharacters($fileName, "\\/");
549
+        $reservedNames = ['*'];
550
+        if (in_array($fileName, $reservedNames)) {
551
+            throw new ReservedWordException();
552
+        }
553
+    }
554
+
555
+    /**
556
+     * @param string $fileName
557
+     * @param string $invalidChars
558
+     * @throws InvalidPathException
559
+     */
560
+    private function scanForInvalidCharacters($fileName, $invalidChars) {
561
+        foreach (str_split($invalidChars) as $char) {
562
+            if (strpos($fileName, $char) !== false) {
563
+                throw new InvalidCharacterInPathException();
564
+            }
565
+        }
566
+
567
+        $sanitizedFileName = filter_var($fileName, FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW);
568
+        if ($sanitizedFileName !== $fileName) {
569
+            throw new InvalidCharacterInPathException();
570
+        }
571
+    }
572
+
573
+    /**
574
+     * @param array $options
575
+     */
576
+    public function setMountOptions(array $options) {
577
+        $this->mountOptions = $options;
578
+    }
579
+
580
+    /**
581
+     * @param string $name
582
+     * @param mixed $default
583
+     * @return mixed
584
+     */
585
+    public function getMountOption($name, $default = null) {
586
+        return isset($this->mountOptions[$name]) ? $this->mountOptions[$name] : $default;
587
+    }
588
+
589
+    /**
590
+     * @param IStorage $sourceStorage
591
+     * @param string $sourceInternalPath
592
+     * @param string $targetInternalPath
593
+     * @param bool $preserveMtime
594
+     * @return bool
595
+     */
596
+    public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) {
597
+        if ($sourceStorage === $this) {
598
+            return $this->copy($sourceInternalPath, $targetInternalPath);
599
+        }
600
+
601
+        if ($sourceStorage->is_dir($sourceInternalPath)) {
602
+            $dh = $sourceStorage->opendir($sourceInternalPath);
603
+            $result = $this->mkdir($targetInternalPath);
604
+            if (is_resource($dh)) {
605
+                while ($result and ($file = readdir($dh)) !== false) {
606
+                    if (!Filesystem::isIgnoredDir($file)) {
607
+                        $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file);
608
+                    }
609
+                }
610
+            }
611
+        } else {
612
+            $source = $sourceStorage->fopen($sourceInternalPath, 'r');
613
+            // TODO: call fopen in a way that we execute again all storage wrappers
614
+            // to avoid that we bypass storage wrappers which perform important actions
615
+            // for this operation. Same is true for all other operations which
616
+            // are not the same as the original one.Once this is fixed we also
617
+            // need to adjust the encryption wrapper.
618
+            $target = $this->fopen($targetInternalPath, 'w');
619
+            list(, $result) = \OC_Helper::streamCopy($source, $target);
620
+            if ($result and $preserveMtime) {
621
+                $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
622
+            }
623
+            fclose($source);
624
+            fclose($target);
625
+
626
+            if (!$result) {
627
+                // delete partially written target file
628
+                $this->unlink($targetInternalPath);
629
+                // delete cache entry that was created by fopen
630
+                $this->getCache()->remove($targetInternalPath);
631
+            }
632
+        }
633
+        return (bool)$result;
634
+    }
635
+
636
+    /**
637
+     * @param IStorage $sourceStorage
638
+     * @param string $sourceInternalPath
639
+     * @param string $targetInternalPath
640
+     * @return bool
641
+     */
642
+    public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
643
+        if ($sourceStorage === $this) {
644
+            return $this->rename($sourceInternalPath, $targetInternalPath);
645
+        }
646
+
647
+        if (!$sourceStorage->isDeletable($sourceInternalPath)) {
648
+            return false;
649
+        }
650
+
651
+        $result = $this->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, true);
652
+        if ($result) {
653
+            if ($sourceStorage->is_dir($sourceInternalPath)) {
654
+                $result &= $sourceStorage->rmdir($sourceInternalPath);
655
+            } else {
656
+                $result &= $sourceStorage->unlink($sourceInternalPath);
657
+            }
658
+        }
659
+        return $result;
660
+    }
661
+
662
+    /**
663
+     * @inheritdoc
664
+     */
665
+    public function getMetaData($path) {
666
+        $permissions = $this->getPermissions($path);
667
+        if (!$permissions & \OCP\Constants::PERMISSION_READ) {
668
+            //can't read, nothing we can do
669
+            return null;
670
+        }
671
+
672
+        $data = [];
673
+        $data['mimetype'] = $this->getMimeType($path);
674
+        $data['mtime'] = $this->filemtime($path);
675
+        if ($data['mtime'] === false) {
676
+            $data['mtime'] = time();
677
+        }
678
+        if ($data['mimetype'] == 'httpd/unix-directory') {
679
+            $data['size'] = -1; //unknown
680
+        } else {
681
+            $data['size'] = $this->filesize($path);
682
+        }
683
+        $data['etag'] = $this->getETag($path);
684
+        $data['storage_mtime'] = $data['mtime'];
685
+        $data['permissions'] = $permissions;
686
+
687
+        return $data;
688
+    }
689
+
690
+    /**
691
+     * @param string $path
692
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
693
+     * @param \OCP\Lock\ILockingProvider $provider
694
+     * @throws \OCP\Lock\LockedException
695
+     */
696
+    public function acquireLock($path, $type, ILockingProvider $provider) {
697
+        $logger = $this->getLockLogger();
698
+        if ($logger) {
699
+            $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
700
+            $logger->info(
701
+                sprintf(
702
+                    'acquire %s lock on "%s" on storage "%s"',
703
+                    $typeString,
704
+                    $path,
705
+                    $this->getId()
706
+                ),
707
+                [
708
+                    'app' => 'locking',
709
+                ]
710
+            );
711
+        }
712
+        try {
713
+            $provider->acquireLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
714
+        } catch (LockedException $e) {
715
+            if ($logger) {
716
+                $logger->logException($e);
717
+            }
718
+            throw $e;
719
+        }
720
+    }
721
+
722
+    /**
723
+     * @param string $path
724
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
725
+     * @param \OCP\Lock\ILockingProvider $provider
726
+     * @throws \OCP\Lock\LockedException
727
+     */
728
+    public function releaseLock($path, $type, ILockingProvider $provider) {
729
+        $logger = $this->getLockLogger();
730
+        if ($logger) {
731
+            $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
732
+            $logger->info(
733
+                sprintf(
734
+                    'release %s lock on "%s" on storage "%s"',
735
+                    $typeString,
736
+                    $path,
737
+                    $this->getId()
738
+                ),
739
+                [
740
+                    'app' => 'locking',
741
+                ]
742
+            );
743
+        }
744
+        try {
745
+            $provider->releaseLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
746
+        } catch (LockedException $e) {
747
+            if ($logger) {
748
+                $logger->logException($e);
749
+            }
750
+            throw $e;
751
+        }
752
+    }
753
+
754
+    /**
755
+     * @param string $path
756
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
757
+     * @param \OCP\Lock\ILockingProvider $provider
758
+     * @throws \OCP\Lock\LockedException
759
+     */
760
+    public function changeLock($path, $type, ILockingProvider $provider) {
761
+        $logger = $this->getLockLogger();
762
+        if ($logger) {
763
+            $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
764
+            $logger->info(
765
+                sprintf(
766
+                    'change lock on "%s" to %s on storage "%s"',
767
+                    $path,
768
+                    $typeString,
769
+                    $this->getId()
770
+                ),
771
+                [
772
+                    'app' => 'locking',
773
+                ]
774
+            );
775
+        }
776
+        try {
777
+            $provider->changeLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
778
+        } catch (LockedException $e) {
779
+            if ($logger) {
780
+                $logger->logException($e);
781
+            }
782
+            throw $e;
783
+        }
784
+    }
785
+
786
+    private function getLockLogger() {
787
+        if (is_null($this->shouldLogLocks)) {
788
+            $this->shouldLogLocks = \OC::$server->getConfig()->getSystemValue('filelocking.debug', false);
789
+            $this->logger = $this->shouldLogLocks ? \OC::$server->getLogger() : null;
790
+        }
791
+        return $this->logger;
792
+    }
793
+
794
+    /**
795
+     * @return array [ available, last_checked ]
796
+     */
797
+    public function getAvailability() {
798
+        return $this->getStorageCache()->getAvailability();
799
+    }
800
+
801
+    /**
802
+     * @param bool $isAvailable
803
+     */
804
+    public function setAvailability($isAvailable) {
805
+        $this->getStorageCache()->setAvailability($isAvailable);
806
+    }
807
+
808
+    /**
809
+     * @return bool
810
+     */
811
+    public function needsPartFile() {
812
+        return true;
813
+    }
814 814
 }
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 			$this->mkdir($path2);
220 220
 			while ($file = readdir($dir)) {
221 221
 				if (!Filesystem::isIgnoredDir($file)) {
222
-					if (!$this->copy($path1 . '/' . $file, $path2 . '/' . $file)) {
222
+					if (!$this->copy($path1.'/'.$file, $path2.'/'.$file)) {
223 223
 						return false;
224 224
 					}
225 225
 				}
@@ -273,12 +273,12 @@  discard block
 block discarded – undo
273 273
 		if (is_resource($dh)) {
274 274
 			while (($file = readdir($dh)) !== false) {
275 275
 				if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
276
-					if ($this->is_dir($path . '/' . $file)) {
277
-						mkdir($target . '/' . $file);
278
-						$this->addLocalFolder($path . '/' . $file, $target . '/' . $file);
276
+					if ($this->is_dir($path.'/'.$file)) {
277
+						mkdir($target.'/'.$file);
278
+						$this->addLocalFolder($path.'/'.$file, $target.'/'.$file);
279 279
 					} else {
280
-						$tmp = $this->toTmpFile($path . '/' . $file);
281
-						rename($tmp, $target . '/' . $file);
280
+						$tmp = $this->toTmpFile($path.'/'.$file);
281
+						rename($tmp, $target.'/'.$file);
282 282
 					}
283 283
 				}
284 284
 			}
@@ -297,10 +297,10 @@  discard block
 block discarded – undo
297 297
 			while (($item = readdir($dh)) !== false) {
298 298
 				if (\OC\Files\Filesystem::isIgnoredDir($item)) continue;
299 299
 				if (strstr(strtolower($item), strtolower($query)) !== false) {
300
-					$files[] = $dir . '/' . $item;
300
+					$files[] = $dir.'/'.$item;
301 301
 				}
302
-				if ($this->is_dir($dir . '/' . $item)) {
303
-					$files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
302
+				if ($this->is_dir($dir.'/'.$item)) {
303
+					$files = array_merge($files, $this->searchInDir($query, $dir.'/'.$item));
304 304
 				}
305 305
 			}
306 306
 		}
@@ -351,7 +351,7 @@  discard block
 block discarded – undo
351 351
 		if (!isset($this->watcher)) {
352 352
 			$this->watcher = new Watcher($storage);
353 353
 			$globalPolicy = \OC::$server->getConfig()->getSystemValue('filesystem_check_changes', Watcher::CHECK_NEVER);
354
-			$this->watcher->setPolicy((int)$this->getMountOption('filesystem_check_changes', $globalPolicy));
354
+			$this->watcher->setPolicy((int) $this->getMountOption('filesystem_check_changes', $globalPolicy));
355 355
 		}
356 356
 		return $this->watcher;
357 357
 	}
@@ -425,7 +425,7 @@  discard block
 block discarded – undo
425 425
 	 */
426 426
 	public function cleanPath($path) {
427 427
 		if (strlen($path) == 0 or $path[0] != '/') {
428
-			$path = '/' . $path;
428
+			$path = '/'.$path;
429 429
 		}
430 430
 
431 431
 		$output = array();
@@ -453,7 +453,7 @@  discard block
 block discarded – undo
453 453
 			\OC::$server->getLogger()->info("External storage not available: stat() failed");
454 454
 			return false;
455 455
 		} catch (\Exception $e) {
456
-			\OC::$server->getLogger()->info("External storage not available: " . $e->getMessage());
456
+			\OC::$server->getLogger()->info("External storage not available: ".$e->getMessage());
457 457
 			\OC::$server->getLogger()->logException($e, ['level' => ILogger::DEBUG]);
458 458
 			return false;
459 459
 		}
@@ -604,7 +604,7 @@  discard block
 block discarded – undo
604 604
 			if (is_resource($dh)) {
605 605
 				while ($result and ($file = readdir($dh)) !== false) {
606 606
 					if (!Filesystem::isIgnoredDir($file)) {
607
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file);
607
+						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath.'/'.$file, $targetInternalPath.'/'.$file);
608 608
 					}
609 609
 				}
610 610
 			}
@@ -630,7 +630,7 @@  discard block
 block discarded – undo
630 630
 				$this->getCache()->remove($targetInternalPath);
631 631
 			}
632 632
 		}
633
-		return (bool)$result;
633
+		return (bool) $result;
634 634
 	}
635 635
 
636 636
 	/**
@@ -710,7 +710,7 @@  discard block
 block discarded – undo
710 710
 			);
711 711
 		}
712 712
 		try {
713
-			$provider->acquireLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
713
+			$provider->acquireLock('files/'.md5($this->getId().'::'.trim($path, '/')), $type);
714 714
 		} catch (LockedException $e) {
715 715
 			if ($logger) {
716 716
 				$logger->logException($e);
@@ -742,7 +742,7 @@  discard block
 block discarded – undo
742 742
 			);
743 743
 		}
744 744
 		try {
745
-			$provider->releaseLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
745
+			$provider->releaseLock('files/'.md5($this->getId().'::'.trim($path, '/')), $type);
746 746
 		} catch (LockedException $e) {
747 747
 			if ($logger) {
748 748
 				$logger->logException($e);
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
 			);
775 775
 		}
776 776
 		try {
777
-			$provider->changeLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
777
+			$provider->changeLock('files/'.md5($this->getId().'::'.trim($path, '/')), $type);
778 778
 		} catch (LockedException $e) {
779 779
 			if ($logger) {
780 780
 				$logger->logException($e);
Please login to merge, or discard this patch.
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/File.php 2 patches
Indentation   +151 added lines, -151 removed lines patch added patch discarded remove patch
@@ -48,159 +48,159 @@
 block discarded – undo
48 48
  */
49 49
 
50 50
 class File implements IWriter, IFileBased {
51
-	/** @var string */
52
-	protected $logFile;
53
-	/** @var IConfig */
54
-	private $config;
51
+    /** @var string */
52
+    protected $logFile;
53
+    /** @var IConfig */
54
+    private $config;
55 55
 
56
-	public function __construct(string $path, string $fallbackPath = '', IConfig $config) {
57
-		$this->logFile = $path;
58
-		if (!file_exists($this->logFile)) {
59
-			if(
60
-				(
61
-					!is_writable(dirname($this->logFile))
62
-					|| !touch($this->logFile)
63
-				)
64
-				&& $fallbackPath !== ''
65
-			) {
66
-				$this->logFile = $fallbackPath;
67
-			}
68
-		}
69
-		$this->config = $config;
70
-	}
56
+    public function __construct(string $path, string $fallbackPath = '', IConfig $config) {
57
+        $this->logFile = $path;
58
+        if (!file_exists($this->logFile)) {
59
+            if(
60
+                (
61
+                    !is_writable(dirname($this->logFile))
62
+                    || !touch($this->logFile)
63
+                )
64
+                && $fallbackPath !== ''
65
+            ) {
66
+                $this->logFile = $fallbackPath;
67
+            }
68
+        }
69
+        $this->config = $config;
70
+    }
71 71
 
72
-	/**
73
-	 * write a message in the log
74
-	 * @param string $app
75
-	 * @param string|array $message
76
-	 * @param int $level
77
-	 */
78
-	public function write(string $app, $message, int $level) {
79
-		// default to ISO8601
80
-		$format = $this->config->getSystemValue('logdateformat', \DateTime::ATOM);
81
-		$logTimeZone = $this->config->getSystemValue('logtimezone', 'UTC');
82
-		try {
83
-			$timezone = new \DateTimeZone($logTimeZone);
84
-		} catch (\Exception $e) {
85
-			$timezone = new \DateTimeZone('UTC');
86
-		}
87
-		$time = \DateTime::createFromFormat("U.u", number_format(microtime(true), 4, ".", ""));
88
-		if ($time === false) {
89
-			$time = new \DateTime(null, $timezone);
90
-		} else {
91
-			// apply timezone if $time is created from UNIX timestamp
92
-			$time->setTimezone($timezone);
93
-		}
94
-		$request = \OC::$server->getRequest();
95
-		$reqId = $request->getId();
96
-		$remoteAddr = $request->getRemoteAddress();
97
-		// remove username/passwords from URLs before writing the to the log file
98
-		$time = $time->format($format);
99
-		$url = ($request->getRequestUri() !== '') ? $request->getRequestUri() : '--';
100
-		$method = is_string($request->getMethod()) ? $request->getMethod() : '--';
101
-		if($this->config->getSystemValue('installed', false)) {
102
-			$user = \OC_User::getUser() ? \OC_User::getUser() : '--';
103
-		} else {
104
-			$user = '--';
105
-		}
106
-		$userAgent = $request->getHeader('User-Agent');
107
-		if ($userAgent === '') {
108
-			$userAgent = '--';
109
-		}
110
-		$version = $this->config->getSystemValue('version', '');
111
-		$entry = compact(
112
-			'reqId',
113
-			'level',
114
-			'time',
115
-			'remoteAddr',
116
-			'user',
117
-			'app',
118
-			'method',
119
-			'url',
120
-			'message',
121
-			'userAgent',
122
-			'version'
123
-		);
124
-		// PHP's json_encode only accept proper UTF-8 strings, loop over all
125
-		// elements to ensure that they are properly UTF-8 compliant or convert
126
-		// them manually.
127
-		foreach($entry as $key => $value) {
128
-			if(is_string($value)) {
129
-				$testEncode = json_encode($value);
130
-				if($testEncode === false) {
131
-					$entry[$key] = utf8_encode($value);
132
-				}
133
-			}
134
-		}
135
-		$entry = json_encode($entry, JSON_PARTIAL_OUTPUT_ON_ERROR);
136
-		$handle = @fopen($this->logFile, 'a');
137
-		if ((fileperms($this->logFile) & 0777) != 0640) {
138
-			@chmod($this->logFile, 0640);
139
-		}
140
-		if ($handle) {
141
-			fwrite($handle, $entry."\n");
142
-			fclose($handle);
143
-		} else {
144
-			// Fall back to error_log
145
-			error_log($entry);
146
-		}
147
-		if (php_sapi_name() === 'cli-server') {
148
-			error_log($message, 4);
149
-		}
150
-	}
72
+    /**
73
+     * write a message in the log
74
+     * @param string $app
75
+     * @param string|array $message
76
+     * @param int $level
77
+     */
78
+    public function write(string $app, $message, int $level) {
79
+        // default to ISO8601
80
+        $format = $this->config->getSystemValue('logdateformat', \DateTime::ATOM);
81
+        $logTimeZone = $this->config->getSystemValue('logtimezone', 'UTC');
82
+        try {
83
+            $timezone = new \DateTimeZone($logTimeZone);
84
+        } catch (\Exception $e) {
85
+            $timezone = new \DateTimeZone('UTC');
86
+        }
87
+        $time = \DateTime::createFromFormat("U.u", number_format(microtime(true), 4, ".", ""));
88
+        if ($time === false) {
89
+            $time = new \DateTime(null, $timezone);
90
+        } else {
91
+            // apply timezone if $time is created from UNIX timestamp
92
+            $time->setTimezone($timezone);
93
+        }
94
+        $request = \OC::$server->getRequest();
95
+        $reqId = $request->getId();
96
+        $remoteAddr = $request->getRemoteAddress();
97
+        // remove username/passwords from URLs before writing the to the log file
98
+        $time = $time->format($format);
99
+        $url = ($request->getRequestUri() !== '') ? $request->getRequestUri() : '--';
100
+        $method = is_string($request->getMethod()) ? $request->getMethod() : '--';
101
+        if($this->config->getSystemValue('installed', false)) {
102
+            $user = \OC_User::getUser() ? \OC_User::getUser() : '--';
103
+        } else {
104
+            $user = '--';
105
+        }
106
+        $userAgent = $request->getHeader('User-Agent');
107
+        if ($userAgent === '') {
108
+            $userAgent = '--';
109
+        }
110
+        $version = $this->config->getSystemValue('version', '');
111
+        $entry = compact(
112
+            'reqId',
113
+            'level',
114
+            'time',
115
+            'remoteAddr',
116
+            'user',
117
+            'app',
118
+            'method',
119
+            'url',
120
+            'message',
121
+            'userAgent',
122
+            'version'
123
+        );
124
+        // PHP's json_encode only accept proper UTF-8 strings, loop over all
125
+        // elements to ensure that they are properly UTF-8 compliant or convert
126
+        // them manually.
127
+        foreach($entry as $key => $value) {
128
+            if(is_string($value)) {
129
+                $testEncode = json_encode($value);
130
+                if($testEncode === false) {
131
+                    $entry[$key] = utf8_encode($value);
132
+                }
133
+            }
134
+        }
135
+        $entry = json_encode($entry, JSON_PARTIAL_OUTPUT_ON_ERROR);
136
+        $handle = @fopen($this->logFile, 'a');
137
+        if ((fileperms($this->logFile) & 0777) != 0640) {
138
+            @chmod($this->logFile, 0640);
139
+        }
140
+        if ($handle) {
141
+            fwrite($handle, $entry."\n");
142
+            fclose($handle);
143
+        } else {
144
+            // Fall back to error_log
145
+            error_log($entry);
146
+        }
147
+        if (php_sapi_name() === 'cli-server') {
148
+            error_log($message, 4);
149
+        }
150
+    }
151 151
 
152
-	/**
153
-	 * get entries from the log in reverse chronological order
154
-	 * @param int $limit
155
-	 * @param int $offset
156
-	 * @return array
157
-	 */
158
-	public function getEntries($limit=50, $offset=0) {
159
-		$minLevel = $this->config->getSystemValue("loglevel", ILogger::WARN);
160
-		$entries = array();
161
-		$handle = @fopen($this->logFile, 'rb');
162
-		if ($handle) {
163
-			fseek($handle, 0, SEEK_END);
164
-			$pos = ftell($handle);
165
-			$line = '';
166
-			$entriesCount = 0;
167
-			$lines = 0;
168
-			// Loop through each character of the file looking for new lines
169
-			while ($pos >= 0 && ($limit === null ||$entriesCount < $limit)) {
170
-				fseek($handle, $pos);
171
-				$ch = fgetc($handle);
172
-				if ($ch == "\n" || $pos == 0) {
173
-					if ($line != '') {
174
-						// Add the first character if at the start of the file,
175
-						// because it doesn't hit the else in the loop
176
-						if ($pos == 0) {
177
-							$line = $ch.$line;
178
-						}
179
-						$entry = json_decode($line);
180
-						// Add the line as an entry if it is passed the offset and is equal or above the log level
181
-						if ($entry->level >= $minLevel) {
182
-							$lines++;
183
-							if ($lines > $offset) {
184
-								$entries[] = $entry;
185
-								$entriesCount++;
186
-							}
187
-						}
188
-						$line = '';
189
-					}
190
-				} else {
191
-					$line = $ch.$line;
192
-				}
193
-				$pos--;
194
-			}
195
-			fclose($handle);
196
-		}
197
-		return $entries;
198
-	}
152
+    /**
153
+     * get entries from the log in reverse chronological order
154
+     * @param int $limit
155
+     * @param int $offset
156
+     * @return array
157
+     */
158
+    public function getEntries($limit=50, $offset=0) {
159
+        $minLevel = $this->config->getSystemValue("loglevel", ILogger::WARN);
160
+        $entries = array();
161
+        $handle = @fopen($this->logFile, 'rb');
162
+        if ($handle) {
163
+            fseek($handle, 0, SEEK_END);
164
+            $pos = ftell($handle);
165
+            $line = '';
166
+            $entriesCount = 0;
167
+            $lines = 0;
168
+            // Loop through each character of the file looking for new lines
169
+            while ($pos >= 0 && ($limit === null ||$entriesCount < $limit)) {
170
+                fseek($handle, $pos);
171
+                $ch = fgetc($handle);
172
+                if ($ch == "\n" || $pos == 0) {
173
+                    if ($line != '') {
174
+                        // Add the first character if at the start of the file,
175
+                        // because it doesn't hit the else in the loop
176
+                        if ($pos == 0) {
177
+                            $line = $ch.$line;
178
+                        }
179
+                        $entry = json_decode($line);
180
+                        // Add the line as an entry if it is passed the offset and is equal or above the log level
181
+                        if ($entry->level >= $minLevel) {
182
+                            $lines++;
183
+                            if ($lines > $offset) {
184
+                                $entries[] = $entry;
185
+                                $entriesCount++;
186
+                            }
187
+                        }
188
+                        $line = '';
189
+                    }
190
+                } else {
191
+                    $line = $ch.$line;
192
+                }
193
+                $pos--;
194
+            }
195
+            fclose($handle);
196
+        }
197
+        return $entries;
198
+    }
199 199
 
200
-	/**
201
-	 * @return string
202
-	 */
203
-	public function getLogFilePath() {
204
-		return $this->logFile;
205
-	}
200
+    /**
201
+     * @return string
202
+     */
203
+    public function getLogFilePath() {
204
+        return $this->logFile;
205
+    }
206 206
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
 	public function __construct(string $path, string $fallbackPath = '', IConfig $config) {
57 57
 		$this->logFile = $path;
58 58
 		if (!file_exists($this->logFile)) {
59
-			if(
59
+			if (
60 60
 				(
61 61
 					!is_writable(dirname($this->logFile))
62 62
 					|| !touch($this->logFile)
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 		$time = $time->format($format);
99 99
 		$url = ($request->getRequestUri() !== '') ? $request->getRequestUri() : '--';
100 100
 		$method = is_string($request->getMethod()) ? $request->getMethod() : '--';
101
-		if($this->config->getSystemValue('installed', false)) {
101
+		if ($this->config->getSystemValue('installed', false)) {
102 102
 			$user = \OC_User::getUser() ? \OC_User::getUser() : '--';
103 103
 		} else {
104 104
 			$user = '--';
@@ -124,10 +124,10 @@  discard block
 block discarded – undo
124 124
 		// PHP's json_encode only accept proper UTF-8 strings, loop over all
125 125
 		// elements to ensure that they are properly UTF-8 compliant or convert
126 126
 		// them manually.
127
-		foreach($entry as $key => $value) {
128
-			if(is_string($value)) {
127
+		foreach ($entry as $key => $value) {
128
+			if (is_string($value)) {
129 129
 				$testEncode = json_encode($value);
130
-				if($testEncode === false) {
130
+				if ($testEncode === false) {
131 131
 					$entry[$key] = utf8_encode($value);
132 132
 				}
133 133
 			}
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 	 * @param int $offset
156 156
 	 * @return array
157 157
 	 */
158
-	public function getEntries($limit=50, $offset=0) {
158
+	public function getEntries($limit = 50, $offset = 0) {
159 159
 		$minLevel = $this->config->getSystemValue("loglevel", ILogger::WARN);
160 160
 		$entries = array();
161 161
 		$handle = @fopen($this->logFile, 'rb');
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
 			$entriesCount = 0;
167 167
 			$lines = 0;
168 168
 			// Loop through each character of the file looking for new lines
169
-			while ($pos >= 0 && ($limit === null ||$entriesCount < $limit)) {
169
+			while ($pos >= 0 && ($limit === null || $entriesCount < $limit)) {
170 170
 				fseek($handle, $pos);
171 171
 				$ch = fgetc($handle);
172 172
 				if ($ch == "\n" || $pos == 0) {
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.