Completed
Pull Request — master (#5623)
by Thomas
16:49
created
apps/files_external/lib/Lib/Storage/Swift.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -616,6 +616,9 @@
 block discarded – undo
616 616
 		return $this->container;
617 617
 	}
618 618
 
619
+	/**
620
+	 * @param string $path
621
+	 */
619 622
 	public function writeBack($tmpFile, $path) {
620 623
 		$fileData = fopen($tmpFile, 'r');
621 624
 		$this->getContainer()->uploadObject($path, $fileData);
Please login to merge, or discard this patch.
Indentation   +601 added lines, -601 removed lines patch added patch discarded remove patch
@@ -48,606 +48,606 @@
 block discarded – undo
48 48
 
49 49
 class Swift extends \OC\Files\Storage\Common {
50 50
 
51
-	/**
52
-	 * @var \OpenCloud\ObjectStore\Service
53
-	 */
54
-	private $connection;
55
-	/**
56
-	 * @var \OpenCloud\ObjectStore\Resource\Container
57
-	 */
58
-	private $container;
59
-	/**
60
-	 * @var \OpenCloud\OpenStack
61
-	 */
62
-	private $anchor;
63
-	/**
64
-	 * @var string
65
-	 */
66
-	private $bucket;
67
-	/**
68
-	 * Connection parameters
69
-	 *
70
-	 * @var array
71
-	 */
72
-	private $params;
73
-
74
-	/** @var string  */
75
-	private $id;
76
-
77
-	/**
78
-	 * @var array
79
-	 */
80
-	private static $tmpFiles = array();
81
-
82
-	/**
83
-	 * Key value cache mapping path to data object. Maps path to
84
-	 * \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject for existing
85
-	 * paths and path to false for not existing paths.
86
-	 * @var \OCP\ICache
87
-	 */
88
-	private $objectCache;
89
-
90
-	/**
91
-	 * @param string $path
92
-	 */
93
-	private function normalizePath($path) {
94
-		$path = trim($path, '/');
95
-
96
-		if (!$path) {
97
-			$path = '.';
98
-		}
99
-
100
-		$path = str_replace('#', '%23', $path);
101
-
102
-		return $path;
103
-	}
104
-
105
-	const SUBCONTAINER_FILE = '.subcontainers';
106
-
107
-	/**
108
-	 * translate directory path to container name
109
-	 *
110
-	 * @param string $path
111
-	 * @return string
112
-	 */
113
-
114
-	/**
115
-	 * Fetches an object from the API.
116
-	 * If the object is cached already or a
117
-	 * failed "doesn't exist" response was cached,
118
-	 * that one will be returned.
119
-	 *
120
-	 * @param string $path
121
-	 * @return \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject|bool object
122
-	 * or false if the object did not exist
123
-	 */
124
-	private function fetchObject($path) {
125
-		if ($this->objectCache->hasKey($path)) {
126
-			// might be "false" if object did not exist from last check
127
-			return $this->objectCache->get($path);
128
-		}
129
-		try {
130
-			$object = $this->getContainer()->getPartialObject($path);
131
-			$this->objectCache->set($path, $object);
132
-			return $object;
133
-		} catch (ClientErrorResponseException $e) {
134
-			// this exception happens when the object does not exist, which
135
-			// is expected in most cases
136
-			$this->objectCache->set($path, false);
137
-			return false;
138
-		} catch (ClientErrorResponseException $e) {
139
-			// Expected response is "404 Not Found", so only log if it isn't
140
-			if ($e->getResponse()->getStatusCode() !== 404) {
141
-				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
142
-			}
143
-			return false;
144
-		}
145
-	}
146
-
147
-	/**
148
-	 * Returns whether the given path exists.
149
-	 *
150
-	 * @param string $path
151
-	 *
152
-	 * @return bool true if the object exist, false otherwise
153
-	 */
154
-	private function doesObjectExist($path) {
155
-		return $this->fetchObject($path) !== false;
156
-	}
157
-
158
-	public function __construct($params) {
159
-		if ((empty($params['key']) and empty($params['password']))
160
-			or empty($params['user']) or empty($params['bucket'])
161
-			or empty($params['region'])
162
-		) {
163
-			throw new \Exception("API Key or password, Username, Bucket and Region have to be configured.");
164
-		}
165
-
166
-		$this->id = 'swift::' . $params['user'] . md5($params['bucket']);
167
-
168
-		$bucketUrl = Url::factory($params['bucket']);
169
-		if ($bucketUrl->isAbsolute()) {
170
-			$this->bucket = end(($bucketUrl->getPathSegments()));
171
-			$params['endpoint_url'] = $bucketUrl->addPath('..')->normalizePath();
172
-		} else {
173
-			$this->bucket = $params['bucket'];
174
-		}
175
-
176
-		if (empty($params['url'])) {
177
-			$params['url'] = 'https://identity.api.rackspacecloud.com/v2.0/';
178
-		}
179
-
180
-		if (empty($params['service_name'])) {
181
-			$params['service_name'] = 'cloudFiles';
182
-		}
183
-
184
-		$this->params = $params;
185
-		// FIXME: private class...
186
-		$this->objectCache = new \OC\Cache\CappedMemoryCache();
187
-	}
188
-
189
-	public function mkdir($path) {
190
-		$path = $this->normalizePath($path);
191
-
192
-		if ($this->is_dir($path)) {
193
-			return false;
194
-		}
195
-
196
-		if ($path !== '.') {
197
-			$path .= '/';
198
-		}
199
-
200
-		try {
201
-			$customHeaders = array('content-type' => 'httpd/unix-directory');
202
-			$metadataHeaders = DataObject::stockHeaders(array());
203
-			$allHeaders = $customHeaders + $metadataHeaders;
204
-			$this->getContainer()->uploadObject($path, '', $allHeaders);
205
-			// invalidate so that the next access gets the real object
206
-			// with all properties
207
-			$this->objectCache->remove($path);
208
-		} catch (Exceptions\CreateUpdateError $e) {
209
-			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
210
-			return false;
211
-		}
212
-
213
-		return true;
214
-	}
215
-
216
-	public function file_exists($path) {
217
-		$path = $this->normalizePath($path);
218
-
219
-		if ($path !== '.' && $this->is_dir($path)) {
220
-			$path .= '/';
221
-		}
222
-
223
-		return $this->doesObjectExist($path);
224
-	}
225
-
226
-	public function rmdir($path) {
227
-		$path = $this->normalizePath($path);
228
-
229
-		if (!$this->is_dir($path) || !$this->isDeletable($path)) {
230
-			return false;
231
-		}
232
-
233
-		$dh = $this->opendir($path);
234
-		while ($file = readdir($dh)) {
235
-			if (\OC\Files\Filesystem::isIgnoredDir($file)) {
236
-				continue;
237
-			}
238
-
239
-			if ($this->is_dir($path . '/' . $file)) {
240
-				$this->rmdir($path . '/' . $file);
241
-			} else {
242
-				$this->unlink($path . '/' . $file);
243
-			}
244
-		}
245
-
246
-		try {
247
-			$this->getContainer()->dataObject()->setName($path . '/')->delete();
248
-			$this->objectCache->remove($path . '/');
249
-		} catch (Exceptions\DeleteError $e) {
250
-			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
251
-			return false;
252
-		}
253
-
254
-		return true;
255
-	}
256
-
257
-	public function opendir($path) {
258
-		$path = $this->normalizePath($path);
259
-
260
-		if ($path === '.') {
261
-			$path = '';
262
-		} else {
263
-			$path .= '/';
264
-		}
265
-
266
-		$path = str_replace('%23', '#', $path); // the prefix is sent as a query param, so revert the encoding of #
267
-
268
-		try {
269
-			$files = array();
270
-			/** @var OpenCloud\Common\Collection $objects */
271
-			$objects = $this->getContainer()->objectList(array(
272
-				'prefix' => $path,
273
-				'delimiter' => '/'
274
-			));
275
-
276
-			/** @var OpenCloud\ObjectStore\Resource\DataObject $object */
277
-			foreach ($objects as $object) {
278
-				$file = basename($object->getName());
279
-				if ($file !== basename($path)) {
280
-					$files[] = $file;
281
-				}
282
-			}
283
-
284
-			return IteratorDirectory::wrap($files);
285
-		} catch (\Exception $e) {
286
-			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
287
-			return false;
288
-		}
289
-
290
-	}
291
-
292
-	public function stat($path) {
293
-		$path = $this->normalizePath($path);
294
-
295
-		if ($path === '.') {
296
-			$path = '';
297
-		} else if ($this->is_dir($path)) {
298
-			$path .= '/';
299
-		}
300
-
301
-		try {
302
-			/** @var DataObject $object */
303
-			$object = $this->fetchObject($path);
304
-			if (!$object) {
305
-				return false;
306
-			}
307
-		} catch (ClientErrorResponseException $e) {
308
-			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
309
-			return false;
310
-		}
311
-
312
-		$dateTime = \DateTime::createFromFormat(\DateTime::RFC1123, $object->getLastModified());
313
-		if ($dateTime !== false) {
314
-			$mtime = $dateTime->getTimestamp();
315
-		} else {
316
-			$mtime = null;
317
-		}
318
-		$objectMetadata = $object->getMetadata();
319
-		$metaTimestamp = $objectMetadata->getProperty('timestamp');
320
-		if (isset($metaTimestamp)) {
321
-			$mtime = $metaTimestamp;
322
-		}
323
-
324
-		if (!empty($mtime)) {
325
-			$mtime = floor($mtime);
326
-		}
327
-
328
-		$stat = array();
329
-		$stat['size'] = (int)$object->getContentLength();
330
-		$stat['mtime'] = $mtime;
331
-		$stat['atime'] = time();
332
-		return $stat;
333
-	}
334
-
335
-	public function filetype($path) {
336
-		$path = $this->normalizePath($path);
337
-
338
-		if ($path !== '.' && $this->doesObjectExist($path)) {
339
-			return 'file';
340
-		}
341
-
342
-		if ($path !== '.') {
343
-			$path .= '/';
344
-		}
345
-
346
-		if ($this->doesObjectExist($path)) {
347
-			return 'dir';
348
-		}
349
-	}
350
-
351
-	public function unlink($path) {
352
-		$path = $this->normalizePath($path);
353
-
354
-		if ($this->is_dir($path)) {
355
-			return $this->rmdir($path);
356
-		}
357
-
358
-		try {
359
-			$this->getContainer()->dataObject()->setName($path)->delete();
360
-			$this->objectCache->remove($path);
361
-			$this->objectCache->remove($path . '/');
362
-		} catch (ClientErrorResponseException $e) {
363
-			if ($e->getResponse()->getStatusCode() !== 404) {
364
-				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
365
-			}
366
-			return false;
367
-		}
368
-
369
-		return true;
370
-	}
371
-
372
-	public function fopen($path, $mode) {
373
-		$path = $this->normalizePath($path);
374
-
375
-		switch ($mode) {
376
-			case 'a':
377
-			case 'ab':
378
-			case 'a+':
379
-				return false;
380
-			case 'r':
381
-			case 'rb':
382
-				try {
383
-					$c = $this->getContainer();
384
-					$streamFactory = new \Guzzle\Stream\PhpStreamRequestFactory();
385
-					$streamInterface = $streamFactory->fromRequest(
386
-						$c->getClient()
387
-							->get($c->getUrl($path)));
388
-					$streamInterface->rewind();
389
-					$stream = $streamInterface->getStream();
390
-					stream_context_set_option($stream, 'swift','content', $streamInterface);
391
-					if(!strrpos($streamInterface
392
-						->getMetaData('wrapper_data')[0], '404 Not Found')) {
393
-						return $stream;
394
-					}
395
-					return false;
396
-				} catch (\Guzzle\Http\Exception\BadResponseException $e) {
397
-					\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
398
-					return false;
399
-				}
400
-			case 'w':
401
-			case 'wb':
402
-			case 'r+':
403
-			case 'w+':
404
-			case 'wb+':
405
-			case 'x':
406
-			case 'x+':
407
-			case 'c':
408
-			case 'c+':
409
-				if (strrpos($path, '.') !== false) {
410
-					$ext = substr($path, strrpos($path, '.'));
411
-				} else {
412
-					$ext = '';
413
-				}
414
-				$tmpFile = \OCP\Files::tmpFile($ext);
415
-				// Fetch existing file if required
416
-				if ($mode[0] !== 'w' && $this->file_exists($path)) {
417
-					if ($mode[0] === 'x') {
418
-						// File cannot already exist
419
-						return false;
420
-					}
421
-					$source = $this->fopen($path, 'r');
422
-					file_put_contents($tmpFile, $source);
423
-				}
424
-				$handle = fopen($tmpFile, $mode);
425
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
426
-					$this->writeBack($tmpFile, $path);
427
-				});
428
-		}
429
-	}
430
-
431
-	public function touch($path, $mtime = null) {
432
-		$path = $this->normalizePath($path);
433
-		if (is_null($mtime)) {
434
-			$mtime = time();
435
-		}
436
-		$metadata = array('timestamp' => $mtime);
437
-		if ($this->file_exists($path)) {
438
-			if ($this->is_dir($path) && $path != '.') {
439
-				$path .= '/';
440
-			}
441
-
442
-			$object = $this->fetchObject($path);
443
-			if ($object->saveMetadata($metadata)) {
444
-				// invalidate target object to force repopulation on fetch
445
-				$this->objectCache->remove($path);
446
-			}
447
-			return true;
448
-		} else {
449
-			$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
450
-			$customHeaders = array('content-type' => $mimeType);
451
-			$metadataHeaders = DataObject::stockHeaders($metadata);
452
-			$allHeaders = $customHeaders + $metadataHeaders;
453
-			$this->getContainer()->uploadObject($path, '', $allHeaders);
454
-			// invalidate target object to force repopulation on fetch
455
-			$this->objectCache->remove($path);
456
-			return true;
457
-		}
458
-	}
459
-
460
-	public function copy($path1, $path2) {
461
-		$path1 = $this->normalizePath($path1);
462
-		$path2 = $this->normalizePath($path2);
463
-
464
-		$fileType = $this->filetype($path1);
465
-		if ($fileType === 'file') {
466
-
467
-			// make way
468
-			$this->unlink($path2);
469
-
470
-			try {
471
-				$source = $this->fetchObject($path1);
472
-				$source->copy($this->bucket . '/' . $path2);
473
-				// invalidate target object to force repopulation on fetch
474
-				$this->objectCache->remove($path2);
475
-				$this->objectCache->remove($path2 . '/');
476
-			} catch (ClientErrorResponseException $e) {
477
-				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
478
-				return false;
479
-			}
480
-
481
-		} else if ($fileType === 'dir') {
482
-
483
-			// make way
484
-			$this->unlink($path2);
485
-
486
-			try {
487
-				$source = $this->fetchObject($path1 . '/');
488
-				$source->copy($this->bucket . '/' . $path2 . '/');
489
-				// invalidate target object to force repopulation on fetch
490
-				$this->objectCache->remove($path2);
491
-				$this->objectCache->remove($path2 . '/');
492
-			} catch (ClientErrorResponseException $e) {
493
-				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
494
-				return false;
495
-			}
496
-
497
-			$dh = $this->opendir($path1);
498
-			while ($file = readdir($dh)) {
499
-				if (\OC\Files\Filesystem::isIgnoredDir($file)) {
500
-					continue;
501
-				}
502
-
503
-				$source = $path1 . '/' . $file;
504
-				$target = $path2 . '/' . $file;
505
-				$this->copy($source, $target);
506
-			}
507
-
508
-		} else {
509
-			//file does not exist
510
-			return false;
511
-		}
512
-
513
-		return true;
514
-	}
515
-
516
-	public function rename($path1, $path2) {
517
-		$path1 = $this->normalizePath($path1);
518
-		$path2 = $this->normalizePath($path2);
519
-
520
-		$fileType = $this->filetype($path1);
521
-
522
-		if ($fileType === 'dir' || $fileType === 'file') {
523
-			// copy
524
-			if ($this->copy($path1, $path2) === false) {
525
-				return false;
526
-			}
527
-
528
-			// cleanup
529
-			if ($this->unlink($path1) === false) {
530
-				$this->unlink($path2);
531
-				return false;
532
-			}
533
-
534
-			return true;
535
-		}
536
-
537
-		return false;
538
-	}
539
-
540
-	public function getId() {
541
-		return $this->id;
542
-	}
543
-
544
-	/**
545
-	 * Returns the connection
546
-	 *
547
-	 * @return OpenCloud\ObjectStore\Service connected client
548
-	 * @throws \Exception if connection could not be made
549
-	 */
550
-	public function getConnection() {
551
-		if (!is_null($this->connection)) {
552
-			return $this->connection;
553
-		}
554
-
555
-		$settings = array(
556
-			'username' => $this->params['user'],
557
-		);
558
-
559
-		if (!empty($this->params['password'])) {
560
-			$settings['password'] = $this->params['password'];
561
-		} else if (!empty($this->params['key'])) {
562
-			$settings['apiKey'] = $this->params['key'];
563
-		}
564
-
565
-		if (!empty($this->params['tenant'])) {
566
-			$settings['tenantName'] = $this->params['tenant'];
567
-		}
568
-
569
-		if (!empty($this->params['timeout'])) {
570
-			$settings['timeout'] = $this->params['timeout'];
571
-		}
572
-
573
-		if (isset($settings['apiKey'])) {
574
-			$this->anchor = new Rackspace($this->params['url'], $settings);
575
-		} else {
576
-			$this->anchor = new OpenStack($this->params['url'], $settings);
577
-		}
578
-
579
-		$connection = $this->anchor->objectStoreService($this->params['service_name'], $this->params['region']);
580
-
581
-		if (!empty($this->params['endpoint_url'])) {
582
-			$endpoint = $connection->getEndpoint();
583
-			$endpoint->setPublicUrl($this->params['endpoint_url']);
584
-			$endpoint->setPrivateUrl($this->params['endpoint_url']);
585
-			$connection->setEndpoint($endpoint);
586
-		}
587
-
588
-		$this->connection = $connection;
589
-
590
-		return $this->connection;
591
-	}
592
-
593
-	/**
594
-	 * Returns the initialized object store container.
595
-	 *
596
-	 * @return OpenCloud\ObjectStore\Resource\Container
597
-	 */
598
-	public function getContainer() {
599
-		if (!is_null($this->container)) {
600
-			return $this->container;
601
-		}
602
-
603
-		try {
604
-			$this->container = $this->getConnection()->getContainer($this->bucket);
605
-		} catch (ClientErrorResponseException $e) {
606
-			$this->container = $this->getConnection()->createContainer($this->bucket);
607
-		}
608
-
609
-		if (!$this->file_exists('.')) {
610
-			$this->mkdir('.');
611
-		}
612
-
613
-		return $this->container;
614
-	}
615
-
616
-	public function writeBack($tmpFile, $path) {
617
-		$fileData = fopen($tmpFile, 'r');
618
-		$this->getContainer()->uploadObject($path, $fileData);
619
-		// invalidate target object to force repopulation on fetch
620
-		$this->objectCache->remove(self::$tmpFiles[$tmpFile]);
621
-		unlink($tmpFile);
622
-	}
623
-
624
-	public function hasUpdated($path, $time) {
625
-		if ($this->is_file($path)) {
626
-			return parent::hasUpdated($path, $time);
627
-		}
628
-		$path = $this->normalizePath($path);
629
-		$dh = $this->opendir($path);
630
-		$content = array();
631
-		while (($file = readdir($dh)) !== false) {
632
-			$content[] = $file;
633
-		}
634
-		if ($path === '.') {
635
-			$path = '';
636
-		}
637
-		$cachedContent = $this->getCache()->getFolderContents($path);
638
-		$cachedNames = array_map(function ($content) {
639
-			return $content['name'];
640
-		}, $cachedContent);
641
-		sort($cachedNames);
642
-		sort($content);
643
-		return $cachedNames != $content;
644
-	}
645
-
646
-	/**
647
-	 * check if curl is installed
648
-	 */
649
-	public static function checkDependencies() {
650
-		return true;
651
-	}
51
+    /**
52
+     * @var \OpenCloud\ObjectStore\Service
53
+     */
54
+    private $connection;
55
+    /**
56
+     * @var \OpenCloud\ObjectStore\Resource\Container
57
+     */
58
+    private $container;
59
+    /**
60
+     * @var \OpenCloud\OpenStack
61
+     */
62
+    private $anchor;
63
+    /**
64
+     * @var string
65
+     */
66
+    private $bucket;
67
+    /**
68
+     * Connection parameters
69
+     *
70
+     * @var array
71
+     */
72
+    private $params;
73
+
74
+    /** @var string  */
75
+    private $id;
76
+
77
+    /**
78
+     * @var array
79
+     */
80
+    private static $tmpFiles = array();
81
+
82
+    /**
83
+     * Key value cache mapping path to data object. Maps path to
84
+     * \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject for existing
85
+     * paths and path to false for not existing paths.
86
+     * @var \OCP\ICache
87
+     */
88
+    private $objectCache;
89
+
90
+    /**
91
+     * @param string $path
92
+     */
93
+    private function normalizePath($path) {
94
+        $path = trim($path, '/');
95
+
96
+        if (!$path) {
97
+            $path = '.';
98
+        }
99
+
100
+        $path = str_replace('#', '%23', $path);
101
+
102
+        return $path;
103
+    }
104
+
105
+    const SUBCONTAINER_FILE = '.subcontainers';
106
+
107
+    /**
108
+     * translate directory path to container name
109
+     *
110
+     * @param string $path
111
+     * @return string
112
+     */
113
+
114
+    /**
115
+     * Fetches an object from the API.
116
+     * If the object is cached already or a
117
+     * failed "doesn't exist" response was cached,
118
+     * that one will be returned.
119
+     *
120
+     * @param string $path
121
+     * @return \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject|bool object
122
+     * or false if the object did not exist
123
+     */
124
+    private function fetchObject($path) {
125
+        if ($this->objectCache->hasKey($path)) {
126
+            // might be "false" if object did not exist from last check
127
+            return $this->objectCache->get($path);
128
+        }
129
+        try {
130
+            $object = $this->getContainer()->getPartialObject($path);
131
+            $this->objectCache->set($path, $object);
132
+            return $object;
133
+        } catch (ClientErrorResponseException $e) {
134
+            // this exception happens when the object does not exist, which
135
+            // is expected in most cases
136
+            $this->objectCache->set($path, false);
137
+            return false;
138
+        } catch (ClientErrorResponseException $e) {
139
+            // Expected response is "404 Not Found", so only log if it isn't
140
+            if ($e->getResponse()->getStatusCode() !== 404) {
141
+                \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
142
+            }
143
+            return false;
144
+        }
145
+    }
146
+
147
+    /**
148
+     * Returns whether the given path exists.
149
+     *
150
+     * @param string $path
151
+     *
152
+     * @return bool true if the object exist, false otherwise
153
+     */
154
+    private function doesObjectExist($path) {
155
+        return $this->fetchObject($path) !== false;
156
+    }
157
+
158
+    public function __construct($params) {
159
+        if ((empty($params['key']) and empty($params['password']))
160
+            or empty($params['user']) or empty($params['bucket'])
161
+            or empty($params['region'])
162
+        ) {
163
+            throw new \Exception("API Key or password, Username, Bucket and Region have to be configured.");
164
+        }
165
+
166
+        $this->id = 'swift::' . $params['user'] . md5($params['bucket']);
167
+
168
+        $bucketUrl = Url::factory($params['bucket']);
169
+        if ($bucketUrl->isAbsolute()) {
170
+            $this->bucket = end(($bucketUrl->getPathSegments()));
171
+            $params['endpoint_url'] = $bucketUrl->addPath('..')->normalizePath();
172
+        } else {
173
+            $this->bucket = $params['bucket'];
174
+        }
175
+
176
+        if (empty($params['url'])) {
177
+            $params['url'] = 'https://identity.api.rackspacecloud.com/v2.0/';
178
+        }
179
+
180
+        if (empty($params['service_name'])) {
181
+            $params['service_name'] = 'cloudFiles';
182
+        }
183
+
184
+        $this->params = $params;
185
+        // FIXME: private class...
186
+        $this->objectCache = new \OC\Cache\CappedMemoryCache();
187
+    }
188
+
189
+    public function mkdir($path) {
190
+        $path = $this->normalizePath($path);
191
+
192
+        if ($this->is_dir($path)) {
193
+            return false;
194
+        }
195
+
196
+        if ($path !== '.') {
197
+            $path .= '/';
198
+        }
199
+
200
+        try {
201
+            $customHeaders = array('content-type' => 'httpd/unix-directory');
202
+            $metadataHeaders = DataObject::stockHeaders(array());
203
+            $allHeaders = $customHeaders + $metadataHeaders;
204
+            $this->getContainer()->uploadObject($path, '', $allHeaders);
205
+            // invalidate so that the next access gets the real object
206
+            // with all properties
207
+            $this->objectCache->remove($path);
208
+        } catch (Exceptions\CreateUpdateError $e) {
209
+            \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
210
+            return false;
211
+        }
212
+
213
+        return true;
214
+    }
215
+
216
+    public function file_exists($path) {
217
+        $path = $this->normalizePath($path);
218
+
219
+        if ($path !== '.' && $this->is_dir($path)) {
220
+            $path .= '/';
221
+        }
222
+
223
+        return $this->doesObjectExist($path);
224
+    }
225
+
226
+    public function rmdir($path) {
227
+        $path = $this->normalizePath($path);
228
+
229
+        if (!$this->is_dir($path) || !$this->isDeletable($path)) {
230
+            return false;
231
+        }
232
+
233
+        $dh = $this->opendir($path);
234
+        while ($file = readdir($dh)) {
235
+            if (\OC\Files\Filesystem::isIgnoredDir($file)) {
236
+                continue;
237
+            }
238
+
239
+            if ($this->is_dir($path . '/' . $file)) {
240
+                $this->rmdir($path . '/' . $file);
241
+            } else {
242
+                $this->unlink($path . '/' . $file);
243
+            }
244
+        }
245
+
246
+        try {
247
+            $this->getContainer()->dataObject()->setName($path . '/')->delete();
248
+            $this->objectCache->remove($path . '/');
249
+        } catch (Exceptions\DeleteError $e) {
250
+            \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
251
+            return false;
252
+        }
253
+
254
+        return true;
255
+    }
256
+
257
+    public function opendir($path) {
258
+        $path = $this->normalizePath($path);
259
+
260
+        if ($path === '.') {
261
+            $path = '';
262
+        } else {
263
+            $path .= '/';
264
+        }
265
+
266
+        $path = str_replace('%23', '#', $path); // the prefix is sent as a query param, so revert the encoding of #
267
+
268
+        try {
269
+            $files = array();
270
+            /** @var OpenCloud\Common\Collection $objects */
271
+            $objects = $this->getContainer()->objectList(array(
272
+                'prefix' => $path,
273
+                'delimiter' => '/'
274
+            ));
275
+
276
+            /** @var OpenCloud\ObjectStore\Resource\DataObject $object */
277
+            foreach ($objects as $object) {
278
+                $file = basename($object->getName());
279
+                if ($file !== basename($path)) {
280
+                    $files[] = $file;
281
+                }
282
+            }
283
+
284
+            return IteratorDirectory::wrap($files);
285
+        } catch (\Exception $e) {
286
+            \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
287
+            return false;
288
+        }
289
+
290
+    }
291
+
292
+    public function stat($path) {
293
+        $path = $this->normalizePath($path);
294
+
295
+        if ($path === '.') {
296
+            $path = '';
297
+        } else if ($this->is_dir($path)) {
298
+            $path .= '/';
299
+        }
300
+
301
+        try {
302
+            /** @var DataObject $object */
303
+            $object = $this->fetchObject($path);
304
+            if (!$object) {
305
+                return false;
306
+            }
307
+        } catch (ClientErrorResponseException $e) {
308
+            \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
309
+            return false;
310
+        }
311
+
312
+        $dateTime = \DateTime::createFromFormat(\DateTime::RFC1123, $object->getLastModified());
313
+        if ($dateTime !== false) {
314
+            $mtime = $dateTime->getTimestamp();
315
+        } else {
316
+            $mtime = null;
317
+        }
318
+        $objectMetadata = $object->getMetadata();
319
+        $metaTimestamp = $objectMetadata->getProperty('timestamp');
320
+        if (isset($metaTimestamp)) {
321
+            $mtime = $metaTimestamp;
322
+        }
323
+
324
+        if (!empty($mtime)) {
325
+            $mtime = floor($mtime);
326
+        }
327
+
328
+        $stat = array();
329
+        $stat['size'] = (int)$object->getContentLength();
330
+        $stat['mtime'] = $mtime;
331
+        $stat['atime'] = time();
332
+        return $stat;
333
+    }
334
+
335
+    public function filetype($path) {
336
+        $path = $this->normalizePath($path);
337
+
338
+        if ($path !== '.' && $this->doesObjectExist($path)) {
339
+            return 'file';
340
+        }
341
+
342
+        if ($path !== '.') {
343
+            $path .= '/';
344
+        }
345
+
346
+        if ($this->doesObjectExist($path)) {
347
+            return 'dir';
348
+        }
349
+    }
350
+
351
+    public function unlink($path) {
352
+        $path = $this->normalizePath($path);
353
+
354
+        if ($this->is_dir($path)) {
355
+            return $this->rmdir($path);
356
+        }
357
+
358
+        try {
359
+            $this->getContainer()->dataObject()->setName($path)->delete();
360
+            $this->objectCache->remove($path);
361
+            $this->objectCache->remove($path . '/');
362
+        } catch (ClientErrorResponseException $e) {
363
+            if ($e->getResponse()->getStatusCode() !== 404) {
364
+                \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
365
+            }
366
+            return false;
367
+        }
368
+
369
+        return true;
370
+    }
371
+
372
+    public function fopen($path, $mode) {
373
+        $path = $this->normalizePath($path);
374
+
375
+        switch ($mode) {
376
+            case 'a':
377
+            case 'ab':
378
+            case 'a+':
379
+                return false;
380
+            case 'r':
381
+            case 'rb':
382
+                try {
383
+                    $c = $this->getContainer();
384
+                    $streamFactory = new \Guzzle\Stream\PhpStreamRequestFactory();
385
+                    $streamInterface = $streamFactory->fromRequest(
386
+                        $c->getClient()
387
+                            ->get($c->getUrl($path)));
388
+                    $streamInterface->rewind();
389
+                    $stream = $streamInterface->getStream();
390
+                    stream_context_set_option($stream, 'swift','content', $streamInterface);
391
+                    if(!strrpos($streamInterface
392
+                        ->getMetaData('wrapper_data')[0], '404 Not Found')) {
393
+                        return $stream;
394
+                    }
395
+                    return false;
396
+                } catch (\Guzzle\Http\Exception\BadResponseException $e) {
397
+                    \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
398
+                    return false;
399
+                }
400
+            case 'w':
401
+            case 'wb':
402
+            case 'r+':
403
+            case 'w+':
404
+            case 'wb+':
405
+            case 'x':
406
+            case 'x+':
407
+            case 'c':
408
+            case 'c+':
409
+                if (strrpos($path, '.') !== false) {
410
+                    $ext = substr($path, strrpos($path, '.'));
411
+                } else {
412
+                    $ext = '';
413
+                }
414
+                $tmpFile = \OCP\Files::tmpFile($ext);
415
+                // Fetch existing file if required
416
+                if ($mode[0] !== 'w' && $this->file_exists($path)) {
417
+                    if ($mode[0] === 'x') {
418
+                        // File cannot already exist
419
+                        return false;
420
+                    }
421
+                    $source = $this->fopen($path, 'r');
422
+                    file_put_contents($tmpFile, $source);
423
+                }
424
+                $handle = fopen($tmpFile, $mode);
425
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
426
+                    $this->writeBack($tmpFile, $path);
427
+                });
428
+        }
429
+    }
430
+
431
+    public function touch($path, $mtime = null) {
432
+        $path = $this->normalizePath($path);
433
+        if (is_null($mtime)) {
434
+            $mtime = time();
435
+        }
436
+        $metadata = array('timestamp' => $mtime);
437
+        if ($this->file_exists($path)) {
438
+            if ($this->is_dir($path) && $path != '.') {
439
+                $path .= '/';
440
+            }
441
+
442
+            $object = $this->fetchObject($path);
443
+            if ($object->saveMetadata($metadata)) {
444
+                // invalidate target object to force repopulation on fetch
445
+                $this->objectCache->remove($path);
446
+            }
447
+            return true;
448
+        } else {
449
+            $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
450
+            $customHeaders = array('content-type' => $mimeType);
451
+            $metadataHeaders = DataObject::stockHeaders($metadata);
452
+            $allHeaders = $customHeaders + $metadataHeaders;
453
+            $this->getContainer()->uploadObject($path, '', $allHeaders);
454
+            // invalidate target object to force repopulation on fetch
455
+            $this->objectCache->remove($path);
456
+            return true;
457
+        }
458
+    }
459
+
460
+    public function copy($path1, $path2) {
461
+        $path1 = $this->normalizePath($path1);
462
+        $path2 = $this->normalizePath($path2);
463
+
464
+        $fileType = $this->filetype($path1);
465
+        if ($fileType === 'file') {
466
+
467
+            // make way
468
+            $this->unlink($path2);
469
+
470
+            try {
471
+                $source = $this->fetchObject($path1);
472
+                $source->copy($this->bucket . '/' . $path2);
473
+                // invalidate target object to force repopulation on fetch
474
+                $this->objectCache->remove($path2);
475
+                $this->objectCache->remove($path2 . '/');
476
+            } catch (ClientErrorResponseException $e) {
477
+                \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
478
+                return false;
479
+            }
480
+
481
+        } else if ($fileType === 'dir') {
482
+
483
+            // make way
484
+            $this->unlink($path2);
485
+
486
+            try {
487
+                $source = $this->fetchObject($path1 . '/');
488
+                $source->copy($this->bucket . '/' . $path2 . '/');
489
+                // invalidate target object to force repopulation on fetch
490
+                $this->objectCache->remove($path2);
491
+                $this->objectCache->remove($path2 . '/');
492
+            } catch (ClientErrorResponseException $e) {
493
+                \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
494
+                return false;
495
+            }
496
+
497
+            $dh = $this->opendir($path1);
498
+            while ($file = readdir($dh)) {
499
+                if (\OC\Files\Filesystem::isIgnoredDir($file)) {
500
+                    continue;
501
+                }
502
+
503
+                $source = $path1 . '/' . $file;
504
+                $target = $path2 . '/' . $file;
505
+                $this->copy($source, $target);
506
+            }
507
+
508
+        } else {
509
+            //file does not exist
510
+            return false;
511
+        }
512
+
513
+        return true;
514
+    }
515
+
516
+    public function rename($path1, $path2) {
517
+        $path1 = $this->normalizePath($path1);
518
+        $path2 = $this->normalizePath($path2);
519
+
520
+        $fileType = $this->filetype($path1);
521
+
522
+        if ($fileType === 'dir' || $fileType === 'file') {
523
+            // copy
524
+            if ($this->copy($path1, $path2) === false) {
525
+                return false;
526
+            }
527
+
528
+            // cleanup
529
+            if ($this->unlink($path1) === false) {
530
+                $this->unlink($path2);
531
+                return false;
532
+            }
533
+
534
+            return true;
535
+        }
536
+
537
+        return false;
538
+    }
539
+
540
+    public function getId() {
541
+        return $this->id;
542
+    }
543
+
544
+    /**
545
+     * Returns the connection
546
+     *
547
+     * @return OpenCloud\ObjectStore\Service connected client
548
+     * @throws \Exception if connection could not be made
549
+     */
550
+    public function getConnection() {
551
+        if (!is_null($this->connection)) {
552
+            return $this->connection;
553
+        }
554
+
555
+        $settings = array(
556
+            'username' => $this->params['user'],
557
+        );
558
+
559
+        if (!empty($this->params['password'])) {
560
+            $settings['password'] = $this->params['password'];
561
+        } else if (!empty($this->params['key'])) {
562
+            $settings['apiKey'] = $this->params['key'];
563
+        }
564
+
565
+        if (!empty($this->params['tenant'])) {
566
+            $settings['tenantName'] = $this->params['tenant'];
567
+        }
568
+
569
+        if (!empty($this->params['timeout'])) {
570
+            $settings['timeout'] = $this->params['timeout'];
571
+        }
572
+
573
+        if (isset($settings['apiKey'])) {
574
+            $this->anchor = new Rackspace($this->params['url'], $settings);
575
+        } else {
576
+            $this->anchor = new OpenStack($this->params['url'], $settings);
577
+        }
578
+
579
+        $connection = $this->anchor->objectStoreService($this->params['service_name'], $this->params['region']);
580
+
581
+        if (!empty($this->params['endpoint_url'])) {
582
+            $endpoint = $connection->getEndpoint();
583
+            $endpoint->setPublicUrl($this->params['endpoint_url']);
584
+            $endpoint->setPrivateUrl($this->params['endpoint_url']);
585
+            $connection->setEndpoint($endpoint);
586
+        }
587
+
588
+        $this->connection = $connection;
589
+
590
+        return $this->connection;
591
+    }
592
+
593
+    /**
594
+     * Returns the initialized object store container.
595
+     *
596
+     * @return OpenCloud\ObjectStore\Resource\Container
597
+     */
598
+    public function getContainer() {
599
+        if (!is_null($this->container)) {
600
+            return $this->container;
601
+        }
602
+
603
+        try {
604
+            $this->container = $this->getConnection()->getContainer($this->bucket);
605
+        } catch (ClientErrorResponseException $e) {
606
+            $this->container = $this->getConnection()->createContainer($this->bucket);
607
+        }
608
+
609
+        if (!$this->file_exists('.')) {
610
+            $this->mkdir('.');
611
+        }
612
+
613
+        return $this->container;
614
+    }
615
+
616
+    public function writeBack($tmpFile, $path) {
617
+        $fileData = fopen($tmpFile, 'r');
618
+        $this->getContainer()->uploadObject($path, $fileData);
619
+        // invalidate target object to force repopulation on fetch
620
+        $this->objectCache->remove(self::$tmpFiles[$tmpFile]);
621
+        unlink($tmpFile);
622
+    }
623
+
624
+    public function hasUpdated($path, $time) {
625
+        if ($this->is_file($path)) {
626
+            return parent::hasUpdated($path, $time);
627
+        }
628
+        $path = $this->normalizePath($path);
629
+        $dh = $this->opendir($path);
630
+        $content = array();
631
+        while (($file = readdir($dh)) !== false) {
632
+            $content[] = $file;
633
+        }
634
+        if ($path === '.') {
635
+            $path = '';
636
+        }
637
+        $cachedContent = $this->getCache()->getFolderContents($path);
638
+        $cachedNames = array_map(function ($content) {
639
+            return $content['name'];
640
+        }, $cachedContent);
641
+        sort($cachedNames);
642
+        sort($content);
643
+        return $cachedNames != $content;
644
+    }
645
+
646
+    /**
647
+     * check if curl is installed
648
+     */
649
+    public static function checkDependencies() {
650
+        return true;
651
+    }
652 652
 
653 653
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 			throw new \Exception("API Key or password, Username, Bucket and Region have to be configured.");
164 164
 		}
165 165
 
166
-		$this->id = 'swift::' . $params['user'] . md5($params['bucket']);
166
+		$this->id = 'swift::'.$params['user'].md5($params['bucket']);
167 167
 
168 168
 		$bucketUrl = Url::factory($params['bucket']);
169 169
 		if ($bucketUrl->isAbsolute()) {
@@ -236,16 +236,16 @@  discard block
 block discarded – undo
236 236
 				continue;
237 237
 			}
238 238
 
239
-			if ($this->is_dir($path . '/' . $file)) {
240
-				$this->rmdir($path . '/' . $file);
239
+			if ($this->is_dir($path.'/'.$file)) {
240
+				$this->rmdir($path.'/'.$file);
241 241
 			} else {
242
-				$this->unlink($path . '/' . $file);
242
+				$this->unlink($path.'/'.$file);
243 243
 			}
244 244
 		}
245 245
 
246 246
 		try {
247
-			$this->getContainer()->dataObject()->setName($path . '/')->delete();
248
-			$this->objectCache->remove($path . '/');
247
+			$this->getContainer()->dataObject()->setName($path.'/')->delete();
248
+			$this->objectCache->remove($path.'/');
249 249
 		} catch (Exceptions\DeleteError $e) {
250 250
 			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
251 251
 			return false;
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
 		}
327 327
 
328 328
 		$stat = array();
329
-		$stat['size'] = (int)$object->getContentLength();
329
+		$stat['size'] = (int) $object->getContentLength();
330 330
 		$stat['mtime'] = $mtime;
331 331
 		$stat['atime'] = time();
332 332
 		return $stat;
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
 		try {
359 359
 			$this->getContainer()->dataObject()->setName($path)->delete();
360 360
 			$this->objectCache->remove($path);
361
-			$this->objectCache->remove($path . '/');
361
+			$this->objectCache->remove($path.'/');
362 362
 		} catch (ClientErrorResponseException $e) {
363 363
 			if ($e->getResponse()->getStatusCode() !== 404) {
364 364
 				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
@@ -387,8 +387,8 @@  discard block
 block discarded – undo
387 387
 							->get($c->getUrl($path)));
388 388
 					$streamInterface->rewind();
389 389
 					$stream = $streamInterface->getStream();
390
-					stream_context_set_option($stream, 'swift','content', $streamInterface);
391
-					if(!strrpos($streamInterface
390
+					stream_context_set_option($stream, 'swift', 'content', $streamInterface);
391
+					if (!strrpos($streamInterface
392 392
 						->getMetaData('wrapper_data')[0], '404 Not Found')) {
393 393
 						return $stream;
394 394
 					}
@@ -422,7 +422,7 @@  discard block
 block discarded – undo
422 422
 					file_put_contents($tmpFile, $source);
423 423
 				}
424 424
 				$handle = fopen($tmpFile, $mode);
425
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
425
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
426 426
 					$this->writeBack($tmpFile, $path);
427 427
 				});
428 428
 		}
@@ -469,10 +469,10 @@  discard block
 block discarded – undo
469 469
 
470 470
 			try {
471 471
 				$source = $this->fetchObject($path1);
472
-				$source->copy($this->bucket . '/' . $path2);
472
+				$source->copy($this->bucket.'/'.$path2);
473 473
 				// invalidate target object to force repopulation on fetch
474 474
 				$this->objectCache->remove($path2);
475
-				$this->objectCache->remove($path2 . '/');
475
+				$this->objectCache->remove($path2.'/');
476 476
 			} catch (ClientErrorResponseException $e) {
477 477
 				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
478 478
 				return false;
@@ -484,11 +484,11 @@  discard block
 block discarded – undo
484 484
 			$this->unlink($path2);
485 485
 
486 486
 			try {
487
-				$source = $this->fetchObject($path1 . '/');
488
-				$source->copy($this->bucket . '/' . $path2 . '/');
487
+				$source = $this->fetchObject($path1.'/');
488
+				$source->copy($this->bucket.'/'.$path2.'/');
489 489
 				// invalidate target object to force repopulation on fetch
490 490
 				$this->objectCache->remove($path2);
491
-				$this->objectCache->remove($path2 . '/');
491
+				$this->objectCache->remove($path2.'/');
492 492
 			} catch (ClientErrorResponseException $e) {
493 493
 				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
494 494
 				return false;
@@ -500,8 +500,8 @@  discard block
 block discarded – undo
500 500
 					continue;
501 501
 				}
502 502
 
503
-				$source = $path1 . '/' . $file;
504
-				$target = $path2 . '/' . $file;
503
+				$source = $path1.'/'.$file;
504
+				$target = $path2.'/'.$file;
505 505
 				$this->copy($source, $target);
506 506
 			}
507 507
 
@@ -635,7 +635,7 @@  discard block
 block discarded – undo
635 635
 			$path = '';
636 636
 		}
637 637
 		$cachedContent = $this->getCache()->getFolderContents($path);
638
-		$cachedNames = array_map(function ($content) {
638
+		$cachedNames = array_map(function($content) {
639 639
 			return $content['name'];
640 640
 		}, $cachedContent);
641 641
 		sort($cachedNames);
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareController.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -597,7 +597,7 @@
 block discarded – undo
597 597
 	 * publish activity
598 598
 	 *
599 599
 	 * @param string $subject
600
-	 * @param array $parameters
600
+	 * @param string[] $parameters
601 601
 	 * @param string $affectedUser
602 602
 	 * @param int $fileId
603 603
 	 * @param string $filePath
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 	public function showAuthenticate($token) {
151 151
 		$share = $this->shareManager->getShareByToken($token);
152 152
 
153
-		if($this->linkShareAuth($share)) {
153
+		if ($this->linkShareAuth($share)) {
154 154
 			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
155 155
 		}
156 156
 
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 
179 179
 		$authenticate = $this->linkShareAuth($share, $password);
180 180
 
181
-		if($authenticate === true) {
181
+		if ($authenticate === true) {
182 182
 			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
183 183
 		}
184 184
 
@@ -199,15 +199,15 @@  discard block
 block discarded – undo
199 199
 	private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
200 200
 		if ($password !== null) {
201 201
 			if ($this->shareManager->checkPassword($share, $password)) {
202
-				$this->session->set('public_link_authenticated', (string)$share->getId());
202
+				$this->session->set('public_link_authenticated', (string) $share->getId());
203 203
 			} else {
204 204
 				$this->emitAccessShareHook($share, 403, 'Wrong password');
205 205
 				return false;
206 206
 			}
207 207
 		} else {
208 208
 			// not authenticated ?
209
-			if ( ! $this->session->exists('public_link_authenticated')
210
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
209
+			if (!$this->session->exists('public_link_authenticated')
210
+				|| $this->session->get('public_link_authenticated') !== (string) $share->getId()) {
211 211
 				return false;
212 212
 			}
213 213
 		}
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 		$itemType = $itemSource = $uidOwner = '';
229 229
 		$token = $share;
230 230
 		$exception = null;
231
-		if($share instanceof \OCP\Share\IShare) {
231
+		if ($share instanceof \OCP\Share\IShare) {
232 232
 			try {
233 233
 				$token = $share->getToken();
234 234
 				$uidOwner = $share->getSharedBy();
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
 			'errorCode' => $errorCode,
248 248
 			'errorMessage' => $errorMessage,
249 249
 		]);
250
-		if(!is_null($exception)) {
250
+		if (!is_null($exception)) {
251 251
 			throw $exception;
252 252
 		}
253 253
 	}
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
 			if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
341 341
 				$freeSpace = max($freeSpace, 0);
342 342
 			} else {
343
-				$freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
343
+				$freeSpace = (INF > 0) ? INF : PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
344 344
 			}
345 345
 
346 346
 			$hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true;
@@ -371,7 +371,7 @@  discard block
 block discarded – undo
371 371
 		$shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
372 372
 		$shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
373 373
 		if ($shareTmpl['previewSupported']) {
374
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
374
+			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview',
375 375
 				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
376 376
 		} else {
377 377
 			$shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
 		}
402 402
 
403 403
 		// OpenGraph Support: http://ogp.me/
404
-		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName() . ' - ' . $this->defaults->getSlogan()]);
404
+		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName().' - '.$this->defaults->getSlogan()]);
405 405
 		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->l10n->t('%s is publicly shared', [$shareTmpl['filename']])]);
406 406
 		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
407 407
 		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
@@ -436,7 +436,7 @@  discard block
 block discarded – undo
436 436
 
437 437
 		$share = $this->shareManager->getShareByToken($token);
438 438
 
439
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
439
+		if (!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
440 440
 			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
441 441
 		}
442 442
 
@@ -514,7 +514,7 @@  discard block
 block discarded – undo
514 514
 
515 515
 		$this->emitAccessShareHook($share);
516 516
 
517
-		$server_params = array( 'head' => $this->request->getMethod() == 'HEAD' );
517
+		$server_params = array('head' => $this->request->getMethod() == 'HEAD');
518 518
 
519 519
 		/**
520 520
 		 * Http range requests support
Please login to merge, or discard this patch.
Indentation   +550 added lines, -550 removed lines patch added patch discarded remove patch
@@ -64,558 +64,558 @@
 block discarded – undo
64 64
  */
65 65
 class ShareController extends Controller {
66 66
 
67
-	/** @var IConfig */
68
-	protected $config;
69
-	/** @var IURLGenerator */
70
-	protected $urlGenerator;
71
-	/** @var IUserManager */
72
-	protected $userManager;
73
-	/** @var ILogger */
74
-	protected $logger;
75
-	/** @var \OCP\Activity\IManager */
76
-	protected $activityManager;
77
-	/** @var \OCP\Share\IManager */
78
-	protected $shareManager;
79
-	/** @var ISession */
80
-	protected $session;
81
-	/** @var IPreview */
82
-	protected $previewManager;
83
-	/** @var IRootFolder */
84
-	protected $rootFolder;
85
-	/** @var FederatedShareProvider */
86
-	protected $federatedShareProvider;
87
-	/** @var EventDispatcherInterface */
88
-	protected $eventDispatcher;
89
-	/** @var IL10N */
90
-	protected $l10n;
91
-	/** @var Defaults */
92
-	protected $defaults;
93
-
94
-	/**
95
-	 * @param string $appName
96
-	 * @param IRequest $request
97
-	 * @param IConfig $config
98
-	 * @param IURLGenerator $urlGenerator
99
-	 * @param IUserManager $userManager
100
-	 * @param ILogger $logger
101
-	 * @param \OCP\Activity\IManager $activityManager
102
-	 * @param \OCP\Share\IManager $shareManager
103
-	 * @param ISession $session
104
-	 * @param IPreview $previewManager
105
-	 * @param IRootFolder $rootFolder
106
-	 * @param FederatedShareProvider $federatedShareProvider
107
-	 * @param EventDispatcherInterface $eventDispatcher
108
-	 * @param IL10N $l10n
109
-	 * @param Defaults $defaults
110
-	 */
111
-	public function __construct($appName,
112
-								IRequest $request,
113
-								IConfig $config,
114
-								IURLGenerator $urlGenerator,
115
-								IUserManager $userManager,
116
-								ILogger $logger,
117
-								\OCP\Activity\IManager $activityManager,
118
-								\OCP\Share\IManager $shareManager,
119
-								ISession $session,
120
-								IPreview $previewManager,
121
-								IRootFolder $rootFolder,
122
-								FederatedShareProvider $federatedShareProvider,
123
-								EventDispatcherInterface $eventDispatcher,
124
-								IL10N $l10n,
125
-								Defaults $defaults) {
126
-		parent::__construct($appName, $request);
127
-
128
-		$this->config = $config;
129
-		$this->urlGenerator = $urlGenerator;
130
-		$this->userManager = $userManager;
131
-		$this->logger = $logger;
132
-		$this->activityManager = $activityManager;
133
-		$this->shareManager = $shareManager;
134
-		$this->session = $session;
135
-		$this->previewManager = $previewManager;
136
-		$this->rootFolder = $rootFolder;
137
-		$this->federatedShareProvider = $federatedShareProvider;
138
-		$this->eventDispatcher = $eventDispatcher;
139
-		$this->l10n = $l10n;
140
-		$this->defaults = $defaults;
141
-	}
142
-
143
-	/**
144
-	 * @PublicPage
145
-	 * @NoCSRFRequired
146
-	 *
147
-	 * @param string $token
148
-	 * @return TemplateResponse|RedirectResponse
149
-	 */
150
-	public function showAuthenticate($token) {
151
-		$share = $this->shareManager->getShareByToken($token);
152
-
153
-		if($this->linkShareAuth($share)) {
154
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
155
-		}
156
-
157
-		return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
158
-	}
159
-
160
-	/**
161
-	 * @PublicPage
162
-	 * @UseSession
163
-	 * @BruteForceProtection(action=publicLinkAuth)
164
-	 *
165
-	 * Authenticates against password-protected shares
166
-	 * @param string $token
167
-	 * @param string $password
168
-	 * @return RedirectResponse|TemplateResponse|NotFoundResponse
169
-	 */
170
-	public function authenticate($token, $password = '') {
171
-
172
-		// Check whether share exists
173
-		try {
174
-			$share = $this->shareManager->getShareByToken($token);
175
-		} catch (ShareNotFound $e) {
176
-			return new NotFoundResponse();
177
-		}
178
-
179
-		$authenticate = $this->linkShareAuth($share, $password);
180
-
181
-		if($authenticate === true) {
182
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
183
-		}
184
-
185
-		$response = new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
186
-		$response->throttle();
187
-		return $response;
188
-	}
189
-
190
-	/**
191
-	 * Authenticate a link item with the given password.
192
-	 * Or use the session if no password is provided.
193
-	 *
194
-	 * This is a modified version of Helper::authenticate
195
-	 * TODO: Try to merge back eventually with Helper::authenticate
196
-	 *
197
-	 * @param \OCP\Share\IShare $share
198
-	 * @param string|null $password
199
-	 * @return bool
200
-	 */
201
-	private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
202
-		if ($password !== null) {
203
-			if ($this->shareManager->checkPassword($share, $password)) {
204
-				$this->session->set('public_link_authenticated', (string)$share->getId());
205
-			} else {
206
-				$this->emitAccessShareHook($share, 403, 'Wrong password');
207
-				return false;
208
-			}
209
-		} else {
210
-			// not authenticated ?
211
-			if ( ! $this->session->exists('public_link_authenticated')
212
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
213
-				return false;
214
-			}
215
-		}
216
-		return true;
217
-	}
218
-
219
-	/**
220
-	 * throws hooks when a share is attempted to be accessed
221
-	 *
222
-	 * @param \OCP\Share\IShare|string $share the Share instance if available,
223
-	 * otherwise token
224
-	 * @param int $errorCode
225
-	 * @param string $errorMessage
226
-	 * @throws \OC\HintException
227
-	 * @throws \OC\ServerNotAvailableException
228
-	 */
229
-	protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
230
-		$itemType = $itemSource = $uidOwner = '';
231
-		$token = $share;
232
-		$exception = null;
233
-		if($share instanceof \OCP\Share\IShare) {
234
-			try {
235
-				$token = $share->getToken();
236
-				$uidOwner = $share->getSharedBy();
237
-				$itemType = $share->getNodeType();
238
-				$itemSource = $share->getNodeId();
239
-			} catch (\Exception $e) {
240
-				// we log what we know and pass on the exception afterwards
241
-				$exception = $e;
242
-			}
243
-		}
244
-		\OC_Hook::emit('OCP\Share', 'share_link_access', [
245
-			'itemType' => $itemType,
246
-			'itemSource' => $itemSource,
247
-			'uidOwner' => $uidOwner,
248
-			'token' => $token,
249
-			'errorCode' => $errorCode,
250
-			'errorMessage' => $errorMessage,
251
-		]);
252
-		if(!is_null($exception)) {
253
-			throw $exception;
254
-		}
255
-	}
256
-
257
-	/**
258
-	 * Validate the permissions of the share
259
-	 *
260
-	 * @param Share\IShare $share
261
-	 * @return bool
262
-	 */
263
-	private function validateShare(\OCP\Share\IShare $share) {
264
-		return $share->getNode()->isReadable() && $share->getNode()->isShareable();
265
-	}
266
-
267
-	/**
268
-	 * @PublicPage
269
-	 * @NoCSRFRequired
270
-	 *
271
-	 * @param string $token
272
-	 * @param string $path
273
-	 * @return TemplateResponse|RedirectResponse|NotFoundResponse
274
-	 * @throws NotFoundException
275
-	 * @throws \Exception
276
-	 */
277
-	public function showShare($token, $path = '') {
278
-		\OC_User::setIncognitoMode(true);
279
-
280
-		// Check whether share exists
281
-		try {
282
-			$share = $this->shareManager->getShareByToken($token);
283
-		} catch (ShareNotFound $e) {
284
-			$this->emitAccessShareHook($token, 404, 'Share not found');
285
-			return new NotFoundResponse();
286
-		}
287
-
288
-		// Share is password protected - check whether the user is permitted to access the share
289
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
290
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
291
-				array('token' => $token)));
292
-		}
293
-
294
-		if (!$this->validateShare($share)) {
295
-			throw new NotFoundException();
296
-		}
297
-		// We can't get the path of a file share
298
-		try {
299
-			if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
300
-				$this->emitAccessShareHook($share, 404, 'Share not found');
301
-				throw new NotFoundException();
302
-			}
303
-		} catch (\Exception $e) {
304
-			$this->emitAccessShareHook($share, 404, 'Share not found');
305
-			throw $e;
306
-		}
307
-
308
-		$shareTmpl = [];
309
-		$shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
310
-		$shareTmpl['owner'] = $share->getShareOwner();
311
-		$shareTmpl['filename'] = $share->getNode()->getName();
312
-		$shareTmpl['directory_path'] = $share->getTarget();
313
-		$shareTmpl['mimetype'] = $share->getNode()->getMimetype();
314
-		$shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
315
-		$shareTmpl['dirToken'] = $token;
316
-		$shareTmpl['sharingToken'] = $token;
317
-		$shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
318
-		$shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
319
-		$shareTmpl['dir'] = '';
320
-		$shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
321
-		$shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
322
-
323
-		// Show file list
324
-		$hideFileList = false;
325
-		if ($share->getNode() instanceof \OCP\Files\Folder) {
326
-			/** @var \OCP\Files\Folder $rootFolder */
327
-			$rootFolder = $share->getNode();
328
-
329
-			try {
330
-				$folderNode = $rootFolder->get($path);
331
-			} catch (\OCP\Files\NotFoundException $e) {
332
-				$this->emitAccessShareHook($share, 404, 'Share not found');
333
-				throw new NotFoundException();
334
-			}
335
-
336
-			$shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
337
-
338
-			/*
67
+    /** @var IConfig */
68
+    protected $config;
69
+    /** @var IURLGenerator */
70
+    protected $urlGenerator;
71
+    /** @var IUserManager */
72
+    protected $userManager;
73
+    /** @var ILogger */
74
+    protected $logger;
75
+    /** @var \OCP\Activity\IManager */
76
+    protected $activityManager;
77
+    /** @var \OCP\Share\IManager */
78
+    protected $shareManager;
79
+    /** @var ISession */
80
+    protected $session;
81
+    /** @var IPreview */
82
+    protected $previewManager;
83
+    /** @var IRootFolder */
84
+    protected $rootFolder;
85
+    /** @var FederatedShareProvider */
86
+    protected $federatedShareProvider;
87
+    /** @var EventDispatcherInterface */
88
+    protected $eventDispatcher;
89
+    /** @var IL10N */
90
+    protected $l10n;
91
+    /** @var Defaults */
92
+    protected $defaults;
93
+
94
+    /**
95
+     * @param string $appName
96
+     * @param IRequest $request
97
+     * @param IConfig $config
98
+     * @param IURLGenerator $urlGenerator
99
+     * @param IUserManager $userManager
100
+     * @param ILogger $logger
101
+     * @param \OCP\Activity\IManager $activityManager
102
+     * @param \OCP\Share\IManager $shareManager
103
+     * @param ISession $session
104
+     * @param IPreview $previewManager
105
+     * @param IRootFolder $rootFolder
106
+     * @param FederatedShareProvider $federatedShareProvider
107
+     * @param EventDispatcherInterface $eventDispatcher
108
+     * @param IL10N $l10n
109
+     * @param Defaults $defaults
110
+     */
111
+    public function __construct($appName,
112
+                                IRequest $request,
113
+                                IConfig $config,
114
+                                IURLGenerator $urlGenerator,
115
+                                IUserManager $userManager,
116
+                                ILogger $logger,
117
+                                \OCP\Activity\IManager $activityManager,
118
+                                \OCP\Share\IManager $shareManager,
119
+                                ISession $session,
120
+                                IPreview $previewManager,
121
+                                IRootFolder $rootFolder,
122
+                                FederatedShareProvider $federatedShareProvider,
123
+                                EventDispatcherInterface $eventDispatcher,
124
+                                IL10N $l10n,
125
+                                Defaults $defaults) {
126
+        parent::__construct($appName, $request);
127
+
128
+        $this->config = $config;
129
+        $this->urlGenerator = $urlGenerator;
130
+        $this->userManager = $userManager;
131
+        $this->logger = $logger;
132
+        $this->activityManager = $activityManager;
133
+        $this->shareManager = $shareManager;
134
+        $this->session = $session;
135
+        $this->previewManager = $previewManager;
136
+        $this->rootFolder = $rootFolder;
137
+        $this->federatedShareProvider = $federatedShareProvider;
138
+        $this->eventDispatcher = $eventDispatcher;
139
+        $this->l10n = $l10n;
140
+        $this->defaults = $defaults;
141
+    }
142
+
143
+    /**
144
+     * @PublicPage
145
+     * @NoCSRFRequired
146
+     *
147
+     * @param string $token
148
+     * @return TemplateResponse|RedirectResponse
149
+     */
150
+    public function showAuthenticate($token) {
151
+        $share = $this->shareManager->getShareByToken($token);
152
+
153
+        if($this->linkShareAuth($share)) {
154
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
155
+        }
156
+
157
+        return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
158
+    }
159
+
160
+    /**
161
+     * @PublicPage
162
+     * @UseSession
163
+     * @BruteForceProtection(action=publicLinkAuth)
164
+     *
165
+     * Authenticates against password-protected shares
166
+     * @param string $token
167
+     * @param string $password
168
+     * @return RedirectResponse|TemplateResponse|NotFoundResponse
169
+     */
170
+    public function authenticate($token, $password = '') {
171
+
172
+        // Check whether share exists
173
+        try {
174
+            $share = $this->shareManager->getShareByToken($token);
175
+        } catch (ShareNotFound $e) {
176
+            return new NotFoundResponse();
177
+        }
178
+
179
+        $authenticate = $this->linkShareAuth($share, $password);
180
+
181
+        if($authenticate === true) {
182
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
183
+        }
184
+
185
+        $response = new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
186
+        $response->throttle();
187
+        return $response;
188
+    }
189
+
190
+    /**
191
+     * Authenticate a link item with the given password.
192
+     * Or use the session if no password is provided.
193
+     *
194
+     * This is a modified version of Helper::authenticate
195
+     * TODO: Try to merge back eventually with Helper::authenticate
196
+     *
197
+     * @param \OCP\Share\IShare $share
198
+     * @param string|null $password
199
+     * @return bool
200
+     */
201
+    private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
202
+        if ($password !== null) {
203
+            if ($this->shareManager->checkPassword($share, $password)) {
204
+                $this->session->set('public_link_authenticated', (string)$share->getId());
205
+            } else {
206
+                $this->emitAccessShareHook($share, 403, 'Wrong password');
207
+                return false;
208
+            }
209
+        } else {
210
+            // not authenticated ?
211
+            if ( ! $this->session->exists('public_link_authenticated')
212
+                || $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
213
+                return false;
214
+            }
215
+        }
216
+        return true;
217
+    }
218
+
219
+    /**
220
+     * throws hooks when a share is attempted to be accessed
221
+     *
222
+     * @param \OCP\Share\IShare|string $share the Share instance if available,
223
+     * otherwise token
224
+     * @param int $errorCode
225
+     * @param string $errorMessage
226
+     * @throws \OC\HintException
227
+     * @throws \OC\ServerNotAvailableException
228
+     */
229
+    protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
230
+        $itemType = $itemSource = $uidOwner = '';
231
+        $token = $share;
232
+        $exception = null;
233
+        if($share instanceof \OCP\Share\IShare) {
234
+            try {
235
+                $token = $share->getToken();
236
+                $uidOwner = $share->getSharedBy();
237
+                $itemType = $share->getNodeType();
238
+                $itemSource = $share->getNodeId();
239
+            } catch (\Exception $e) {
240
+                // we log what we know and pass on the exception afterwards
241
+                $exception = $e;
242
+            }
243
+        }
244
+        \OC_Hook::emit('OCP\Share', 'share_link_access', [
245
+            'itemType' => $itemType,
246
+            'itemSource' => $itemSource,
247
+            'uidOwner' => $uidOwner,
248
+            'token' => $token,
249
+            'errorCode' => $errorCode,
250
+            'errorMessage' => $errorMessage,
251
+        ]);
252
+        if(!is_null($exception)) {
253
+            throw $exception;
254
+        }
255
+    }
256
+
257
+    /**
258
+     * Validate the permissions of the share
259
+     *
260
+     * @param Share\IShare $share
261
+     * @return bool
262
+     */
263
+    private function validateShare(\OCP\Share\IShare $share) {
264
+        return $share->getNode()->isReadable() && $share->getNode()->isShareable();
265
+    }
266
+
267
+    /**
268
+     * @PublicPage
269
+     * @NoCSRFRequired
270
+     *
271
+     * @param string $token
272
+     * @param string $path
273
+     * @return TemplateResponse|RedirectResponse|NotFoundResponse
274
+     * @throws NotFoundException
275
+     * @throws \Exception
276
+     */
277
+    public function showShare($token, $path = '') {
278
+        \OC_User::setIncognitoMode(true);
279
+
280
+        // Check whether share exists
281
+        try {
282
+            $share = $this->shareManager->getShareByToken($token);
283
+        } catch (ShareNotFound $e) {
284
+            $this->emitAccessShareHook($token, 404, 'Share not found');
285
+            return new NotFoundResponse();
286
+        }
287
+
288
+        // Share is password protected - check whether the user is permitted to access the share
289
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
290
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
291
+                array('token' => $token)));
292
+        }
293
+
294
+        if (!$this->validateShare($share)) {
295
+            throw new NotFoundException();
296
+        }
297
+        // We can't get the path of a file share
298
+        try {
299
+            if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
300
+                $this->emitAccessShareHook($share, 404, 'Share not found');
301
+                throw new NotFoundException();
302
+            }
303
+        } catch (\Exception $e) {
304
+            $this->emitAccessShareHook($share, 404, 'Share not found');
305
+            throw $e;
306
+        }
307
+
308
+        $shareTmpl = [];
309
+        $shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
310
+        $shareTmpl['owner'] = $share->getShareOwner();
311
+        $shareTmpl['filename'] = $share->getNode()->getName();
312
+        $shareTmpl['directory_path'] = $share->getTarget();
313
+        $shareTmpl['mimetype'] = $share->getNode()->getMimetype();
314
+        $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
315
+        $shareTmpl['dirToken'] = $token;
316
+        $shareTmpl['sharingToken'] = $token;
317
+        $shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
318
+        $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
319
+        $shareTmpl['dir'] = '';
320
+        $shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
321
+        $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
322
+
323
+        // Show file list
324
+        $hideFileList = false;
325
+        if ($share->getNode() instanceof \OCP\Files\Folder) {
326
+            /** @var \OCP\Files\Folder $rootFolder */
327
+            $rootFolder = $share->getNode();
328
+
329
+            try {
330
+                $folderNode = $rootFolder->get($path);
331
+            } catch (\OCP\Files\NotFoundException $e) {
332
+                $this->emitAccessShareHook($share, 404, 'Share not found');
333
+                throw new NotFoundException();
334
+            }
335
+
336
+            $shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
337
+
338
+            /*
339 339
 			 * The OC_Util methods require a view. This just uses the node API
340 340
 			 */
341
-			$freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
342
-			if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
343
-				$freeSpace = max($freeSpace, 0);
344
-			} else {
345
-				$freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
346
-			}
347
-
348
-			$hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true;
349
-			$maxUploadFilesize = $freeSpace;
350
-
351
-			$folder = new Template('files', 'list', '');
352
-			$folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
353
-			$folder->assign('dirToken', $token);
354
-			$folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
355
-			$folder->assign('isPublic', true);
356
-			$folder->assign('hideFileList', $hideFileList);
357
-			$folder->assign('publicUploadEnabled', 'no');
358
-			$folder->assign('uploadMaxFilesize', $maxUploadFilesize);
359
-			$folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
360
-			$folder->assign('freeSpace', $freeSpace);
361
-			$folder->assign('usedSpacePercent', 0);
362
-			$folder->assign('trash', false);
363
-			$shareTmpl['folder'] = $folder->fetchPage();
364
-		}
365
-
366
-		$shareTmpl['hideFileList'] = $hideFileList;
367
-		$shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
368
-		$shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
369
-		$shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
370
-		$shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
371
-		$shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
372
-		$shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
373
-		$shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
374
-		$shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
375
-		if ($shareTmpl['previewSupported']) {
376
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
377
-				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
378
-		} else {
379
-			$shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
380
-		}
381
-
382
-		// Load files we need
383
-		\OCP\Util::addScript('files', 'file-upload');
384
-		\OCP\Util::addStyle('files_sharing', 'publicView');
385
-		\OCP\Util::addScript('files_sharing', 'public');
386
-		\OCP\Util::addScript('files', 'fileactions');
387
-		\OCP\Util::addScript('files', 'fileactionsmenu');
388
-		\OCP\Util::addScript('files', 'jquery.fileupload');
389
-		\OCP\Util::addScript('files_sharing', 'files_drop');
390
-
391
-		if (isset($shareTmpl['folder'])) {
392
-			// JS required for folders
393
-			\OCP\Util::addStyle('files', 'merged');
394
-			\OCP\Util::addScript('files', 'filesummary');
395
-			\OCP\Util::addScript('files', 'breadcrumb');
396
-			\OCP\Util::addScript('files', 'fileinfomodel');
397
-			\OCP\Util::addScript('files', 'newfilemenu');
398
-			\OCP\Util::addScript('files', 'files');
399
-			\OCP\Util::addScript('files', 'filelist');
400
-			\OCP\Util::addScript('files', 'keyboardshortcuts');
401
-		}
402
-
403
-		// OpenGraph Support: http://ogp.me/
404
-		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName() . ' - ' . $this->defaults->getSlogan()]);
405
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->l10n->t('%s is publicly shared', [$shareTmpl['filename']])]);
406
-		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
407
-		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
408
-		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
409
-		\OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $shareTmpl['previewImage']]);
410
-
411
-		$this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
412
-
413
-		$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
414
-		$csp->addAllowedFrameDomain('\'self\'');
415
-		$response = new TemplateResponse($this->appName, 'public', $shareTmpl, 'base');
416
-		$response->setContentSecurityPolicy($csp);
417
-
418
-		$this->emitAccessShareHook($share);
419
-
420
-		return $response;
421
-	}
422
-
423
-	/**
424
-	 * @PublicPage
425
-	 * @NoCSRFRequired
426
-	 *
427
-	 * @param string $token
428
-	 * @param string $files
429
-	 * @param string $path
430
-	 * @param string $downloadStartSecret
431
-	 * @return void|\OCP\AppFramework\Http\Response
432
-	 * @throws NotFoundException
433
-	 */
434
-	public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
435
-		\OC_User::setIncognitoMode(true);
436
-
437
-		$share = $this->shareManager->getShareByToken($token);
438
-
439
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
440
-			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
441
-		}
442
-
443
-		// Share is password protected - check whether the user is permitted to access the share
444
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
445
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
446
-				['token' => $token]));
447
-		}
448
-
449
-		$files_list = null;
450
-		if (!is_null($files)) { // download selected files
451
-			$files_list = json_decode($files);
452
-			// in case we get only a single file
453
-			if ($files_list === null) {
454
-				$files_list = [$files];
455
-			}
456
-		}
457
-
458
-		$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
459
-		$originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
460
-
461
-		if (!$this->validateShare($share)) {
462
-			throw new NotFoundException();
463
-		}
464
-
465
-		// Single file share
466
-		if ($share->getNode() instanceof \OCP\Files\File) {
467
-			// Single file download
468
-			$this->singleFileDownloaded($share, $share->getNode());
469
-		}
470
-		// Directory share
471
-		else {
472
-			/** @var \OCP\Files\Folder $node */
473
-			$node = $share->getNode();
474
-
475
-			// Try to get the path
476
-			if ($path !== '') {
477
-				try {
478
-					$node = $node->get($path);
479
-				} catch (NotFoundException $e) {
480
-					$this->emitAccessShareHook($share, 404, 'Share not found');
481
-					return new NotFoundResponse();
482
-				}
483
-			}
484
-
485
-			$originalSharePath = $userFolder->getRelativePath($node->getPath());
486
-
487
-			if ($node instanceof \OCP\Files\File) {
488
-				// Single file download
489
-				$this->singleFileDownloaded($share, $share->getNode());
490
-			} else if (!empty($files_list)) {
491
-				$this->fileListDownloaded($share, $files_list, $node);
492
-			} else {
493
-				// The folder is downloaded
494
-				$this->singleFileDownloaded($share, $share->getNode());
495
-			}
496
-		}
497
-
498
-		/* FIXME: We should do this all nicely in OCP */
499
-		OC_Util::tearDownFS();
500
-		OC_Util::setupFS($share->getShareOwner());
501
-
502
-		/**
503
-		 * this sets a cookie to be able to recognize the start of the download
504
-		 * the content must not be longer than 32 characters and must only contain
505
-		 * alphanumeric characters
506
-		 */
507
-		if (!empty($downloadStartSecret)
508
-			&& !isset($downloadStartSecret[32])
509
-			&& preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
510
-
511
-			// FIXME: set on the response once we use an actual app framework response
512
-			setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
513
-		}
514
-
515
-		$this->emitAccessShareHook($share);
516
-
517
-		$server_params = array( 'head' => $this->request->getMethod() == 'HEAD' );
518
-
519
-		/**
520
-		 * Http range requests support
521
-		 */
522
-		if (isset($_SERVER['HTTP_RANGE'])) {
523
-			$server_params['range'] = $this->request->getHeader('Range');
524
-		}
525
-
526
-		// download selected files
527
-		if (!is_null($files) && $files !== '') {
528
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
529
-			// after dispatching the request which results in a "Cannot modify header information" notice.
530
-			OC_Files::get($originalSharePath, $files_list, $server_params);
531
-			exit();
532
-		} else {
533
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
534
-			// after dispatching the request which results in a "Cannot modify header information" notice.
535
-			OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
536
-			exit();
537
-		}
538
-	}
539
-
540
-	/**
541
-	 * create activity for every downloaded file
542
-	 *
543
-	 * @param Share\IShare $share
544
-	 * @param array $files_list
545
-	 * @param \OCP\Files\Folder $node
546
-	 */
547
-	protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
548
-		foreach ($files_list as $file) {
549
-			$subNode = $node->get($file);
550
-			$this->singleFileDownloaded($share, $subNode);
551
-		}
552
-
553
-	}
554
-
555
-	/**
556
-	 * create activity if a single file was downloaded from a link share
557
-	 *
558
-	 * @param Share\IShare $share
559
-	 */
560
-	protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
561
-
562
-		$fileId = $node->getId();
563
-
564
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
565
-		$userNodeList = $userFolder->getById($fileId);
566
-		$userNode = $userNodeList[0];
567
-		$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
568
-		$userPath = $userFolder->getRelativePath($userNode->getPath());
569
-		$ownerPath = $ownerFolder->getRelativePath($node->getPath());
570
-
571
-		$parameters = [$userPath];
572
-
573
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
574
-			if ($node instanceof \OCP\Files\File) {
575
-				$subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
576
-			} else {
577
-				$subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
578
-			}
579
-			$parameters[] = $share->getSharedWith();
580
-		} else {
581
-			if ($node instanceof \OCP\Files\File) {
582
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
583
-			} else {
584
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
585
-			}
586
-		}
587
-
588
-		$this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
589
-
590
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
591
-			$parameters[0] = $ownerPath;
592
-			$this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
593
-		}
594
-	}
595
-
596
-	/**
597
-	 * publish activity
598
-	 *
599
-	 * @param string $subject
600
-	 * @param array $parameters
601
-	 * @param string $affectedUser
602
-	 * @param int $fileId
603
-	 * @param string $filePath
604
-	 */
605
-	protected function publishActivity($subject,
606
-										array $parameters,
607
-										$affectedUser,
608
-										$fileId,
609
-										$filePath) {
610
-
611
-		$event = $this->activityManager->generateEvent();
612
-		$event->setApp('files_sharing')
613
-			->setType('public_links')
614
-			->setSubject($subject, $parameters)
615
-			->setAffectedUser($affectedUser)
616
-			->setObject('files', $fileId, $filePath);
617
-		$this->activityManager->publish($event);
618
-	}
341
+            $freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
342
+            if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
343
+                $freeSpace = max($freeSpace, 0);
344
+            } else {
345
+                $freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
346
+            }
347
+
348
+            $hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true;
349
+            $maxUploadFilesize = $freeSpace;
350
+
351
+            $folder = new Template('files', 'list', '');
352
+            $folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
353
+            $folder->assign('dirToken', $token);
354
+            $folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
355
+            $folder->assign('isPublic', true);
356
+            $folder->assign('hideFileList', $hideFileList);
357
+            $folder->assign('publicUploadEnabled', 'no');
358
+            $folder->assign('uploadMaxFilesize', $maxUploadFilesize);
359
+            $folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
360
+            $folder->assign('freeSpace', $freeSpace);
361
+            $folder->assign('usedSpacePercent', 0);
362
+            $folder->assign('trash', false);
363
+            $shareTmpl['folder'] = $folder->fetchPage();
364
+        }
365
+
366
+        $shareTmpl['hideFileList'] = $hideFileList;
367
+        $shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
368
+        $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
369
+        $shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
370
+        $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
371
+        $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
372
+        $shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
373
+        $shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
374
+        $shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
375
+        if ($shareTmpl['previewSupported']) {
376
+            $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
377
+                ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
378
+        } else {
379
+            $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
380
+        }
381
+
382
+        // Load files we need
383
+        \OCP\Util::addScript('files', 'file-upload');
384
+        \OCP\Util::addStyle('files_sharing', 'publicView');
385
+        \OCP\Util::addScript('files_sharing', 'public');
386
+        \OCP\Util::addScript('files', 'fileactions');
387
+        \OCP\Util::addScript('files', 'fileactionsmenu');
388
+        \OCP\Util::addScript('files', 'jquery.fileupload');
389
+        \OCP\Util::addScript('files_sharing', 'files_drop');
390
+
391
+        if (isset($shareTmpl['folder'])) {
392
+            // JS required for folders
393
+            \OCP\Util::addStyle('files', 'merged');
394
+            \OCP\Util::addScript('files', 'filesummary');
395
+            \OCP\Util::addScript('files', 'breadcrumb');
396
+            \OCP\Util::addScript('files', 'fileinfomodel');
397
+            \OCP\Util::addScript('files', 'newfilemenu');
398
+            \OCP\Util::addScript('files', 'files');
399
+            \OCP\Util::addScript('files', 'filelist');
400
+            \OCP\Util::addScript('files', 'keyboardshortcuts');
401
+        }
402
+
403
+        // OpenGraph Support: http://ogp.me/
404
+        \OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName() . ' - ' . $this->defaults->getSlogan()]);
405
+        \OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->l10n->t('%s is publicly shared', [$shareTmpl['filename']])]);
406
+        \OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
407
+        \OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
408
+        \OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
409
+        \OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $shareTmpl['previewImage']]);
410
+
411
+        $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
412
+
413
+        $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
414
+        $csp->addAllowedFrameDomain('\'self\'');
415
+        $response = new TemplateResponse($this->appName, 'public', $shareTmpl, 'base');
416
+        $response->setContentSecurityPolicy($csp);
417
+
418
+        $this->emitAccessShareHook($share);
419
+
420
+        return $response;
421
+    }
422
+
423
+    /**
424
+     * @PublicPage
425
+     * @NoCSRFRequired
426
+     *
427
+     * @param string $token
428
+     * @param string $files
429
+     * @param string $path
430
+     * @param string $downloadStartSecret
431
+     * @return void|\OCP\AppFramework\Http\Response
432
+     * @throws NotFoundException
433
+     */
434
+    public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
435
+        \OC_User::setIncognitoMode(true);
436
+
437
+        $share = $this->shareManager->getShareByToken($token);
438
+
439
+        if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
440
+            return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
441
+        }
442
+
443
+        // Share is password protected - check whether the user is permitted to access the share
444
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
445
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
446
+                ['token' => $token]));
447
+        }
448
+
449
+        $files_list = null;
450
+        if (!is_null($files)) { // download selected files
451
+            $files_list = json_decode($files);
452
+            // in case we get only a single file
453
+            if ($files_list === null) {
454
+                $files_list = [$files];
455
+            }
456
+        }
457
+
458
+        $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
459
+        $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
460
+
461
+        if (!$this->validateShare($share)) {
462
+            throw new NotFoundException();
463
+        }
464
+
465
+        // Single file share
466
+        if ($share->getNode() instanceof \OCP\Files\File) {
467
+            // Single file download
468
+            $this->singleFileDownloaded($share, $share->getNode());
469
+        }
470
+        // Directory share
471
+        else {
472
+            /** @var \OCP\Files\Folder $node */
473
+            $node = $share->getNode();
474
+
475
+            // Try to get the path
476
+            if ($path !== '') {
477
+                try {
478
+                    $node = $node->get($path);
479
+                } catch (NotFoundException $e) {
480
+                    $this->emitAccessShareHook($share, 404, 'Share not found');
481
+                    return new NotFoundResponse();
482
+                }
483
+            }
484
+
485
+            $originalSharePath = $userFolder->getRelativePath($node->getPath());
486
+
487
+            if ($node instanceof \OCP\Files\File) {
488
+                // Single file download
489
+                $this->singleFileDownloaded($share, $share->getNode());
490
+            } else if (!empty($files_list)) {
491
+                $this->fileListDownloaded($share, $files_list, $node);
492
+            } else {
493
+                // The folder is downloaded
494
+                $this->singleFileDownloaded($share, $share->getNode());
495
+            }
496
+        }
497
+
498
+        /* FIXME: We should do this all nicely in OCP */
499
+        OC_Util::tearDownFS();
500
+        OC_Util::setupFS($share->getShareOwner());
501
+
502
+        /**
503
+         * this sets a cookie to be able to recognize the start of the download
504
+         * the content must not be longer than 32 characters and must only contain
505
+         * alphanumeric characters
506
+         */
507
+        if (!empty($downloadStartSecret)
508
+            && !isset($downloadStartSecret[32])
509
+            && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
510
+
511
+            // FIXME: set on the response once we use an actual app framework response
512
+            setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
513
+        }
514
+
515
+        $this->emitAccessShareHook($share);
516
+
517
+        $server_params = array( 'head' => $this->request->getMethod() == 'HEAD' );
518
+
519
+        /**
520
+         * Http range requests support
521
+         */
522
+        if (isset($_SERVER['HTTP_RANGE'])) {
523
+            $server_params['range'] = $this->request->getHeader('Range');
524
+        }
525
+
526
+        // download selected files
527
+        if (!is_null($files) && $files !== '') {
528
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
529
+            // after dispatching the request which results in a "Cannot modify header information" notice.
530
+            OC_Files::get($originalSharePath, $files_list, $server_params);
531
+            exit();
532
+        } else {
533
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
534
+            // after dispatching the request which results in a "Cannot modify header information" notice.
535
+            OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
536
+            exit();
537
+        }
538
+    }
539
+
540
+    /**
541
+     * create activity for every downloaded file
542
+     *
543
+     * @param Share\IShare $share
544
+     * @param array $files_list
545
+     * @param \OCP\Files\Folder $node
546
+     */
547
+    protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
548
+        foreach ($files_list as $file) {
549
+            $subNode = $node->get($file);
550
+            $this->singleFileDownloaded($share, $subNode);
551
+        }
552
+
553
+    }
554
+
555
+    /**
556
+     * create activity if a single file was downloaded from a link share
557
+     *
558
+     * @param Share\IShare $share
559
+     */
560
+    protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
561
+
562
+        $fileId = $node->getId();
563
+
564
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
565
+        $userNodeList = $userFolder->getById($fileId);
566
+        $userNode = $userNodeList[0];
567
+        $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
568
+        $userPath = $userFolder->getRelativePath($userNode->getPath());
569
+        $ownerPath = $ownerFolder->getRelativePath($node->getPath());
570
+
571
+        $parameters = [$userPath];
572
+
573
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
574
+            if ($node instanceof \OCP\Files\File) {
575
+                $subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
576
+            } else {
577
+                $subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
578
+            }
579
+            $parameters[] = $share->getSharedWith();
580
+        } else {
581
+            if ($node instanceof \OCP\Files\File) {
582
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
583
+            } else {
584
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
585
+            }
586
+        }
587
+
588
+        $this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
589
+
590
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
591
+            $parameters[0] = $ownerPath;
592
+            $this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
593
+        }
594
+    }
595
+
596
+    /**
597
+     * publish activity
598
+     *
599
+     * @param string $subject
600
+     * @param array $parameters
601
+     * @param string $affectedUser
602
+     * @param int $fileId
603
+     * @param string $filePath
604
+     */
605
+    protected function publishActivity($subject,
606
+                                        array $parameters,
607
+                                        $affectedUser,
608
+                                        $fileId,
609
+                                        $filePath) {
610
+
611
+        $event = $this->activityManager->generateEvent();
612
+        $event->setApp('files_sharing')
613
+            ->setType('public_links')
614
+            ->setSubject($subject, $parameters)
615
+            ->setAffectedUser($affectedUser)
616
+            ->setObject('files', $fileId, $filePath);
617
+        $this->activityManager->publish($event);
618
+    }
619 619
 
620 620
 
621 621
 }
Please login to merge, or discard this patch.
apps/provisioning_api/lib/Controller/UsersController.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -225,7 +225,7 @@
 block discarded – undo
225 225
 	/**
226 226
 	 * creates a array with all user data
227 227
 	 *
228
-	 * @param $userId
228
+	 * @param string $userId
229 229
 	 * @return array
230 230
 	 * @throws OCSException
231 231
 	 */
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -335,7 +335,7 @@
 block discarded – undo
335 335
 					}
336 336
 					if($quota === 0) {
337 337
 						$quota = 'default';
338
-					}else if($quota === -1) {
338
+					} else if($quota === -1) {
339 339
 						$quota = 'none';
340 340
 					} else {
341 341
 						$quota = \OCP\Util::humanFileSize($quota);
Please login to merge, or discard this patch.
Spacing   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 		// Admin? Or SubAdmin?
124 124
 		$uid = $user->getUID();
125 125
 		$subAdminManager = $this->groupManager->getSubAdmin();
126
-		if($this->groupManager->isAdmin($uid)){
126
+		if ($this->groupManager->isAdmin($uid)) {
127 127
 			$users = $this->userManager->search($search, $limit, $offset);
128 128
 		} else if ($subAdminManager->isSubAdmin($user)) {
129 129
 			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
 				$subAdminOfGroups[$key] = $group->getGID();
132 132
 			}
133 133
 
134
-			if($offset === null) {
134
+			if ($offset === null) {
135 135
 				$offset = 0;
136 136
 			}
137 137
 
@@ -165,22 +165,22 @@  discard block
 block discarded – undo
165 165
 		$isAdmin = $this->groupManager->isAdmin($user->getUID());
166 166
 		$subAdminManager = $this->groupManager->getSubAdmin();
167 167
 
168
-		if($this->userManager->userExists($userid)) {
168
+		if ($this->userManager->userExists($userid)) {
169 169
 			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
170 170
 			throw new OCSException('User already exists', 102);
171 171
 		}
172 172
 
173
-		if(is_array($groups)) {
173
+		if (is_array($groups)) {
174 174
 			foreach ($groups as $group) {
175
-				if(!$this->groupManager->groupExists($group)) {
175
+				if (!$this->groupManager->groupExists($group)) {
176 176
 					throw new OCSException('group '.$group.' does not exist', 104);
177 177
 				}
178
-				if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
179
-					throw new OCSException('insufficient privileges for group '. $group, 105);
178
+				if (!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
179
+					throw new OCSException('insufficient privileges for group '.$group, 105);
180 180
 				}
181 181
 			}
182 182
 		} else {
183
-			if(!$isAdmin) {
183
+			if (!$isAdmin) {
184 184
 				throw new OCSException('no group specified (required for subadmins)', 106);
185 185
 			}
186 186
 		}
@@ -229,7 +229,7 @@  discard block
 block discarded – undo
229 229
 	public function getCurrentUser() {
230 230
 		$user = $this->userSession->getUser();
231 231
 		if ($user) {
232
-			$data =  $this->getUserData($user->getUID());
232
+			$data = $this->getUserData($user->getUID());
233 233
 			// rename "displayname" to "display-name" only for this call to keep
234 234
 			// the API stable.
235 235
 			$data['display-name'] = $data['displayname'];
@@ -255,17 +255,17 @@  discard block
 block discarded – undo
255 255
 
256 256
 		// Check if the target user exists
257 257
 		$targetUserObject = $this->userManager->get($userId);
258
-		if($targetUserObject === null) {
258
+		if ($targetUserObject === null) {
259 259
 			throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
260 260
 		}
261 261
 
262 262
 		// Admin? Or SubAdmin?
263
-		if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
263
+		if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())
264 264
 			|| $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
265 265
 			$data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true');
266 266
 		} else {
267 267
 			// Check they are looking up themselves
268
-			if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
268
+			if ($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
269 269
 				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
270 270
 			}
271 271
 		}
@@ -311,12 +311,12 @@  discard block
 block discarded – undo
311 311
 		$currentLoggedInUser = $this->userSession->getUser();
312 312
 
313 313
 		$targetUser = $this->userManager->get($userId);
314
-		if($targetUser === null) {
314
+		if ($targetUser === null) {
315 315
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
316 316
 		}
317 317
 
318 318
 		$permittedFields = [];
319
-		if($targetUser->getUID() === $currentLoggedInUser->getUID()) {
319
+		if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
320 320
 			// Editing self (display, email)
321 321
 			if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
322 322
 				$permittedFields[] = 'display';
@@ -343,13 +343,13 @@  discard block
 block discarded – undo
343 343
 			}
344 344
 
345 345
 			// If admin they can edit their own quota
346
-			if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
346
+			if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
347 347
 				$permittedFields[] = 'quota';
348 348
 			}
349 349
 		} else {
350 350
 			// Check if admin / subadmin
351 351
 			$subAdminManager = $this->groupManager->getSubAdmin();
352
-			if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
352
+			if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
353 353
 			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
354 354
 				// They have permissions over the user
355 355
 				$permittedFields[] = 'display';
@@ -369,18 +369,18 @@  discard block
 block discarded – undo
369 369
 			}
370 370
 		}
371 371
 		// Check if permitted to edit this field
372
-		if(!in_array($key, $permittedFields)) {
372
+		if (!in_array($key, $permittedFields)) {
373 373
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
374 374
 		}
375 375
 		// Process the edit
376
-		switch($key) {
376
+		switch ($key) {
377 377
 			case 'display':
378 378
 			case AccountManager::PROPERTY_DISPLAYNAME:
379 379
 				$targetUser->setDisplayName($value);
380 380
 				break;
381 381
 			case 'quota':
382 382
 				$quota = $value;
383
-				if($quota !== 'none' && $quota !== 'default') {
383
+				if ($quota !== 'none' && $quota !== 'default') {
384 384
 					if (is_numeric($quota)) {
385 385
 						$quota = (float) $quota;
386 386
 					} else {
@@ -389,9 +389,9 @@  discard block
 block discarded – undo
389 389
 					if ($quota === false) {
390 390
 						throw new OCSException('Invalid quota value '.$value, 103);
391 391
 					}
392
-					if($quota === 0) {
392
+					if ($quota === 0) {
393 393
 						$quota = 'default';
394
-					}else if($quota === -1) {
394
+					} else if ($quota === -1) {
395 395
 						$quota = 'none';
396 396
 					} else {
397 397
 						$quota = \OCP\Util::humanFileSize($quota);
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
 				$this->config->setUserValue($targetUser->getUID(), 'core', 'locale', $value);
415 415
 				break;
416 416
 			case AccountManager::PROPERTY_EMAIL:
417
-				if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
417
+				if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
418 418
 					$targetUser->setEMailAddress($value);
419 419
 				} else {
420 420
 					throw new OCSException('', 102);
@@ -450,18 +450,18 @@  discard block
 block discarded – undo
450 450
 
451 451
 		$targetUser = $this->userManager->get($userId);
452 452
 
453
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
453
+		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
454 454
 			throw new OCSException('', 101);
455 455
 		}
456 456
 
457 457
 		// If not permitted
458 458
 		$subAdminManager = $this->groupManager->getSubAdmin();
459
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
459
+		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
460 460
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
461 461
 		}
462 462
 
463 463
 		// Go ahead with the delete
464
-		if($targetUser->delete()) {
464
+		if ($targetUser->delete()) {
465 465
 			return new DataResponse();
466 466
 		} else {
467 467
 			throw new OCSException('', 101);
@@ -505,13 +505,13 @@  discard block
 block discarded – undo
505 505
 		$currentLoggedInUser = $this->userSession->getUser();
506 506
 
507 507
 		$targetUser = $this->userManager->get($userId);
508
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
508
+		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
509 509
 			throw new OCSException('', 101);
510 510
 		}
511 511
 
512 512
 		// If not permitted
513 513
 		$subAdminManager = $this->groupManager->getSubAdmin();
514
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
514
+		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
515 515
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
516 516
 		}
517 517
 
@@ -532,11 +532,11 @@  discard block
 block discarded – undo
532 532
 		$loggedInUser = $this->userSession->getUser();
533 533
 
534 534
 		$targetUser = $this->userManager->get($userId);
535
-		if($targetUser === null) {
535
+		if ($targetUser === null) {
536 536
 			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
537 537
 		}
538 538
 
539
-		if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
539
+		if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
540 540
 			// Self lookup or admin lookup
541 541
 			return new DataResponse([
542 542
 				'groups' => $this->groupManager->getUserGroupIds($targetUser)
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
 			$subAdminManager = $this->groupManager->getSubAdmin();
546 546
 
547 547
 			// Looking up someone else
548
-			if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
548
+			if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
549 549
 				// Return the group that the method caller is subadmin of for the user in question
550 550
 				/** @var IGroup[] $getSubAdminsGroups */
551 551
 				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
@@ -575,16 +575,16 @@  discard block
 block discarded – undo
575 575
 	 * @throws OCSException
576 576
 	 */
577 577
 	public function addToGroup($userId, $groupid = '') {
578
-		if($groupid === '') {
578
+		if ($groupid === '') {
579 579
 			throw new OCSException('', 101);
580 580
 		}
581 581
 
582 582
 		$group = $this->groupManager->get($groupid);
583 583
 		$targetUser = $this->userManager->get($userId);
584
-		if($group === null) {
584
+		if ($group === null) {
585 585
 			throw new OCSException('', 102);
586 586
 		}
587
-		if($targetUser === null) {
587
+		if ($targetUser === null) {
588 588
 			throw new OCSException('', 103);
589 589
 		}
590 590
 
@@ -612,17 +612,17 @@  discard block
 block discarded – undo
612 612
 	public function removeFromGroup($userId, $groupid) {
613 613
 		$loggedInUser = $this->userSession->getUser();
614 614
 
615
-		if($groupid === null) {
615
+		if ($groupid === null) {
616 616
 			throw new OCSException('', 101);
617 617
 		}
618 618
 
619 619
 		$group = $this->groupManager->get($groupid);
620
-		if($group === null) {
620
+		if ($group === null) {
621 621
 			throw new OCSException('', 102);
622 622
 		}
623 623
 
624 624
 		$targetUser = $this->userManager->get($userId);
625
-		if($targetUser === null) {
625
+		if ($targetUser === null) {
626 626
 			throw new OCSException('', 103);
627 627
 		}
628 628
 
@@ -646,7 +646,7 @@  discard block
 block discarded – undo
646 646
 		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
647 647
 			/** @var IGroup[] $subAdminGroups */
648 648
 			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
649
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
649
+			$subAdminGroups = array_map(function(IGroup $subAdminGroup) {
650 650
 				return $subAdminGroup->getGID();
651 651
 			}, $subAdminGroups);
652 652
 			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
@@ -678,15 +678,15 @@  discard block
 block discarded – undo
678 678
 		$user = $this->userManager->get($userId);
679 679
 
680 680
 		// Check if the user exists
681
-		if($user === null) {
681
+		if ($user === null) {
682 682
 			throw new OCSException('User does not exist', 101);
683 683
 		}
684 684
 		// Check if group exists
685
-		if($group === null) {
686
-			throw new OCSException('Group does not exist',  102);
685
+		if ($group === null) {
686
+			throw new OCSException('Group does not exist', 102);
687 687
 		}
688 688
 		// Check if trying to make subadmin of admin group
689
-		if($group->getGID() === 'admin') {
689
+		if ($group->getGID() === 'admin') {
690 690
 			throw new OCSException('Cannot create subadmins for admin group', 103);
691 691
 		}
692 692
 
@@ -697,7 +697,7 @@  discard block
 block discarded – undo
697 697
 			return new DataResponse();
698 698
 		}
699 699
 		// Go
700
-		if($subAdminManager->createSubAdmin($user, $group)) {
700
+		if ($subAdminManager->createSubAdmin($user, $group)) {
701 701
 			return new DataResponse();
702 702
 		} else {
703 703
 			throw new OCSException('Unknown error occurred', 103);
@@ -720,20 +720,20 @@  discard block
 block discarded – undo
720 720
 		$subAdminManager = $this->groupManager->getSubAdmin();
721 721
 
722 722
 		// Check if the user exists
723
-		if($user === null) {
723
+		if ($user === null) {
724 724
 			throw new OCSException('User does not exist', 101);
725 725
 		}
726 726
 		// Check if the group exists
727
-		if($group === null) {
727
+		if ($group === null) {
728 728
 			throw new OCSException('Group does not exist', 101);
729 729
 		}
730 730
 		// Check if they are a subadmin of this said group
731
-		if(!$subAdminManager->isSubAdminOfGroup($user, $group)) {
731
+		if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
732 732
 			throw new OCSException('User is not a subadmin of this group', 102);
733 733
 		}
734 734
 
735 735
 		// Go
736
-		if($subAdminManager->deleteSubAdmin($user, $group)) {
736
+		if ($subAdminManager->deleteSubAdmin($user, $group)) {
737 737
 			return new DataResponse();
738 738
 		} else {
739 739
 			throw new OCSException('Unknown error occurred', 103);
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
 	public function getUserSubAdminGroups($userId) {
751 751
 		$user = $this->userManager->get($userId);
752 752
 		// Check if the user exists
753
-		if($user === null) {
753
+		if ($user === null) {
754 754
 			throw new OCSException('User does not exist', 101);
755 755
 		}
756 756
 
@@ -760,7 +760,7 @@  discard block
 block discarded – undo
760 760
 			$groups[$key] = $group->getGID();
761 761
 		}
762 762
 
763
-		if(!$groups) {
763
+		if (!$groups) {
764 764
 			throw new OCSException('Unknown error occurred', 102);
765 765
 		} else {
766 766
 			return new DataResponse($groups);
@@ -804,13 +804,13 @@  discard block
 block discarded – undo
804 804
 		$currentLoggedInUser = $this->userSession->getUser();
805 805
 
806 806
 		$targetUser = $this->userManager->get($userId);
807
-		if($targetUser === null) {
807
+		if ($targetUser === null) {
808 808
 			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
809 809
 		}
810 810
 
811 811
 		// Check if admin / subadmin
812 812
 		$subAdminManager = $this->groupManager->getSubAdmin();
813
-		if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
813
+		if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
814 814
 			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
815 815
 			// No rights
816 816
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
@@ -832,8 +832,8 @@  discard block
 block discarded – undo
832 832
 			$this->newUserMailHelper->setL10N($l10n);
833 833
 			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
834 834
 			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
835
-		} catch(\Exception $e) {
836
-			$this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
835
+		} catch (\Exception $e) {
836
+			$this->logger->error("Can't send new user mail to $email: ".$e->getMessage(), array('app' => 'settings'));
837 837
 			throw new OCSException('Sending email failed', 102);
838 838
 		}
839 839
 
Please login to merge, or discard this patch.
Indentation   +791 added lines, -791 removed lines patch added patch discarded remove patch
@@ -50,795 +50,795 @@
 block discarded – undo
50 50
 
51 51
 class UsersController extends OCSController {
52 52
 
53
-	/** @var IUserManager */
54
-	private $userManager;
55
-	/** @var IConfig */
56
-	private $config;
57
-	/** @var IAppManager */
58
-	private $appManager;
59
-	/** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface
60
-	private $groupManager;
61
-	/** @var IUserSession */
62
-	private $userSession;
63
-	/** @var AccountManager */
64
-	private $accountManager;
65
-	/** @var ILogger */
66
-	private $logger;
67
-	/** @var IFactory */
68
-	private $l10nFactory;
69
-	/** @var NewUserMailHelper */
70
-	private $newUserMailHelper;
71
-
72
-	/**
73
-	 * @param string $appName
74
-	 * @param IRequest $request
75
-	 * @param IUserManager $userManager
76
-	 * @param IConfig $config
77
-	 * @param IAppManager $appManager
78
-	 * @param IGroupManager $groupManager
79
-	 * @param IUserSession $userSession
80
-	 * @param AccountManager $accountManager
81
-	 * @param ILogger $logger
82
-	 * @param IFactory $l10nFactory
83
-	 * @param NewUserMailHelper $newUserMailHelper
84
-	 */
85
-	public function __construct($appName,
86
-								IRequest $request,
87
-								IUserManager $userManager,
88
-								IConfig $config,
89
-								IAppManager $appManager,
90
-								IGroupManager $groupManager,
91
-								IUserSession $userSession,
92
-								AccountManager $accountManager,
93
-								ILogger $logger,
94
-								IFactory $l10nFactory,
95
-								NewUserMailHelper $newUserMailHelper) {
96
-		parent::__construct($appName, $request);
97
-
98
-		$this->userManager = $userManager;
99
-		$this->config = $config;
100
-		$this->appManager = $appManager;
101
-		$this->groupManager = $groupManager;
102
-		$this->userSession = $userSession;
103
-		$this->accountManager = $accountManager;
104
-		$this->logger = $logger;
105
-		$this->l10nFactory = $l10nFactory;
106
-		$this->newUserMailHelper = $newUserMailHelper;
107
-	}
108
-
109
-	/**
110
-	 * @NoAdminRequired
111
-	 *
112
-	 * returns a list of users
113
-	 *
114
-	 * @param string $search
115
-	 * @param int $limit
116
-	 * @param int $offset
117
-	 * @return DataResponse
118
-	 */
119
-	public function getUsers($search = '', $limit = null, $offset = null) {
120
-		$user = $this->userSession->getUser();
121
-		$users = [];
122
-
123
-		// Admin? Or SubAdmin?
124
-		$uid = $user->getUID();
125
-		$subAdminManager = $this->groupManager->getSubAdmin();
126
-		if($this->groupManager->isAdmin($uid)){
127
-			$users = $this->userManager->search($search, $limit, $offset);
128
-		} else if ($subAdminManager->isSubAdmin($user)) {
129
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
130
-			foreach ($subAdminOfGroups as $key => $group) {
131
-				$subAdminOfGroups[$key] = $group->getGID();
132
-			}
133
-
134
-			if($offset === null) {
135
-				$offset = 0;
136
-			}
137
-
138
-			$users = [];
139
-			foreach ($subAdminOfGroups as $group) {
140
-				$users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search));
141
-			}
142
-
143
-			$users = array_slice($users, $offset, $limit);
144
-		}
145
-
146
-		$users = array_keys($users);
147
-
148
-		return new DataResponse([
149
-			'users' => $users
150
-		]);
151
-	}
152
-
153
-	/**
154
-	 * @PasswordConfirmationRequired
155
-	 * @NoAdminRequired
156
-	 *
157
-	 * @param string $userid
158
-	 * @param string $password
159
-	 * @param array $groups
160
-	 * @return DataResponse
161
-	 * @throws OCSException
162
-	 */
163
-	public function addUser($userid, $password, $groups = null) {
164
-		$user = $this->userSession->getUser();
165
-		$isAdmin = $this->groupManager->isAdmin($user->getUID());
166
-		$subAdminManager = $this->groupManager->getSubAdmin();
167
-
168
-		if($this->userManager->userExists($userid)) {
169
-			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
170
-			throw new OCSException('User already exists', 102);
171
-		}
172
-
173
-		if(is_array($groups)) {
174
-			foreach ($groups as $group) {
175
-				if(!$this->groupManager->groupExists($group)) {
176
-					throw new OCSException('group '.$group.' does not exist', 104);
177
-				}
178
-				if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
179
-					throw new OCSException('insufficient privileges for group '. $group, 105);
180
-				}
181
-			}
182
-		} else {
183
-			if(!$isAdmin) {
184
-				throw new OCSException('no group specified (required for subadmins)', 106);
185
-			}
186
-		}
187
-
188
-		try {
189
-			$newUser = $this->userManager->createUser($userid, $password);
190
-			$this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
191
-
192
-			if (is_array($groups)) {
193
-				foreach ($groups as $group) {
194
-					$this->groupManager->get($group)->addUser($newUser);
195
-					$this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
196
-				}
197
-			}
198
-			return new DataResponse();
199
-		} catch (\Exception $e) {
200
-			$this->logger->error('Failed addUser attempt with exception: '.$e->getMessage(), ['app' => 'ocs_api']);
201
-			throw new OCSException('Bad request', 101);
202
-		}
203
-	}
204
-
205
-	/**
206
-	 * @NoAdminRequired
207
-	 * @NoSubAdminRequired
208
-	 *
209
-	 * gets user info
210
-	 *
211
-	 * @param string $userId
212
-	 * @return DataResponse
213
-	 * @throws OCSException
214
-	 */
215
-	public function getUser($userId) {
216
-		$data = $this->getUserData($userId);
217
-		return new DataResponse($data);
218
-	}
219
-
220
-	/**
221
-	 * @NoAdminRequired
222
-	 * @NoSubAdminRequired
223
-	 *
224
-	 * gets user info from the currently logged in user
225
-	 *
226
-	 * @return DataResponse
227
-	 * @throws OCSException
228
-	 */
229
-	public function getCurrentUser() {
230
-		$user = $this->userSession->getUser();
231
-		if ($user) {
232
-			$data =  $this->getUserData($user->getUID());
233
-			// rename "displayname" to "display-name" only for this call to keep
234
-			// the API stable.
235
-			$data['display-name'] = $data['displayname'];
236
-			unset($data['displayname']);
237
-			return new DataResponse($data);
238
-
239
-		}
240
-
241
-		throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
242
-	}
243
-
244
-	/**
245
-	 * creates a array with all user data
246
-	 *
247
-	 * @param $userId
248
-	 * @return array
249
-	 * @throws OCSException
250
-	 */
251
-	protected function getUserData($userId) {
252
-		$currentLoggedInUser = $this->userSession->getUser();
253
-
254
-		$data = [];
255
-
256
-		// Check if the target user exists
257
-		$targetUserObject = $this->userManager->get($userId);
258
-		if($targetUserObject === null) {
259
-			throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
260
-		}
261
-
262
-		// Admin? Or SubAdmin?
263
-		if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
264
-			|| $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
265
-			$data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true');
266
-		} else {
267
-			// Check they are looking up themselves
268
-			if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
269
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
270
-			}
271
-		}
272
-
273
-		$userAccount = $this->accountManager->getUser($targetUserObject);
274
-		$groups = $this->groupManager->getUserGroups($targetUserObject);
275
-		$gids = [];
276
-		foreach ($groups as $group) {
277
-			$gids[] = $group->getDisplayName();
278
-		}
279
-
280
-		// Find the data
281
-		$data['id'] = $targetUserObject->getUID();
282
-		$data['quota'] = $this->fillStorageInfo($targetUserObject->getUID());
283
-		$data[AccountManager::PROPERTY_EMAIL] = $targetUserObject->getEMailAddress();
284
-		$data[AccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
285
-		$data[AccountManager::PROPERTY_PHONE] = $userAccount[AccountManager::PROPERTY_PHONE]['value'];
286
-		$data[AccountManager::PROPERTY_ADDRESS] = $userAccount[AccountManager::PROPERTY_ADDRESS]['value'];
287
-		$data[AccountManager::PROPERTY_WEBSITE] = $userAccount[AccountManager::PROPERTY_WEBSITE]['value'];
288
-		$data[AccountManager::PROPERTY_TWITTER] = $userAccount[AccountManager::PROPERTY_TWITTER]['value'];
289
-		$data['groups'] = $gids;
290
-		$data['language'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'lang');
291
-		$data['locale'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'locale');
292
-
293
-		return $data;
294
-	}
295
-
296
-	/**
297
-	 * @NoAdminRequired
298
-	 * @NoSubAdminRequired
299
-	 * @PasswordConfirmationRequired
300
-	 *
301
-	 * edit users
302
-	 *
303
-	 * @param string $userId
304
-	 * @param string $key
305
-	 * @param string $value
306
-	 * @return DataResponse
307
-	 * @throws OCSException
308
-	 * @throws OCSForbiddenException
309
-	 */
310
-	public function editUser($userId, $key, $value) {
311
-		$currentLoggedInUser = $this->userSession->getUser();
312
-
313
-		$targetUser = $this->userManager->get($userId);
314
-		if($targetUser === null) {
315
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
316
-		}
317
-
318
-		$permittedFields = [];
319
-		if($targetUser->getUID() === $currentLoggedInUser->getUID()) {
320
-			// Editing self (display, email)
321
-			if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
322
-				$permittedFields[] = 'display';
323
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
324
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
325
-			}
326
-
327
-			$permittedFields[] = 'password';
328
-			if ($this->config->getSystemValue('force_language', false) === false ||
329
-				$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
330
-				$permittedFields[] = 'language';
331
-				$permittedFields[] = 'locale';
332
-			}
333
-
334
-			if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
335
-				$federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
336
-				$shareProvider = $federatedFileSharing->getFederatedShareProvider();
337
-				if ($shareProvider->isLookupServerUploadEnabled()) {
338
-					$permittedFields[] = AccountManager::PROPERTY_PHONE;
339
-					$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
340
-					$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
341
-					$permittedFields[] = AccountManager::PROPERTY_TWITTER;
342
-				}
343
-			}
344
-
345
-			// If admin they can edit their own quota
346
-			if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
347
-				$permittedFields[] = 'quota';
348
-			}
349
-		} else {
350
-			// Check if admin / subadmin
351
-			$subAdminManager = $this->groupManager->getSubAdmin();
352
-			if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
353
-			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
354
-				// They have permissions over the user
355
-				$permittedFields[] = 'display';
356
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
357
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
358
-				$permittedFields[] = 'password';
359
-				$permittedFields[] = 'language';
360
-				$permittedFields[] = 'locale';
361
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
362
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
363
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
364
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
365
-				$permittedFields[] = 'quota';
366
-			} else {
367
-				// No rights
368
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
369
-			}
370
-		}
371
-		// Check if permitted to edit this field
372
-		if(!in_array($key, $permittedFields)) {
373
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
374
-		}
375
-		// Process the edit
376
-		switch($key) {
377
-			case 'display':
378
-			case AccountManager::PROPERTY_DISPLAYNAME:
379
-				$targetUser->setDisplayName($value);
380
-				break;
381
-			case 'quota':
382
-				$quota = $value;
383
-				if($quota !== 'none' && $quota !== 'default') {
384
-					if (is_numeric($quota)) {
385
-						$quota = (float) $quota;
386
-					} else {
387
-						$quota = \OCP\Util::computerFileSize($quota);
388
-					}
389
-					if ($quota === false) {
390
-						throw new OCSException('Invalid quota value '.$value, 103);
391
-					}
392
-					if($quota === 0) {
393
-						$quota = 'default';
394
-					}else if($quota === -1) {
395
-						$quota = 'none';
396
-					} else {
397
-						$quota = \OCP\Util::humanFileSize($quota);
398
-					}
399
-				}
400
-				$targetUser->setQuota($quota);
401
-				break;
402
-			case 'password':
403
-				$targetUser->setPassword($value);
404
-				break;
405
-			case 'language':
406
-				$languagesCodes = $this->l10nFactory->findAvailableLanguages();
407
-				if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
408
-					throw new OCSException('Invalid language', 102);
409
-				}
410
-				$this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
411
-				break;
412
-			case 'locale':
413
-				if (!$this->l10nFactory->localeExists($value)) {
414
-					throw new OCSException('Invalid locale', 102);
415
-				}
416
-				$this->config->setUserValue($targetUser->getUID(), 'core', 'locale', $value);
417
-				break;
418
-			case AccountManager::PROPERTY_EMAIL:
419
-				if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
420
-					$targetUser->setEMailAddress($value);
421
-				} else {
422
-					throw new OCSException('', 102);
423
-				}
424
-				break;
425
-			case AccountManager::PROPERTY_PHONE:
426
-			case AccountManager::PROPERTY_ADDRESS:
427
-			case AccountManager::PROPERTY_WEBSITE:
428
-			case AccountManager::PROPERTY_TWITTER:
429
-				$userAccount = $this->accountManager->getUser($targetUser);
430
-				if ($userAccount[$key]['value'] !== $value) {
431
-					$userAccount[$key]['value'] = $value;
432
-					$this->accountManager->updateUser($targetUser, $userAccount);
433
-				}
434
-				break;
435
-			default:
436
-				throw new OCSException('', 103);
437
-		}
438
-		return new DataResponse();
439
-	}
440
-
441
-	/**
442
-	 * @PasswordConfirmationRequired
443
-	 * @NoAdminRequired
444
-	 *
445
-	 * @param string $userId
446
-	 * @return DataResponse
447
-	 * @throws OCSException
448
-	 * @throws OCSForbiddenException
449
-	 */
450
-	public function deleteUser($userId) {
451
-		$currentLoggedInUser = $this->userSession->getUser();
452
-
453
-		$targetUser = $this->userManager->get($userId);
454
-
455
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
456
-			throw new OCSException('', 101);
457
-		}
458
-
459
-		// If not permitted
460
-		$subAdminManager = $this->groupManager->getSubAdmin();
461
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
462
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
463
-		}
464
-
465
-		// Go ahead with the delete
466
-		if($targetUser->delete()) {
467
-			return new DataResponse();
468
-		} else {
469
-			throw new OCSException('', 101);
470
-		}
471
-	}
472
-
473
-	/**
474
-	 * @PasswordConfirmationRequired
475
-	 * @NoAdminRequired
476
-	 *
477
-	 * @param string $userId
478
-	 * @return DataResponse
479
-	 * @throws OCSException
480
-	 * @throws OCSForbiddenException
481
-	 */
482
-	public function disableUser($userId) {
483
-		return $this->setEnabled($userId, false);
484
-	}
485
-
486
-	/**
487
-	 * @PasswordConfirmationRequired
488
-	 * @NoAdminRequired
489
-	 *
490
-	 * @param string $userId
491
-	 * @return DataResponse
492
-	 * @throws OCSException
493
-	 * @throws OCSForbiddenException
494
-	 */
495
-	public function enableUser($userId) {
496
-		return $this->setEnabled($userId, true);
497
-	}
498
-
499
-	/**
500
-	 * @param string $userId
501
-	 * @param bool $value
502
-	 * @return DataResponse
503
-	 * @throws OCSException
504
-	 * @throws OCSForbiddenException
505
-	 */
506
-	private function setEnabled($userId, $value) {
507
-		$currentLoggedInUser = $this->userSession->getUser();
508
-
509
-		$targetUser = $this->userManager->get($userId);
510
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
511
-			throw new OCSException('', 101);
512
-		}
513
-
514
-		// If not permitted
515
-		$subAdminManager = $this->groupManager->getSubAdmin();
516
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
517
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
518
-		}
519
-
520
-		// enable/disable the user now
521
-		$targetUser->setEnabled($value);
522
-		return new DataResponse();
523
-	}
524
-
525
-	/**
526
-	 * @NoAdminRequired
527
-	 * @NoSubAdminRequired
528
-	 *
529
-	 * @param string $userId
530
-	 * @return DataResponse
531
-	 * @throws OCSException
532
-	 */
533
-	public function getUsersGroups($userId) {
534
-		$loggedInUser = $this->userSession->getUser();
535
-
536
-		$targetUser = $this->userManager->get($userId);
537
-		if($targetUser === null) {
538
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
539
-		}
540
-
541
-		if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
542
-			// Self lookup or admin lookup
543
-			return new DataResponse([
544
-				'groups' => $this->groupManager->getUserGroupIds($targetUser)
545
-			]);
546
-		} else {
547
-			$subAdminManager = $this->groupManager->getSubAdmin();
548
-
549
-			// Looking up someone else
550
-			if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
551
-				// Return the group that the method caller is subadmin of for the user in question
552
-				/** @var IGroup[] $getSubAdminsGroups */
553
-				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
554
-				foreach ($getSubAdminsGroups as $key => $group) {
555
-					$getSubAdminsGroups[$key] = $group->getGID();
556
-				}
557
-				$groups = array_intersect(
558
-					$getSubAdminsGroups,
559
-					$this->groupManager->getUserGroupIds($targetUser)
560
-				);
561
-				return new DataResponse(['groups' => $groups]);
562
-			} else {
563
-				// Not permitted
564
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
565
-			}
566
-		}
567
-
568
-	}
569
-
570
-	/**
571
-	 * @PasswordConfirmationRequired
572
-	 * @NoAdminRequired
573
-	 *
574
-	 * @param string $userId
575
-	 * @param string $groupid
576
-	 * @return DataResponse
577
-	 * @throws OCSException
578
-	 */
579
-	public function addToGroup($userId, $groupid = '') {
580
-		if($groupid === '') {
581
-			throw new OCSException('', 101);
582
-		}
583
-
584
-		$group = $this->groupManager->get($groupid);
585
-		$targetUser = $this->userManager->get($userId);
586
-		if($group === null) {
587
-			throw new OCSException('', 102);
588
-		}
589
-		if($targetUser === null) {
590
-			throw new OCSException('', 103);
591
-		}
592
-
593
-		// If they're not an admin, check they are a subadmin of the group in question
594
-		$loggedInUser = $this->userSession->getUser();
595
-		$subAdminManager = $this->groupManager->getSubAdmin();
596
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
597
-			throw new OCSException('', 104);
598
-		}
599
-
600
-		// Add user to group
601
-		$group->addUser($targetUser);
602
-		return new DataResponse();
603
-	}
604
-
605
-	/**
606
-	 * @PasswordConfirmationRequired
607
-	 * @NoAdminRequired
608
-	 *
609
-	 * @param string $userId
610
-	 * @param string $groupid
611
-	 * @return DataResponse
612
-	 * @throws OCSException
613
-	 */
614
-	public function removeFromGroup($userId, $groupid) {
615
-		$loggedInUser = $this->userSession->getUser();
616
-
617
-		if($groupid === null) {
618
-			throw new OCSException('', 101);
619
-		}
620
-
621
-		$group = $this->groupManager->get($groupid);
622
-		if($group === null) {
623
-			throw new OCSException('', 102);
624
-		}
625
-
626
-		$targetUser = $this->userManager->get($userId);
627
-		if($targetUser === null) {
628
-			throw new OCSException('', 103);
629
-		}
630
-
631
-		// If they're not an admin, check they are a subadmin of the group in question
632
-		$subAdminManager = $this->groupManager->getSubAdmin();
633
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
634
-			throw new OCSException('', 104);
635
-		}
636
-
637
-		// Check they aren't removing themselves from 'admin' or their 'subadmin; group
638
-		if ($targetUser->getUID() === $loggedInUser->getUID()) {
639
-			if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
640
-				if ($group->getGID() === 'admin') {
641
-					throw new OCSException('Cannot remove yourself from the admin group', 105);
642
-				}
643
-			} else {
644
-				// Not an admin, so the user must be a subadmin of this group, but that is not allowed.
645
-				throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
646
-			}
647
-
648
-		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
649
-			/** @var IGroup[] $subAdminGroups */
650
-			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
651
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
652
-				return $subAdminGroup->getGID();
653
-			}, $subAdminGroups);
654
-			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
655
-			$userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
656
-
657
-			if (count($userSubAdminGroups) <= 1) {
658
-				// Subadmin must not be able to remove a user from all their subadmin groups.
659
-				throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
660
-			}
661
-		}
662
-
663
-		// Remove user from group
664
-		$group->removeUser($targetUser);
665
-		return new DataResponse();
666
-	}
667
-
668
-	/**
669
-	 * Creates a subadmin
670
-	 *
671
-	 * @PasswordConfirmationRequired
672
-	 *
673
-	 * @param string $userId
674
-	 * @param string $groupid
675
-	 * @return DataResponse
676
-	 * @throws OCSException
677
-	 */
678
-	public function addSubAdmin($userId, $groupid) {
679
-		$group = $this->groupManager->get($groupid);
680
-		$user = $this->userManager->get($userId);
681
-
682
-		// Check if the user exists
683
-		if($user === null) {
684
-			throw new OCSException('User does not exist', 101);
685
-		}
686
-		// Check if group exists
687
-		if($group === null) {
688
-			throw new OCSException('Group does not exist',  102);
689
-		}
690
-		// Check if trying to make subadmin of admin group
691
-		if($group->getGID() === 'admin') {
692
-			throw new OCSException('Cannot create subadmins for admin group', 103);
693
-		}
694
-
695
-		$subAdminManager = $this->groupManager->getSubAdmin();
696
-
697
-		// We cannot be subadmin twice
698
-		if ($subAdminManager->isSubAdminofGroup($user, $group)) {
699
-			return new DataResponse();
700
-		}
701
-		// Go
702
-		if($subAdminManager->createSubAdmin($user, $group)) {
703
-			return new DataResponse();
704
-		} else {
705
-			throw new OCSException('Unknown error occurred', 103);
706
-		}
707
-	}
708
-
709
-	/**
710
-	 * Removes a subadmin from a group
711
-	 *
712
-	 * @PasswordConfirmationRequired
713
-	 *
714
-	 * @param string $userId
715
-	 * @param string $groupid
716
-	 * @return DataResponse
717
-	 * @throws OCSException
718
-	 */
719
-	public function removeSubAdmin($userId, $groupid) {
720
-		$group = $this->groupManager->get($groupid);
721
-		$user = $this->userManager->get($userId);
722
-		$subAdminManager = $this->groupManager->getSubAdmin();
723
-
724
-		// Check if the user exists
725
-		if($user === null) {
726
-			throw new OCSException('User does not exist', 101);
727
-		}
728
-		// Check if the group exists
729
-		if($group === null) {
730
-			throw new OCSException('Group does not exist', 101);
731
-		}
732
-		// Check if they are a subadmin of this said group
733
-		if(!$subAdminManager->isSubAdminOfGroup($user, $group)) {
734
-			throw new OCSException('User is not a subadmin of this group', 102);
735
-		}
736
-
737
-		// Go
738
-		if($subAdminManager->deleteSubAdmin($user, $group)) {
739
-			return new DataResponse();
740
-		} else {
741
-			throw new OCSException('Unknown error occurred', 103);
742
-		}
743
-	}
744
-
745
-	/**
746
-	 * Get the groups a user is a subadmin of
747
-	 *
748
-	 * @param string $userId
749
-	 * @return DataResponse
750
-	 * @throws OCSException
751
-	 */
752
-	public function getUserSubAdminGroups($userId) {
753
-		$user = $this->userManager->get($userId);
754
-		// Check if the user exists
755
-		if($user === null) {
756
-			throw new OCSException('User does not exist', 101);
757
-		}
758
-
759
-		// Get the subadmin groups
760
-		$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
761
-		foreach ($groups as $key => $group) {
762
-			$groups[$key] = $group->getGID();
763
-		}
764
-
765
-		if(!$groups) {
766
-			throw new OCSException('Unknown error occurred', 102);
767
-		} else {
768
-			return new DataResponse($groups);
769
-		}
770
-	}
771
-
772
-	/**
773
-	 * @param string $userId
774
-	 * @return array
775
-	 * @throws \OCP\Files\NotFoundException
776
-	 */
777
-	protected function fillStorageInfo($userId) {
778
-		try {
779
-			\OC_Util::tearDownFS();
780
-			\OC_Util::setupFS($userId);
781
-			$storage = OC_Helper::getStorageInfo('/');
782
-			$data = [
783
-				'free' => $storage['free'],
784
-				'used' => $storage['used'],
785
-				'total' => $storage['total'],
786
-				'relative' => $storage['relative'],
787
-				'quota' => $storage['quota'],
788
-			];
789
-		} catch (NotFoundException $ex) {
790
-			$data = [];
791
-		}
792
-		return $data;
793
-	}
794
-
795
-	/**
796
-	 * @NoAdminRequired
797
-	 * @PasswordConfirmationRequired
798
-	 *
799
-	 * resend welcome message
800
-	 *
801
-	 * @param string $userId
802
-	 * @return DataResponse
803
-	 * @throws OCSException
804
-	 */
805
-	public function resendWelcomeMessage($userId) {
806
-		$currentLoggedInUser = $this->userSession->getUser();
807
-
808
-		$targetUser = $this->userManager->get($userId);
809
-		if($targetUser === null) {
810
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
811
-		}
812
-
813
-		// Check if admin / subadmin
814
-		$subAdminManager = $this->groupManager->getSubAdmin();
815
-		if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
816
-			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
817
-			// No rights
818
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
819
-		}
820
-
821
-		$email = $targetUser->getEMailAddress();
822
-		if ($email === '' || $email === null) {
823
-			throw new OCSException('Email address not available', 101);
824
-		}
825
-		$username = $targetUser->getUID();
826
-		$lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
827
-		if (!$this->l10nFactory->languageExists('settings', $lang)) {
828
-			$lang = 'en';
829
-		}
830
-
831
-		$l10n = $this->l10nFactory->get('settings', $lang);
832
-
833
-		try {
834
-			$this->newUserMailHelper->setL10N($l10n);
835
-			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
836
-			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
837
-		} catch(\Exception $e) {
838
-			$this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
839
-			throw new OCSException('Sending email failed', 102);
840
-		}
841
-
842
-		return new DataResponse();
843
-	}
53
+    /** @var IUserManager */
54
+    private $userManager;
55
+    /** @var IConfig */
56
+    private $config;
57
+    /** @var IAppManager */
58
+    private $appManager;
59
+    /** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface
60
+    private $groupManager;
61
+    /** @var IUserSession */
62
+    private $userSession;
63
+    /** @var AccountManager */
64
+    private $accountManager;
65
+    /** @var ILogger */
66
+    private $logger;
67
+    /** @var IFactory */
68
+    private $l10nFactory;
69
+    /** @var NewUserMailHelper */
70
+    private $newUserMailHelper;
71
+
72
+    /**
73
+     * @param string $appName
74
+     * @param IRequest $request
75
+     * @param IUserManager $userManager
76
+     * @param IConfig $config
77
+     * @param IAppManager $appManager
78
+     * @param IGroupManager $groupManager
79
+     * @param IUserSession $userSession
80
+     * @param AccountManager $accountManager
81
+     * @param ILogger $logger
82
+     * @param IFactory $l10nFactory
83
+     * @param NewUserMailHelper $newUserMailHelper
84
+     */
85
+    public function __construct($appName,
86
+                                IRequest $request,
87
+                                IUserManager $userManager,
88
+                                IConfig $config,
89
+                                IAppManager $appManager,
90
+                                IGroupManager $groupManager,
91
+                                IUserSession $userSession,
92
+                                AccountManager $accountManager,
93
+                                ILogger $logger,
94
+                                IFactory $l10nFactory,
95
+                                NewUserMailHelper $newUserMailHelper) {
96
+        parent::__construct($appName, $request);
97
+
98
+        $this->userManager = $userManager;
99
+        $this->config = $config;
100
+        $this->appManager = $appManager;
101
+        $this->groupManager = $groupManager;
102
+        $this->userSession = $userSession;
103
+        $this->accountManager = $accountManager;
104
+        $this->logger = $logger;
105
+        $this->l10nFactory = $l10nFactory;
106
+        $this->newUserMailHelper = $newUserMailHelper;
107
+    }
108
+
109
+    /**
110
+     * @NoAdminRequired
111
+     *
112
+     * returns a list of users
113
+     *
114
+     * @param string $search
115
+     * @param int $limit
116
+     * @param int $offset
117
+     * @return DataResponse
118
+     */
119
+    public function getUsers($search = '', $limit = null, $offset = null) {
120
+        $user = $this->userSession->getUser();
121
+        $users = [];
122
+
123
+        // Admin? Or SubAdmin?
124
+        $uid = $user->getUID();
125
+        $subAdminManager = $this->groupManager->getSubAdmin();
126
+        if($this->groupManager->isAdmin($uid)){
127
+            $users = $this->userManager->search($search, $limit, $offset);
128
+        } else if ($subAdminManager->isSubAdmin($user)) {
129
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
130
+            foreach ($subAdminOfGroups as $key => $group) {
131
+                $subAdminOfGroups[$key] = $group->getGID();
132
+            }
133
+
134
+            if($offset === null) {
135
+                $offset = 0;
136
+            }
137
+
138
+            $users = [];
139
+            foreach ($subAdminOfGroups as $group) {
140
+                $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search));
141
+            }
142
+
143
+            $users = array_slice($users, $offset, $limit);
144
+        }
145
+
146
+        $users = array_keys($users);
147
+
148
+        return new DataResponse([
149
+            'users' => $users
150
+        ]);
151
+    }
152
+
153
+    /**
154
+     * @PasswordConfirmationRequired
155
+     * @NoAdminRequired
156
+     *
157
+     * @param string $userid
158
+     * @param string $password
159
+     * @param array $groups
160
+     * @return DataResponse
161
+     * @throws OCSException
162
+     */
163
+    public function addUser($userid, $password, $groups = null) {
164
+        $user = $this->userSession->getUser();
165
+        $isAdmin = $this->groupManager->isAdmin($user->getUID());
166
+        $subAdminManager = $this->groupManager->getSubAdmin();
167
+
168
+        if($this->userManager->userExists($userid)) {
169
+            $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
170
+            throw new OCSException('User already exists', 102);
171
+        }
172
+
173
+        if(is_array($groups)) {
174
+            foreach ($groups as $group) {
175
+                if(!$this->groupManager->groupExists($group)) {
176
+                    throw new OCSException('group '.$group.' does not exist', 104);
177
+                }
178
+                if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
179
+                    throw new OCSException('insufficient privileges for group '. $group, 105);
180
+                }
181
+            }
182
+        } else {
183
+            if(!$isAdmin) {
184
+                throw new OCSException('no group specified (required for subadmins)', 106);
185
+            }
186
+        }
187
+
188
+        try {
189
+            $newUser = $this->userManager->createUser($userid, $password);
190
+            $this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
191
+
192
+            if (is_array($groups)) {
193
+                foreach ($groups as $group) {
194
+                    $this->groupManager->get($group)->addUser($newUser);
195
+                    $this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
196
+                }
197
+            }
198
+            return new DataResponse();
199
+        } catch (\Exception $e) {
200
+            $this->logger->error('Failed addUser attempt with exception: '.$e->getMessage(), ['app' => 'ocs_api']);
201
+            throw new OCSException('Bad request', 101);
202
+        }
203
+    }
204
+
205
+    /**
206
+     * @NoAdminRequired
207
+     * @NoSubAdminRequired
208
+     *
209
+     * gets user info
210
+     *
211
+     * @param string $userId
212
+     * @return DataResponse
213
+     * @throws OCSException
214
+     */
215
+    public function getUser($userId) {
216
+        $data = $this->getUserData($userId);
217
+        return new DataResponse($data);
218
+    }
219
+
220
+    /**
221
+     * @NoAdminRequired
222
+     * @NoSubAdminRequired
223
+     *
224
+     * gets user info from the currently logged in user
225
+     *
226
+     * @return DataResponse
227
+     * @throws OCSException
228
+     */
229
+    public function getCurrentUser() {
230
+        $user = $this->userSession->getUser();
231
+        if ($user) {
232
+            $data =  $this->getUserData($user->getUID());
233
+            // rename "displayname" to "display-name" only for this call to keep
234
+            // the API stable.
235
+            $data['display-name'] = $data['displayname'];
236
+            unset($data['displayname']);
237
+            return new DataResponse($data);
238
+
239
+        }
240
+
241
+        throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
242
+    }
243
+
244
+    /**
245
+     * creates a array with all user data
246
+     *
247
+     * @param $userId
248
+     * @return array
249
+     * @throws OCSException
250
+     */
251
+    protected function getUserData($userId) {
252
+        $currentLoggedInUser = $this->userSession->getUser();
253
+
254
+        $data = [];
255
+
256
+        // Check if the target user exists
257
+        $targetUserObject = $this->userManager->get($userId);
258
+        if($targetUserObject === null) {
259
+            throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
260
+        }
261
+
262
+        // Admin? Or SubAdmin?
263
+        if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
264
+            || $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
265
+            $data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true');
266
+        } else {
267
+            // Check they are looking up themselves
268
+            if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
269
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
270
+            }
271
+        }
272
+
273
+        $userAccount = $this->accountManager->getUser($targetUserObject);
274
+        $groups = $this->groupManager->getUserGroups($targetUserObject);
275
+        $gids = [];
276
+        foreach ($groups as $group) {
277
+            $gids[] = $group->getDisplayName();
278
+        }
279
+
280
+        // Find the data
281
+        $data['id'] = $targetUserObject->getUID();
282
+        $data['quota'] = $this->fillStorageInfo($targetUserObject->getUID());
283
+        $data[AccountManager::PROPERTY_EMAIL] = $targetUserObject->getEMailAddress();
284
+        $data[AccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
285
+        $data[AccountManager::PROPERTY_PHONE] = $userAccount[AccountManager::PROPERTY_PHONE]['value'];
286
+        $data[AccountManager::PROPERTY_ADDRESS] = $userAccount[AccountManager::PROPERTY_ADDRESS]['value'];
287
+        $data[AccountManager::PROPERTY_WEBSITE] = $userAccount[AccountManager::PROPERTY_WEBSITE]['value'];
288
+        $data[AccountManager::PROPERTY_TWITTER] = $userAccount[AccountManager::PROPERTY_TWITTER]['value'];
289
+        $data['groups'] = $gids;
290
+        $data['language'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'lang');
291
+        $data['locale'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'locale');
292
+
293
+        return $data;
294
+    }
295
+
296
+    /**
297
+     * @NoAdminRequired
298
+     * @NoSubAdminRequired
299
+     * @PasswordConfirmationRequired
300
+     *
301
+     * edit users
302
+     *
303
+     * @param string $userId
304
+     * @param string $key
305
+     * @param string $value
306
+     * @return DataResponse
307
+     * @throws OCSException
308
+     * @throws OCSForbiddenException
309
+     */
310
+    public function editUser($userId, $key, $value) {
311
+        $currentLoggedInUser = $this->userSession->getUser();
312
+
313
+        $targetUser = $this->userManager->get($userId);
314
+        if($targetUser === null) {
315
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
316
+        }
317
+
318
+        $permittedFields = [];
319
+        if($targetUser->getUID() === $currentLoggedInUser->getUID()) {
320
+            // Editing self (display, email)
321
+            if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
322
+                $permittedFields[] = 'display';
323
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
324
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
325
+            }
326
+
327
+            $permittedFields[] = 'password';
328
+            if ($this->config->getSystemValue('force_language', false) === false ||
329
+                $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
330
+                $permittedFields[] = 'language';
331
+                $permittedFields[] = 'locale';
332
+            }
333
+
334
+            if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
335
+                $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
336
+                $shareProvider = $federatedFileSharing->getFederatedShareProvider();
337
+                if ($shareProvider->isLookupServerUploadEnabled()) {
338
+                    $permittedFields[] = AccountManager::PROPERTY_PHONE;
339
+                    $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
340
+                    $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
341
+                    $permittedFields[] = AccountManager::PROPERTY_TWITTER;
342
+                }
343
+            }
344
+
345
+            // If admin they can edit their own quota
346
+            if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
347
+                $permittedFields[] = 'quota';
348
+            }
349
+        } else {
350
+            // Check if admin / subadmin
351
+            $subAdminManager = $this->groupManager->getSubAdmin();
352
+            if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
353
+            || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
354
+                // They have permissions over the user
355
+                $permittedFields[] = 'display';
356
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
357
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
358
+                $permittedFields[] = 'password';
359
+                $permittedFields[] = 'language';
360
+                $permittedFields[] = 'locale';
361
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
362
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
363
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
364
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
365
+                $permittedFields[] = 'quota';
366
+            } else {
367
+                // No rights
368
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
369
+            }
370
+        }
371
+        // Check if permitted to edit this field
372
+        if(!in_array($key, $permittedFields)) {
373
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
374
+        }
375
+        // Process the edit
376
+        switch($key) {
377
+            case 'display':
378
+            case AccountManager::PROPERTY_DISPLAYNAME:
379
+                $targetUser->setDisplayName($value);
380
+                break;
381
+            case 'quota':
382
+                $quota = $value;
383
+                if($quota !== 'none' && $quota !== 'default') {
384
+                    if (is_numeric($quota)) {
385
+                        $quota = (float) $quota;
386
+                    } else {
387
+                        $quota = \OCP\Util::computerFileSize($quota);
388
+                    }
389
+                    if ($quota === false) {
390
+                        throw new OCSException('Invalid quota value '.$value, 103);
391
+                    }
392
+                    if($quota === 0) {
393
+                        $quota = 'default';
394
+                    }else if($quota === -1) {
395
+                        $quota = 'none';
396
+                    } else {
397
+                        $quota = \OCP\Util::humanFileSize($quota);
398
+                    }
399
+                }
400
+                $targetUser->setQuota($quota);
401
+                break;
402
+            case 'password':
403
+                $targetUser->setPassword($value);
404
+                break;
405
+            case 'language':
406
+                $languagesCodes = $this->l10nFactory->findAvailableLanguages();
407
+                if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
408
+                    throw new OCSException('Invalid language', 102);
409
+                }
410
+                $this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
411
+                break;
412
+            case 'locale':
413
+                if (!$this->l10nFactory->localeExists($value)) {
414
+                    throw new OCSException('Invalid locale', 102);
415
+                }
416
+                $this->config->setUserValue($targetUser->getUID(), 'core', 'locale', $value);
417
+                break;
418
+            case AccountManager::PROPERTY_EMAIL:
419
+                if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
420
+                    $targetUser->setEMailAddress($value);
421
+                } else {
422
+                    throw new OCSException('', 102);
423
+                }
424
+                break;
425
+            case AccountManager::PROPERTY_PHONE:
426
+            case AccountManager::PROPERTY_ADDRESS:
427
+            case AccountManager::PROPERTY_WEBSITE:
428
+            case AccountManager::PROPERTY_TWITTER:
429
+                $userAccount = $this->accountManager->getUser($targetUser);
430
+                if ($userAccount[$key]['value'] !== $value) {
431
+                    $userAccount[$key]['value'] = $value;
432
+                    $this->accountManager->updateUser($targetUser, $userAccount);
433
+                }
434
+                break;
435
+            default:
436
+                throw new OCSException('', 103);
437
+        }
438
+        return new DataResponse();
439
+    }
440
+
441
+    /**
442
+     * @PasswordConfirmationRequired
443
+     * @NoAdminRequired
444
+     *
445
+     * @param string $userId
446
+     * @return DataResponse
447
+     * @throws OCSException
448
+     * @throws OCSForbiddenException
449
+     */
450
+    public function deleteUser($userId) {
451
+        $currentLoggedInUser = $this->userSession->getUser();
452
+
453
+        $targetUser = $this->userManager->get($userId);
454
+
455
+        if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
456
+            throw new OCSException('', 101);
457
+        }
458
+
459
+        // If not permitted
460
+        $subAdminManager = $this->groupManager->getSubAdmin();
461
+        if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
462
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
463
+        }
464
+
465
+        // Go ahead with the delete
466
+        if($targetUser->delete()) {
467
+            return new DataResponse();
468
+        } else {
469
+            throw new OCSException('', 101);
470
+        }
471
+    }
472
+
473
+    /**
474
+     * @PasswordConfirmationRequired
475
+     * @NoAdminRequired
476
+     *
477
+     * @param string $userId
478
+     * @return DataResponse
479
+     * @throws OCSException
480
+     * @throws OCSForbiddenException
481
+     */
482
+    public function disableUser($userId) {
483
+        return $this->setEnabled($userId, false);
484
+    }
485
+
486
+    /**
487
+     * @PasswordConfirmationRequired
488
+     * @NoAdminRequired
489
+     *
490
+     * @param string $userId
491
+     * @return DataResponse
492
+     * @throws OCSException
493
+     * @throws OCSForbiddenException
494
+     */
495
+    public function enableUser($userId) {
496
+        return $this->setEnabled($userId, true);
497
+    }
498
+
499
+    /**
500
+     * @param string $userId
501
+     * @param bool $value
502
+     * @return DataResponse
503
+     * @throws OCSException
504
+     * @throws OCSForbiddenException
505
+     */
506
+    private function setEnabled($userId, $value) {
507
+        $currentLoggedInUser = $this->userSession->getUser();
508
+
509
+        $targetUser = $this->userManager->get($userId);
510
+        if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
511
+            throw new OCSException('', 101);
512
+        }
513
+
514
+        // If not permitted
515
+        $subAdminManager = $this->groupManager->getSubAdmin();
516
+        if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
517
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
518
+        }
519
+
520
+        // enable/disable the user now
521
+        $targetUser->setEnabled($value);
522
+        return new DataResponse();
523
+    }
524
+
525
+    /**
526
+     * @NoAdminRequired
527
+     * @NoSubAdminRequired
528
+     *
529
+     * @param string $userId
530
+     * @return DataResponse
531
+     * @throws OCSException
532
+     */
533
+    public function getUsersGroups($userId) {
534
+        $loggedInUser = $this->userSession->getUser();
535
+
536
+        $targetUser = $this->userManager->get($userId);
537
+        if($targetUser === null) {
538
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
539
+        }
540
+
541
+        if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
542
+            // Self lookup or admin lookup
543
+            return new DataResponse([
544
+                'groups' => $this->groupManager->getUserGroupIds($targetUser)
545
+            ]);
546
+        } else {
547
+            $subAdminManager = $this->groupManager->getSubAdmin();
548
+
549
+            // Looking up someone else
550
+            if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
551
+                // Return the group that the method caller is subadmin of for the user in question
552
+                /** @var IGroup[] $getSubAdminsGroups */
553
+                $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
554
+                foreach ($getSubAdminsGroups as $key => $group) {
555
+                    $getSubAdminsGroups[$key] = $group->getGID();
556
+                }
557
+                $groups = array_intersect(
558
+                    $getSubAdminsGroups,
559
+                    $this->groupManager->getUserGroupIds($targetUser)
560
+                );
561
+                return new DataResponse(['groups' => $groups]);
562
+            } else {
563
+                // Not permitted
564
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
565
+            }
566
+        }
567
+
568
+    }
569
+
570
+    /**
571
+     * @PasswordConfirmationRequired
572
+     * @NoAdminRequired
573
+     *
574
+     * @param string $userId
575
+     * @param string $groupid
576
+     * @return DataResponse
577
+     * @throws OCSException
578
+     */
579
+    public function addToGroup($userId, $groupid = '') {
580
+        if($groupid === '') {
581
+            throw new OCSException('', 101);
582
+        }
583
+
584
+        $group = $this->groupManager->get($groupid);
585
+        $targetUser = $this->userManager->get($userId);
586
+        if($group === null) {
587
+            throw new OCSException('', 102);
588
+        }
589
+        if($targetUser === null) {
590
+            throw new OCSException('', 103);
591
+        }
592
+
593
+        // If they're not an admin, check they are a subadmin of the group in question
594
+        $loggedInUser = $this->userSession->getUser();
595
+        $subAdminManager = $this->groupManager->getSubAdmin();
596
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
597
+            throw new OCSException('', 104);
598
+        }
599
+
600
+        // Add user to group
601
+        $group->addUser($targetUser);
602
+        return new DataResponse();
603
+    }
604
+
605
+    /**
606
+     * @PasswordConfirmationRequired
607
+     * @NoAdminRequired
608
+     *
609
+     * @param string $userId
610
+     * @param string $groupid
611
+     * @return DataResponse
612
+     * @throws OCSException
613
+     */
614
+    public function removeFromGroup($userId, $groupid) {
615
+        $loggedInUser = $this->userSession->getUser();
616
+
617
+        if($groupid === null) {
618
+            throw new OCSException('', 101);
619
+        }
620
+
621
+        $group = $this->groupManager->get($groupid);
622
+        if($group === null) {
623
+            throw new OCSException('', 102);
624
+        }
625
+
626
+        $targetUser = $this->userManager->get($userId);
627
+        if($targetUser === null) {
628
+            throw new OCSException('', 103);
629
+        }
630
+
631
+        // If they're not an admin, check they are a subadmin of the group in question
632
+        $subAdminManager = $this->groupManager->getSubAdmin();
633
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
634
+            throw new OCSException('', 104);
635
+        }
636
+
637
+        // Check they aren't removing themselves from 'admin' or their 'subadmin; group
638
+        if ($targetUser->getUID() === $loggedInUser->getUID()) {
639
+            if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
640
+                if ($group->getGID() === 'admin') {
641
+                    throw new OCSException('Cannot remove yourself from the admin group', 105);
642
+                }
643
+            } else {
644
+                // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
645
+                throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
646
+            }
647
+
648
+        } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
649
+            /** @var IGroup[] $subAdminGroups */
650
+            $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
651
+            $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
652
+                return $subAdminGroup->getGID();
653
+            }, $subAdminGroups);
654
+            $userGroups = $this->groupManager->getUserGroupIds($targetUser);
655
+            $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
656
+
657
+            if (count($userSubAdminGroups) <= 1) {
658
+                // Subadmin must not be able to remove a user from all their subadmin groups.
659
+                throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
660
+            }
661
+        }
662
+
663
+        // Remove user from group
664
+        $group->removeUser($targetUser);
665
+        return new DataResponse();
666
+    }
667
+
668
+    /**
669
+     * Creates a subadmin
670
+     *
671
+     * @PasswordConfirmationRequired
672
+     *
673
+     * @param string $userId
674
+     * @param string $groupid
675
+     * @return DataResponse
676
+     * @throws OCSException
677
+     */
678
+    public function addSubAdmin($userId, $groupid) {
679
+        $group = $this->groupManager->get($groupid);
680
+        $user = $this->userManager->get($userId);
681
+
682
+        // Check if the user exists
683
+        if($user === null) {
684
+            throw new OCSException('User does not exist', 101);
685
+        }
686
+        // Check if group exists
687
+        if($group === null) {
688
+            throw new OCSException('Group does not exist',  102);
689
+        }
690
+        // Check if trying to make subadmin of admin group
691
+        if($group->getGID() === 'admin') {
692
+            throw new OCSException('Cannot create subadmins for admin group', 103);
693
+        }
694
+
695
+        $subAdminManager = $this->groupManager->getSubAdmin();
696
+
697
+        // We cannot be subadmin twice
698
+        if ($subAdminManager->isSubAdminofGroup($user, $group)) {
699
+            return new DataResponse();
700
+        }
701
+        // Go
702
+        if($subAdminManager->createSubAdmin($user, $group)) {
703
+            return new DataResponse();
704
+        } else {
705
+            throw new OCSException('Unknown error occurred', 103);
706
+        }
707
+    }
708
+
709
+    /**
710
+     * Removes a subadmin from a group
711
+     *
712
+     * @PasswordConfirmationRequired
713
+     *
714
+     * @param string $userId
715
+     * @param string $groupid
716
+     * @return DataResponse
717
+     * @throws OCSException
718
+     */
719
+    public function removeSubAdmin($userId, $groupid) {
720
+        $group = $this->groupManager->get($groupid);
721
+        $user = $this->userManager->get($userId);
722
+        $subAdminManager = $this->groupManager->getSubAdmin();
723
+
724
+        // Check if the user exists
725
+        if($user === null) {
726
+            throw new OCSException('User does not exist', 101);
727
+        }
728
+        // Check if the group exists
729
+        if($group === null) {
730
+            throw new OCSException('Group does not exist', 101);
731
+        }
732
+        // Check if they are a subadmin of this said group
733
+        if(!$subAdminManager->isSubAdminOfGroup($user, $group)) {
734
+            throw new OCSException('User is not a subadmin of this group', 102);
735
+        }
736
+
737
+        // Go
738
+        if($subAdminManager->deleteSubAdmin($user, $group)) {
739
+            return new DataResponse();
740
+        } else {
741
+            throw new OCSException('Unknown error occurred', 103);
742
+        }
743
+    }
744
+
745
+    /**
746
+     * Get the groups a user is a subadmin of
747
+     *
748
+     * @param string $userId
749
+     * @return DataResponse
750
+     * @throws OCSException
751
+     */
752
+    public function getUserSubAdminGroups($userId) {
753
+        $user = $this->userManager->get($userId);
754
+        // Check if the user exists
755
+        if($user === null) {
756
+            throw new OCSException('User does not exist', 101);
757
+        }
758
+
759
+        // Get the subadmin groups
760
+        $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
761
+        foreach ($groups as $key => $group) {
762
+            $groups[$key] = $group->getGID();
763
+        }
764
+
765
+        if(!$groups) {
766
+            throw new OCSException('Unknown error occurred', 102);
767
+        } else {
768
+            return new DataResponse($groups);
769
+        }
770
+    }
771
+
772
+    /**
773
+     * @param string $userId
774
+     * @return array
775
+     * @throws \OCP\Files\NotFoundException
776
+     */
777
+    protected function fillStorageInfo($userId) {
778
+        try {
779
+            \OC_Util::tearDownFS();
780
+            \OC_Util::setupFS($userId);
781
+            $storage = OC_Helper::getStorageInfo('/');
782
+            $data = [
783
+                'free' => $storage['free'],
784
+                'used' => $storage['used'],
785
+                'total' => $storage['total'],
786
+                'relative' => $storage['relative'],
787
+                'quota' => $storage['quota'],
788
+            ];
789
+        } catch (NotFoundException $ex) {
790
+            $data = [];
791
+        }
792
+        return $data;
793
+    }
794
+
795
+    /**
796
+     * @NoAdminRequired
797
+     * @PasswordConfirmationRequired
798
+     *
799
+     * resend welcome message
800
+     *
801
+     * @param string $userId
802
+     * @return DataResponse
803
+     * @throws OCSException
804
+     */
805
+    public function resendWelcomeMessage($userId) {
806
+        $currentLoggedInUser = $this->userSession->getUser();
807
+
808
+        $targetUser = $this->userManager->get($userId);
809
+        if($targetUser === null) {
810
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
811
+        }
812
+
813
+        // Check if admin / subadmin
814
+        $subAdminManager = $this->groupManager->getSubAdmin();
815
+        if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
816
+            && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
817
+            // No rights
818
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
819
+        }
820
+
821
+        $email = $targetUser->getEMailAddress();
822
+        if ($email === '' || $email === null) {
823
+            throw new OCSException('Email address not available', 101);
824
+        }
825
+        $username = $targetUser->getUID();
826
+        $lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
827
+        if (!$this->l10nFactory->languageExists('settings', $lang)) {
828
+            $lang = 'en';
829
+        }
830
+
831
+        $l10n = $this->l10nFactory->get('settings', $lang);
832
+
833
+        try {
834
+            $this->newUserMailHelper->setL10N($l10n);
835
+            $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
836
+            $this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
837
+        } catch(\Exception $e) {
838
+            $this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
839
+            throw new OCSException('Sending email failed', 102);
840
+        }
841
+
842
+        return new DataResponse();
843
+    }
844 844
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Helper.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -124,6 +124,9 @@
 block discarded – undo
124 124
 		return $nextPrefix;
125 125
 	}
126 126
 
127
+	/**
128
+	 * @param string $value
129
+	 */
127 130
 	private function getServersConfig($value) {
128 131
 		$regex = '/' . $value . '$/S';
129 132
 
Please login to merge, or discard this patch.
Indentation   +259 added lines, -259 removed lines patch added patch discarded remove patch
@@ -34,126 +34,126 @@  discard block
 block discarded – undo
34 34
 
35 35
 class Helper {
36 36
 
37
-	/** @var IConfig */
38
-	private $config;
39
-
40
-	/**
41
-	 * Helper constructor.
42
-	 *
43
-	 * @param IConfig $config
44
-	 */
45
-	public function __construct(IConfig $config) {
46
-		$this->config = $config;
47
-	}
48
-
49
-	/**
50
-	 * returns prefixes for each saved LDAP/AD server configuration.
51
-	 * @param bool $activeConfigurations optional, whether only active configuration shall be
52
-	 * retrieved, defaults to false
53
-	 * @return array with a list of the available prefixes
54
-	 *
55
-	 * Configuration prefixes are used to set up configurations for n LDAP or
56
-	 * AD servers. Since configuration is stored in the database, table
57
-	 * appconfig under appid user_ldap, the common identifiers in column
58
-	 * 'configkey' have a prefix. The prefix for the very first server
59
-	 * configuration is empty.
60
-	 * Configkey Examples:
61
-	 * Server 1: ldap_login_filter
62
-	 * Server 2: s1_ldap_login_filter
63
-	 * Server 3: s2_ldap_login_filter
64
-	 *
65
-	 * The prefix needs to be passed to the constructor of Connection class,
66
-	 * except the default (first) server shall be connected to.
67
-	 *
68
-	 */
69
-	public function getServerConfigurationPrefixes($activeConfigurations = false) {
70
-		$referenceConfigkey = 'ldap_configuration_active';
71
-
72
-		$keys = $this->getServersConfig($referenceConfigkey);
73
-
74
-		$prefixes = [];
75
-		foreach ($keys as $key) {
76
-			if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') {
77
-				continue;
78
-			}
79
-
80
-			$len = strlen($key) - strlen($referenceConfigkey);
81
-			$prefixes[] = substr($key, 0, $len);
82
-		}
83
-
84
-		return $prefixes;
85
-	}
86
-
87
-	/**
88
-	 *
89
-	 * determines the host for every configured connection
90
-	 * @return array an array with configprefix as keys
91
-	 *
92
-	 */
93
-	public function getServerConfigurationHosts() {
94
-		$referenceConfigkey = 'ldap_host';
95
-
96
-		$keys = $this->getServersConfig($referenceConfigkey);
97
-
98
-		$result = array();
99
-		foreach($keys as $key) {
100
-			$len = strlen($key) - strlen($referenceConfigkey);
101
-			$prefix = substr($key, 0, $len);
102
-			$result[$prefix] = $this->config->getAppValue('user_ldap', $key);
103
-		}
104
-
105
-		return $result;
106
-	}
107
-
108
-	/**
109
-	 * return the next available configuration prefix
110
-	 *
111
-	 * @return string
112
-	 */
113
-	public function getNextServerConfigurationPrefix() {
114
-		$serverConnections = $this->getServerConfigurationPrefixes();
115
-
116
-		if(count($serverConnections) === 0) {
117
-			return 's01';
118
-		}
119
-
120
-		sort($serverConnections);
121
-		$lastKey = array_pop($serverConnections);
122
-		$lastNumber = intval(str_replace('s', '', $lastKey));
123
-		$nextPrefix = 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
124
-		return $nextPrefix;
125
-	}
126
-
127
-	private function getServersConfig($value) {
128
-		$regex = '/' . $value . '$/S';
129
-
130
-		$keys = $this->config->getAppKeys('user_ldap');
131
-		$result = [];
132
-		foreach ($keys as $key) {
133
-			if (preg_match($regex, $key) === 1) {
134
-				$result[] = $key;
135
-			}
136
-		}
137
-
138
-		return $result;
139
-	}
140
-
141
-	/**
142
-	 * deletes a given saved LDAP/AD server configuration.
143
-	 * @param string $prefix the configuration prefix of the config to delete
144
-	 * @return bool true on success, false otherwise
145
-	 */
146
-	public function deleteServerConfiguration($prefix) {
147
-		if(!in_array($prefix, self::getServerConfigurationPrefixes())) {
148
-			return false;
149
-		}
150
-
151
-		$saveOtherConfigurations = '';
152
-		if(empty($prefix)) {
153
-			$saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
154
-		}
155
-
156
-		$query = \OCP\DB::prepare('
37
+    /** @var IConfig */
38
+    private $config;
39
+
40
+    /**
41
+     * Helper constructor.
42
+     *
43
+     * @param IConfig $config
44
+     */
45
+    public function __construct(IConfig $config) {
46
+        $this->config = $config;
47
+    }
48
+
49
+    /**
50
+     * returns prefixes for each saved LDAP/AD server configuration.
51
+     * @param bool $activeConfigurations optional, whether only active configuration shall be
52
+     * retrieved, defaults to false
53
+     * @return array with a list of the available prefixes
54
+     *
55
+     * Configuration prefixes are used to set up configurations for n LDAP or
56
+     * AD servers. Since configuration is stored in the database, table
57
+     * appconfig under appid user_ldap, the common identifiers in column
58
+     * 'configkey' have a prefix. The prefix for the very first server
59
+     * configuration is empty.
60
+     * Configkey Examples:
61
+     * Server 1: ldap_login_filter
62
+     * Server 2: s1_ldap_login_filter
63
+     * Server 3: s2_ldap_login_filter
64
+     *
65
+     * The prefix needs to be passed to the constructor of Connection class,
66
+     * except the default (first) server shall be connected to.
67
+     *
68
+     */
69
+    public function getServerConfigurationPrefixes($activeConfigurations = false) {
70
+        $referenceConfigkey = 'ldap_configuration_active';
71
+
72
+        $keys = $this->getServersConfig($referenceConfigkey);
73
+
74
+        $prefixes = [];
75
+        foreach ($keys as $key) {
76
+            if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') {
77
+                continue;
78
+            }
79
+
80
+            $len = strlen($key) - strlen($referenceConfigkey);
81
+            $prefixes[] = substr($key, 0, $len);
82
+        }
83
+
84
+        return $prefixes;
85
+    }
86
+
87
+    /**
88
+     *
89
+     * determines the host for every configured connection
90
+     * @return array an array with configprefix as keys
91
+     *
92
+     */
93
+    public function getServerConfigurationHosts() {
94
+        $referenceConfigkey = 'ldap_host';
95
+
96
+        $keys = $this->getServersConfig($referenceConfigkey);
97
+
98
+        $result = array();
99
+        foreach($keys as $key) {
100
+            $len = strlen($key) - strlen($referenceConfigkey);
101
+            $prefix = substr($key, 0, $len);
102
+            $result[$prefix] = $this->config->getAppValue('user_ldap', $key);
103
+        }
104
+
105
+        return $result;
106
+    }
107
+
108
+    /**
109
+     * return the next available configuration prefix
110
+     *
111
+     * @return string
112
+     */
113
+    public function getNextServerConfigurationPrefix() {
114
+        $serverConnections = $this->getServerConfigurationPrefixes();
115
+
116
+        if(count($serverConnections) === 0) {
117
+            return 's01';
118
+        }
119
+
120
+        sort($serverConnections);
121
+        $lastKey = array_pop($serverConnections);
122
+        $lastNumber = intval(str_replace('s', '', $lastKey));
123
+        $nextPrefix = 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
124
+        return $nextPrefix;
125
+    }
126
+
127
+    private function getServersConfig($value) {
128
+        $regex = '/' . $value . '$/S';
129
+
130
+        $keys = $this->config->getAppKeys('user_ldap');
131
+        $result = [];
132
+        foreach ($keys as $key) {
133
+            if (preg_match($regex, $key) === 1) {
134
+                $result[] = $key;
135
+            }
136
+        }
137
+
138
+        return $result;
139
+    }
140
+
141
+    /**
142
+     * deletes a given saved LDAP/AD server configuration.
143
+     * @param string $prefix the configuration prefix of the config to delete
144
+     * @return bool true on success, false otherwise
145
+     */
146
+    public function deleteServerConfiguration($prefix) {
147
+        if(!in_array($prefix, self::getServerConfigurationPrefixes())) {
148
+            return false;
149
+        }
150
+
151
+        $saveOtherConfigurations = '';
152
+        if(empty($prefix)) {
153
+            $saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
154
+        }
155
+
156
+        $query = \OCP\DB::prepare('
157 157
 			DELETE
158 158
 			FROM `*PREFIX*appconfig`
159 159
 			WHERE `configkey` LIKE ?
@@ -161,146 +161,146 @@  discard block
 block discarded – undo
161 161
 				AND `appid` = \'user_ldap\'
162 162
 				AND `configkey` NOT IN (\'enabled\', \'installed_version\', \'types\', \'bgjUpdateGroupsLastRun\')
163 163
 		');
164
-		$delRows = $query->execute(array($prefix.'%'));
165
-
166
-		if(\OCP\DB::isError($delRows)) {
167
-			return false;
168
-		}
169
-
170
-		if($delRows === 0) {
171
-			return false;
172
-		}
173
-
174
-		return true;
175
-	}
176
-
177
-	/**
178
-	 * checks whether there is one or more disabled LDAP configurations
179
-	 * @throws \Exception
180
-	 * @return bool
181
-	 */
182
-	public function haveDisabledConfigurations() {
183
-		$all = $this->getServerConfigurationPrefixes(false);
184
-		$active = $this->getServerConfigurationPrefixes(true);
185
-
186
-		if(!is_array($all) || !is_array($active)) {
187
-			throw new \Exception('Unexpected Return Value');
188
-		}
189
-
190
-		return count($all) !== count($active) || count($all) === 0;
191
-	}
192
-
193
-	/**
194
-	 * extracts the domain from a given URL
195
-	 * @param string $url the URL
196
-	 * @return string|false domain as string on success, false otherwise
197
-	 */
198
-	public function getDomainFromURL($url) {
199
-		$uinfo = parse_url($url);
200
-		if(!is_array($uinfo)) {
201
-			return false;
202
-		}
203
-
204
-		$domain = false;
205
-		if(isset($uinfo['host'])) {
206
-			$domain = $uinfo['host'];
207
-		} else if(isset($uinfo['path'])) {
208
-			$domain = $uinfo['path'];
209
-		}
210
-
211
-		return $domain;
212
-	}
164
+        $delRows = $query->execute(array($prefix.'%'));
165
+
166
+        if(\OCP\DB::isError($delRows)) {
167
+            return false;
168
+        }
169
+
170
+        if($delRows === 0) {
171
+            return false;
172
+        }
173
+
174
+        return true;
175
+    }
176
+
177
+    /**
178
+     * checks whether there is one or more disabled LDAP configurations
179
+     * @throws \Exception
180
+     * @return bool
181
+     */
182
+    public function haveDisabledConfigurations() {
183
+        $all = $this->getServerConfigurationPrefixes(false);
184
+        $active = $this->getServerConfigurationPrefixes(true);
185
+
186
+        if(!is_array($all) || !is_array($active)) {
187
+            throw new \Exception('Unexpected Return Value');
188
+        }
189
+
190
+        return count($all) !== count($active) || count($all) === 0;
191
+    }
192
+
193
+    /**
194
+     * extracts the domain from a given URL
195
+     * @param string $url the URL
196
+     * @return string|false domain as string on success, false otherwise
197
+     */
198
+    public function getDomainFromURL($url) {
199
+        $uinfo = parse_url($url);
200
+        if(!is_array($uinfo)) {
201
+            return false;
202
+        }
203
+
204
+        $domain = false;
205
+        if(isset($uinfo['host'])) {
206
+            $domain = $uinfo['host'];
207
+        } else if(isset($uinfo['path'])) {
208
+            $domain = $uinfo['path'];
209
+        }
210
+
211
+        return $domain;
212
+    }
213 213
 	
214
-	/**
215
-	 *
216
-	 * Set the LDAPProvider in the config
217
-	 *
218
-	 */
219
-	public function setLDAPProvider() {
220
-		$current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
221
-		if(is_null($current)) {
222
-			\OC::$server->getConfig()->setSystemValue('ldapProviderFactory', '\\OCA\\User_LDAP\\LDAPProviderFactory');
223
-		}
224
-	}
214
+    /**
215
+     *
216
+     * Set the LDAPProvider in the config
217
+     *
218
+     */
219
+    public function setLDAPProvider() {
220
+        $current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
221
+        if(is_null($current)) {
222
+            \OC::$server->getConfig()->setSystemValue('ldapProviderFactory', '\\OCA\\User_LDAP\\LDAPProviderFactory');
223
+        }
224
+    }
225 225
 	
226
-	/**
227
-	 * sanitizes a DN received from the LDAP server
228
-	 * @param array $dn the DN in question
229
-	 * @return array the sanitized DN
230
-	 */
231
-	public function sanitizeDN($dn) {
232
-		//treating multiple base DNs
233
-		if(is_array($dn)) {
234
-			$result = array();
235
-			foreach($dn as $singleDN) {
236
-				$result[] = $this->sanitizeDN($singleDN);
237
-			}
238
-			return $result;
239
-		}
240
-
241
-		//OID sometimes gives back DNs with whitespace after the comma
242
-		// a la "uid=foo, cn=bar, dn=..." We need to tackle this!
243
-		$dn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
244
-
245
-		//make comparisons and everything work
246
-		$dn = mb_strtolower($dn, 'UTF-8');
247
-
248
-		//escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
249
-		//to use the DN in search filters, \ needs to be escaped to \5c additionally
250
-		//to use them in bases, we convert them back to simple backslashes in readAttribute()
251
-		$replacements = array(
252
-			'\,' => '\5c2C',
253
-			'\=' => '\5c3D',
254
-			'\+' => '\5c2B',
255
-			'\<' => '\5c3C',
256
-			'\>' => '\5c3E',
257
-			'\;' => '\5c3B',
258
-			'\"' => '\5c22',
259
-			'\#' => '\5c23',
260
-			'('  => '\28',
261
-			')'  => '\29',
262
-			'*'  => '\2A',
263
-		);
264
-		$dn = str_replace(array_keys($replacements), array_values($replacements), $dn);
265
-
266
-		return $dn;
267
-	}
226
+    /**
227
+     * sanitizes a DN received from the LDAP server
228
+     * @param array $dn the DN in question
229
+     * @return array the sanitized DN
230
+     */
231
+    public function sanitizeDN($dn) {
232
+        //treating multiple base DNs
233
+        if(is_array($dn)) {
234
+            $result = array();
235
+            foreach($dn as $singleDN) {
236
+                $result[] = $this->sanitizeDN($singleDN);
237
+            }
238
+            return $result;
239
+        }
240
+
241
+        //OID sometimes gives back DNs with whitespace after the comma
242
+        // a la "uid=foo, cn=bar, dn=..." We need to tackle this!
243
+        $dn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
244
+
245
+        //make comparisons and everything work
246
+        $dn = mb_strtolower($dn, 'UTF-8');
247
+
248
+        //escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
249
+        //to use the DN in search filters, \ needs to be escaped to \5c additionally
250
+        //to use them in bases, we convert them back to simple backslashes in readAttribute()
251
+        $replacements = array(
252
+            '\,' => '\5c2C',
253
+            '\=' => '\5c3D',
254
+            '\+' => '\5c2B',
255
+            '\<' => '\5c3C',
256
+            '\>' => '\5c3E',
257
+            '\;' => '\5c3B',
258
+            '\"' => '\5c22',
259
+            '\#' => '\5c23',
260
+            '('  => '\28',
261
+            ')'  => '\29',
262
+            '*'  => '\2A',
263
+        );
264
+        $dn = str_replace(array_keys($replacements), array_values($replacements), $dn);
265
+
266
+        return $dn;
267
+    }
268 268
 	
269
-	/**
270
-	 * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters
271
-	 * @param string $dn the DN
272
-	 * @return string
273
-	 */
274
-	public function DNasBaseParameter($dn) {
275
-		return str_ireplace('\\5c', '\\', $dn);
276
-	}
277
-
278
-	/**
279
-	 * listens to a hook thrown by server2server sharing and replaces the given
280
-	 * login name by a username, if it matches an LDAP user.
281
-	 *
282
-	 * @param array $param
283
-	 * @throws \Exception
284
-	 */
285
-	public static function loginName2UserName($param) {
286
-		if(!isset($param['uid'])) {
287
-			throw new \Exception('key uid is expected to be set in $param');
288
-		}
289
-
290
-		//ain't it ironic?
291
-		$helper = new Helper(\OC::$server->getConfig());
292
-
293
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
294
-		$ldapWrapper = new LDAP();
295
-		$ocConfig = \OC::$server->getConfig();
296
-		$notificationManager = \OC::$server->getNotificationManager();
297
-
298
-		$userBackend  = new User_Proxy(
299
-			$configPrefixes, $ldapWrapper, $ocConfig, $notificationManager
300
-		);
301
-		$uid = $userBackend->loginName2UserName($param['uid'] );
302
-		if($uid !== false) {
303
-			$param['uid'] = $uid;
304
-		}
305
-	}
269
+    /**
270
+     * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters
271
+     * @param string $dn the DN
272
+     * @return string
273
+     */
274
+    public function DNasBaseParameter($dn) {
275
+        return str_ireplace('\\5c', '\\', $dn);
276
+    }
277
+
278
+    /**
279
+     * listens to a hook thrown by server2server sharing and replaces the given
280
+     * login name by a username, if it matches an LDAP user.
281
+     *
282
+     * @param array $param
283
+     * @throws \Exception
284
+     */
285
+    public static function loginName2UserName($param) {
286
+        if(!isset($param['uid'])) {
287
+            throw new \Exception('key uid is expected to be set in $param');
288
+        }
289
+
290
+        //ain't it ironic?
291
+        $helper = new Helper(\OC::$server->getConfig());
292
+
293
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
294
+        $ldapWrapper = new LDAP();
295
+        $ocConfig = \OC::$server->getConfig();
296
+        $notificationManager = \OC::$server->getNotificationManager();
297
+
298
+        $userBackend  = new User_Proxy(
299
+            $configPrefixes, $ldapWrapper, $ocConfig, $notificationManager
300
+        );
301
+        $uid = $userBackend->loginName2UserName($param['uid'] );
302
+        if($uid !== false) {
303
+            $param['uid'] = $uid;
304
+        }
305
+    }
306 306
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
 		$keys = $this->getServersConfig($referenceConfigkey);
97 97
 
98 98
 		$result = array();
99
-		foreach($keys as $key) {
99
+		foreach ($keys as $key) {
100 100
 			$len = strlen($key) - strlen($referenceConfigkey);
101 101
 			$prefix = substr($key, 0, $len);
102 102
 			$result[$prefix] = $this->config->getAppValue('user_ldap', $key);
@@ -113,19 +113,19 @@  discard block
 block discarded – undo
113 113
 	public function getNextServerConfigurationPrefix() {
114 114
 		$serverConnections = $this->getServerConfigurationPrefixes();
115 115
 
116
-		if(count($serverConnections) === 0) {
116
+		if (count($serverConnections) === 0) {
117 117
 			return 's01';
118 118
 		}
119 119
 
120 120
 		sort($serverConnections);
121 121
 		$lastKey = array_pop($serverConnections);
122 122
 		$lastNumber = intval(str_replace('s', '', $lastKey));
123
-		$nextPrefix = 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
123
+		$nextPrefix = 's'.str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
124 124
 		return $nextPrefix;
125 125
 	}
126 126
 
127 127
 	private function getServersConfig($value) {
128
-		$regex = '/' . $value . '$/S';
128
+		$regex = '/'.$value.'$/S';
129 129
 
130 130
 		$keys = $this->config->getAppKeys('user_ldap');
131 131
 		$result = [];
@@ -144,12 +144,12 @@  discard block
 block discarded – undo
144 144
 	 * @return bool true on success, false otherwise
145 145
 	 */
146 146
 	public function deleteServerConfiguration($prefix) {
147
-		if(!in_array($prefix, self::getServerConfigurationPrefixes())) {
147
+		if (!in_array($prefix, self::getServerConfigurationPrefixes())) {
148 148
 			return false;
149 149
 		}
150 150
 
151 151
 		$saveOtherConfigurations = '';
152
-		if(empty($prefix)) {
152
+		if (empty($prefix)) {
153 153
 			$saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
154 154
 		}
155 155
 
@@ -163,11 +163,11 @@  discard block
 block discarded – undo
163 163
 		');
164 164
 		$delRows = $query->execute(array($prefix.'%'));
165 165
 
166
-		if(\OCP\DB::isError($delRows)) {
166
+		if (\OCP\DB::isError($delRows)) {
167 167
 			return false;
168 168
 		}
169 169
 
170
-		if($delRows === 0) {
170
+		if ($delRows === 0) {
171 171
 			return false;
172 172
 		}
173 173
 
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 		$all = $this->getServerConfigurationPrefixes(false);
184 184
 		$active = $this->getServerConfigurationPrefixes(true);
185 185
 
186
-		if(!is_array($all) || !is_array($active)) {
186
+		if (!is_array($all) || !is_array($active)) {
187 187
 			throw new \Exception('Unexpected Return Value');
188 188
 		}
189 189
 
@@ -197,14 +197,14 @@  discard block
 block discarded – undo
197 197
 	 */
198 198
 	public function getDomainFromURL($url) {
199 199
 		$uinfo = parse_url($url);
200
-		if(!is_array($uinfo)) {
200
+		if (!is_array($uinfo)) {
201 201
 			return false;
202 202
 		}
203 203
 
204 204
 		$domain = false;
205
-		if(isset($uinfo['host'])) {
205
+		if (isset($uinfo['host'])) {
206 206
 			$domain = $uinfo['host'];
207
-		} else if(isset($uinfo['path'])) {
207
+		} else if (isset($uinfo['path'])) {
208 208
 			$domain = $uinfo['path'];
209 209
 		}
210 210
 
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 	 */
219 219
 	public function setLDAPProvider() {
220 220
 		$current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
221
-		if(is_null($current)) {
221
+		if (is_null($current)) {
222 222
 			\OC::$server->getConfig()->setSystemValue('ldapProviderFactory', '\\OCA\\User_LDAP\\LDAPProviderFactory');
223 223
 		}
224 224
 	}
@@ -230,9 +230,9 @@  discard block
 block discarded – undo
230 230
 	 */
231 231
 	public function sanitizeDN($dn) {
232 232
 		//treating multiple base DNs
233
-		if(is_array($dn)) {
233
+		if (is_array($dn)) {
234 234
 			$result = array();
235
-			foreach($dn as $singleDN) {
235
+			foreach ($dn as $singleDN) {
236 236
 				$result[] = $this->sanitizeDN($singleDN);
237 237
 			}
238 238
 			return $result;
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
 	 * @throws \Exception
284 284
 	 */
285 285
 	public static function loginName2UserName($param) {
286
-		if(!isset($param['uid'])) {
286
+		if (!isset($param['uid'])) {
287 287
 			throw new \Exception('key uid is expected to be set in $param');
288 288
 		}
289 289
 
@@ -295,11 +295,11 @@  discard block
 block discarded – undo
295 295
 		$ocConfig = \OC::$server->getConfig();
296 296
 		$notificationManager = \OC::$server->getNotificationManager();
297 297
 
298
-		$userBackend  = new User_Proxy(
298
+		$userBackend = new User_Proxy(
299 299
 			$configPrefixes, $ldapWrapper, $ocConfig, $notificationManager
300 300
 		);
301
-		$uid = $userBackend->loginName2UserName($param['uid'] );
302
-		if($uid !== false) {
301
+		$uid = $userBackend->loginName2UserName($param['uid']);
302
+		if ($uid !== false) {
303 303
 			$param['uid'] = $uid;
304 304
 		}
305 305
 	}
Please login to merge, or discard this patch.
core/Middleware/TwoFactorMiddleware.php 2 patches
Doc Comments   +4 added lines patch added patch discarded remove patch
@@ -104,6 +104,10 @@
 block discarded – undo
104 104
 		// TODO: dont check/enforce 2FA if a auth token is used
105 105
 	}
106 106
 
107
+	/**
108
+	 * @param Controller $controller
109
+	 * @param string $methodName
110
+	 */
107 111
 	private function checkTwoFactor($controller, $methodName, IUser $user) {
108 112
 		// If two-factor auth is in progress disallow access to any controllers
109 113
 		// defined within "LoginController".
Please login to merge, or discard this patch.
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -41,100 +41,100 @@
 block discarded – undo
41 41
 
42 42
 class TwoFactorMiddleware extends Middleware {
43 43
 
44
-	/** @var Manager */
45
-	private $twoFactorManager;
46
-
47
-	/** @var Session */
48
-	private $userSession;
49
-
50
-	/** @var ISession */
51
-	private $session;
52
-
53
-	/** @var IURLGenerator */
54
-	private $urlGenerator;
55
-
56
-	/** @var IControllerMethodReflector */
57
-	private $reflector;
58
-
59
-	/** @var IRequest */
60
-	private $request;
61
-
62
-	/**
63
-	 * @param Manager $twoFactorManager
64
-	 * @param Session $userSession
65
-	 * @param ISession $session
66
-	 * @param IURLGenerator $urlGenerator
67
-	 */
68
-	public function __construct(Manager $twoFactorManager, Session $userSession, ISession $session,
69
-		IURLGenerator $urlGenerator, IControllerMethodReflector $reflector, IRequest $request) {
70
-		$this->twoFactorManager = $twoFactorManager;
71
-		$this->userSession = $userSession;
72
-		$this->session = $session;
73
-		$this->urlGenerator = $urlGenerator;
74
-		$this->reflector = $reflector;
75
-		$this->request = $request;
76
-	}
77
-
78
-	/**
79
-	 * @param Controller $controller
80
-	 * @param string $methodName
81
-	 */
82
-	public function beforeController($controller, $methodName) {
83
-		if ($this->reflector->hasAnnotation('PublicPage')) {
84
-			// Don't block public pages
85
-			return;
86
-		}
87
-
88
-		if ($controller instanceof LoginController && $methodName === 'logout') {
89
-			// Don't block the logout page, to allow canceling the 2FA
90
-			return;
91
-		}
92
-
93
-		if ($this->userSession->isLoggedIn()) {
94
-			$user = $this->userSession->getUser();
95
-
96
-			if ($this->twoFactorManager->isTwoFactorAuthenticated($user)) {
97
-				$this->checkTwoFactor($controller, $methodName, $user);
98
-			} else if ($controller instanceof TwoFactorChallengeController) {
99
-				// Allow access to the two-factor controllers only if two-factor authentication
100
-				// is in progress.
101
-				throw new UserAlreadyLoggedInException();
102
-			}
103
-		}
104
-		// TODO: dont check/enforce 2FA if a auth token is used
105
-	}
106
-
107
-	private function checkTwoFactor($controller, $methodName, IUser $user) {
108
-		// If two-factor auth is in progress disallow access to any controllers
109
-		// defined within "LoginController".
110
-		$needsSecondFactor = $this->twoFactorManager->needsSecondFactor($user);
111
-		$twoFactor = $controller instanceof TwoFactorChallengeController;
112
-
113
-		// Disallow access to any controller if 2FA needs to be checked
114
-		if ($needsSecondFactor && !$twoFactor) {
115
-			throw new TwoFactorAuthRequiredException();
116
-		}
117
-
118
-		// Allow access to the two-factor controllers only if two-factor authentication
119
-		// is in progress.
120
-		if (!$needsSecondFactor && $twoFactor) {
121
-			throw new UserAlreadyLoggedInException();
122
-		}
123
-	}
124
-
125
-	public function afterException($controller, $methodName, Exception $exception) {
126
-		if ($exception instanceof TwoFactorAuthRequiredException) {
127
-			$params = [];
128
-			if (isset($this->request->server['REQUEST_URI'])) {
129
-				$params['redirect_url'] = $this->request->server['REQUEST_URI'];
130
-			}
131
-			return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge', $params));
132
-		}
133
-		if ($exception instanceof UserAlreadyLoggedInException) {
134
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
135
-		}
136
-
137
-		throw $exception;
138
-	}
44
+    /** @var Manager */
45
+    private $twoFactorManager;
46
+
47
+    /** @var Session */
48
+    private $userSession;
49
+
50
+    /** @var ISession */
51
+    private $session;
52
+
53
+    /** @var IURLGenerator */
54
+    private $urlGenerator;
55
+
56
+    /** @var IControllerMethodReflector */
57
+    private $reflector;
58
+
59
+    /** @var IRequest */
60
+    private $request;
61
+
62
+    /**
63
+     * @param Manager $twoFactorManager
64
+     * @param Session $userSession
65
+     * @param ISession $session
66
+     * @param IURLGenerator $urlGenerator
67
+     */
68
+    public function __construct(Manager $twoFactorManager, Session $userSession, ISession $session,
69
+        IURLGenerator $urlGenerator, IControllerMethodReflector $reflector, IRequest $request) {
70
+        $this->twoFactorManager = $twoFactorManager;
71
+        $this->userSession = $userSession;
72
+        $this->session = $session;
73
+        $this->urlGenerator = $urlGenerator;
74
+        $this->reflector = $reflector;
75
+        $this->request = $request;
76
+    }
77
+
78
+    /**
79
+     * @param Controller $controller
80
+     * @param string $methodName
81
+     */
82
+    public function beforeController($controller, $methodName) {
83
+        if ($this->reflector->hasAnnotation('PublicPage')) {
84
+            // Don't block public pages
85
+            return;
86
+        }
87
+
88
+        if ($controller instanceof LoginController && $methodName === 'logout') {
89
+            // Don't block the logout page, to allow canceling the 2FA
90
+            return;
91
+        }
92
+
93
+        if ($this->userSession->isLoggedIn()) {
94
+            $user = $this->userSession->getUser();
95
+
96
+            if ($this->twoFactorManager->isTwoFactorAuthenticated($user)) {
97
+                $this->checkTwoFactor($controller, $methodName, $user);
98
+            } else if ($controller instanceof TwoFactorChallengeController) {
99
+                // Allow access to the two-factor controllers only if two-factor authentication
100
+                // is in progress.
101
+                throw new UserAlreadyLoggedInException();
102
+            }
103
+        }
104
+        // TODO: dont check/enforce 2FA if a auth token is used
105
+    }
106
+
107
+    private function checkTwoFactor($controller, $methodName, IUser $user) {
108
+        // If two-factor auth is in progress disallow access to any controllers
109
+        // defined within "LoginController".
110
+        $needsSecondFactor = $this->twoFactorManager->needsSecondFactor($user);
111
+        $twoFactor = $controller instanceof TwoFactorChallengeController;
112
+
113
+        // Disallow access to any controller if 2FA needs to be checked
114
+        if ($needsSecondFactor && !$twoFactor) {
115
+            throw new TwoFactorAuthRequiredException();
116
+        }
117
+
118
+        // Allow access to the two-factor controllers only if two-factor authentication
119
+        // is in progress.
120
+        if (!$needsSecondFactor && $twoFactor) {
121
+            throw new UserAlreadyLoggedInException();
122
+        }
123
+    }
124
+
125
+    public function afterException($controller, $methodName, Exception $exception) {
126
+        if ($exception instanceof TwoFactorAuthRequiredException) {
127
+            $params = [];
128
+            if (isset($this->request->server['REQUEST_URI'])) {
129
+                $params['redirect_url'] = $this->request->server['REQUEST_URI'];
130
+            }
131
+            return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge', $params));
132
+        }
133
+        if ($exception instanceof UserAlreadyLoggedInException) {
134
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
135
+        }
136
+
137
+        throw $exception;
138
+    }
139 139
 
140 140
 }
Please login to merge, or discard this patch.
lib/private/Archive/ZIP.php 4 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -370,6 +370,7 @@
 block discarded – undo
370 370
 
371 371
 	/**
372 372
 	 * write back temporary files
373
+	 * @param string $path
373 374
 	 */
374 375
 	function writeBack($tmpFile, $path) {
375 376
 		$this->addFile($path, $tmpFile);
Please login to merge, or discard this patch.
Indentation   +192 added lines, -192 removed lines patch added patch discarded remove patch
@@ -34,199 +34,199 @@
 block discarded – undo
34 34
 use Icewind\Streams\CallbackWrapper;
35 35
 
36 36
 class ZIP extends Archive{
37
-	/**
38
-	 * @var \ZipArchive zip
39
-	 */
40
-	private $zip=null;
41
-	private $path;
37
+    /**
38
+     * @var \ZipArchive zip
39
+     */
40
+    private $zip=null;
41
+    private $path;
42 42
 
43
-	/**
44
-	 * @param string $source
45
-	 */
46
-	function __construct($source) {
47
-		$this->path=$source;
48
-		$this->zip=new \ZipArchive();
49
-		if($this->zip->open($source, \ZipArchive::CREATE)) {
50
-		}else{
51
-			\OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, \OCP\Util::WARN);
52
-		}
53
-	}
54
-	/**
55
-	 * add an empty folder to the archive
56
-	 * @param string $path
57
-	 * @return bool
58
-	 */
59
-	function addFolder($path) {
60
-		return $this->zip->addEmptyDir($path);
61
-	}
62
-	/**
63
-	 * add a file to the archive
64
-	 * @param string $path
65
-	 * @param string $source either a local file or string data
66
-	 * @return bool
67
-	 */
68
-	function addFile($path, $source='') {
69
-		if($source and $source[0]=='/' and file_exists($source)) {
70
-			$result=$this->zip->addFile($source, $path);
71
-		}else{
72
-			$result=$this->zip->addFromString($path, $source);
73
-		}
74
-		if($result) {
75
-			$this->zip->close();//close and reopen to save the zip
76
-			$this->zip->open($this->path);
77
-		}
78
-		return $result;
79
-	}
80
-	/**
81
-	 * rename a file or folder in the archive
82
-	 * @param string $source
83
-	 * @param string $dest
84
-	 * @return boolean|null
85
-	 */
86
-	function rename($source, $dest) {
87
-		$source=$this->stripPath($source);
88
-		$dest=$this->stripPath($dest);
89
-		$this->zip->renameName($source, $dest);
90
-	}
91
-	/**
92
-	 * get the uncompressed size of a file in the archive
93
-	 * @param string $path
94
-	 * @return int
95
-	 */
96
-	function filesize($path) {
97
-		$stat=$this->zip->statName($path);
98
-		return $stat['size'];
99
-	}
100
-	/**
101
-	 * get the last modified time of a file in the archive
102
-	 * @param string $path
103
-	 * @return int
104
-	 */
105
-	function mtime($path) {
106
-		return filemtime($this->path);
107
-	}
108
-	/**
109
-	 * get the files in a folder
110
-	 * @param string $path
111
-	 * @return array
112
-	 */
113
-	function getFolder($path) {
114
-		$files=$this->getFiles();
115
-		$folderContent=array();
116
-		$pathLength=strlen($path);
117
-		foreach($files as $file) {
118
-			if(substr($file, 0, $pathLength)==$path and $file!=$path) {
119
-				if(strrpos(substr($file, 0, -1), '/')<=$pathLength) {
120
-					$folderContent[]=substr($file, $pathLength);
121
-				}
122
-			}
123
-		}
124
-		return $folderContent;
125
-	}
126
-	/**
127
-	 * get all files in the archive
128
-	 * @return array
129
-	 */
130
-	function getFiles() {
131
-		$fileCount=$this->zip->numFiles;
132
-		$files=array();
133
-		for($i=0;$i<$fileCount;$i++) {
134
-			$files[]=$this->zip->getNameIndex($i);
135
-		}
136
-		return $files;
137
-	}
138
-	/**
139
-	 * get the content of a file
140
-	 * @param string $path
141
-	 * @return string
142
-	 */
143
-	function getFile($path) {
144
-		return $this->zip->getFromName($path);
145
-	}
146
-	/**
147
-	 * extract a single file from the archive
148
-	 * @param string $path
149
-	 * @param string $dest
150
-	 * @return boolean|null
151
-	 */
152
-	function extractFile($path, $dest) {
153
-		$fp = $this->zip->getStream($path);
154
-		file_put_contents($dest, $fp);
155
-	}
156
-	/**
157
-	 * extract the archive
158
-	 * @param string $dest
159
-	 * @return bool
160
-	 */
161
-	function extract($dest) {
162
-		return $this->zip->extractTo($dest);
163
-	}
164
-	/**
165
-	 * check if a file or folder exists in the archive
166
-	 * @param string $path
167
-	 * @return bool
168
-	 */
169
-	function fileExists($path) {
170
-		return ($this->zip->locateName($path)!==false) or ($this->zip->locateName($path.'/')!==false);
171
-	}
172
-	/**
173
-	 * remove a file or folder from the archive
174
-	 * @param string $path
175
-	 * @return bool
176
-	 */
177
-	function remove($path) {
178
-		if($this->fileExists($path.'/')) {
179
-			return $this->zip->deleteName($path.'/');
180
-		}else{
181
-			return $this->zip->deleteName($path);
182
-		}
183
-	}
184
-	/**
185
-	 * get a file handler
186
-	 * @param string $path
187
-	 * @param string $mode
188
-	 * @return resource
189
-	 */
190
-	function getStream($path, $mode) {
191
-		if($mode=='r' or $mode=='rb') {
192
-			return $this->zip->getStream($path);
193
-		} else {
194
-			//since we can't directly get a writable stream,
195
-			//make a temp copy of the file and put it back
196
-			//in the archive when the stream is closed
197
-			if(strrpos($path, '.')!==false) {
198
-				$ext=substr($path, strrpos($path, '.'));
199
-			}else{
200
-				$ext='';
201
-			}
202
-			$tmpFile=\OCP\Files::tmpFile($ext);
203
-			if($this->fileExists($path)) {
204
-				$this->extractFile($path, $tmpFile);
205
-			}
206
-			$handle = fopen($tmpFile, $mode);
207
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
208
-				$this->writeBack($tmpFile, $path);
209
-			});
210
-		}
211
-	}
43
+    /**
44
+     * @param string $source
45
+     */
46
+    function __construct($source) {
47
+        $this->path=$source;
48
+        $this->zip=new \ZipArchive();
49
+        if($this->zip->open($source, \ZipArchive::CREATE)) {
50
+        }else{
51
+            \OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, \OCP\Util::WARN);
52
+        }
53
+    }
54
+    /**
55
+     * add an empty folder to the archive
56
+     * @param string $path
57
+     * @return bool
58
+     */
59
+    function addFolder($path) {
60
+        return $this->zip->addEmptyDir($path);
61
+    }
62
+    /**
63
+     * add a file to the archive
64
+     * @param string $path
65
+     * @param string $source either a local file or string data
66
+     * @return bool
67
+     */
68
+    function addFile($path, $source='') {
69
+        if($source and $source[0]=='/' and file_exists($source)) {
70
+            $result=$this->zip->addFile($source, $path);
71
+        }else{
72
+            $result=$this->zip->addFromString($path, $source);
73
+        }
74
+        if($result) {
75
+            $this->zip->close();//close and reopen to save the zip
76
+            $this->zip->open($this->path);
77
+        }
78
+        return $result;
79
+    }
80
+    /**
81
+     * rename a file or folder in the archive
82
+     * @param string $source
83
+     * @param string $dest
84
+     * @return boolean|null
85
+     */
86
+    function rename($source, $dest) {
87
+        $source=$this->stripPath($source);
88
+        $dest=$this->stripPath($dest);
89
+        $this->zip->renameName($source, $dest);
90
+    }
91
+    /**
92
+     * get the uncompressed size of a file in the archive
93
+     * @param string $path
94
+     * @return int
95
+     */
96
+    function filesize($path) {
97
+        $stat=$this->zip->statName($path);
98
+        return $stat['size'];
99
+    }
100
+    /**
101
+     * get the last modified time of a file in the archive
102
+     * @param string $path
103
+     * @return int
104
+     */
105
+    function mtime($path) {
106
+        return filemtime($this->path);
107
+    }
108
+    /**
109
+     * get the files in a folder
110
+     * @param string $path
111
+     * @return array
112
+     */
113
+    function getFolder($path) {
114
+        $files=$this->getFiles();
115
+        $folderContent=array();
116
+        $pathLength=strlen($path);
117
+        foreach($files as $file) {
118
+            if(substr($file, 0, $pathLength)==$path and $file!=$path) {
119
+                if(strrpos(substr($file, 0, -1), '/')<=$pathLength) {
120
+                    $folderContent[]=substr($file, $pathLength);
121
+                }
122
+            }
123
+        }
124
+        return $folderContent;
125
+    }
126
+    /**
127
+     * get all files in the archive
128
+     * @return array
129
+     */
130
+    function getFiles() {
131
+        $fileCount=$this->zip->numFiles;
132
+        $files=array();
133
+        for($i=0;$i<$fileCount;$i++) {
134
+            $files[]=$this->zip->getNameIndex($i);
135
+        }
136
+        return $files;
137
+    }
138
+    /**
139
+     * get the content of a file
140
+     * @param string $path
141
+     * @return string
142
+     */
143
+    function getFile($path) {
144
+        return $this->zip->getFromName($path);
145
+    }
146
+    /**
147
+     * extract a single file from the archive
148
+     * @param string $path
149
+     * @param string $dest
150
+     * @return boolean|null
151
+     */
152
+    function extractFile($path, $dest) {
153
+        $fp = $this->zip->getStream($path);
154
+        file_put_contents($dest, $fp);
155
+    }
156
+    /**
157
+     * extract the archive
158
+     * @param string $dest
159
+     * @return bool
160
+     */
161
+    function extract($dest) {
162
+        return $this->zip->extractTo($dest);
163
+    }
164
+    /**
165
+     * check if a file or folder exists in the archive
166
+     * @param string $path
167
+     * @return bool
168
+     */
169
+    function fileExists($path) {
170
+        return ($this->zip->locateName($path)!==false) or ($this->zip->locateName($path.'/')!==false);
171
+    }
172
+    /**
173
+     * remove a file or folder from the archive
174
+     * @param string $path
175
+     * @return bool
176
+     */
177
+    function remove($path) {
178
+        if($this->fileExists($path.'/')) {
179
+            return $this->zip->deleteName($path.'/');
180
+        }else{
181
+            return $this->zip->deleteName($path);
182
+        }
183
+    }
184
+    /**
185
+     * get a file handler
186
+     * @param string $path
187
+     * @param string $mode
188
+     * @return resource
189
+     */
190
+    function getStream($path, $mode) {
191
+        if($mode=='r' or $mode=='rb') {
192
+            return $this->zip->getStream($path);
193
+        } else {
194
+            //since we can't directly get a writable stream,
195
+            //make a temp copy of the file and put it back
196
+            //in the archive when the stream is closed
197
+            if(strrpos($path, '.')!==false) {
198
+                $ext=substr($path, strrpos($path, '.'));
199
+            }else{
200
+                $ext='';
201
+            }
202
+            $tmpFile=\OCP\Files::tmpFile($ext);
203
+            if($this->fileExists($path)) {
204
+                $this->extractFile($path, $tmpFile);
205
+            }
206
+            $handle = fopen($tmpFile, $mode);
207
+            return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
208
+                $this->writeBack($tmpFile, $path);
209
+            });
210
+        }
211
+    }
212 212
 
213
-	/**
214
-	 * write back temporary files
215
-	 */
216
-	function writeBack($tmpFile, $path) {
217
-		$this->addFile($path, $tmpFile);
218
-		unlink($tmpFile);
219
-	}
213
+    /**
214
+     * write back temporary files
215
+     */
216
+    function writeBack($tmpFile, $path) {
217
+        $this->addFile($path, $tmpFile);
218
+        unlink($tmpFile);
219
+    }
220 220
 
221
-	/**
222
-	 * @param string $path
223
-	 * @return string
224
-	 */
225
-	private function stripPath($path) {
226
-		if(!$path || $path[0]=='/') {
227
-			return substr($path, 1);
228
-		}else{
229
-			return $path;
230
-		}
231
-	}
221
+    /**
222
+     * @param string $path
223
+     * @return string
224
+     */
225
+    private function stripPath($path) {
226
+        if(!$path || $path[0]=='/') {
227
+            return substr($path, 1);
228
+        }else{
229
+            return $path;
230
+        }
231
+    }
232 232
 }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -33,21 +33,21 @@  discard block
 block discarded – undo
33 33
 
34 34
 use Icewind\Streams\CallbackWrapper;
35 35
 
36
-class ZIP extends Archive{
36
+class ZIP extends Archive {
37 37
 	/**
38 38
 	 * @var \ZipArchive zip
39 39
 	 */
40
-	private $zip=null;
40
+	private $zip = null;
41 41
 	private $path;
42 42
 
43 43
 	/**
44 44
 	 * @param string $source
45 45
 	 */
46 46
 	function __construct($source) {
47
-		$this->path=$source;
48
-		$this->zip=new \ZipArchive();
49
-		if($this->zip->open($source, \ZipArchive::CREATE)) {
50
-		}else{
47
+		$this->path = $source;
48
+		$this->zip = new \ZipArchive();
49
+		if ($this->zip->open($source, \ZipArchive::CREATE)) {
50
+		} else {
51 51
 			\OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, \OCP\Util::WARN);
52 52
 		}
53 53
 	}
@@ -65,14 +65,14 @@  discard block
 block discarded – undo
65 65
 	 * @param string $source either a local file or string data
66 66
 	 * @return bool
67 67
 	 */
68
-	function addFile($path, $source='') {
69
-		if($source and $source[0]=='/' and file_exists($source)) {
70
-			$result=$this->zip->addFile($source, $path);
71
-		}else{
72
-			$result=$this->zip->addFromString($path, $source);
68
+	function addFile($path, $source = '') {
69
+		if ($source and $source[0] == '/' and file_exists($source)) {
70
+			$result = $this->zip->addFile($source, $path);
71
+		} else {
72
+			$result = $this->zip->addFromString($path, $source);
73 73
 		}
74
-		if($result) {
75
-			$this->zip->close();//close and reopen to save the zip
74
+		if ($result) {
75
+			$this->zip->close(); //close and reopen to save the zip
76 76
 			$this->zip->open($this->path);
77 77
 		}
78 78
 		return $result;
@@ -84,8 +84,8 @@  discard block
 block discarded – undo
84 84
 	 * @return boolean|null
85 85
 	 */
86 86
 	function rename($source, $dest) {
87
-		$source=$this->stripPath($source);
88
-		$dest=$this->stripPath($dest);
87
+		$source = $this->stripPath($source);
88
+		$dest = $this->stripPath($dest);
89 89
 		$this->zip->renameName($source, $dest);
90 90
 	}
91 91
 	/**
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 	 * @return int
95 95
 	 */
96 96
 	function filesize($path) {
97
-		$stat=$this->zip->statName($path);
97
+		$stat = $this->zip->statName($path);
98 98
 		return $stat['size'];
99 99
 	}
100 100
 	/**
@@ -111,13 +111,13 @@  discard block
 block discarded – undo
111 111
 	 * @return array
112 112
 	 */
113 113
 	function getFolder($path) {
114
-		$files=$this->getFiles();
115
-		$folderContent=array();
116
-		$pathLength=strlen($path);
117
-		foreach($files as $file) {
118
-			if(substr($file, 0, $pathLength)==$path and $file!=$path) {
119
-				if(strrpos(substr($file, 0, -1), '/')<=$pathLength) {
120
-					$folderContent[]=substr($file, $pathLength);
114
+		$files = $this->getFiles();
115
+		$folderContent = array();
116
+		$pathLength = strlen($path);
117
+		foreach ($files as $file) {
118
+			if (substr($file, 0, $pathLength) == $path and $file != $path) {
119
+				if (strrpos(substr($file, 0, -1), '/') <= $pathLength) {
120
+					$folderContent[] = substr($file, $pathLength);
121 121
 				}
122 122
 			}
123 123
 		}
@@ -128,10 +128,10 @@  discard block
 block discarded – undo
128 128
 	 * @return array
129 129
 	 */
130 130
 	function getFiles() {
131
-		$fileCount=$this->zip->numFiles;
132
-		$files=array();
133
-		for($i=0;$i<$fileCount;$i++) {
134
-			$files[]=$this->zip->getNameIndex($i);
131
+		$fileCount = $this->zip->numFiles;
132
+		$files = array();
133
+		for ($i = 0; $i < $fileCount; $i++) {
134
+			$files[] = $this->zip->getNameIndex($i);
135 135
 		}
136 136
 		return $files;
137 137
 	}
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 	 * @return bool
168 168
 	 */
169 169
 	function fileExists($path) {
170
-		return ($this->zip->locateName($path)!==false) or ($this->zip->locateName($path.'/')!==false);
170
+		return ($this->zip->locateName($path) !== false) or ($this->zip->locateName($path.'/') !== false);
171 171
 	}
172 172
 	/**
173 173
 	 * remove a file or folder from the archive
@@ -175,9 +175,9 @@  discard block
 block discarded – undo
175 175
 	 * @return bool
176 176
 	 */
177 177
 	function remove($path) {
178
-		if($this->fileExists($path.'/')) {
178
+		if ($this->fileExists($path.'/')) {
179 179
 			return $this->zip->deleteName($path.'/');
180
-		}else{
180
+		} else {
181 181
 			return $this->zip->deleteName($path);
182 182
 		}
183 183
 	}
@@ -188,23 +188,23 @@  discard block
 block discarded – undo
188 188
 	 * @return resource
189 189
 	 */
190 190
 	function getStream($path, $mode) {
191
-		if($mode=='r' or $mode=='rb') {
191
+		if ($mode == 'r' or $mode == 'rb') {
192 192
 			return $this->zip->getStream($path);
193 193
 		} else {
194 194
 			//since we can't directly get a writable stream,
195 195
 			//make a temp copy of the file and put it back
196 196
 			//in the archive when the stream is closed
197
-			if(strrpos($path, '.')!==false) {
198
-				$ext=substr($path, strrpos($path, '.'));
199
-			}else{
200
-				$ext='';
197
+			if (strrpos($path, '.') !== false) {
198
+				$ext = substr($path, strrpos($path, '.'));
199
+			} else {
200
+				$ext = '';
201 201
 			}
202
-			$tmpFile=\OCP\Files::tmpFile($ext);
203
-			if($this->fileExists($path)) {
202
+			$tmpFile = \OCP\Files::tmpFile($ext);
203
+			if ($this->fileExists($path)) {
204 204
 				$this->extractFile($path, $tmpFile);
205 205
 			}
206 206
 			$handle = fopen($tmpFile, $mode);
207
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
207
+			return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
208 208
 				$this->writeBack($tmpFile, $path);
209 209
 			});
210 210
 		}
@@ -223,9 +223,9 @@  discard block
 block discarded – undo
223 223
 	 * @return string
224 224
 	 */
225 225
 	private function stripPath($path) {
226
-		if(!$path || $path[0]=='/') {
226
+		if (!$path || $path[0] == '/') {
227 227
 			return substr($path, 1);
228
-		}else{
228
+		} else {
229 229
 			return $path;
230 230
 		}
231 231
 	}
Please login to merge, or discard this patch.
Braces   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
 		$this->path=$source;
48 48
 		$this->zip=new \ZipArchive();
49 49
 		if($this->zip->open($source, \ZipArchive::CREATE)) {
50
-		}else{
50
+		} else{
51 51
 			\OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, \OCP\Util::WARN);
52 52
 		}
53 53
 	}
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 	function addFile($path, $source='') {
69 69
 		if($source and $source[0]=='/' and file_exists($source)) {
70 70
 			$result=$this->zip->addFile($source, $path);
71
-		}else{
71
+		} else{
72 72
 			$result=$this->zip->addFromString($path, $source);
73 73
 		}
74 74
 		if($result) {
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 	function remove($path) {
178 178
 		if($this->fileExists($path.'/')) {
179 179
 			return $this->zip->deleteName($path.'/');
180
-		}else{
180
+		} else{
181 181
 			return $this->zip->deleteName($path);
182 182
 		}
183 183
 	}
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
 			//in the archive when the stream is closed
197 197
 			if(strrpos($path, '.')!==false) {
198 198
 				$ext=substr($path, strrpos($path, '.'));
199
-			}else{
199
+			} else{
200 200
 				$ext='';
201 201
 			}
202 202
 			$tmpFile=\OCP\Files::tmpFile($ext);
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
 	private function stripPath($path) {
226 226
 		if(!$path || $path[0]=='/') {
227 227
 			return substr($path, 1);
228
-		}else{
228
+		} else{
229 229
 			return $path;
230 230
 		}
231 231
 	}
Please login to merge, or discard this patch.
lib/private/Files/Cache/Wrapper/CacheJail.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -194,6 +194,9 @@
 block discarded – undo
194 194
 		return $this->getCache()->getStatus($this->getSourcePath($file));
195 195
 	}
196 196
 
197
+	/**
198
+	 * @param ICacheEntry[] $results
199
+	 */
197 200
 	private function formatSearchResults($results) {
198 201
 		$results = array_filter($results, array($this, 'filterCacheEntry'));
199 202
 		$results = array_values($results);
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
 		if ($path === '') {
52 52
 			return $this->root;
53 53
 		} else {
54
-			return $this->root . '/' . ltrim($path, '/');
54
+			return $this->root.'/'.ltrim($path, '/');
55 55
 		}
56 56
 	}
57 57
 
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
 		$rootLength = strlen($this->root) + 1;
67 67
 		if ($path === $this->root) {
68 68
 			return '';
69
-		} else if (substr($path, 0, $rootLength) === $this->root . '/') {
69
+		} else if (substr($path, 0, $rootLength) === $this->root.'/') {
70 70
 			return substr($path, $rootLength);
71 71
 		} else {
72 72
 			return null;
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 
87 87
 	protected function filterCacheEntry($entry) {
88 88
 		$rootLength = strlen($this->root) + 1;
89
-		return ($entry['path'] === $this->root) or (substr($entry['path'], 0, $rootLength) === $this->root . '/');
89
+		return ($entry['path'] === $this->root) or (substr($entry['path'], 0, $rootLength) === $this->root.'/');
90 90
 	}
91 91
 
92 92
 	/**
Please login to merge, or discard this patch.
Indentation   +262 added lines, -262 removed lines patch added patch discarded remove patch
@@ -34,294 +34,294 @@
 block discarded – undo
34 34
  * Jail to a subdirectory of the wrapped cache
35 35
  */
36 36
 class CacheJail extends CacheWrapper {
37
-	/**
38
-	 * @var string
39
-	 */
40
-	protected $root;
37
+    /**
38
+     * @var string
39
+     */
40
+    protected $root;
41 41
 
42
-	/**
43
-	 * @param \OCP\Files\Cache\ICache $cache
44
-	 * @param string $root
45
-	 */
46
-	public function __construct($cache, $root) {
47
-		parent::__construct($cache);
48
-		$this->root = $root;
49
-	}
42
+    /**
43
+     * @param \OCP\Files\Cache\ICache $cache
44
+     * @param string $root
45
+     */
46
+    public function __construct($cache, $root) {
47
+        parent::__construct($cache);
48
+        $this->root = $root;
49
+    }
50 50
 
51
-	protected function getSourcePath($path) {
52
-		if ($path === '') {
53
-			return $this->root;
54
-		} else {
55
-			return $this->root . '/' . ltrim($path, '/');
56
-		}
57
-	}
51
+    protected function getSourcePath($path) {
52
+        if ($path === '') {
53
+            return $this->root;
54
+        } else {
55
+            return $this->root . '/' . ltrim($path, '/');
56
+        }
57
+    }
58 58
 
59
-	/**
60
-	 * @param string $path
61
-	 * @return null|string the jailed path or null if the path is outside the jail
62
-	 */
63
-	protected function getJailedPath($path) {
64
-		if ($this->root === '') {
65
-			return $path;
66
-		}
67
-		$rootLength = strlen($this->root) + 1;
68
-		if ($path === $this->root) {
69
-			return '';
70
-		} else if (substr($path, 0, $rootLength) === $this->root . '/') {
71
-			return substr($path, $rootLength);
72
-		} else {
73
-			return null;
74
-		}
75
-	}
59
+    /**
60
+     * @param string $path
61
+     * @return null|string the jailed path or null if the path is outside the jail
62
+     */
63
+    protected function getJailedPath($path) {
64
+        if ($this->root === '') {
65
+            return $path;
66
+        }
67
+        $rootLength = strlen($this->root) + 1;
68
+        if ($path === $this->root) {
69
+            return '';
70
+        } else if (substr($path, 0, $rootLength) === $this->root . '/') {
71
+            return substr($path, $rootLength);
72
+        } else {
73
+            return null;
74
+        }
75
+    }
76 76
 
77
-	/**
78
-	 * @param ICacheEntry|array $entry
79
-	 * @return array
80
-	 */
81
-	protected function formatCacheEntry($entry) {
82
-		if (isset($entry['path'])) {
83
-			$entry['path'] = $this->getJailedPath($entry['path']);
84
-		}
85
-		return $entry;
86
-	}
77
+    /**
78
+     * @param ICacheEntry|array $entry
79
+     * @return array
80
+     */
81
+    protected function formatCacheEntry($entry) {
82
+        if (isset($entry['path'])) {
83
+            $entry['path'] = $this->getJailedPath($entry['path']);
84
+        }
85
+        return $entry;
86
+    }
87 87
 
88
-	protected function filterCacheEntry($entry) {
89
-		$rootLength = strlen($this->root) + 1;
90
-		return ($entry['path'] === $this->root) or (substr($entry['path'], 0, $rootLength) === $this->root . '/');
91
-	}
88
+    protected function filterCacheEntry($entry) {
89
+        $rootLength = strlen($this->root) + 1;
90
+        return ($entry['path'] === $this->root) or (substr($entry['path'], 0, $rootLength) === $this->root . '/');
91
+    }
92 92
 
93
-	/**
94
-	 * get the stored metadata of a file or folder
95
-	 *
96
-	 * @param string /int $file
97
-	 * @return ICacheEntry|false
98
-	 */
99
-	public function get($file) {
100
-		if (is_string($file) or $file == '') {
101
-			$file = $this->getSourcePath($file);
102
-		}
103
-		return parent::get($file);
104
-	}
93
+    /**
94
+     * get the stored metadata of a file or folder
95
+     *
96
+     * @param string /int $file
97
+     * @return ICacheEntry|false
98
+     */
99
+    public function get($file) {
100
+        if (is_string($file) or $file == '') {
101
+            $file = $this->getSourcePath($file);
102
+        }
103
+        return parent::get($file);
104
+    }
105 105
 
106
-	/**
107
-	 * insert meta data for a new file or folder
108
-	 *
109
-	 * @param string $file
110
-	 * @param array $data
111
-	 *
112
-	 * @return int file id
113
-	 * @throws \RuntimeException
114
-	 */
115
-	public function insert($file, array $data) {
116
-		return $this->getCache()->insert($this->getSourcePath($file), $data);
117
-	}
106
+    /**
107
+     * insert meta data for a new file or folder
108
+     *
109
+     * @param string $file
110
+     * @param array $data
111
+     *
112
+     * @return int file id
113
+     * @throws \RuntimeException
114
+     */
115
+    public function insert($file, array $data) {
116
+        return $this->getCache()->insert($this->getSourcePath($file), $data);
117
+    }
118 118
 
119
-	/**
120
-	 * update the metadata in the cache
121
-	 *
122
-	 * @param int $id
123
-	 * @param array $data
124
-	 */
125
-	public function update($id, array $data) {
126
-		$this->getCache()->update($id, $data);
127
-	}
119
+    /**
120
+     * update the metadata in the cache
121
+     *
122
+     * @param int $id
123
+     * @param array $data
124
+     */
125
+    public function update($id, array $data) {
126
+        $this->getCache()->update($id, $data);
127
+    }
128 128
 
129
-	/**
130
-	 * get the file id for a file
131
-	 *
132
-	 * @param string $file
133
-	 * @return int
134
-	 */
135
-	public function getId($file) {
136
-		return $this->getCache()->getId($this->getSourcePath($file));
137
-	}
129
+    /**
130
+     * get the file id for a file
131
+     *
132
+     * @param string $file
133
+     * @return int
134
+     */
135
+    public function getId($file) {
136
+        return $this->getCache()->getId($this->getSourcePath($file));
137
+    }
138 138
 
139
-	/**
140
-	 * get the id of the parent folder of a file
141
-	 *
142
-	 * @param string $file
143
-	 * @return int
144
-	 */
145
-	public function getParentId($file) {
146
-		return $this->getCache()->getParentId($this->getSourcePath($file));
147
-	}
139
+    /**
140
+     * get the id of the parent folder of a file
141
+     *
142
+     * @param string $file
143
+     * @return int
144
+     */
145
+    public function getParentId($file) {
146
+        return $this->getCache()->getParentId($this->getSourcePath($file));
147
+    }
148 148
 
149
-	/**
150
-	 * check if a file is available in the cache
151
-	 *
152
-	 * @param string $file
153
-	 * @return bool
154
-	 */
155
-	public function inCache($file) {
156
-		return $this->getCache()->inCache($this->getSourcePath($file));
157
-	}
149
+    /**
150
+     * check if a file is available in the cache
151
+     *
152
+     * @param string $file
153
+     * @return bool
154
+     */
155
+    public function inCache($file) {
156
+        return $this->getCache()->inCache($this->getSourcePath($file));
157
+    }
158 158
 
159
-	/**
160
-	 * remove a file or folder from the cache
161
-	 *
162
-	 * @param string $file
163
-	 */
164
-	public function remove($file) {
165
-		$this->getCache()->remove($this->getSourcePath($file));
166
-	}
159
+    /**
160
+     * remove a file or folder from the cache
161
+     *
162
+     * @param string $file
163
+     */
164
+    public function remove($file) {
165
+        $this->getCache()->remove($this->getSourcePath($file));
166
+    }
167 167
 
168
-	/**
169
-	 * Move a file or folder in the cache
170
-	 *
171
-	 * @param string $source
172
-	 * @param string $target
173
-	 */
174
-	public function move($source, $target) {
175
-		$this->getCache()->move($this->getSourcePath($source), $this->getSourcePath($target));
176
-	}
168
+    /**
169
+     * Move a file or folder in the cache
170
+     *
171
+     * @param string $source
172
+     * @param string $target
173
+     */
174
+    public function move($source, $target) {
175
+        $this->getCache()->move($this->getSourcePath($source), $this->getSourcePath($target));
176
+    }
177 177
 
178
-	/**
179
-	 * Get the storage id and path needed for a move
180
-	 *
181
-	 * @param string $path
182
-	 * @return array [$storageId, $internalPath]
183
-	 */
184
-	protected function getMoveInfo($path) {
185
-		return [$this->getNumericStorageId(), $this->getSourcePath($path)];
186
-	}
178
+    /**
179
+     * Get the storage id and path needed for a move
180
+     *
181
+     * @param string $path
182
+     * @return array [$storageId, $internalPath]
183
+     */
184
+    protected function getMoveInfo($path) {
185
+        return [$this->getNumericStorageId(), $this->getSourcePath($path)];
186
+    }
187 187
 
188
-	/**
189
-	 * remove all entries for files that are stored on the storage from the cache
190
-	 */
191
-	public function clear() {
192
-		$this->getCache()->remove($this->root);
193
-	}
188
+    /**
189
+     * remove all entries for files that are stored on the storage from the cache
190
+     */
191
+    public function clear() {
192
+        $this->getCache()->remove($this->root);
193
+    }
194 194
 
195
-	/**
196
-	 * @param string $file
197
-	 *
198
-	 * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
199
-	 */
200
-	public function getStatus($file) {
201
-		return $this->getCache()->getStatus($this->getSourcePath($file));
202
-	}
195
+    /**
196
+     * @param string $file
197
+     *
198
+     * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
199
+     */
200
+    public function getStatus($file) {
201
+        return $this->getCache()->getStatus($this->getSourcePath($file));
202
+    }
203 203
 
204
-	private function formatSearchResults($results) {
205
-		$results = array_filter($results, array($this, 'filterCacheEntry'));
206
-		$results = array_values($results);
207
-		return array_map(array($this, 'formatCacheEntry'), $results);
208
-	}
204
+    private function formatSearchResults($results) {
205
+        $results = array_filter($results, array($this, 'filterCacheEntry'));
206
+        $results = array_values($results);
207
+        return array_map(array($this, 'formatCacheEntry'), $results);
208
+    }
209 209
 
210
-	/**
211
-	 * search for files matching $pattern
212
-	 *
213
-	 * @param string $pattern
214
-	 * @return array an array of file data
215
-	 */
216
-	public function search($pattern) {
217
-		$results = $this->getCache()->search($pattern);
218
-		return $this->formatSearchResults($results);
219
-	}
210
+    /**
211
+     * search for files matching $pattern
212
+     *
213
+     * @param string $pattern
214
+     * @return array an array of file data
215
+     */
216
+    public function search($pattern) {
217
+        $results = $this->getCache()->search($pattern);
218
+        return $this->formatSearchResults($results);
219
+    }
220 220
 
221
-	/**
222
-	 * search for files by mimetype
223
-	 *
224
-	 * @param string $mimetype
225
-	 * @return array
226
-	 */
227
-	public function searchByMime($mimetype) {
228
-		$results = $this->getCache()->searchByMime($mimetype);
229
-		return $this->formatSearchResults($results);
230
-	}
221
+    /**
222
+     * search for files by mimetype
223
+     *
224
+     * @param string $mimetype
225
+     * @return array
226
+     */
227
+    public function searchByMime($mimetype) {
228
+        $results = $this->getCache()->searchByMime($mimetype);
229
+        return $this->formatSearchResults($results);
230
+    }
231 231
 
232
-	public function searchQuery(ISearchQuery $query) {
233
-		$results = $this->getCache()->searchQuery($query);
234
-		return $this->formatSearchResults($results);
235
-	}
232
+    public function searchQuery(ISearchQuery $query) {
233
+        $results = $this->getCache()->searchQuery($query);
234
+        return $this->formatSearchResults($results);
235
+    }
236 236
 
237
-	/**
238
-	 * search for files by mimetype
239
-	 *
240
-	 * @param string|int $tag name or tag id
241
-	 * @param string $userId owner of the tags
242
-	 * @return array
243
-	 */
244
-	public function searchByTag($tag, $userId) {
245
-		$results = $this->getCache()->searchByTag($tag, $userId);
246
-		return $this->formatSearchResults($results);
247
-	}
237
+    /**
238
+     * search for files by mimetype
239
+     *
240
+     * @param string|int $tag name or tag id
241
+     * @param string $userId owner of the tags
242
+     * @return array
243
+     */
244
+    public function searchByTag($tag, $userId) {
245
+        $results = $this->getCache()->searchByTag($tag, $userId);
246
+        return $this->formatSearchResults($results);
247
+    }
248 248
 
249
-	/**
250
-	 * update the folder size and the size of all parent folders
251
-	 *
252
-	 * @param string|boolean $path
253
-	 * @param array $data (optional) meta data of the folder
254
-	 */
255
-	public function correctFolderSize($path, $data = null) {
256
-		if ($this->getCache() instanceof Cache) {
257
-			$this->getCache()->correctFolderSize($this->getSourcePath($path), $data);
258
-		}
259
-	}
249
+    /**
250
+     * update the folder size and the size of all parent folders
251
+     *
252
+     * @param string|boolean $path
253
+     * @param array $data (optional) meta data of the folder
254
+     */
255
+    public function correctFolderSize($path, $data = null) {
256
+        if ($this->getCache() instanceof Cache) {
257
+            $this->getCache()->correctFolderSize($this->getSourcePath($path), $data);
258
+        }
259
+    }
260 260
 
261
-	/**
262
-	 * get the size of a folder and set it in the cache
263
-	 *
264
-	 * @param string $path
265
-	 * @param array $entry (optional) meta data of the folder
266
-	 * @return int
267
-	 */
268
-	public function calculateFolderSize($path, $entry = null) {
269
-		if ($this->getCache() instanceof Cache) {
270
-			return $this->getCache()->calculateFolderSize($this->getSourcePath($path), $entry);
271
-		} else {
272
-			return 0;
273
-		}
261
+    /**
262
+     * get the size of a folder and set it in the cache
263
+     *
264
+     * @param string $path
265
+     * @param array $entry (optional) meta data of the folder
266
+     * @return int
267
+     */
268
+    public function calculateFolderSize($path, $entry = null) {
269
+        if ($this->getCache() instanceof Cache) {
270
+            return $this->getCache()->calculateFolderSize($this->getSourcePath($path), $entry);
271
+        } else {
272
+            return 0;
273
+        }
274 274
 
275
-	}
275
+    }
276 276
 
277
-	/**
278
-	 * get all file ids on the files on the storage
279
-	 *
280
-	 * @return int[]
281
-	 */
282
-	public function getAll() {
283
-		// not supported
284
-		return array();
285
-	}
277
+    /**
278
+     * get all file ids on the files on the storage
279
+     *
280
+     * @return int[]
281
+     */
282
+    public function getAll() {
283
+        // not supported
284
+        return array();
285
+    }
286 286
 
287
-	/**
288
-	 * find a folder in the cache which has not been fully scanned
289
-	 *
290
-	 * If multiply incomplete folders are in the cache, the one with the highest id will be returned,
291
-	 * use the one with the highest id gives the best result with the background scanner, since that is most
292
-	 * likely the folder where we stopped scanning previously
293
-	 *
294
-	 * @return string|bool the path of the folder or false when no folder matched
295
-	 */
296
-	public function getIncomplete() {
297
-		// not supported
298
-		return false;
299
-	}
287
+    /**
288
+     * find a folder in the cache which has not been fully scanned
289
+     *
290
+     * If multiply incomplete folders are in the cache, the one with the highest id will be returned,
291
+     * use the one with the highest id gives the best result with the background scanner, since that is most
292
+     * likely the folder where we stopped scanning previously
293
+     *
294
+     * @return string|bool the path of the folder or false when no folder matched
295
+     */
296
+    public function getIncomplete() {
297
+        // not supported
298
+        return false;
299
+    }
300 300
 
301
-	/**
302
-	 * get the path of a file on this storage by it's id
303
-	 *
304
-	 * @param int $id
305
-	 * @return string|null
306
-	 */
307
-	public function getPathById($id) {
308
-		$path = $this->getCache()->getPathById($id);
309
-		return $this->getJailedPath($path);
310
-	}
301
+    /**
302
+     * get the path of a file on this storage by it's id
303
+     *
304
+     * @param int $id
305
+     * @return string|null
306
+     */
307
+    public function getPathById($id) {
308
+        $path = $this->getCache()->getPathById($id);
309
+        return $this->getJailedPath($path);
310
+    }
311 311
 
312
-	/**
313
-	 * Move a file or folder in the cache
314
-	 *
315
-	 * Note that this should make sure the entries are removed from the source cache
316
-	 *
317
-	 * @param \OCP\Files\Cache\ICache $sourceCache
318
-	 * @param string $sourcePath
319
-	 * @param string $targetPath
320
-	 */
321
-	public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
322
-		if ($sourceCache === $this) {
323
-			return $this->move($sourcePath, $targetPath);
324
-		}
325
-		return $this->getCache()->moveFromCache($sourceCache, $sourcePath, $this->getSourcePath($targetPath));
326
-	}
312
+    /**
313
+     * Move a file or folder in the cache
314
+     *
315
+     * Note that this should make sure the entries are removed from the source cache
316
+     *
317
+     * @param \OCP\Files\Cache\ICache $sourceCache
318
+     * @param string $sourcePath
319
+     * @param string $targetPath
320
+     */
321
+    public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
322
+        if ($sourceCache === $this) {
323
+            return $this->move($sourcePath, $targetPath);
324
+        }
325
+        return $this->getCache()->moveFromCache($sourceCache, $sourcePath, $this->getSourcePath($targetPath));
326
+    }
327 327
 }
Please login to merge, or discard this patch.
lib/private/Group/Manager.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -156,7 +156,7 @@
 block discarded – undo
156 156
 	/**
157 157
 	 * @param string $gid
158 158
 	 * @param string $displayName
159
-	 * @return \OCP\IGroup
159
+	 * @return null|Group
160 160
 	 */
161 161
 	protected function getGroupObject($gid, $displayName = null) {
162 162
 		$backends = array();
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -93,20 +93,20 @@  discard block
 block discarded – undo
93 93
 		$this->logger = $logger;
94 94
 		$cachedGroups = & $this->cachedGroups;
95 95
 		$cachedUserGroups = & $this->cachedUserGroups;
96
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
96
+		$this->listen('\OC\Group', 'postDelete', function($group) use (&$cachedGroups, &$cachedUserGroups) {
97 97
 			/**
98 98
 			 * @var \OC\Group\Group $group
99 99
 			 */
100 100
 			unset($cachedGroups[$group->getGID()]);
101 101
 			$cachedUserGroups = array();
102 102
 		});
103
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
103
+		$this->listen('\OC\Group', 'postAddUser', function($group) use (&$cachedUserGroups) {
104 104
 			/**
105 105
 			 * @var \OC\Group\Group $group
106 106
 			 */
107 107
 			$cachedUserGroups = array();
108 108
 		});
109
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
109
+		$this->listen('\OC\Group', 'postRemoveUser', function($group) use (&$cachedUserGroups) {
110 110
 			/**
111 111
 			 * @var \OC\Group\Group $group
112 112
 			 */
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
 				if ($aGroup instanceof IGroup) {
236 236
 					$groups[$groupId] = $aGroup;
237 237
 				} else {
238
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
238
+					$this->logger->debug('Group "'.$groupId.'" was returned by search but not found through direct access', ['app' => 'core']);
239 239
 				}
240 240
 			}
241 241
 			if (!is_null($limit) and $limit <= 0) {
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
 					if ($aGroup instanceof IGroup) {
274 274
 						$groups[$groupId] = $aGroup;
275 275
 					} else {
276
-						$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
276
+						$this->logger->debug('User "'.$uid.'" belongs to deleted group: "'.$groupId.'"', ['app' => 'core']);
277 277
 					}
278 278
 				}
279 279
 			}
@@ -322,32 +322,32 @@  discard block
 block discarded – undo
322 322
 	 */
323 323
 	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
324 324
 		$group = $this->get($gid);
325
-		if(is_null($group)) {
325
+		if (is_null($group)) {
326 326
 			return array();
327 327
 		}
328 328
 
329 329
 		$search = trim($search);
330 330
 		$groupUsers = array();
331 331
 
332
-		if(!empty($search)) {
332
+		if (!empty($search)) {
333 333
 			// only user backends have the capability to do a complex search for users
334 334
 			$searchOffset = 0;
335 335
 			$searchLimit = $limit * 100;
336
-			if($limit === -1) {
336
+			if ($limit === -1) {
337 337
 				$searchLimit = 500;
338 338
 			}
339 339
 
340 340
 			do {
341 341
 				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
342
-				foreach($filteredUsers as $filteredUser) {
343
-					if($group->inGroup($filteredUser)) {
344
-						$groupUsers[]= $filteredUser;
342
+				foreach ($filteredUsers as $filteredUser) {
343
+					if ($group->inGroup($filteredUser)) {
344
+						$groupUsers[] = $filteredUser;
345 345
 					}
346 346
 				}
347 347
 				$searchOffset += $searchLimit;
348
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
348
+			} while (count($groupUsers) < $searchLimit + $offset && count($filteredUsers) >= $searchLimit);
349 349
 
350
-			if($limit === -1) {
350
+			if ($limit === -1) {
351 351
 				$groupUsers = array_slice($groupUsers, $offset);
352 352
 			} else {
353 353
 				$groupUsers = array_slice($groupUsers, $offset, $limit);
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 		}
358 358
 
359 359
 		$matchingUsers = array();
360
-		foreach($groupUsers as $groupUser) {
360
+		foreach ($groupUsers as $groupUser) {
361 361
 			$matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
362 362
 		}
363 363
 		return $matchingUsers;
Please login to merge, or discard this patch.
Indentation   +318 added lines, -318 removed lines patch added patch discarded remove patch
@@ -58,323 +58,323 @@
 block discarded – undo
58 58
  * @package OC\Group
59 59
  */
60 60
 class Manager extends PublicEmitter implements IGroupManager {
61
-	/**
62
-	 * @var GroupInterface[] $backends
63
-	 */
64
-	private $backends = array();
65
-
66
-	/**
67
-	 * @var \OC\User\Manager $userManager
68
-	 */
69
-	private $userManager;
70
-
71
-	/**
72
-	 * @var \OC\Group\Group[]
73
-	 */
74
-	private $cachedGroups = array();
75
-
76
-	/**
77
-	 * @var \OC\Group\Group[][]
78
-	 */
79
-	private $cachedUserGroups = array();
80
-
81
-	/** @var \OC\SubAdmin */
82
-	private $subAdmin = null;
83
-
84
-	/** @var ILogger */
85
-	private $logger;
86
-
87
-	/**
88
-	 * @param \OC\User\Manager $userManager
89
-	 * @param ILogger $logger
90
-	 */
91
-	public function __construct(\OC\User\Manager $userManager, ILogger $logger) {
92
-		$this->userManager = $userManager;
93
-		$this->logger = $logger;
94
-		$cachedGroups = & $this->cachedGroups;
95
-		$cachedUserGroups = & $this->cachedUserGroups;
96
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
97
-			/**
98
-			 * @var \OC\Group\Group $group
99
-			 */
100
-			unset($cachedGroups[$group->getGID()]);
101
-			$cachedUserGroups = array();
102
-		});
103
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
104
-			/**
105
-			 * @var \OC\Group\Group $group
106
-			 */
107
-			$cachedUserGroups = array();
108
-		});
109
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
110
-			/**
111
-			 * @var \OC\Group\Group $group
112
-			 */
113
-			$cachedUserGroups = array();
114
-		});
115
-	}
116
-
117
-	/**
118
-	 * Checks whether a given backend is used
119
-	 *
120
-	 * @param string $backendClass Full classname including complete namespace
121
-	 * @return bool
122
-	 */
123
-	public function isBackendUsed($backendClass) {
124
-		$backendClass = strtolower(ltrim($backendClass, '\\'));
125
-
126
-		foreach ($this->backends as $backend) {
127
-			if (strtolower(get_class($backend)) === $backendClass) {
128
-				return true;
129
-			}
130
-		}
131
-
132
-		return false;
133
-	}
134
-
135
-	/**
136
-	 * @param \OCP\GroupInterface $backend
137
-	 */
138
-	public function addBackend($backend) {
139
-		$this->backends[] = $backend;
140
-		$this->clearCaches();
141
-	}
142
-
143
-	public function clearBackends() {
144
-		$this->backends = array();
145
-		$this->clearCaches();
146
-	}
61
+    /**
62
+     * @var GroupInterface[] $backends
63
+     */
64
+    private $backends = array();
65
+
66
+    /**
67
+     * @var \OC\User\Manager $userManager
68
+     */
69
+    private $userManager;
70
+
71
+    /**
72
+     * @var \OC\Group\Group[]
73
+     */
74
+    private $cachedGroups = array();
75
+
76
+    /**
77
+     * @var \OC\Group\Group[][]
78
+     */
79
+    private $cachedUserGroups = array();
80
+
81
+    /** @var \OC\SubAdmin */
82
+    private $subAdmin = null;
83
+
84
+    /** @var ILogger */
85
+    private $logger;
86
+
87
+    /**
88
+     * @param \OC\User\Manager $userManager
89
+     * @param ILogger $logger
90
+     */
91
+    public function __construct(\OC\User\Manager $userManager, ILogger $logger) {
92
+        $this->userManager = $userManager;
93
+        $this->logger = $logger;
94
+        $cachedGroups = & $this->cachedGroups;
95
+        $cachedUserGroups = & $this->cachedUserGroups;
96
+        $this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
97
+            /**
98
+             * @var \OC\Group\Group $group
99
+             */
100
+            unset($cachedGroups[$group->getGID()]);
101
+            $cachedUserGroups = array();
102
+        });
103
+        $this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
104
+            /**
105
+             * @var \OC\Group\Group $group
106
+             */
107
+            $cachedUserGroups = array();
108
+        });
109
+        $this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
110
+            /**
111
+             * @var \OC\Group\Group $group
112
+             */
113
+            $cachedUserGroups = array();
114
+        });
115
+    }
116
+
117
+    /**
118
+     * Checks whether a given backend is used
119
+     *
120
+     * @param string $backendClass Full classname including complete namespace
121
+     * @return bool
122
+     */
123
+    public function isBackendUsed($backendClass) {
124
+        $backendClass = strtolower(ltrim($backendClass, '\\'));
125
+
126
+        foreach ($this->backends as $backend) {
127
+            if (strtolower(get_class($backend)) === $backendClass) {
128
+                return true;
129
+            }
130
+        }
131
+
132
+        return false;
133
+    }
134
+
135
+    /**
136
+     * @param \OCP\GroupInterface $backend
137
+     */
138
+    public function addBackend($backend) {
139
+        $this->backends[] = $backend;
140
+        $this->clearCaches();
141
+    }
142
+
143
+    public function clearBackends() {
144
+        $this->backends = array();
145
+        $this->clearCaches();
146
+    }
147 147
 	
148
-	protected function clearCaches() {
149
-		$this->cachedGroups = array();
150
-		$this->cachedUserGroups = array();
151
-	}
152
-
153
-	/**
154
-	 * @param string $gid
155
-	 * @return \OC\Group\Group
156
-	 */
157
-	public function get($gid) {
158
-		if (isset($this->cachedGroups[$gid])) {
159
-			return $this->cachedGroups[$gid];
160
-		}
161
-		return $this->getGroupObject($gid);
162
-	}
163
-
164
-	/**
165
-	 * @param string $gid
166
-	 * @param string $displayName
167
-	 * @return \OCP\IGroup
168
-	 */
169
-	protected function getGroupObject($gid, $displayName = null) {
170
-		$backends = array();
171
-		foreach ($this->backends as $backend) {
172
-			if ($backend->implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
173
-				$groupData = $backend->getGroupDetails($gid);
174
-				if (is_array($groupData)) {
175
-					// take the display name from the first backend that has a non-null one
176
-					if (is_null($displayName) && isset($groupData['displayName'])) {
177
-						$displayName = $groupData['displayName'];
178
-					}
179
-					$backends[] = $backend;
180
-				}
181
-			} else if ($backend->groupExists($gid)) {
182
-				$backends[] = $backend;
183
-			}
184
-		}
185
-		if (count($backends) === 0) {
186
-			return null;
187
-		}
188
-		$this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this, $displayName);
189
-		return $this->cachedGroups[$gid];
190
-	}
191
-
192
-	/**
193
-	 * @param string $gid
194
-	 * @return bool
195
-	 */
196
-	public function groupExists($gid) {
197
-		return $this->get($gid) instanceof IGroup;
198
-	}
199
-
200
-	/**
201
-	 * @param string $gid
202
-	 * @return \OC\Group\Group
203
-	 */
204
-	public function createGroup($gid) {
205
-		if ($gid === '' || $gid === null) {
206
-			return false;
207
-		} else if ($group = $this->get($gid)) {
208
-			return $group;
209
-		} else {
210
-			$this->emit('\OC\Group', 'preCreate', array($gid));
211
-			foreach ($this->backends as $backend) {
212
-				if ($backend->implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
213
-					$backend->createGroup($gid);
214
-					$group = $this->getGroupObject($gid);
215
-					$this->emit('\OC\Group', 'postCreate', array($group));
216
-					return $group;
217
-				}
218
-			}
219
-			return null;
220
-		}
221
-	}
222
-
223
-	/**
224
-	 * @param string $search
225
-	 * @param int $limit
226
-	 * @param int $offset
227
-	 * @return \OC\Group\Group[]
228
-	 */
229
-	public function search($search, $limit = null, $offset = null) {
230
-		$groups = array();
231
-		foreach ($this->backends as $backend) {
232
-			$groupIds = $backend->getGroups($search, $limit, $offset);
233
-			foreach ($groupIds as $groupId) {
234
-				$aGroup = $this->get($groupId);
235
-				if ($aGroup instanceof IGroup) {
236
-					$groups[$groupId] = $aGroup;
237
-				} else {
238
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
239
-				}
240
-			}
241
-			if (!is_null($limit) and $limit <= 0) {
242
-				return array_values($groups);
243
-			}
244
-		}
245
-		return array_values($groups);
246
-	}
247
-
248
-	/**
249
-	 * @param \OC\User\User|null $user
250
-	 * @return \OC\Group\Group[]
251
-	 */
252
-	public function getUserGroups($user) {
253
-		if (!$user instanceof IUser) {
254
-			return [];
255
-		}
256
-		return $this->getUserIdGroups($user->getUID());
257
-	}
258
-
259
-	/**
260
-	 * @param string $uid the user id
261
-	 * @return \OC\Group\Group[]
262
-	 */
263
-	public function getUserIdGroups($uid) {
264
-		if (isset($this->cachedUserGroups[$uid])) {
265
-			return $this->cachedUserGroups[$uid];
266
-		}
267
-		$groups = array();
268
-		foreach ($this->backends as $backend) {
269
-			$groupIds = $backend->getUserGroups($uid);
270
-			if (is_array($groupIds)) {
271
-				foreach ($groupIds as $groupId) {
272
-					$aGroup = $this->get($groupId);
273
-					if ($aGroup instanceof IGroup) {
274
-						$groups[$groupId] = $aGroup;
275
-					} else {
276
-						$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
277
-					}
278
-				}
279
-			}
280
-		}
281
-		$this->cachedUserGroups[$uid] = $groups;
282
-		return $this->cachedUserGroups[$uid];
283
-	}
284
-
285
-	/**
286
-	 * Checks if a userId is in the admin group
287
-	 * @param string $userId
288
-	 * @return bool if admin
289
-	 */
290
-	public function isAdmin($userId) {
291
-		return $this->isInGroup($userId, 'admin');
292
-	}
293
-
294
-	/**
295
-	 * Checks if a userId is in a group
296
-	 * @param string $userId
297
-	 * @param string $group
298
-	 * @return bool if in group
299
-	 */
300
-	public function isInGroup($userId, $group) {
301
-		return array_key_exists($group, $this->getUserIdGroups($userId));
302
-	}
303
-
304
-	/**
305
-	 * get a list of group ids for a user
306
-	 * @param \OC\User\User $user
307
-	 * @return array with group ids
308
-	 */
309
-	public function getUserGroupIds($user) {
310
-		return array_map(function($value) {
311
-			return (string) $value;
312
-		}, array_keys($this->getUserGroups($user)));
313
-	}
314
-
315
-	/**
316
-	 * get a list of all display names in a group
317
-	 * @param string $gid
318
-	 * @param string $search
319
-	 * @param int $limit
320
-	 * @param int $offset
321
-	 * @return array an array of display names (value) and user ids (key)
322
-	 */
323
-	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
324
-		$group = $this->get($gid);
325
-		if(is_null($group)) {
326
-			return array();
327
-		}
328
-
329
-		$search = trim($search);
330
-		$groupUsers = array();
331
-
332
-		if(!empty($search)) {
333
-			// only user backends have the capability to do a complex search for users
334
-			$searchOffset = 0;
335
-			$searchLimit = $limit * 100;
336
-			if($limit === -1) {
337
-				$searchLimit = 500;
338
-			}
339
-
340
-			do {
341
-				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
342
-				foreach($filteredUsers as $filteredUser) {
343
-					if($group->inGroup($filteredUser)) {
344
-						$groupUsers[]= $filteredUser;
345
-					}
346
-				}
347
-				$searchOffset += $searchLimit;
348
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
349
-
350
-			if($limit === -1) {
351
-				$groupUsers = array_slice($groupUsers, $offset);
352
-			} else {
353
-				$groupUsers = array_slice($groupUsers, $offset, $limit);
354
-			}
355
-		} else {
356
-			$groupUsers = $group->searchUsers('', $limit, $offset);
357
-		}
358
-
359
-		$matchingUsers = array();
360
-		foreach($groupUsers as $groupUser) {
361
-			$matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
362
-		}
363
-		return $matchingUsers;
364
-	}
365
-
366
-	/**
367
-	 * @return \OC\SubAdmin
368
-	 */
369
-	public function getSubAdmin() {
370
-		if (!$this->subAdmin) {
371
-			$this->subAdmin = new \OC\SubAdmin(
372
-				$this->userManager,
373
-				$this,
374
-				\OC::$server->getDatabaseConnection()
375
-			);
376
-		}
377
-
378
-		return $this->subAdmin;
379
-	}
148
+    protected function clearCaches() {
149
+        $this->cachedGroups = array();
150
+        $this->cachedUserGroups = array();
151
+    }
152
+
153
+    /**
154
+     * @param string $gid
155
+     * @return \OC\Group\Group
156
+     */
157
+    public function get($gid) {
158
+        if (isset($this->cachedGroups[$gid])) {
159
+            return $this->cachedGroups[$gid];
160
+        }
161
+        return $this->getGroupObject($gid);
162
+    }
163
+
164
+    /**
165
+     * @param string $gid
166
+     * @param string $displayName
167
+     * @return \OCP\IGroup
168
+     */
169
+    protected function getGroupObject($gid, $displayName = null) {
170
+        $backends = array();
171
+        foreach ($this->backends as $backend) {
172
+            if ($backend->implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
173
+                $groupData = $backend->getGroupDetails($gid);
174
+                if (is_array($groupData)) {
175
+                    // take the display name from the first backend that has a non-null one
176
+                    if (is_null($displayName) && isset($groupData['displayName'])) {
177
+                        $displayName = $groupData['displayName'];
178
+                    }
179
+                    $backends[] = $backend;
180
+                }
181
+            } else if ($backend->groupExists($gid)) {
182
+                $backends[] = $backend;
183
+            }
184
+        }
185
+        if (count($backends) === 0) {
186
+            return null;
187
+        }
188
+        $this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this, $displayName);
189
+        return $this->cachedGroups[$gid];
190
+    }
191
+
192
+    /**
193
+     * @param string $gid
194
+     * @return bool
195
+     */
196
+    public function groupExists($gid) {
197
+        return $this->get($gid) instanceof IGroup;
198
+    }
199
+
200
+    /**
201
+     * @param string $gid
202
+     * @return \OC\Group\Group
203
+     */
204
+    public function createGroup($gid) {
205
+        if ($gid === '' || $gid === null) {
206
+            return false;
207
+        } else if ($group = $this->get($gid)) {
208
+            return $group;
209
+        } else {
210
+            $this->emit('\OC\Group', 'preCreate', array($gid));
211
+            foreach ($this->backends as $backend) {
212
+                if ($backend->implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
213
+                    $backend->createGroup($gid);
214
+                    $group = $this->getGroupObject($gid);
215
+                    $this->emit('\OC\Group', 'postCreate', array($group));
216
+                    return $group;
217
+                }
218
+            }
219
+            return null;
220
+        }
221
+    }
222
+
223
+    /**
224
+     * @param string $search
225
+     * @param int $limit
226
+     * @param int $offset
227
+     * @return \OC\Group\Group[]
228
+     */
229
+    public function search($search, $limit = null, $offset = null) {
230
+        $groups = array();
231
+        foreach ($this->backends as $backend) {
232
+            $groupIds = $backend->getGroups($search, $limit, $offset);
233
+            foreach ($groupIds as $groupId) {
234
+                $aGroup = $this->get($groupId);
235
+                if ($aGroup instanceof IGroup) {
236
+                    $groups[$groupId] = $aGroup;
237
+                } else {
238
+                    $this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
239
+                }
240
+            }
241
+            if (!is_null($limit) and $limit <= 0) {
242
+                return array_values($groups);
243
+            }
244
+        }
245
+        return array_values($groups);
246
+    }
247
+
248
+    /**
249
+     * @param \OC\User\User|null $user
250
+     * @return \OC\Group\Group[]
251
+     */
252
+    public function getUserGroups($user) {
253
+        if (!$user instanceof IUser) {
254
+            return [];
255
+        }
256
+        return $this->getUserIdGroups($user->getUID());
257
+    }
258
+
259
+    /**
260
+     * @param string $uid the user id
261
+     * @return \OC\Group\Group[]
262
+     */
263
+    public function getUserIdGroups($uid) {
264
+        if (isset($this->cachedUserGroups[$uid])) {
265
+            return $this->cachedUserGroups[$uid];
266
+        }
267
+        $groups = array();
268
+        foreach ($this->backends as $backend) {
269
+            $groupIds = $backend->getUserGroups($uid);
270
+            if (is_array($groupIds)) {
271
+                foreach ($groupIds as $groupId) {
272
+                    $aGroup = $this->get($groupId);
273
+                    if ($aGroup instanceof IGroup) {
274
+                        $groups[$groupId] = $aGroup;
275
+                    } else {
276
+                        $this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
277
+                    }
278
+                }
279
+            }
280
+        }
281
+        $this->cachedUserGroups[$uid] = $groups;
282
+        return $this->cachedUserGroups[$uid];
283
+    }
284
+
285
+    /**
286
+     * Checks if a userId is in the admin group
287
+     * @param string $userId
288
+     * @return bool if admin
289
+     */
290
+    public function isAdmin($userId) {
291
+        return $this->isInGroup($userId, 'admin');
292
+    }
293
+
294
+    /**
295
+     * Checks if a userId is in a group
296
+     * @param string $userId
297
+     * @param string $group
298
+     * @return bool if in group
299
+     */
300
+    public function isInGroup($userId, $group) {
301
+        return array_key_exists($group, $this->getUserIdGroups($userId));
302
+    }
303
+
304
+    /**
305
+     * get a list of group ids for a user
306
+     * @param \OC\User\User $user
307
+     * @return array with group ids
308
+     */
309
+    public function getUserGroupIds($user) {
310
+        return array_map(function($value) {
311
+            return (string) $value;
312
+        }, array_keys($this->getUserGroups($user)));
313
+    }
314
+
315
+    /**
316
+     * get a list of all display names in a group
317
+     * @param string $gid
318
+     * @param string $search
319
+     * @param int $limit
320
+     * @param int $offset
321
+     * @return array an array of display names (value) and user ids (key)
322
+     */
323
+    public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
324
+        $group = $this->get($gid);
325
+        if(is_null($group)) {
326
+            return array();
327
+        }
328
+
329
+        $search = trim($search);
330
+        $groupUsers = array();
331
+
332
+        if(!empty($search)) {
333
+            // only user backends have the capability to do a complex search for users
334
+            $searchOffset = 0;
335
+            $searchLimit = $limit * 100;
336
+            if($limit === -1) {
337
+                $searchLimit = 500;
338
+            }
339
+
340
+            do {
341
+                $filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
342
+                foreach($filteredUsers as $filteredUser) {
343
+                    if($group->inGroup($filteredUser)) {
344
+                        $groupUsers[]= $filteredUser;
345
+                    }
346
+                }
347
+                $searchOffset += $searchLimit;
348
+            } while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
349
+
350
+            if($limit === -1) {
351
+                $groupUsers = array_slice($groupUsers, $offset);
352
+            } else {
353
+                $groupUsers = array_slice($groupUsers, $offset, $limit);
354
+            }
355
+        } else {
356
+            $groupUsers = $group->searchUsers('', $limit, $offset);
357
+        }
358
+
359
+        $matchingUsers = array();
360
+        foreach($groupUsers as $groupUser) {
361
+            $matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
362
+        }
363
+        return $matchingUsers;
364
+    }
365
+
366
+    /**
367
+     * @return \OC\SubAdmin
368
+     */
369
+    public function getSubAdmin() {
370
+        if (!$this->subAdmin) {
371
+            $this->subAdmin = new \OC\SubAdmin(
372
+                $this->userManager,
373
+                $this,
374
+                \OC::$server->getDatabaseConnection()
375
+            );
376
+        }
377
+
378
+        return $this->subAdmin;
379
+    }
380 380
 }
Please login to merge, or discard this patch.
lib/private/Memcache/APCu.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@
 block discarded – undo
65 65
 	 * Set a value in the cache if it's not already stored
66 66
 	 *
67 67
 	 * @param string $key
68
-	 * @param mixed $value
68
+	 * @param integer $value
69 69
 	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
70 70
 	 * @return bool
71 71
 	 */
Please login to merge, or discard this patch.
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -30,140 +30,140 @@
 block discarded – undo
30 30
 use OCP\IMemcache;
31 31
 
32 32
 class APCu extends Cache implements IMemcache {
33
-	use CASTrait {
34
-		cas as casEmulated;
35
-	}
33
+    use CASTrait {
34
+        cas as casEmulated;
35
+    }
36 36
 
37
-	use CADTrait;
37
+    use CADTrait;
38 38
 
39
-	public function get($key) {
40
-		$result = apcu_fetch($this->getPrefix() . $key, $success);
41
-		if (!$success) {
42
-			return null;
43
-		}
44
-		return $result;
45
-	}
39
+    public function get($key) {
40
+        $result = apcu_fetch($this->getPrefix() . $key, $success);
41
+        if (!$success) {
42
+            return null;
43
+        }
44
+        return $result;
45
+    }
46 46
 
47
-	public function set($key, $value, $ttl = 0) {
48
-		return apcu_store($this->getPrefix() . $key, $value, $ttl);
49
-	}
47
+    public function set($key, $value, $ttl = 0) {
48
+        return apcu_store($this->getPrefix() . $key, $value, $ttl);
49
+    }
50 50
 
51
-	public function hasKey($key) {
52
-		return apcu_exists($this->getPrefix() . $key);
53
-	}
51
+    public function hasKey($key) {
52
+        return apcu_exists($this->getPrefix() . $key);
53
+    }
54 54
 
55
-	public function remove($key) {
56
-		return apcu_delete($this->getPrefix() . $key);
57
-	}
55
+    public function remove($key) {
56
+        return apcu_delete($this->getPrefix() . $key);
57
+    }
58 58
 
59
-	public function clear($prefix = '') {
60
-		$ns = $this->getPrefix() . $prefix;
61
-		$ns = preg_quote($ns, '/');
62
-		if(class_exists('\APCIterator')) {
63
-			$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
64
-		} else {
65
-			$iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
66
-		}
67
-		return apcu_delete($iter);
68
-	}
59
+    public function clear($prefix = '') {
60
+        $ns = $this->getPrefix() . $prefix;
61
+        $ns = preg_quote($ns, '/');
62
+        if(class_exists('\APCIterator')) {
63
+            $iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
64
+        } else {
65
+            $iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
66
+        }
67
+        return apcu_delete($iter);
68
+    }
69 69
 
70
-	/**
71
-	 * Set a value in the cache if it's not already stored
72
-	 *
73
-	 * @param string $key
74
-	 * @param mixed $value
75
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
76
-	 * @return bool
77
-	 */
78
-	public function add($key, $value, $ttl = 0) {
79
-		return apcu_add($this->getPrefix() . $key, $value, $ttl);
80
-	}
70
+    /**
71
+     * Set a value in the cache if it's not already stored
72
+     *
73
+     * @param string $key
74
+     * @param mixed $value
75
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
76
+     * @return bool
77
+     */
78
+    public function add($key, $value, $ttl = 0) {
79
+        return apcu_add($this->getPrefix() . $key, $value, $ttl);
80
+    }
81 81
 
82
-	/**
83
-	 * Increase a stored number
84
-	 *
85
-	 * @param string $key
86
-	 * @param int $step
87
-	 * @return int | bool
88
-	 */
89
-	public function inc($key, $step = 1) {
90
-		$this->add($key, 0);
91
-		/**
92
-		 * TODO - hack around a PHP 7 specific issue in APCu
93
-		 *
94
-		 * on PHP 7 the apcu_inc method on a non-existing object will increment
95
-		 * "0" and result in "1" as value - therefore we check for existence
96
-		 * first
97
-		 *
98
-		 * on PHP 5.6 this is not the case
99
-		 *
100
-		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101
-		 * for details
102
-		 */
103
-		return apcu_exists($this->getPrefix() . $key)
104
-			? apcu_inc($this->getPrefix() . $key, $step)
105
-			: false;
106
-	}
82
+    /**
83
+     * Increase a stored number
84
+     *
85
+     * @param string $key
86
+     * @param int $step
87
+     * @return int | bool
88
+     */
89
+    public function inc($key, $step = 1) {
90
+        $this->add($key, 0);
91
+        /**
92
+         * TODO - hack around a PHP 7 specific issue in APCu
93
+         *
94
+         * on PHP 7 the apcu_inc method on a non-existing object will increment
95
+         * "0" and result in "1" as value - therefore we check for existence
96
+         * first
97
+         *
98
+         * on PHP 5.6 this is not the case
99
+         *
100
+         * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101
+         * for details
102
+         */
103
+        return apcu_exists($this->getPrefix() . $key)
104
+            ? apcu_inc($this->getPrefix() . $key, $step)
105
+            : false;
106
+    }
107 107
 
108
-	/**
109
-	 * Decrease a stored number
110
-	 *
111
-	 * @param string $key
112
-	 * @param int $step
113
-	 * @return int | bool
114
-	 */
115
-	public function dec($key, $step = 1) {
116
-		/**
117
-		 * TODO - hack around a PHP 7 specific issue in APCu
118
-		 *
119
-		 * on PHP 7 the apcu_dec method on a non-existing object will decrement
120
-		 * "0" and result in "-1" as value - therefore we check for existence
121
-		 * first
122
-		 *
123
-		 * on PHP 5.6 this is not the case
124
-		 *
125
-		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126
-		 * for details
127
-		 */
128
-		return apcu_exists($this->getPrefix() . $key)
129
-			? apcu_dec($this->getPrefix() . $key, $step)
130
-			: false;
131
-	}
108
+    /**
109
+     * Decrease a stored number
110
+     *
111
+     * @param string $key
112
+     * @param int $step
113
+     * @return int | bool
114
+     */
115
+    public function dec($key, $step = 1) {
116
+        /**
117
+         * TODO - hack around a PHP 7 specific issue in APCu
118
+         *
119
+         * on PHP 7 the apcu_dec method on a non-existing object will decrement
120
+         * "0" and result in "-1" as value - therefore we check for existence
121
+         * first
122
+         *
123
+         * on PHP 5.6 this is not the case
124
+         *
125
+         * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126
+         * for details
127
+         */
128
+        return apcu_exists($this->getPrefix() . $key)
129
+            ? apcu_dec($this->getPrefix() . $key, $step)
130
+            : false;
131
+    }
132 132
 
133
-	/**
134
-	 * Compare and set
135
-	 *
136
-	 * @param string $key
137
-	 * @param mixed $old
138
-	 * @param mixed $new
139
-	 * @return bool
140
-	 */
141
-	public function cas($key, $old, $new) {
142
-		// apc only does cas for ints
143
-		if (is_int($old) and is_int($new)) {
144
-			return apcu_cas($this->getPrefix() . $key, $old, $new);
145
-		} else {
146
-			return $this->casEmulated($key, $old, $new);
147
-		}
148
-	}
133
+    /**
134
+     * Compare and set
135
+     *
136
+     * @param string $key
137
+     * @param mixed $old
138
+     * @param mixed $new
139
+     * @return bool
140
+     */
141
+    public function cas($key, $old, $new) {
142
+        // apc only does cas for ints
143
+        if (is_int($old) and is_int($new)) {
144
+            return apcu_cas($this->getPrefix() . $key, $old, $new);
145
+        } else {
146
+            return $this->casEmulated($key, $old, $new);
147
+        }
148
+    }
149 149
 
150
-	/**
151
-	 * @return bool
152
-	 */
153
-	static public function isAvailable() {
154
-		if (!extension_loaded('apcu')) {
155
-			return false;
156
-		} elseif (!\OC::$server->getIniWrapper()->getBool('apc.enabled')) {
157
-			return false;
158
-		} elseif (!\OC::$server->getIniWrapper()->getBool('apc.enable_cli') && \OC::$CLI) {
159
-			return false;
160
-		} elseif (
161
-				version_compare(phpversion('apc'), '4.0.6') === -1 &&
162
-				version_compare(phpversion('apcu'), '5.1.0') === -1
163
-		) {
164
-			return false;
165
-		} else {
166
-			return true;
167
-		}
168
-	}
150
+    /**
151
+     * @return bool
152
+     */
153
+    static public function isAvailable() {
154
+        if (!extension_loaded('apcu')) {
155
+            return false;
156
+        } elseif (!\OC::$server->getIniWrapper()->getBool('apc.enabled')) {
157
+            return false;
158
+        } elseif (!\OC::$server->getIniWrapper()->getBool('apc.enable_cli') && \OC::$CLI) {
159
+            return false;
160
+        } elseif (
161
+                version_compare(phpversion('apc'), '4.0.6') === -1 &&
162
+                version_compare(phpversion('apcu'), '5.1.0') === -1
163
+        ) {
164
+            return false;
165
+        } else {
166
+            return true;
167
+        }
168
+    }
169 169
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
 	use CADTrait;
38 38
 
39 39
 	public function get($key) {
40
-		$result = apcu_fetch($this->getPrefix() . $key, $success);
40
+		$result = apcu_fetch($this->getPrefix().$key, $success);
41 41
 		if (!$success) {
42 42
 			return null;
43 43
 		}
@@ -45,24 +45,24 @@  discard block
 block discarded – undo
45 45
 	}
46 46
 
47 47
 	public function set($key, $value, $ttl = 0) {
48
-		return apcu_store($this->getPrefix() . $key, $value, $ttl);
48
+		return apcu_store($this->getPrefix().$key, $value, $ttl);
49 49
 	}
50 50
 
51 51
 	public function hasKey($key) {
52
-		return apcu_exists($this->getPrefix() . $key);
52
+		return apcu_exists($this->getPrefix().$key);
53 53
 	}
54 54
 
55 55
 	public function remove($key) {
56
-		return apcu_delete($this->getPrefix() . $key);
56
+		return apcu_delete($this->getPrefix().$key);
57 57
 	}
58 58
 
59 59
 	public function clear($prefix = '') {
60
-		$ns = $this->getPrefix() . $prefix;
60
+		$ns = $this->getPrefix().$prefix;
61 61
 		$ns = preg_quote($ns, '/');
62
-		if(class_exists('\APCIterator')) {
63
-			$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
62
+		if (class_exists('\APCIterator')) {
63
+			$iter = new \APCIterator('user', '/^'.$ns.'/', APC_ITER_KEY);
64 64
 		} else {
65
-			$iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
65
+			$iter = new \APCUIterator('/^'.$ns.'/', APC_ITER_KEY);
66 66
 		}
67 67
 		return apcu_delete($iter);
68 68
 	}
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	 * @return bool
77 77
 	 */
78 78
 	public function add($key, $value, $ttl = 0) {
79
-		return apcu_add($this->getPrefix() . $key, $value, $ttl);
79
+		return apcu_add($this->getPrefix().$key, $value, $ttl);
80 80
 	}
81 81
 
82 82
 	/**
@@ -100,8 +100,8 @@  discard block
 block discarded – undo
100 100
 		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101 101
 		 * for details
102 102
 		 */
103
-		return apcu_exists($this->getPrefix() . $key)
104
-			? apcu_inc($this->getPrefix() . $key, $step)
103
+		return apcu_exists($this->getPrefix().$key)
104
+			? apcu_inc($this->getPrefix().$key, $step)
105 105
 			: false;
106 106
 	}
107 107
 
@@ -125,8 +125,8 @@  discard block
 block discarded – undo
125 125
 		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126 126
 		 * for details
127 127
 		 */
128
-		return apcu_exists($this->getPrefix() . $key)
129
-			? apcu_dec($this->getPrefix() . $key, $step)
128
+		return apcu_exists($this->getPrefix().$key)
129
+			? apcu_dec($this->getPrefix().$key, $step)
130 130
 			: false;
131 131
 	}
132 132
 
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 	public function cas($key, $old, $new) {
142 142
 		// apc only does cas for ints
143 143
 		if (is_int($old) and is_int($new)) {
144
-			return apcu_cas($this->getPrefix() . $key, $old, $new);
144
+			return apcu_cas($this->getPrefix().$key, $old, $new);
145 145
 		} else {
146 146
 			return $this->casEmulated($key, $old, $new);
147 147
 		}
Please login to merge, or discard this patch.