Completed
Pull Request — master (#7115)
by Björn
14:02
created
lib/private/Tags.php 3 patches
Doc Comments   +10 added lines, -2 removed lines patch added patch discarded remove patch
@@ -742,11 +742,19 @@  discard block
 block discarded – undo
742 742
 	}
743 743
 
744 744
 	// case-insensitive array_search
745
+
746
+	/**
747
+	 * @param string $needle
748
+	 */
745 749
 	protected function array_searchi($needle, $haystack, $mem='getName') {
746 750
 		if(!is_array($haystack)) {
747 751
 			return false;
748 752
 		}
749 753
 		return array_search(strtolower($needle), array_map(
754
+
755
+			/**
756
+			 * @param string $tag
757
+			 */
750 758
 			function($tag) use($mem) {
751 759
 				return strtolower(call_user_func(array($tag, $mem)));
752 760
 			}, $haystack)
@@ -771,7 +779,7 @@  discard block
 block discarded – undo
771 779
 	* Get a tag by its name.
772 780
 	*
773 781
 	* @param string $name The tag name.
774
-	* @return integer|bool The tag object's offset within the $this->tags
782
+	* @return \OCP\AppFramework\Db\Entity The tag object's offset within the $this->tags
775 783
 	*                      array or false if it doesn't exist.
776 784
 	*/
777 785
 	private function getTagByName($name) {
@@ -782,7 +790,7 @@  discard block
 block discarded – undo
782 790
 	* Get a tag by its ID.
783 791
 	*
784 792
 	* @param string $id The tag ID to look for.
785
-	* @return integer|bool The tag object's offset within the $this->tags
793
+	* @return \OCP\AppFramework\Db\Entity The tag object's offset within the $this->tags
786 794
 	*                      array or false if it doesn't exist.
787 795
 	*/
788 796
 	private function getTagById($id) {
Please login to merge, or discard this patch.
Spacing   +85 added lines, -85 removed lines patch added patch discarded remove patch
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 		}
133 133
 		$this->tags = $this->mapper->loadTags($this->owners, $this->type);
134 134
 
135
-		if(count($defaultTags) > 0 && count($this->tags) === 0) {
135
+		if (count($defaultTags) > 0 && count($this->tags) === 0) {
136 136
 			$this->addMultiple($defaultTags, true);
137 137
 		}
138 138
 	}
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 	* @return array
174 174
 	*/
175 175
 	public function getTags() {
176
-		if(!count($this->tags)) {
176
+		if (!count($this->tags)) {
177 177
 			return array();
178 178
 		}
179 179
 
@@ -182,8 +182,8 @@  discard block
 block discarded – undo
182 182
 		});
183 183
 		$tagMap = array();
184 184
 
185
-		foreach($this->tags as $tag) {
186
-			if($tag->getName() !== self::TAG_FAVORITE) {
185
+		foreach ($this->tags as $tag) {
186
+			if ($tag->getName() !== self::TAG_FAVORITE) {
187 187
 				$tagMap[] = $this->tagMap($tag);
188 188
 			}
189 189
 		}
@@ -221,25 +221,25 @@  discard block
 block discarded – undo
221 221
 			$chunks = array_chunk($objIds, 900, false);
222 222
 			foreach ($chunks as $chunk) {
223 223
 				$result = $conn->executeQuery(
224
-					'SELECT `category`, `categoryid`, `objid` ' .
225
-					'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
224
+					'SELECT `category`, `categoryid`, `objid` '.
225
+					'FROM `'.self::RELATION_TABLE.'` r, `'.self::TAG_TABLE.'` '.
226 226
 					'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
227 227
 					array($this->user, $this->type, $chunk),
228 228
 					array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
229 229
 				);
230 230
 				while ($row = $result->fetch()) {
231
-					$objId = (int)$row['objid'];
231
+					$objId = (int) $row['objid'];
232 232
 					if (!isset($entries[$objId])) {
233 233
 						$entries[$objId] = array();
234 234
 					}
235 235
 					$entries[$objId][] = $row['category'];
236 236
 				}
237 237
 				if (\OCP\DB::isError($result)) {
238
-					\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
238
+					\OCP\Util::writeLog('core', __METHOD__.'DB error: '.\OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
239 239
 					return false;
240 240
 				}
241 241
 			}
242
-		} catch(\Exception $e) {
242
+		} catch (\Exception $e) {
243 243
 			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
244 244
 				\OCP\Util::ERROR);
245 245
 			return false;
@@ -260,18 +260,18 @@  discard block
 block discarded – undo
260 260
 	public function getIdsForTag($tag) {
261 261
 		$result = null;
262 262
 		$tagId = false;
263
-		if(is_numeric($tag)) {
263
+		if (is_numeric($tag)) {
264 264
 			$tagId = $tag;
265
-		} elseif(is_string($tag)) {
265
+		} elseif (is_string($tag)) {
266 266
 			$tag = trim($tag);
267
-			if($tag === '') {
267
+			if ($tag === '') {
268 268
 				\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
269 269
 				return false;
270 270
 			}
271 271
 			$tagId = $this->getTagId($tag);
272 272
 		}
273 273
 
274
-		if($tagId === false) {
274
+		if ($tagId === false) {
275 275
 			$l10n = \OC::$server->getL10N('core');
276 276
 			throw new \Exception(
277 277
 				$l10n->t('Could not find category "%s"', [$tag])
@@ -279,25 +279,25 @@  discard block
 block discarded – undo
279 279
 		}
280 280
 
281 281
 		$ids = array();
282
-		$sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
282
+		$sql = 'SELECT `objid` FROM `'.self::RELATION_TABLE
283 283
 			. '` WHERE `categoryid` = ?';
284 284
 
285 285
 		try {
286 286
 			$stmt = \OCP\DB::prepare($sql);
287 287
 			$result = $stmt->execute(array($tagId));
288 288
 			if (\OCP\DB::isError($result)) {
289
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
289
+				\OCP\Util::writeLog('core', __METHOD__.'DB error: '.\OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
290 290
 				return false;
291 291
 			}
292
-		} catch(\Exception $e) {
292
+		} catch (\Exception $e) {
293 293
 			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
294 294
 				\OCP\Util::ERROR);
295 295
 			return false;
296 296
 		}
297 297
 
298
-		if(!is_null($result)) {
299
-			while( $row = $result->fetchRow()) {
300
-				$id = (int)$row['objid'];
298
+		if (!is_null($result)) {
299
+			while ($row = $result->fetchRow()) {
300
+				$id = (int) $row['objid'];
301 301
 
302 302
 				if ($this->includeShared) {
303 303
 					// We have to check if we are really allowed to access the
@@ -351,24 +351,24 @@  discard block
 block discarded – undo
351 351
 	public function add($name) {
352 352
 		$name = trim($name);
353 353
 
354
-		if($name === '') {
354
+		if ($name === '') {
355 355
 			\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
356 356
 			return false;
357 357
 		}
358
-		if($this->userHasTag($name, $this->user)) {
359
-			\OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', \OCP\Util::DEBUG);
358
+		if ($this->userHasTag($name, $this->user)) {
359
+			\OCP\Util::writeLog('core', __METHOD__.', name: '.$name.' exists already', \OCP\Util::DEBUG);
360 360
 			return false;
361 361
 		}
362 362
 		try {
363 363
 			$tag = new Tag($this->user, $this->type, $name);
364 364
 			$tag = $this->mapper->insert($tag);
365 365
 			$this->tags[] = $tag;
366
-		} catch(\Exception $e) {
366
+		} catch (\Exception $e) {
367 367
 			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
368 368
 				\OCP\Util::ERROR);
369 369
 			return false;
370 370
 		}
371
-		\OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), \OCP\Util::DEBUG);
371
+		\OCP\Util::writeLog('core', __METHOD__.', id: '.$tag->getId(), \OCP\Util::DEBUG);
372 372
 		return $tag->getId();
373 373
 	}
374 374
 
@@ -383,7 +383,7 @@  discard block
 block discarded – undo
383 383
 		$from = trim($from);
384 384
 		$to = trim($to);
385 385
 
386
-		if($to === '' || $from === '') {
386
+		if ($to === '' || $from === '') {
387 387
 			\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
388 388
 			return false;
389 389
 		}
@@ -393,21 +393,21 @@  discard block
 block discarded – undo
393 393
 		} else {
394 394
 			$key = $this->getTagByName($from);
395 395
 		}
396
-		if($key === false) {
397
-			\OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', \OCP\Util::DEBUG);
396
+		if ($key === false) {
397
+			\OCP\Util::writeLog('core', __METHOD__.', tag: '.$from.' does not exist', \OCP\Util::DEBUG);
398 398
 			return false;
399 399
 		}
400 400
 		$tag = $this->tags[$key];
401 401
 
402
-		if($this->userHasTag($to, $tag->getOwner())) {
403
-			\OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', \OCP\Util::DEBUG);
402
+		if ($this->userHasTag($to, $tag->getOwner())) {
403
+			\OCP\Util::writeLog('core', __METHOD__.', A tag named '.$to.' already exists for user '.$tag->getOwner().'.', \OCP\Util::DEBUG);
404 404
 			return false;
405 405
 		}
406 406
 
407 407
 		try {
408 408
 			$tag->setName($to);
409 409
 			$this->tags[$key] = $this->mapper->update($tag);
410
-		} catch(\Exception $e) {
410
+		} catch (\Exception $e) {
411 411
 			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
412 412
 				\OCP\Util::ERROR);
413 413
 			return false;
@@ -424,25 +424,25 @@  discard block
 block discarded – undo
424 424
 	* @param int|null $id int Optional object id to add to this|these tag(s)
425 425
 	* @return bool Returns false on error.
426 426
 	*/
427
-	public function addMultiple($names, $sync=false, $id = null) {
428
-		if(!is_array($names)) {
427
+	public function addMultiple($names, $sync = false, $id = null) {
428
+		if (!is_array($names)) {
429 429
 			$names = array($names);
430 430
 		}
431 431
 		$names = array_map('trim', $names);
432 432
 		array_filter($names);
433 433
 
434 434
 		$newones = array();
435
-		foreach($names as $name) {
436
-			if(!$this->hasTag($name) && $name !== '') {
435
+		foreach ($names as $name) {
436
+			if (!$this->hasTag($name) && $name !== '') {
437 437
 				$newones[] = new Tag($this->user, $this->type, $name);
438 438
 			}
439
-			if(!is_null($id) ) {
439
+			if (!is_null($id)) {
440 440
 				// Insert $objectid, $categoryid  pairs if not exist.
441 441
 				self::$relations[] = array('objid' => $id, 'tag' => $name);
442 442
 			}
443 443
 		}
444 444
 		$this->tags = array_merge($this->tags, $newones);
445
-		if($sync === true) {
445
+		if ($sync === true) {
446 446
 			$this->save();
447 447
 		}
448 448
 
@@ -453,13 +453,13 @@  discard block
 block discarded – undo
453 453
 	 * Save the list of tags and their object relations
454 454
 	 */
455 455
 	protected function save() {
456
-		if(is_array($this->tags)) {
457
-			foreach($this->tags as $tag) {
456
+		if (is_array($this->tags)) {
457
+			foreach ($this->tags as $tag) {
458 458
 				try {
459 459
 					if (!$this->mapper->tagExists($tag)) {
460 460
 						$this->mapper->insert($tag);
461 461
 					}
462
-				} catch(\Exception $e) {
462
+				} catch (\Exception $e) {
463 463
 					\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
464 464
 						\OCP\Util::ERROR);
465 465
 				}
@@ -467,17 +467,17 @@  discard block
 block discarded – undo
467 467
 
468 468
 			// reload tags to get the proper ids.
469 469
 			$this->tags = $this->mapper->loadTags($this->owners, $this->type);
470
-			\OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
470
+			\OCP\Util::writeLog('core', __METHOD__.', tags: '.print_r($this->tags, true),
471 471
 				\OCP\Util::DEBUG);
472 472
 			// Loop through temporarily cached objectid/tagname pairs
473 473
 			// and save relations.
474 474
 			$tags = $this->tags;
475 475
 			// For some reason this is needed or array_search(i) will return 0..?
476 476
 			ksort($tags);
477
-			foreach(self::$relations as $relation) {
477
+			foreach (self::$relations as $relation) {
478 478
 				$tagId = $this->getTagId($relation['tag']);
479
-				\OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, \OCP\Util::DEBUG);
480
-				if($tagId) {
479
+				\OCP\Util::writeLog('core', __METHOD__.'catid, '.$relation['tag'].' '.$tagId, \OCP\Util::DEBUG);
480
+				if ($tagId) {
481 481
 					try {
482 482
 						\OCP\DB::insertIfNotExist(self::RELATION_TABLE,
483 483
 							array(
@@ -485,7 +485,7 @@  discard block
 block discarded – undo
485 485
 								'categoryid' => $tagId,
486 486
 								'type' => $this->type,
487 487
 								));
488
-					} catch(\Exception $e) {
488
+					} catch (\Exception $e) {
489 489
 						\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
490 490
 							\OCP\Util::ERROR);
491 491
 					}
@@ -509,43 +509,43 @@  discard block
 block discarded – undo
509 509
 		// Find all objectid/tagId pairs.
510 510
 		$result = null;
511 511
 		try {
512
-			$stmt = \OCP\DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
512
+			$stmt = \OCP\DB::prepare('SELECT `id` FROM `'.self::TAG_TABLE.'` '
513 513
 				. 'WHERE `uid` = ?');
514 514
 			$result = $stmt->execute(array($arguments['uid']));
515 515
 			if (\OCP\DB::isError($result)) {
516
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
516
+				\OCP\Util::writeLog('core', __METHOD__.'DB error: '.\OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
517 517
 			}
518
-		} catch(\Exception $e) {
518
+		} catch (\Exception $e) {
519 519
 			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
520 520
 				\OCP\Util::ERROR);
521 521
 		}
522 522
 
523
-		if(!is_null($result)) {
523
+		if (!is_null($result)) {
524 524
 			try {
525
-				$stmt = \OCP\DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
525
+				$stmt = \OCP\DB::prepare('DELETE FROM `'.self::RELATION_TABLE.'` '
526 526
 					. 'WHERE `categoryid` = ?');
527
-				while( $row = $result->fetchRow()) {
527
+				while ($row = $result->fetchRow()) {
528 528
 					try {
529 529
 						$stmt->execute(array($row['id']));
530
-					} catch(\Exception $e) {
530
+					} catch (\Exception $e) {
531 531
 						\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
532 532
 							\OCP\Util::ERROR);
533 533
 					}
534 534
 				}
535
-			} catch(\Exception $e) {
535
+			} catch (\Exception $e) {
536 536
 				\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
537 537
 					\OCP\Util::ERROR);
538 538
 			}
539 539
 		}
540 540
 		try {
541
-			$stmt = \OCP\DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
541
+			$stmt = \OCP\DB::prepare('DELETE FROM `'.self::TAG_TABLE.'` '
542 542
 				. 'WHERE `uid` = ?');
543 543
 			$result = $stmt->execute(array($arguments['uid']));
544 544
 			if (\OCP\DB::isError($result)) {
545
-				\OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
545
+				\OCP\Util::writeLog('core', __METHOD__.', DB error: '.\OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
546 546
 			}
547
-		} catch(\Exception $e) {
548
-			\OCP\Util::writeLog('core', __METHOD__ . ', exception: '
547
+		} catch (\Exception $e) {
548
+			\OCP\Util::writeLog('core', __METHOD__.', exception: '
549 549
 				. $e->getMessage(), \OCP\Util::ERROR);
550 550
 		}
551 551
 	}
@@ -557,24 +557,24 @@  discard block
 block discarded – undo
557 557
 	* @return boolean Returns false on error.
558 558
 	*/
559 559
 	public function purgeObjects(array $ids) {
560
-		if(count($ids) === 0) {
560
+		if (count($ids) === 0) {
561 561
 			// job done ;)
562 562
 			return true;
563 563
 		}
564 564
 		$updates = $ids;
565 565
 		try {
566
-			$query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
567
-			$query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
566
+			$query = 'DELETE FROM `'.self::RELATION_TABLE.'` ';
567
+			$query .= 'WHERE `objid` IN ('.str_repeat('?,', count($ids) - 1).'?) ';
568 568
 			$query .= 'AND `type`= ?';
569 569
 			$updates[] = $this->type;
570 570
 			$stmt = \OCP\DB::prepare($query);
571 571
 			$result = $stmt->execute($updates);
572 572
 			if (\OCP\DB::isError($result)) {
573
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
573
+				\OCP\Util::writeLog('core', __METHOD__.'DB error: '.\OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
574 574
 				return false;
575 575
 			}
576
-		} catch(\Exception $e) {
577
-			\OCP\Util::writeLog('core', __METHOD__.', exception: ' . $e->getMessage(),
576
+		} catch (\Exception $e) {
577
+			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
578 578
 				\OCP\Util::ERROR);
579 579
 			return false;
580 580
 		}
@@ -589,8 +589,8 @@  discard block
 block discarded – undo
589 589
 	public function getFavorites() {
590 590
 		try {
591 591
 			return $this->getIdsForTag(self::TAG_FAVORITE);
592
-		} catch(\Exception $e) {
593
-			\OCP\Util::writeLog('core', __METHOD__.', exception: ' . $e->getMessage(),
592
+		} catch (\Exception $e) {
593
+			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
594 594
 				\OCP\Util::DEBUG);
595 595
 			return array();
596 596
 		}
@@ -603,7 +603,7 @@  discard block
 block discarded – undo
603 603
 	* @return boolean
604 604
 	*/
605 605
 	public function addToFavorites($objid) {
606
-		if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
606
+		if (!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
607 607
 			$this->add(self::TAG_FAVORITE);
608 608
 		}
609 609
 		return $this->tagAs($objid, self::TAG_FAVORITE);
@@ -627,16 +627,16 @@  discard block
 block discarded – undo
627 627
 	* @return boolean Returns false on error.
628 628
 	*/
629 629
 	public function tagAs($objid, $tag) {
630
-		if(is_string($tag) && !is_numeric($tag)) {
630
+		if (is_string($tag) && !is_numeric($tag)) {
631 631
 			$tag = trim($tag);
632
-			if($tag === '') {
632
+			if ($tag === '') {
633 633
 				\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
634 634
 				return false;
635 635
 			}
636
-			if(!$this->hasTag($tag)) {
636
+			if (!$this->hasTag($tag)) {
637 637
 				$this->add($tag);
638 638
 			}
639
-			$tagId =  $this->getTagId($tag);
639
+			$tagId = $this->getTagId($tag);
640 640
 		} else {
641 641
 			$tagId = $tag;
642 642
 		}
@@ -647,7 +647,7 @@  discard block
 block discarded – undo
647 647
 					'categoryid' => $tagId,
648 648
 					'type' => $this->type,
649 649
 				));
650
-		} catch(\Exception $e) {
650
+		} catch (\Exception $e) {
651 651
 			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
652 652
 				\OCP\Util::ERROR);
653 653
 			return false;
@@ -663,23 +663,23 @@  discard block
 block discarded – undo
663 663
 	* @return boolean
664 664
 	*/
665 665
 	public function unTag($objid, $tag) {
666
-		if(is_string($tag) && !is_numeric($tag)) {
666
+		if (is_string($tag) && !is_numeric($tag)) {
667 667
 			$tag = trim($tag);
668
-			if($tag === '') {
668
+			if ($tag === '') {
669 669
 				\OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', \OCP\Util::DEBUG);
670 670
 				return false;
671 671
 			}
672
-			$tagId =  $this->getTagId($tag);
672
+			$tagId = $this->getTagId($tag);
673 673
 		} else {
674 674
 			$tagId = $tag;
675 675
 		}
676 676
 
677 677
 		try {
678
-			$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
678
+			$sql = 'DELETE FROM `'.self::RELATION_TABLE.'` '
679 679
 					. 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
680 680
 			$stmt = \OCP\DB::prepare($sql);
681 681
 			$stmt->execute(array($objid, $tagId, $this->type));
682
-		} catch(\Exception $e) {
682
+		} catch (\Exception $e) {
683 683
 			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
684 684
 				\OCP\Util::ERROR);
685 685
 			return false;
@@ -694,16 +694,16 @@  discard block
 block discarded – undo
694 694
 	* @return bool Returns false on error
695 695
 	*/
696 696
 	public function delete($names) {
697
-		if(!is_array($names)) {
697
+		if (!is_array($names)) {
698 698
 			$names = array($names);
699 699
 		}
700 700
 
701 701
 		$names = array_map('trim', $names);
702 702
 		array_filter($names);
703 703
 
704
-		\OCP\Util::writeLog('core', __METHOD__ . ', before: '
704
+		\OCP\Util::writeLog('core', __METHOD__.', before: '
705 705
 			. print_r($this->tags, true), \OCP\Util::DEBUG);
706
-		foreach($names as $name) {
706
+		foreach ($names as $name) {
707 707
 			$id = null;
708 708
 
709 709
 			if (is_numeric($name)) {
@@ -717,22 +717,22 @@  discard block
 block discarded – undo
717 717
 				unset($this->tags[$key]);
718 718
 				$this->mapper->delete($tag);
719 719
 			} else {
720
-				\OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
720
+				\OCP\Util::writeLog('core', __METHOD__.'Cannot delete tag '.$name
721 721
 					. ': not found.', \OCP\Util::ERROR);
722 722
 			}
723
-			if(!is_null($id) && $id !== false) {
723
+			if (!is_null($id) && $id !== false) {
724 724
 				try {
725
-					$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
725
+					$sql = 'DELETE FROM `'.self::RELATION_TABLE.'` '
726 726
 							. 'WHERE `categoryid` = ?';
727 727
 					$stmt = \OCP\DB::prepare($sql);
728 728
 					$result = $stmt->execute(array($id));
729 729
 					if (\OCP\DB::isError($result)) {
730 730
 						\OCP\Util::writeLog('core',
731
-							__METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(),
731
+							__METHOD__.'DB error: '.\OCP\DB::getErrorMessage(),
732 732
 							\OCP\Util::ERROR);
733 733
 						return false;
734 734
 					}
735
-				} catch(\Exception $e) {
735
+				} catch (\Exception $e) {
736 736
 					\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
737 737
 						\OCP\Util::ERROR);
738 738
 					return false;
@@ -743,8 +743,8 @@  discard block
 block discarded – undo
743 743
 	}
744 744
 
745 745
 	// case-insensitive array_search
746
-	protected function array_searchi($needle, $haystack, $mem='getName') {
747
-		if(!is_array($haystack)) {
746
+	protected function array_searchi($needle, $haystack, $mem = 'getName') {
747
+		if (!is_array($haystack)) {
748 748
 			return false;
749 749
 		}
750 750
 		return array_search(strtolower($needle), array_map(
Please login to merge, or discard this patch.
Indentation   +757 added lines, -757 removed lines patch added patch discarded remove patch
@@ -48,761 +48,761 @@
 block discarded – undo
48 48
 
49 49
 class Tags implements \OCP\ITags {
50 50
 
51
-	/**
52
-	 * Tags
53
-	 *
54
-	 * @var array
55
-	 */
56
-	private $tags = array();
57
-
58
-	/**
59
-	 * Used for storing objectid/categoryname pairs while rescanning.
60
-	 *
61
-	 * @var array
62
-	 */
63
-	private static $relations = array();
64
-
65
-	/**
66
-	 * Type
67
-	 *
68
-	 * @var string
69
-	 */
70
-	private $type;
71
-
72
-	/**
73
-	 * User
74
-	 *
75
-	 * @var string
76
-	 */
77
-	private $user;
78
-
79
-	/**
80
-	 * Are we including tags for shared items?
81
-	 *
82
-	 * @var bool
83
-	 */
84
-	private $includeShared = false;
85
-
86
-	/**
87
-	 * The current user, plus any owners of the items shared with the current
88
-	 * user, if $this->includeShared === true.
89
-	 *
90
-	 * @var array
91
-	 */
92
-	private $owners = array();
93
-
94
-	/**
95
-	 * The Mapper we're using to communicate our Tag objects to the database.
96
-	 *
97
-	 * @var TagMapper
98
-	 */
99
-	private $mapper;
100
-
101
-	/**
102
-	 * The sharing backend for objects of $this->type. Required if
103
-	 * $this->includeShared === true to determine ownership of items.
104
-	 *
105
-	 * @var \OCP\Share_Backend
106
-	 */
107
-	private $backend;
108
-
109
-	const TAG_TABLE = '*PREFIX*vcategory';
110
-	const RELATION_TABLE = '*PREFIX*vcategory_to_object';
111
-
112
-	const TAG_FAVORITE = '_$!<Favorite>!$_';
113
-
114
-	/**
115
-	* Constructor.
116
-	*
117
-	* @param TagMapper $mapper Instance of the TagMapper abstraction layer.
118
-	* @param string $user The user whose data the object will operate on.
119
-	* @param string $type The type of items for which tags will be loaded.
120
-	* @param array $defaultTags Tags that should be created at construction.
121
-	* @param boolean $includeShared Whether to include tags for items shared with this user by others.
122
-	*/
123
-	public function __construct(TagMapper $mapper, $user, $type, $defaultTags = array(), $includeShared = false) {
124
-		$this->mapper = $mapper;
125
-		$this->user = $user;
126
-		$this->type = $type;
127
-		$this->includeShared = $includeShared;
128
-		$this->owners = array($this->user);
129
-		if ($this->includeShared) {
130
-			$this->owners = array_merge($this->owners, \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true));
131
-			$this->backend = \OC\Share\Share::getBackend($this->type);
132
-		}
133
-		$this->tags = $this->mapper->loadTags($this->owners, $this->type);
134
-
135
-		if(count($defaultTags) > 0 && count($this->tags) === 0) {
136
-			$this->addMultiple($defaultTags, true);
137
-		}
138
-	}
139
-
140
-	/**
141
-	* Check if any tags are saved for this type and user.
142
-	*
143
-	* @return boolean
144
-	*/
145
-	public function isEmpty() {
146
-		return count($this->tags) === 0;
147
-	}
148
-
149
-	/**
150
-	* Returns an array mapping a given tag's properties to its values:
151
-	* ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
152
-	*
153
-	* @param string $id The ID of the tag that is going to be mapped
154
-	* @return array|false
155
-	*/
156
-	public function getTag($id) {
157
-		$key = $this->getTagById($id);
158
-		if ($key !== false) {
159
-			return $this->tagMap($this->tags[$key]);
160
-		}
161
-		return false;
162
-	}
163
-
164
-	/**
165
-	* Get the tags for a specific user.
166
-	*
167
-	* This returns an array with maps containing each tag's properties:
168
-	* [
169
-	* 	['id' => 0, 'name' = 'First tag', 'owner' = 'User', 'type' => 'tagtype'],
170
-	* 	['id' => 1, 'name' = 'Shared tag', 'owner' = 'Other user', 'type' => 'tagtype'],
171
-	* ]
172
-	*
173
-	* @return array
174
-	*/
175
-	public function getTags() {
176
-		if(!count($this->tags)) {
177
-			return array();
178
-		}
179
-
180
-		usort($this->tags, function($a, $b) {
181
-			return strnatcasecmp($a->getName(), $b->getName());
182
-		});
183
-		$tagMap = array();
184
-
185
-		foreach($this->tags as $tag) {
186
-			if($tag->getName() !== self::TAG_FAVORITE) {
187
-				$tagMap[] = $this->tagMap($tag);
188
-			}
189
-		}
190
-		return $tagMap;
191
-
192
-	}
193
-
194
-	/**
195
-	* Return only the tags owned by the given user, omitting any tags shared
196
-	* by other users.
197
-	*
198
-	* @param string $user The user whose tags are to be checked.
199
-	* @return array An array of Tag objects.
200
-	*/
201
-	public function getTagsForUser($user) {
202
-		return array_filter($this->tags,
203
-			function($tag) use($user) {
204
-				return $tag->getOwner() === $user;
205
-			}
206
-		);
207
-	}
208
-
209
-	/**
210
-	 * Get the list of tags for the given ids.
211
-	 *
212
-	 * @param array $objIds array of object ids
213
-	 * @return array|boolean of tags id as key to array of tag names
214
-	 * or false if an error occurred
215
-	 */
216
-	public function getTagsForObjects(array $objIds) {
217
-		$entries = array();
218
-
219
-		try {
220
-			$conn = \OC::$server->getDatabaseConnection();
221
-			$chunks = array_chunk($objIds, 900, false);
222
-			foreach ($chunks as $chunk) {
223
-				$result = $conn->executeQuery(
224
-					'SELECT `category`, `categoryid`, `objid` ' .
225
-					'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
226
-					'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
227
-					array($this->user, $this->type, $chunk),
228
-					array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
229
-				);
230
-				while ($row = $result->fetch()) {
231
-					$objId = (int)$row['objid'];
232
-					if (!isset($entries[$objId])) {
233
-						$entries[$objId] = array();
234
-					}
235
-					$entries[$objId][] = $row['category'];
236
-				}
237
-				if (\OCP\DB::isError($result)) {
238
-					\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
239
-					return false;
240
-				}
241
-			}
242
-		} catch(\Exception $e) {
243
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
244
-				\OCP\Util::ERROR);
245
-			return false;
246
-		}
247
-
248
-		return $entries;
249
-	}
250
-
251
-	/**
252
-	* Get the a list if items tagged with $tag.
253
-	*
254
-	* Throws an exception if the tag could not be found.
255
-	*
256
-	* @param string $tag Tag id or name.
257
-	* @return array|false An array of object ids or false on error.
258
-	* @throws \Exception
259
-	*/
260
-	public function getIdsForTag($tag) {
261
-		$result = null;
262
-		$tagId = false;
263
-		if(is_numeric($tag)) {
264
-			$tagId = $tag;
265
-		} elseif(is_string($tag)) {
266
-			$tag = trim($tag);
267
-			if($tag === '') {
268
-				\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
269
-				return false;
270
-			}
271
-			$tagId = $this->getTagId($tag);
272
-		}
273
-
274
-		if($tagId === false) {
275
-			$l10n = \OC::$server->getL10N('core');
276
-			throw new \Exception(
277
-				$l10n->t('Could not find category "%s"', [$tag])
278
-			);
279
-		}
280
-
281
-		$ids = array();
282
-		$sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
283
-			. '` WHERE `categoryid` = ?';
284
-
285
-		try {
286
-			$stmt = \OCP\DB::prepare($sql);
287
-			$result = $stmt->execute(array($tagId));
288
-			if (\OCP\DB::isError($result)) {
289
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
290
-				return false;
291
-			}
292
-		} catch(\Exception $e) {
293
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
294
-				\OCP\Util::ERROR);
295
-			return false;
296
-		}
297
-
298
-		if(!is_null($result)) {
299
-			while( $row = $result->fetchRow()) {
300
-				$id = (int)$row['objid'];
301
-
302
-				if ($this->includeShared) {
303
-					// We have to check if we are really allowed to access the
304
-					// items that are tagged with $tag. To that end, we ask the
305
-					// corresponding sharing backend if the item identified by $id
306
-					// is owned by any of $this->owners.
307
-					foreach ($this->owners as $owner) {
308
-						if ($this->backend->isValidSource($id, $owner)) {
309
-							$ids[] = $id;
310
-							break;
311
-						}
312
-					}
313
-				} else {
314
-					$ids[] = $id;
315
-				}
316
-			}
317
-		}
318
-
319
-		return $ids;
320
-	}
321
-
322
-	/**
323
-	* Checks whether a tag is saved for the given user,
324
-	* disregarding the ones shared with him or her.
325
-	*
326
-	* @param string $name The tag name to check for.
327
-	* @param string $user The user whose tags are to be checked.
328
-	* @return bool
329
-	*/
330
-	public function userHasTag($name, $user) {
331
-		$key = $this->array_searchi($name, $this->getTagsForUser($user));
332
-		return ($key !== false) ? $this->tags[$key]->getId() : false;
333
-	}
334
-
335
-	/**
336
-	* Checks whether a tag is saved for or shared with the current user.
337
-	*
338
-	* @param string $name The tag name to check for.
339
-	* @return bool
340
-	*/
341
-	public function hasTag($name) {
342
-		return $this->getTagId($name) !== false;
343
-	}
344
-
345
-	/**
346
-	* Add a new tag.
347
-	*
348
-	* @param string $name A string with a name of the tag
349
-	* @return false|int the id of the added tag or false on error.
350
-	*/
351
-	public function add($name) {
352
-		$name = trim($name);
353
-
354
-		if($name === '') {
355
-			\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
356
-			return false;
357
-		}
358
-		if($this->userHasTag($name, $this->user)) {
359
-			\OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', \OCP\Util::DEBUG);
360
-			return false;
361
-		}
362
-		try {
363
-			$tag = new Tag($this->user, $this->type, $name);
364
-			$tag = $this->mapper->insert($tag);
365
-			$this->tags[] = $tag;
366
-		} catch(\Exception $e) {
367
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
368
-				\OCP\Util::ERROR);
369
-			return false;
370
-		}
371
-		\OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), \OCP\Util::DEBUG);
372
-		return $tag->getId();
373
-	}
374
-
375
-	/**
376
-	* Rename tag.
377
-	*
378
-	* @param string|integer $from The name or ID of the existing tag
379
-	* @param string $to The new name of the tag.
380
-	* @return bool
381
-	*/
382
-	public function rename($from, $to) {
383
-		$from = trim($from);
384
-		$to = trim($to);
385
-
386
-		if($to === '' || $from === '') {
387
-			\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
388
-			return false;
389
-		}
390
-
391
-		if (is_numeric($from)) {
392
-			$key = $this->getTagById($from);
393
-		} else {
394
-			$key = $this->getTagByName($from);
395
-		}
396
-		if($key === false) {
397
-			\OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', \OCP\Util::DEBUG);
398
-			return false;
399
-		}
400
-		$tag = $this->tags[$key];
401
-
402
-		if($this->userHasTag($to, $tag->getOwner())) {
403
-			\OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', \OCP\Util::DEBUG);
404
-			return false;
405
-		}
406
-
407
-		try {
408
-			$tag->setName($to);
409
-			$this->tags[$key] = $this->mapper->update($tag);
410
-		} catch(\Exception $e) {
411
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
412
-				\OCP\Util::ERROR);
413
-			return false;
414
-		}
415
-		return true;
416
-	}
417
-
418
-	/**
419
-	* Add a list of new tags.
420
-	*
421
-	* @param string[] $names A string with a name or an array of strings containing
422
-	* the name(s) of the tag(s) to add.
423
-	* @param bool $sync When true, save the tags
424
-	* @param int|null $id int Optional object id to add to this|these tag(s)
425
-	* @return bool Returns false on error.
426
-	*/
427
-	public function addMultiple($names, $sync=false, $id = null) {
428
-		if(!is_array($names)) {
429
-			$names = array($names);
430
-		}
431
-		$names = array_map('trim', $names);
432
-		array_filter($names);
433
-
434
-		$newones = array();
435
-		foreach($names as $name) {
436
-			if(!$this->hasTag($name) && $name !== '') {
437
-				$newones[] = new Tag($this->user, $this->type, $name);
438
-			}
439
-			if(!is_null($id) ) {
440
-				// Insert $objectid, $categoryid  pairs if not exist.
441
-				self::$relations[] = array('objid' => $id, 'tag' => $name);
442
-			}
443
-		}
444
-		$this->tags = array_merge($this->tags, $newones);
445
-		if($sync === true) {
446
-			$this->save();
447
-		}
448
-
449
-		return true;
450
-	}
451
-
452
-	/**
453
-	 * Save the list of tags and their object relations
454
-	 */
455
-	protected function save() {
456
-		if(is_array($this->tags)) {
457
-			foreach($this->tags as $tag) {
458
-				try {
459
-					if (!$this->mapper->tagExists($tag)) {
460
-						$this->mapper->insert($tag);
461
-					}
462
-				} catch(\Exception $e) {
463
-					\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
464
-						\OCP\Util::ERROR);
465
-				}
466
-			}
467
-
468
-			// reload tags to get the proper ids.
469
-			$this->tags = $this->mapper->loadTags($this->owners, $this->type);
470
-			\OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
471
-				\OCP\Util::DEBUG);
472
-			// Loop through temporarily cached objectid/tagname pairs
473
-			// and save relations.
474
-			$tags = $this->tags;
475
-			// For some reason this is needed or array_search(i) will return 0..?
476
-			ksort($tags);
477
-			foreach(self::$relations as $relation) {
478
-				$tagId = $this->getTagId($relation['tag']);
479
-				\OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, \OCP\Util::DEBUG);
480
-				if($tagId) {
481
-					try {
482
-						\OCP\DB::insertIfNotExist(self::RELATION_TABLE,
483
-							array(
484
-								'objid' => $relation['objid'],
485
-								'categoryid' => $tagId,
486
-								'type' => $this->type,
487
-								));
488
-					} catch(\Exception $e) {
489
-						\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
490
-							\OCP\Util::ERROR);
491
-					}
492
-				}
493
-			}
494
-			self::$relations = array(); // reset
495
-		} else {
496
-			\OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! '
497
-				. print_r($this->tags, true), \OCP\Util::ERROR);
498
-		}
499
-	}
500
-
501
-	/**
502
-	* Delete tags and tag/object relations for a user.
503
-	*
504
-	* For hooking up on post_deleteUser
505
-	*
506
-	* @param array $arguments
507
-	*/
508
-	public static function post_deleteUser($arguments) {
509
-		// Find all objectid/tagId pairs.
510
-		$result = null;
511
-		try {
512
-			$stmt = \OCP\DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
513
-				. 'WHERE `uid` = ?');
514
-			$result = $stmt->execute(array($arguments['uid']));
515
-			if (\OCP\DB::isError($result)) {
516
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
517
-			}
518
-		} catch(\Exception $e) {
519
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
520
-				\OCP\Util::ERROR);
521
-		}
522
-
523
-		if(!is_null($result)) {
524
-			try {
525
-				$stmt = \OCP\DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
526
-					. 'WHERE `categoryid` = ?');
527
-				while( $row = $result->fetchRow()) {
528
-					try {
529
-						$stmt->execute(array($row['id']));
530
-					} catch(\Exception $e) {
531
-						\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
532
-							\OCP\Util::ERROR);
533
-					}
534
-				}
535
-			} catch(\Exception $e) {
536
-				\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
537
-					\OCP\Util::ERROR);
538
-			}
539
-		}
540
-		try {
541
-			$stmt = \OCP\DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
542
-				. 'WHERE `uid` = ?');
543
-			$result = $stmt->execute(array($arguments['uid']));
544
-			if (\OCP\DB::isError($result)) {
545
-				\OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
546
-			}
547
-		} catch(\Exception $e) {
548
-			\OCP\Util::writeLog('core', __METHOD__ . ', exception: '
549
-				. $e->getMessage(), \OCP\Util::ERROR);
550
-		}
551
-	}
552
-
553
-	/**
554
-	* Delete tag/object relations from the db
555
-	*
556
-	* @param array $ids The ids of the objects
557
-	* @return boolean Returns false on error.
558
-	*/
559
-	public function purgeObjects(array $ids) {
560
-		if(count($ids) === 0) {
561
-			// job done ;)
562
-			return true;
563
-		}
564
-		$updates = $ids;
565
-		try {
566
-			$query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
567
-			$query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
568
-			$query .= 'AND `type`= ?';
569
-			$updates[] = $this->type;
570
-			$stmt = \OCP\DB::prepare($query);
571
-			$result = $stmt->execute($updates);
572
-			if (\OCP\DB::isError($result)) {
573
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
574
-				return false;
575
-			}
576
-		} catch(\Exception $e) {
577
-			\OCP\Util::writeLog('core', __METHOD__.', exception: ' . $e->getMessage(),
578
-				\OCP\Util::ERROR);
579
-			return false;
580
-		}
581
-		return true;
582
-	}
583
-
584
-	/**
585
-	* Get favorites for an object type
586
-	*
587
-	* @return array|false An array of object ids.
588
-	*/
589
-	public function getFavorites() {
590
-		try {
591
-			return $this->getIdsForTag(self::TAG_FAVORITE);
592
-		} catch(\Exception $e) {
593
-			\OCP\Util::writeLog('core', __METHOD__.', exception: ' . $e->getMessage(),
594
-				\OCP\Util::DEBUG);
595
-			return array();
596
-		}
597
-	}
598
-
599
-	/**
600
-	* Add an object to favorites
601
-	*
602
-	* @param int $objid The id of the object
603
-	* @return boolean
604
-	*/
605
-	public function addToFavorites($objid) {
606
-		if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
607
-			$this->add(self::TAG_FAVORITE);
608
-		}
609
-		return $this->tagAs($objid, self::TAG_FAVORITE);
610
-	}
611
-
612
-	/**
613
-	* Remove an object from favorites
614
-	*
615
-	* @param int $objid The id of the object
616
-	* @return boolean
617
-	*/
618
-	public function removeFromFavorites($objid) {
619
-		return $this->unTag($objid, self::TAG_FAVORITE);
620
-	}
621
-
622
-	/**
623
-	* Creates a tag/object relation.
624
-	*
625
-	* @param int $objid The id of the object
626
-	* @param string $tag The id or name of the tag
627
-	* @return boolean Returns false on error.
628
-	*/
629
-	public function tagAs($objid, $tag) {
630
-		if(is_string($tag) && !is_numeric($tag)) {
631
-			$tag = trim($tag);
632
-			if($tag === '') {
633
-				\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
634
-				return false;
635
-			}
636
-			if(!$this->hasTag($tag)) {
637
-				$this->add($tag);
638
-			}
639
-			$tagId =  $this->getTagId($tag);
640
-		} else {
641
-			$tagId = $tag;
642
-		}
643
-		try {
644
-			\OCP\DB::insertIfNotExist(self::RELATION_TABLE,
645
-				array(
646
-					'objid' => $objid,
647
-					'categoryid' => $tagId,
648
-					'type' => $this->type,
649
-				));
650
-		} catch(\Exception $e) {
651
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
652
-				\OCP\Util::ERROR);
653
-			return false;
654
-		}
655
-		return true;
656
-	}
657
-
658
-	/**
659
-	* Delete single tag/object relation from the db
660
-	*
661
-	* @param int $objid The id of the object
662
-	* @param string $tag The id or name of the tag
663
-	* @return boolean
664
-	*/
665
-	public function unTag($objid, $tag) {
666
-		if(is_string($tag) && !is_numeric($tag)) {
667
-			$tag = trim($tag);
668
-			if($tag === '') {
669
-				\OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', \OCP\Util::DEBUG);
670
-				return false;
671
-			}
672
-			$tagId =  $this->getTagId($tag);
673
-		} else {
674
-			$tagId = $tag;
675
-		}
676
-
677
-		try {
678
-			$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
679
-					. 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
680
-			$stmt = \OCP\DB::prepare($sql);
681
-			$stmt->execute(array($objid, $tagId, $this->type));
682
-		} catch(\Exception $e) {
683
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
684
-				\OCP\Util::ERROR);
685
-			return false;
686
-		}
687
-		return true;
688
-	}
689
-
690
-	/**
691
-	* Delete tags from the database.
692
-	*
693
-	* @param string[]|integer[] $names An array of tags (names or IDs) to delete
694
-	* @return bool Returns false on error
695
-	*/
696
-	public function delete($names) {
697
-		if(!is_array($names)) {
698
-			$names = array($names);
699
-		}
700
-
701
-		$names = array_map('trim', $names);
702
-		array_filter($names);
703
-
704
-		\OCP\Util::writeLog('core', __METHOD__ . ', before: '
705
-			. print_r($this->tags, true), \OCP\Util::DEBUG);
706
-		foreach($names as $name) {
707
-			$id = null;
708
-
709
-			if (is_numeric($name)) {
710
-				$key = $this->getTagById($name);
711
-			} else {
712
-				$key = $this->getTagByName($name);
713
-			}
714
-			if ($key !== false) {
715
-				$tag = $this->tags[$key];
716
-				$id = $tag->getId();
717
-				unset($this->tags[$key]);
718
-				$this->mapper->delete($tag);
719
-			} else {
720
-				\OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
721
-					. ': not found.', \OCP\Util::ERROR);
722
-			}
723
-			if(!is_null($id) && $id !== false) {
724
-				try {
725
-					$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
726
-							. 'WHERE `categoryid` = ?';
727
-					$stmt = \OCP\DB::prepare($sql);
728
-					$result = $stmt->execute(array($id));
729
-					if (\OCP\DB::isError($result)) {
730
-						\OCP\Util::writeLog('core',
731
-							__METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(),
732
-							\OCP\Util::ERROR);
733
-						return false;
734
-					}
735
-				} catch(\Exception $e) {
736
-					\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
737
-						\OCP\Util::ERROR);
738
-					return false;
739
-				}
740
-			}
741
-		}
742
-		return true;
743
-	}
744
-
745
-	// case-insensitive array_search
746
-	protected function array_searchi($needle, $haystack, $mem='getName') {
747
-		if(!is_array($haystack)) {
748
-			return false;
749
-		}
750
-		return array_search(strtolower($needle), array_map(
751
-			function($tag) use($mem) {
752
-				return strtolower(call_user_func(array($tag, $mem)));
753
-			}, $haystack)
754
-		);
755
-	}
756
-
757
-	/**
758
-	* Get a tag's ID.
759
-	*
760
-	* @param string $name The tag name to look for.
761
-	* @return string|bool The tag's id or false if no matching tag is found.
762
-	*/
763
-	private function getTagId($name) {
764
-		$key = $this->array_searchi($name, $this->tags);
765
-		if ($key !== false) {
766
-			return $this->tags[$key]->getId();
767
-		}
768
-		return false;
769
-	}
770
-
771
-	/**
772
-	* Get a tag by its name.
773
-	*
774
-	* @param string $name The tag name.
775
-	* @return integer|bool The tag object's offset within the $this->tags
776
-	*                      array or false if it doesn't exist.
777
-	*/
778
-	private function getTagByName($name) {
779
-		return $this->array_searchi($name, $this->tags, 'getName');
780
-	}
781
-
782
-	/**
783
-	* Get a tag by its ID.
784
-	*
785
-	* @param string $id The tag ID to look for.
786
-	* @return integer|bool The tag object's offset within the $this->tags
787
-	*                      array or false if it doesn't exist.
788
-	*/
789
-	private function getTagById($id) {
790
-		return $this->array_searchi($id, $this->tags, 'getId');
791
-	}
792
-
793
-	/**
794
-	* Returns an array mapping a given tag's properties to its values:
795
-	* ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
796
-	*
797
-	* @param Tag $tag The tag that is going to be mapped
798
-	* @return array
799
-	*/
800
-	private function tagMap(Tag $tag) {
801
-		return array(
802
-			'id'    => $tag->getId(),
803
-			'name'  => $tag->getName(),
804
-			'owner' => $tag->getOwner(),
805
-			'type'  => $tag->getType()
806
-		);
807
-	}
51
+    /**
52
+     * Tags
53
+     *
54
+     * @var array
55
+     */
56
+    private $tags = array();
57
+
58
+    /**
59
+     * Used for storing objectid/categoryname pairs while rescanning.
60
+     *
61
+     * @var array
62
+     */
63
+    private static $relations = array();
64
+
65
+    /**
66
+     * Type
67
+     *
68
+     * @var string
69
+     */
70
+    private $type;
71
+
72
+    /**
73
+     * User
74
+     *
75
+     * @var string
76
+     */
77
+    private $user;
78
+
79
+    /**
80
+     * Are we including tags for shared items?
81
+     *
82
+     * @var bool
83
+     */
84
+    private $includeShared = false;
85
+
86
+    /**
87
+     * The current user, plus any owners of the items shared with the current
88
+     * user, if $this->includeShared === true.
89
+     *
90
+     * @var array
91
+     */
92
+    private $owners = array();
93
+
94
+    /**
95
+     * The Mapper we're using to communicate our Tag objects to the database.
96
+     *
97
+     * @var TagMapper
98
+     */
99
+    private $mapper;
100
+
101
+    /**
102
+     * The sharing backend for objects of $this->type. Required if
103
+     * $this->includeShared === true to determine ownership of items.
104
+     *
105
+     * @var \OCP\Share_Backend
106
+     */
107
+    private $backend;
108
+
109
+    const TAG_TABLE = '*PREFIX*vcategory';
110
+    const RELATION_TABLE = '*PREFIX*vcategory_to_object';
111
+
112
+    const TAG_FAVORITE = '_$!<Favorite>!$_';
113
+
114
+    /**
115
+     * Constructor.
116
+     *
117
+     * @param TagMapper $mapper Instance of the TagMapper abstraction layer.
118
+     * @param string $user The user whose data the object will operate on.
119
+     * @param string $type The type of items for which tags will be loaded.
120
+     * @param array $defaultTags Tags that should be created at construction.
121
+     * @param boolean $includeShared Whether to include tags for items shared with this user by others.
122
+     */
123
+    public function __construct(TagMapper $mapper, $user, $type, $defaultTags = array(), $includeShared = false) {
124
+        $this->mapper = $mapper;
125
+        $this->user = $user;
126
+        $this->type = $type;
127
+        $this->includeShared = $includeShared;
128
+        $this->owners = array($this->user);
129
+        if ($this->includeShared) {
130
+            $this->owners = array_merge($this->owners, \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true));
131
+            $this->backend = \OC\Share\Share::getBackend($this->type);
132
+        }
133
+        $this->tags = $this->mapper->loadTags($this->owners, $this->type);
134
+
135
+        if(count($defaultTags) > 0 && count($this->tags) === 0) {
136
+            $this->addMultiple($defaultTags, true);
137
+        }
138
+    }
139
+
140
+    /**
141
+     * Check if any tags are saved for this type and user.
142
+     *
143
+     * @return boolean
144
+     */
145
+    public function isEmpty() {
146
+        return count($this->tags) === 0;
147
+    }
148
+
149
+    /**
150
+     * Returns an array mapping a given tag's properties to its values:
151
+     * ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
152
+     *
153
+     * @param string $id The ID of the tag that is going to be mapped
154
+     * @return array|false
155
+     */
156
+    public function getTag($id) {
157
+        $key = $this->getTagById($id);
158
+        if ($key !== false) {
159
+            return $this->tagMap($this->tags[$key]);
160
+        }
161
+        return false;
162
+    }
163
+
164
+    /**
165
+     * Get the tags for a specific user.
166
+     *
167
+     * This returns an array with maps containing each tag's properties:
168
+     * [
169
+     * 	['id' => 0, 'name' = 'First tag', 'owner' = 'User', 'type' => 'tagtype'],
170
+     * 	['id' => 1, 'name' = 'Shared tag', 'owner' = 'Other user', 'type' => 'tagtype'],
171
+     * ]
172
+     *
173
+     * @return array
174
+     */
175
+    public function getTags() {
176
+        if(!count($this->tags)) {
177
+            return array();
178
+        }
179
+
180
+        usort($this->tags, function($a, $b) {
181
+            return strnatcasecmp($a->getName(), $b->getName());
182
+        });
183
+        $tagMap = array();
184
+
185
+        foreach($this->tags as $tag) {
186
+            if($tag->getName() !== self::TAG_FAVORITE) {
187
+                $tagMap[] = $this->tagMap($tag);
188
+            }
189
+        }
190
+        return $tagMap;
191
+
192
+    }
193
+
194
+    /**
195
+     * Return only the tags owned by the given user, omitting any tags shared
196
+     * by other users.
197
+     *
198
+     * @param string $user The user whose tags are to be checked.
199
+     * @return array An array of Tag objects.
200
+     */
201
+    public function getTagsForUser($user) {
202
+        return array_filter($this->tags,
203
+            function($tag) use($user) {
204
+                return $tag->getOwner() === $user;
205
+            }
206
+        );
207
+    }
208
+
209
+    /**
210
+     * Get the list of tags for the given ids.
211
+     *
212
+     * @param array $objIds array of object ids
213
+     * @return array|boolean of tags id as key to array of tag names
214
+     * or false if an error occurred
215
+     */
216
+    public function getTagsForObjects(array $objIds) {
217
+        $entries = array();
218
+
219
+        try {
220
+            $conn = \OC::$server->getDatabaseConnection();
221
+            $chunks = array_chunk($objIds, 900, false);
222
+            foreach ($chunks as $chunk) {
223
+                $result = $conn->executeQuery(
224
+                    'SELECT `category`, `categoryid`, `objid` ' .
225
+                    'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
226
+                    'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
227
+                    array($this->user, $this->type, $chunk),
228
+                    array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
229
+                );
230
+                while ($row = $result->fetch()) {
231
+                    $objId = (int)$row['objid'];
232
+                    if (!isset($entries[$objId])) {
233
+                        $entries[$objId] = array();
234
+                    }
235
+                    $entries[$objId][] = $row['category'];
236
+                }
237
+                if (\OCP\DB::isError($result)) {
238
+                    \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
239
+                    return false;
240
+                }
241
+            }
242
+        } catch(\Exception $e) {
243
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
244
+                \OCP\Util::ERROR);
245
+            return false;
246
+        }
247
+
248
+        return $entries;
249
+    }
250
+
251
+    /**
252
+     * Get the a list if items tagged with $tag.
253
+     *
254
+     * Throws an exception if the tag could not be found.
255
+     *
256
+     * @param string $tag Tag id or name.
257
+     * @return array|false An array of object ids or false on error.
258
+     * @throws \Exception
259
+     */
260
+    public function getIdsForTag($tag) {
261
+        $result = null;
262
+        $tagId = false;
263
+        if(is_numeric($tag)) {
264
+            $tagId = $tag;
265
+        } elseif(is_string($tag)) {
266
+            $tag = trim($tag);
267
+            if($tag === '') {
268
+                \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
269
+                return false;
270
+            }
271
+            $tagId = $this->getTagId($tag);
272
+        }
273
+
274
+        if($tagId === false) {
275
+            $l10n = \OC::$server->getL10N('core');
276
+            throw new \Exception(
277
+                $l10n->t('Could not find category "%s"', [$tag])
278
+            );
279
+        }
280
+
281
+        $ids = array();
282
+        $sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
283
+            . '` WHERE `categoryid` = ?';
284
+
285
+        try {
286
+            $stmt = \OCP\DB::prepare($sql);
287
+            $result = $stmt->execute(array($tagId));
288
+            if (\OCP\DB::isError($result)) {
289
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
290
+                return false;
291
+            }
292
+        } catch(\Exception $e) {
293
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
294
+                \OCP\Util::ERROR);
295
+            return false;
296
+        }
297
+
298
+        if(!is_null($result)) {
299
+            while( $row = $result->fetchRow()) {
300
+                $id = (int)$row['objid'];
301
+
302
+                if ($this->includeShared) {
303
+                    // We have to check if we are really allowed to access the
304
+                    // items that are tagged with $tag. To that end, we ask the
305
+                    // corresponding sharing backend if the item identified by $id
306
+                    // is owned by any of $this->owners.
307
+                    foreach ($this->owners as $owner) {
308
+                        if ($this->backend->isValidSource($id, $owner)) {
309
+                            $ids[] = $id;
310
+                            break;
311
+                        }
312
+                    }
313
+                } else {
314
+                    $ids[] = $id;
315
+                }
316
+            }
317
+        }
318
+
319
+        return $ids;
320
+    }
321
+
322
+    /**
323
+     * Checks whether a tag is saved for the given user,
324
+     * disregarding the ones shared with him or her.
325
+     *
326
+     * @param string $name The tag name to check for.
327
+     * @param string $user The user whose tags are to be checked.
328
+     * @return bool
329
+     */
330
+    public function userHasTag($name, $user) {
331
+        $key = $this->array_searchi($name, $this->getTagsForUser($user));
332
+        return ($key !== false) ? $this->tags[$key]->getId() : false;
333
+    }
334
+
335
+    /**
336
+     * Checks whether a tag is saved for or shared with the current user.
337
+     *
338
+     * @param string $name The tag name to check for.
339
+     * @return bool
340
+     */
341
+    public function hasTag($name) {
342
+        return $this->getTagId($name) !== false;
343
+    }
344
+
345
+    /**
346
+     * Add a new tag.
347
+     *
348
+     * @param string $name A string with a name of the tag
349
+     * @return false|int the id of the added tag or false on error.
350
+     */
351
+    public function add($name) {
352
+        $name = trim($name);
353
+
354
+        if($name === '') {
355
+            \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
356
+            return false;
357
+        }
358
+        if($this->userHasTag($name, $this->user)) {
359
+            \OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', \OCP\Util::DEBUG);
360
+            return false;
361
+        }
362
+        try {
363
+            $tag = new Tag($this->user, $this->type, $name);
364
+            $tag = $this->mapper->insert($tag);
365
+            $this->tags[] = $tag;
366
+        } catch(\Exception $e) {
367
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
368
+                \OCP\Util::ERROR);
369
+            return false;
370
+        }
371
+        \OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), \OCP\Util::DEBUG);
372
+        return $tag->getId();
373
+    }
374
+
375
+    /**
376
+     * Rename tag.
377
+     *
378
+     * @param string|integer $from The name or ID of the existing tag
379
+     * @param string $to The new name of the tag.
380
+     * @return bool
381
+     */
382
+    public function rename($from, $to) {
383
+        $from = trim($from);
384
+        $to = trim($to);
385
+
386
+        if($to === '' || $from === '') {
387
+            \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
388
+            return false;
389
+        }
390
+
391
+        if (is_numeric($from)) {
392
+            $key = $this->getTagById($from);
393
+        } else {
394
+            $key = $this->getTagByName($from);
395
+        }
396
+        if($key === false) {
397
+            \OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', \OCP\Util::DEBUG);
398
+            return false;
399
+        }
400
+        $tag = $this->tags[$key];
401
+
402
+        if($this->userHasTag($to, $tag->getOwner())) {
403
+            \OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', \OCP\Util::DEBUG);
404
+            return false;
405
+        }
406
+
407
+        try {
408
+            $tag->setName($to);
409
+            $this->tags[$key] = $this->mapper->update($tag);
410
+        } catch(\Exception $e) {
411
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
412
+                \OCP\Util::ERROR);
413
+            return false;
414
+        }
415
+        return true;
416
+    }
417
+
418
+    /**
419
+     * Add a list of new tags.
420
+     *
421
+     * @param string[] $names A string with a name or an array of strings containing
422
+     * the name(s) of the tag(s) to add.
423
+     * @param bool $sync When true, save the tags
424
+     * @param int|null $id int Optional object id to add to this|these tag(s)
425
+     * @return bool Returns false on error.
426
+     */
427
+    public function addMultiple($names, $sync=false, $id = null) {
428
+        if(!is_array($names)) {
429
+            $names = array($names);
430
+        }
431
+        $names = array_map('trim', $names);
432
+        array_filter($names);
433
+
434
+        $newones = array();
435
+        foreach($names as $name) {
436
+            if(!$this->hasTag($name) && $name !== '') {
437
+                $newones[] = new Tag($this->user, $this->type, $name);
438
+            }
439
+            if(!is_null($id) ) {
440
+                // Insert $objectid, $categoryid  pairs if not exist.
441
+                self::$relations[] = array('objid' => $id, 'tag' => $name);
442
+            }
443
+        }
444
+        $this->tags = array_merge($this->tags, $newones);
445
+        if($sync === true) {
446
+            $this->save();
447
+        }
448
+
449
+        return true;
450
+    }
451
+
452
+    /**
453
+     * Save the list of tags and their object relations
454
+     */
455
+    protected function save() {
456
+        if(is_array($this->tags)) {
457
+            foreach($this->tags as $tag) {
458
+                try {
459
+                    if (!$this->mapper->tagExists($tag)) {
460
+                        $this->mapper->insert($tag);
461
+                    }
462
+                } catch(\Exception $e) {
463
+                    \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
464
+                        \OCP\Util::ERROR);
465
+                }
466
+            }
467
+
468
+            // reload tags to get the proper ids.
469
+            $this->tags = $this->mapper->loadTags($this->owners, $this->type);
470
+            \OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
471
+                \OCP\Util::DEBUG);
472
+            // Loop through temporarily cached objectid/tagname pairs
473
+            // and save relations.
474
+            $tags = $this->tags;
475
+            // For some reason this is needed or array_search(i) will return 0..?
476
+            ksort($tags);
477
+            foreach(self::$relations as $relation) {
478
+                $tagId = $this->getTagId($relation['tag']);
479
+                \OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, \OCP\Util::DEBUG);
480
+                if($tagId) {
481
+                    try {
482
+                        \OCP\DB::insertIfNotExist(self::RELATION_TABLE,
483
+                            array(
484
+                                'objid' => $relation['objid'],
485
+                                'categoryid' => $tagId,
486
+                                'type' => $this->type,
487
+                                ));
488
+                    } catch(\Exception $e) {
489
+                        \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
490
+                            \OCP\Util::ERROR);
491
+                    }
492
+                }
493
+            }
494
+            self::$relations = array(); // reset
495
+        } else {
496
+            \OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! '
497
+                . print_r($this->tags, true), \OCP\Util::ERROR);
498
+        }
499
+    }
500
+
501
+    /**
502
+     * Delete tags and tag/object relations for a user.
503
+     *
504
+     * For hooking up on post_deleteUser
505
+     *
506
+     * @param array $arguments
507
+     */
508
+    public static function post_deleteUser($arguments) {
509
+        // Find all objectid/tagId pairs.
510
+        $result = null;
511
+        try {
512
+            $stmt = \OCP\DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
513
+                . 'WHERE `uid` = ?');
514
+            $result = $stmt->execute(array($arguments['uid']));
515
+            if (\OCP\DB::isError($result)) {
516
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
517
+            }
518
+        } catch(\Exception $e) {
519
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
520
+                \OCP\Util::ERROR);
521
+        }
522
+
523
+        if(!is_null($result)) {
524
+            try {
525
+                $stmt = \OCP\DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
526
+                    . 'WHERE `categoryid` = ?');
527
+                while( $row = $result->fetchRow()) {
528
+                    try {
529
+                        $stmt->execute(array($row['id']));
530
+                    } catch(\Exception $e) {
531
+                        \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
532
+                            \OCP\Util::ERROR);
533
+                    }
534
+                }
535
+            } catch(\Exception $e) {
536
+                \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
537
+                    \OCP\Util::ERROR);
538
+            }
539
+        }
540
+        try {
541
+            $stmt = \OCP\DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
542
+                . 'WHERE `uid` = ?');
543
+            $result = $stmt->execute(array($arguments['uid']));
544
+            if (\OCP\DB::isError($result)) {
545
+                \OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
546
+            }
547
+        } catch(\Exception $e) {
548
+            \OCP\Util::writeLog('core', __METHOD__ . ', exception: '
549
+                . $e->getMessage(), \OCP\Util::ERROR);
550
+        }
551
+    }
552
+
553
+    /**
554
+     * Delete tag/object relations from the db
555
+     *
556
+     * @param array $ids The ids of the objects
557
+     * @return boolean Returns false on error.
558
+     */
559
+    public function purgeObjects(array $ids) {
560
+        if(count($ids) === 0) {
561
+            // job done ;)
562
+            return true;
563
+        }
564
+        $updates = $ids;
565
+        try {
566
+            $query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
567
+            $query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
568
+            $query .= 'AND `type`= ?';
569
+            $updates[] = $this->type;
570
+            $stmt = \OCP\DB::prepare($query);
571
+            $result = $stmt->execute($updates);
572
+            if (\OCP\DB::isError($result)) {
573
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
574
+                return false;
575
+            }
576
+        } catch(\Exception $e) {
577
+            \OCP\Util::writeLog('core', __METHOD__.', exception: ' . $e->getMessage(),
578
+                \OCP\Util::ERROR);
579
+            return false;
580
+        }
581
+        return true;
582
+    }
583
+
584
+    /**
585
+     * Get favorites for an object type
586
+     *
587
+     * @return array|false An array of object ids.
588
+     */
589
+    public function getFavorites() {
590
+        try {
591
+            return $this->getIdsForTag(self::TAG_FAVORITE);
592
+        } catch(\Exception $e) {
593
+            \OCP\Util::writeLog('core', __METHOD__.', exception: ' . $e->getMessage(),
594
+                \OCP\Util::DEBUG);
595
+            return array();
596
+        }
597
+    }
598
+
599
+    /**
600
+     * Add an object to favorites
601
+     *
602
+     * @param int $objid The id of the object
603
+     * @return boolean
604
+     */
605
+    public function addToFavorites($objid) {
606
+        if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
607
+            $this->add(self::TAG_FAVORITE);
608
+        }
609
+        return $this->tagAs($objid, self::TAG_FAVORITE);
610
+    }
611
+
612
+    /**
613
+     * Remove an object from favorites
614
+     *
615
+     * @param int $objid The id of the object
616
+     * @return boolean
617
+     */
618
+    public function removeFromFavorites($objid) {
619
+        return $this->unTag($objid, self::TAG_FAVORITE);
620
+    }
621
+
622
+    /**
623
+     * Creates a tag/object relation.
624
+     *
625
+     * @param int $objid The id of the object
626
+     * @param string $tag The id or name of the tag
627
+     * @return boolean Returns false on error.
628
+     */
629
+    public function tagAs($objid, $tag) {
630
+        if(is_string($tag) && !is_numeric($tag)) {
631
+            $tag = trim($tag);
632
+            if($tag === '') {
633
+                \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
634
+                return false;
635
+            }
636
+            if(!$this->hasTag($tag)) {
637
+                $this->add($tag);
638
+            }
639
+            $tagId =  $this->getTagId($tag);
640
+        } else {
641
+            $tagId = $tag;
642
+        }
643
+        try {
644
+            \OCP\DB::insertIfNotExist(self::RELATION_TABLE,
645
+                array(
646
+                    'objid' => $objid,
647
+                    'categoryid' => $tagId,
648
+                    'type' => $this->type,
649
+                ));
650
+        } catch(\Exception $e) {
651
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
652
+                \OCP\Util::ERROR);
653
+            return false;
654
+        }
655
+        return true;
656
+    }
657
+
658
+    /**
659
+     * Delete single tag/object relation from the db
660
+     *
661
+     * @param int $objid The id of the object
662
+     * @param string $tag The id or name of the tag
663
+     * @return boolean
664
+     */
665
+    public function unTag($objid, $tag) {
666
+        if(is_string($tag) && !is_numeric($tag)) {
667
+            $tag = trim($tag);
668
+            if($tag === '') {
669
+                \OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', \OCP\Util::DEBUG);
670
+                return false;
671
+            }
672
+            $tagId =  $this->getTagId($tag);
673
+        } else {
674
+            $tagId = $tag;
675
+        }
676
+
677
+        try {
678
+            $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
679
+                    . 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
680
+            $stmt = \OCP\DB::prepare($sql);
681
+            $stmt->execute(array($objid, $tagId, $this->type));
682
+        } catch(\Exception $e) {
683
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
684
+                \OCP\Util::ERROR);
685
+            return false;
686
+        }
687
+        return true;
688
+    }
689
+
690
+    /**
691
+     * Delete tags from the database.
692
+     *
693
+     * @param string[]|integer[] $names An array of tags (names or IDs) to delete
694
+     * @return bool Returns false on error
695
+     */
696
+    public function delete($names) {
697
+        if(!is_array($names)) {
698
+            $names = array($names);
699
+        }
700
+
701
+        $names = array_map('trim', $names);
702
+        array_filter($names);
703
+
704
+        \OCP\Util::writeLog('core', __METHOD__ . ', before: '
705
+            . print_r($this->tags, true), \OCP\Util::DEBUG);
706
+        foreach($names as $name) {
707
+            $id = null;
708
+
709
+            if (is_numeric($name)) {
710
+                $key = $this->getTagById($name);
711
+            } else {
712
+                $key = $this->getTagByName($name);
713
+            }
714
+            if ($key !== false) {
715
+                $tag = $this->tags[$key];
716
+                $id = $tag->getId();
717
+                unset($this->tags[$key]);
718
+                $this->mapper->delete($tag);
719
+            } else {
720
+                \OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
721
+                    . ': not found.', \OCP\Util::ERROR);
722
+            }
723
+            if(!is_null($id) && $id !== false) {
724
+                try {
725
+                    $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
726
+                            . 'WHERE `categoryid` = ?';
727
+                    $stmt = \OCP\DB::prepare($sql);
728
+                    $result = $stmt->execute(array($id));
729
+                    if (\OCP\DB::isError($result)) {
730
+                        \OCP\Util::writeLog('core',
731
+                            __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(),
732
+                            \OCP\Util::ERROR);
733
+                        return false;
734
+                    }
735
+                } catch(\Exception $e) {
736
+                    \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
737
+                        \OCP\Util::ERROR);
738
+                    return false;
739
+                }
740
+            }
741
+        }
742
+        return true;
743
+    }
744
+
745
+    // case-insensitive array_search
746
+    protected function array_searchi($needle, $haystack, $mem='getName') {
747
+        if(!is_array($haystack)) {
748
+            return false;
749
+        }
750
+        return array_search(strtolower($needle), array_map(
751
+            function($tag) use($mem) {
752
+                return strtolower(call_user_func(array($tag, $mem)));
753
+            }, $haystack)
754
+        );
755
+    }
756
+
757
+    /**
758
+     * Get a tag's ID.
759
+     *
760
+     * @param string $name The tag name to look for.
761
+     * @return string|bool The tag's id or false if no matching tag is found.
762
+     */
763
+    private function getTagId($name) {
764
+        $key = $this->array_searchi($name, $this->tags);
765
+        if ($key !== false) {
766
+            return $this->tags[$key]->getId();
767
+        }
768
+        return false;
769
+    }
770
+
771
+    /**
772
+     * Get a tag by its name.
773
+     *
774
+     * @param string $name The tag name.
775
+     * @return integer|bool The tag object's offset within the $this->tags
776
+     *                      array or false if it doesn't exist.
777
+     */
778
+    private function getTagByName($name) {
779
+        return $this->array_searchi($name, $this->tags, 'getName');
780
+    }
781
+
782
+    /**
783
+     * Get a tag by its ID.
784
+     *
785
+     * @param string $id The tag ID to look for.
786
+     * @return integer|bool The tag object's offset within the $this->tags
787
+     *                      array or false if it doesn't exist.
788
+     */
789
+    private function getTagById($id) {
790
+        return $this->array_searchi($id, $this->tags, 'getId');
791
+    }
792
+
793
+    /**
794
+     * Returns an array mapping a given tag's properties to its values:
795
+     * ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
796
+     *
797
+     * @param Tag $tag The tag that is going to be mapped
798
+     * @return array
799
+     */
800
+    private function tagMap(Tag $tag) {
801
+        return array(
802
+            'id'    => $tag->getId(),
803
+            'name'  => $tag->getName(),
804
+            'owner' => $tag->getOwner(),
805
+            'type'  => $tag->getType()
806
+        );
807
+    }
808 808
 }
Please login to merge, or discard this patch.
lib/private/Template/Base.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -103,7 +103,7 @@
 block discarded – undo
103 103
 	/**
104 104
 	 * Appends a variable
105 105
 	 * @param string $key key
106
-	 * @param mixed $value value
106
+	 * @param string $value value
107 107
 	 * @return boolean|null
108 108
 	 *
109 109
 	 * This function assigns a variable in an array context. If the key already
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -114,8 +114,7 @@  discard block
 block discarded – undo
114 114
 	public function append( $key, $value ) {
115 115
 		if( array_key_exists( $key, $this->vars )) {
116 116
 			$this->vars[$key][] = $value;
117
-		}
118
-		else{
117
+		} else{
119 118
 			$this->vars[$key] = array( $value );
120 119
 		}
121 120
 	}
@@ -130,8 +129,7 @@  discard block
 block discarded – undo
130 129
 		$data = $this->fetchPage();
131 130
 		if( $data === false ) {
132 131
 			return false;
133
-		}
134
-		else{
132
+		} else{
135 133
 			print $data;
136 134
 			return true;
137 135
 		}
Please login to merge, or discard this patch.
Indentation   +153 added lines, -153 removed lines patch added patch discarded remove patch
@@ -31,158 +31,158 @@
 block discarded – undo
31 31
 use OCP\Defaults;
32 32
 
33 33
 class Base {
34
-	private $template; // The template
35
-	private $vars; // Vars
36
-
37
-	/** @var \OCP\IL10N */
38
-	private $l10n;
39
-
40
-	/** @var Defaults */
41
-	private $theme;
42
-
43
-	/**
44
-	 * @param string $template
45
-	 * @param string $requestToken
46
-	 * @param \OCP\IL10N $l10n
47
-	 * @param Defaults $theme
48
-	 */
49
-	public function __construct($template, $requestToken, $l10n, $theme ) {
50
-		$this->vars = array();
51
-		$this->vars['requesttoken'] = $requestToken;
52
-		$this->l10n = $l10n;
53
-		$this->template = $template;
54
-		$this->theme = $theme;
55
-	}
56
-
57
-	/**
58
-	 * @param string $serverRoot
59
-	 * @param string|false $app_dir
60
-	 * @param string $theme
61
-	 * @param string $app
62
-	 * @return string[]
63
-	 */
64
-	protected function getAppTemplateDirs($theme, $app, $serverRoot, $app_dir) {
65
-		// Check if the app is in the app folder or in the root
66
-		if( file_exists($app_dir.'/templates/' )) {
67
-			return [
68
-				$serverRoot.'/themes/'.$theme.'/apps/'.$app.'/templates/',
69
-				$app_dir.'/templates/',
70
-			];
71
-		}
72
-		return [
73
-			$serverRoot.'/themes/'.$theme.'/'.$app.'/templates/',
74
-			$serverRoot.'/'.$app.'/templates/',
75
-		];
76
-	}
77
-
78
-	/**
79
-	 * @param string $serverRoot
80
-	 * @param string $theme
81
-	 * @return string[]
82
-	 */
83
-	protected function getCoreTemplateDirs($theme, $serverRoot) {
84
-		return [
85
-			$serverRoot.'/themes/'.$theme.'/core/templates/',
86
-			$serverRoot.'/core/templates/',
87
-		];
88
-	}
89
-
90
-	/**
91
-	 * Assign variables
92
-	 * @param string $key key
93
-	 * @param array|bool|integer|string $value value
94
-	 * @return bool
95
-	 *
96
-	 * This function assigns a variable. It can be accessed via $_[$key] in
97
-	 * the template.
98
-	 *
99
-	 * If the key existed before, it will be overwritten
100
-	 */
101
-	public function assign( $key, $value) {
102
-		$this->vars[$key] = $value;
103
-		return true;
104
-	}
105
-
106
-	/**
107
-	 * Appends a variable
108
-	 * @param string $key key
109
-	 * @param mixed $value value
110
-	 * @return boolean|null
111
-	 *
112
-	 * This function assigns a variable in an array context. If the key already
113
-	 * exists, the value will be appended. It can be accessed via
114
-	 * $_[$key][$position] in the template.
115
-	 */
116
-	public function append( $key, $value ) {
117
-		if( array_key_exists( $key, $this->vars )) {
118
-			$this->vars[$key][] = $value;
119
-		}
120
-		else{
121
-			$this->vars[$key] = array( $value );
122
-		}
123
-	}
124
-
125
-	/**
126
-	 * Prints the proceeded template
127
-	 * @return bool
128
-	 *
129
-	 * This function proceeds the template and prints its output.
130
-	 */
131
-	public function printPage() {
132
-		$data = $this->fetchPage();
133
-		if( $data === false ) {
134
-			return false;
135
-		}
136
-		else{
137
-			print $data;
138
-			return true;
139
-		}
140
-	}
141
-
142
-	/**
143
-	 * Process the template
144
-	 *
145
-	 * @param array|null $additionalParams
146
-	 * @return string This function processes the template.
147
-	 *
148
-	 * This function processes the template.
149
-	 */
150
-	public function fetchPage($additionalParams = null) {
151
-		return $this->load($this->template, $additionalParams);
152
-	}
153
-
154
-	/**
155
-	 * doing the actual work
156
-	 *
157
-	 * @param string $file
158
-	 * @param array|null $additionalParams
159
-	 * @return string content
160
-	 *
161
-	 * Includes the template file, fetches its output
162
-	 */
163
-	protected function load($file, $additionalParams = null) {
164
-		// Register the variables
165
-		$_ = $this->vars;
166
-		$l = $this->l10n;
167
-		$theme = $this->theme;
168
-
169
-		if( !is_null($additionalParams)) {
170
-			$_ = array_merge( $additionalParams, $this->vars );
171
-		}
172
-
173
-		// Include
174
-		ob_start();
175
-		try {
176
-			include $file;
177
-			$data = ob_get_contents();
178
-		} catch (\Exception $e) {
179
-			@ob_end_clean();
180
-			throw $e;
181
-		}
182
-		@ob_end_clean();
183
-
184
-		// Return data
185
-		return $data;
186
-	}
34
+    private $template; // The template
35
+    private $vars; // Vars
36
+
37
+    /** @var \OCP\IL10N */
38
+    private $l10n;
39
+
40
+    /** @var Defaults */
41
+    private $theme;
42
+
43
+    /**
44
+     * @param string $template
45
+     * @param string $requestToken
46
+     * @param \OCP\IL10N $l10n
47
+     * @param Defaults $theme
48
+     */
49
+    public function __construct($template, $requestToken, $l10n, $theme ) {
50
+        $this->vars = array();
51
+        $this->vars['requesttoken'] = $requestToken;
52
+        $this->l10n = $l10n;
53
+        $this->template = $template;
54
+        $this->theme = $theme;
55
+    }
56
+
57
+    /**
58
+     * @param string $serverRoot
59
+     * @param string|false $app_dir
60
+     * @param string $theme
61
+     * @param string $app
62
+     * @return string[]
63
+     */
64
+    protected function getAppTemplateDirs($theme, $app, $serverRoot, $app_dir) {
65
+        // Check if the app is in the app folder or in the root
66
+        if( file_exists($app_dir.'/templates/' )) {
67
+            return [
68
+                $serverRoot.'/themes/'.$theme.'/apps/'.$app.'/templates/',
69
+                $app_dir.'/templates/',
70
+            ];
71
+        }
72
+        return [
73
+            $serverRoot.'/themes/'.$theme.'/'.$app.'/templates/',
74
+            $serverRoot.'/'.$app.'/templates/',
75
+        ];
76
+    }
77
+
78
+    /**
79
+     * @param string $serverRoot
80
+     * @param string $theme
81
+     * @return string[]
82
+     */
83
+    protected function getCoreTemplateDirs($theme, $serverRoot) {
84
+        return [
85
+            $serverRoot.'/themes/'.$theme.'/core/templates/',
86
+            $serverRoot.'/core/templates/',
87
+        ];
88
+    }
89
+
90
+    /**
91
+     * Assign variables
92
+     * @param string $key key
93
+     * @param array|bool|integer|string $value value
94
+     * @return bool
95
+     *
96
+     * This function assigns a variable. It can be accessed via $_[$key] in
97
+     * the template.
98
+     *
99
+     * If the key existed before, it will be overwritten
100
+     */
101
+    public function assign( $key, $value) {
102
+        $this->vars[$key] = $value;
103
+        return true;
104
+    }
105
+
106
+    /**
107
+     * Appends a variable
108
+     * @param string $key key
109
+     * @param mixed $value value
110
+     * @return boolean|null
111
+     *
112
+     * This function assigns a variable in an array context. If the key already
113
+     * exists, the value will be appended. It can be accessed via
114
+     * $_[$key][$position] in the template.
115
+     */
116
+    public function append( $key, $value ) {
117
+        if( array_key_exists( $key, $this->vars )) {
118
+            $this->vars[$key][] = $value;
119
+        }
120
+        else{
121
+            $this->vars[$key] = array( $value );
122
+        }
123
+    }
124
+
125
+    /**
126
+     * Prints the proceeded template
127
+     * @return bool
128
+     *
129
+     * This function proceeds the template and prints its output.
130
+     */
131
+    public function printPage() {
132
+        $data = $this->fetchPage();
133
+        if( $data === false ) {
134
+            return false;
135
+        }
136
+        else{
137
+            print $data;
138
+            return true;
139
+        }
140
+    }
141
+
142
+    /**
143
+     * Process the template
144
+     *
145
+     * @param array|null $additionalParams
146
+     * @return string This function processes the template.
147
+     *
148
+     * This function processes the template.
149
+     */
150
+    public function fetchPage($additionalParams = null) {
151
+        return $this->load($this->template, $additionalParams);
152
+    }
153
+
154
+    /**
155
+     * doing the actual work
156
+     *
157
+     * @param string $file
158
+     * @param array|null $additionalParams
159
+     * @return string content
160
+     *
161
+     * Includes the template file, fetches its output
162
+     */
163
+    protected function load($file, $additionalParams = null) {
164
+        // Register the variables
165
+        $_ = $this->vars;
166
+        $l = $this->l10n;
167
+        $theme = $this->theme;
168
+
169
+        if( !is_null($additionalParams)) {
170
+            $_ = array_merge( $additionalParams, $this->vars );
171
+        }
172
+
173
+        // Include
174
+        ob_start();
175
+        try {
176
+            include $file;
177
+            $data = ob_get_contents();
178
+        } catch (\Exception $e) {
179
+            @ob_end_clean();
180
+            throw $e;
181
+        }
182
+        @ob_end_clean();
183
+
184
+        // Return data
185
+        return $data;
186
+    }
187 187
 
188 188
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
 	 * @param \OCP\IL10N $l10n
47 47
 	 * @param Defaults $theme
48 48
 	 */
49
-	public function __construct($template, $requestToken, $l10n, $theme ) {
49
+	public function __construct($template, $requestToken, $l10n, $theme) {
50 50
 		$this->vars = array();
51 51
 		$this->vars['requesttoken'] = $requestToken;
52 52
 		$this->l10n = $l10n;
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
 	 */
64 64
 	protected function getAppTemplateDirs($theme, $app, $serverRoot, $app_dir) {
65 65
 		// Check if the app is in the app folder or in the root
66
-		if( file_exists($app_dir.'/templates/' )) {
66
+		if (file_exists($app_dir.'/templates/')) {
67 67
 			return [
68 68
 				$serverRoot.'/themes/'.$theme.'/apps/'.$app.'/templates/',
69 69
 				$app_dir.'/templates/',
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 	 *
99 99
 	 * If the key existed before, it will be overwritten
100 100
 	 */
101
-	public function assign( $key, $value) {
101
+	public function assign($key, $value) {
102 102
 		$this->vars[$key] = $value;
103 103
 		return true;
104 104
 	}
@@ -113,12 +113,12 @@  discard block
 block discarded – undo
113 113
 	 * exists, the value will be appended. It can be accessed via
114 114
 	 * $_[$key][$position] in the template.
115 115
 	 */
116
-	public function append( $key, $value ) {
117
-		if( array_key_exists( $key, $this->vars )) {
116
+	public function append($key, $value) {
117
+		if (array_key_exists($key, $this->vars)) {
118 118
 			$this->vars[$key][] = $value;
119 119
 		}
120
-		else{
121
-			$this->vars[$key] = array( $value );
120
+		else {
121
+			$this->vars[$key] = array($value);
122 122
 		}
123 123
 	}
124 124
 
@@ -130,10 +130,10 @@  discard block
 block discarded – undo
130 130
 	 */
131 131
 	public function printPage() {
132 132
 		$data = $this->fetchPage();
133
-		if( $data === false ) {
133
+		if ($data === false) {
134 134
 			return false;
135 135
 		}
136
-		else{
136
+		else {
137 137
 			print $data;
138 138
 			return true;
139 139
 		}
@@ -166,8 +166,8 @@  discard block
 block discarded – undo
166 166
 		$l = $this->l10n;
167 167
 		$theme = $this->theme;
168 168
 
169
-		if( !is_null($additionalParams)) {
170
-			$_ = array_merge( $additionalParams, $this->vars );
169
+		if (!is_null($additionalParams)) {
170
+			$_ = array_merge($additionalParams, $this->vars);
171 171
 		}
172 172
 
173 173
 		// Include
Please login to merge, or discard this patch.
lib/public/Migration/IOutput.php 2 patches
Doc Comments   +5 added lines, -1 removed lines patch added patch discarded remove patch
@@ -32,18 +32,21 @@  discard block
 block discarded – undo
32 32
 	/**
33 33
 	 * @param string $message
34 34
 	 * @since 9.1.0
35
+	 * @return void
35 36
 	 */
36 37
 	public function info($message);
37 38
 
38 39
 	/**
39 40
 	 * @param string $message
40 41
 	 * @since 9.1.0
42
+	 * @return void
41 43
 	 */
42 44
 	public function warning($message);
43 45
 
44 46
 	/**
45 47
 	 * @param int $max
46 48
 	 * @since 9.1.0
49
+	 * @return void
47 50
 	 */
48 51
 	public function startProgress($max = 0);
49 52
 
@@ -51,12 +54,13 @@  discard block
 block discarded – undo
51 54
 	 * @param int $step
52 55
 	 * @param string $description
53 56
 	 * @since 9.1.0
57
+	 * @return void
54 58
 	 */
55 59
 	public function advance($step = 1, $description = '');
56 60
 
57 61
 	/**
58
-	 * @param int $max
59 62
 	 * @since 9.1.0
63
+	 * @return void
60 64
 	 */
61 65
 	public function finishProgress();
62 66
 
Please login to merge, or discard this patch.
Indentation   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -30,35 +30,35 @@
 block discarded – undo
30 30
  */
31 31
 interface IOutput {
32 32
 
33
-	/**
34
-	 * @param string $message
35
-	 * @since 9.1.0
36
-	 */
37
-	public function info($message);
33
+    /**
34
+     * @param string $message
35
+     * @since 9.1.0
36
+     */
37
+    public function info($message);
38 38
 
39
-	/**
40
-	 * @param string $message
41
-	 * @since 9.1.0
42
-	 */
43
-	public function warning($message);
39
+    /**
40
+     * @param string $message
41
+     * @since 9.1.0
42
+     */
43
+    public function warning($message);
44 44
 
45
-	/**
46
-	 * @param int $max
47
-	 * @since 9.1.0
48
-	 */
49
-	public function startProgress($max = 0);
45
+    /**
46
+     * @param int $max
47
+     * @since 9.1.0
48
+     */
49
+    public function startProgress($max = 0);
50 50
 
51
-	/**
52
-	 * @param int $step
53
-	 * @param string $description
54
-	 * @since 9.1.0
55
-	 */
56
-	public function advance($step = 1, $description = '');
51
+    /**
52
+     * @param int $step
53
+     * @param string $description
54
+     * @since 9.1.0
55
+     */
56
+    public function advance($step = 1, $description = '');
57 57
 
58
-	/**
59
-	 * @param int $max
60
-	 * @since 9.1.0
61
-	 */
62
-	public function finishProgress();
58
+    /**
59
+     * @param int $max
60
+     * @since 9.1.0
61
+     */
62
+    public function finishProgress();
63 63
 
64 64
 }
Please login to merge, or discard this patch.
lib/public/SystemTag/ISystemTagManager.php 2 patches
Doc Comments   +7 added lines, -4 removed lines patch added patch discarded remove patch
@@ -102,17 +102,19 @@  discard block
 block discarded – undo
102 102
 	 * with the same attributes
103 103
 	 *
104 104
 	 * @since 9.0.0
105
+	 * @return void
105 106
 	 */
106 107
 	public function updateTag($tagId, $newName, $userVisible, $userAssignable);
107 108
 
108 109
 	/**
109 110
 	 * Delete the given tags from the database and all their relationships.
110 111
 	 *
111
-	 * @param string|array $tagIds array of tag ids
112
+	 * @param string $tagIds array of tag ids
112 113
 	 *
113 114
 	 * @throws \OCP\SystemTag\TagNotFoundException if at least one tag did not exist
114 115
 	 *
115 116
 	 * @since 9.0.0
117
+	 * @return void
116 118
 	 */
117 119
 	public function deleteTags($tagIds);
118 120
 
@@ -123,7 +125,7 @@  discard block
 block discarded – undo
123 125
 	 * @param ISystemTag $tag tag to check permission for
124 126
 	 * @param IUser $user user to check permission for
125 127
 	 *
126
-	 * @return true if the user is allowed to assign/unassign the tag, false otherwise
128
+	 * @return boolean if the user is allowed to assign/unassign the tag, false otherwise
127 129
 	 *
128 130
 	 * @since 9.1.0
129 131
 	 */
@@ -133,9 +135,9 @@  discard block
 block discarded – undo
133 135
 	 * Checks whether the given user is allowed to see the tag with the given id.
134 136
 	 *
135 137
 	 * @param ISystemTag $tag tag to check permission for
136
-	 * @param IUser $user user to check permission for
138
+	 * @param IUser $userId user to check permission for
137 139
 	 *
138
-	 * @return true if the user can see the tag, false otherwise
140
+	 * @return boolean if the user can see the tag, false otherwise
139 141
 	 *
140 142
 	 * @since 9.1.0
141 143
 	 */
@@ -148,6 +150,7 @@  discard block
 block discarded – undo
148 150
 	 * @param string[] $groupIds group ids of groups that can assign/unassign the tag
149 151
 	 *
150 152
 	 * @since 9.1.0
153
+	 * @return void
151 154
 	 */
152 155
 	public function setTagGroups(ISystemTag $tag, $groupIds);
153 156
 
Please login to merge, or discard this patch.
Indentation   +120 added lines, -120 removed lines patch added patch discarded remove patch
@@ -33,133 +33,133 @@
 block discarded – undo
33 33
  */
34 34
 interface ISystemTagManager {
35 35
 
36
-	/**
37
-	 * Returns the tag objects matching the given tag ids.
38
-	 *
39
-	 * @param array|string $tagIds id or array of unique ids of the tag to retrieve
40
-	 *
41
-	 * @return \OCP\SystemTag\ISystemTag[] array of system tags with tag id as key
42
-	 *
43
-	 * @throws \InvalidArgumentException if at least one given tag ids is invalid (string instead of integer, etc.)
44
-	 * @throws \OCP\SystemTag\TagNotFoundException if at least one given tag ids did no exist
45
-	 * 			The message contains a json_encoded array of the ids that could not be found
46
-	 *
47
-	 * @since 9.0.0
48
-	 */
49
-	public function getTagsByIds($tagIds);
36
+    /**
37
+     * Returns the tag objects matching the given tag ids.
38
+     *
39
+     * @param array|string $tagIds id or array of unique ids of the tag to retrieve
40
+     *
41
+     * @return \OCP\SystemTag\ISystemTag[] array of system tags with tag id as key
42
+     *
43
+     * @throws \InvalidArgumentException if at least one given tag ids is invalid (string instead of integer, etc.)
44
+     * @throws \OCP\SystemTag\TagNotFoundException if at least one given tag ids did no exist
45
+     * 			The message contains a json_encoded array of the ids that could not be found
46
+     *
47
+     * @since 9.0.0
48
+     */
49
+    public function getTagsByIds($tagIds);
50 50
 
51
-	/**
52
-	 * Returns the tag object matching the given attributes.
53
-	 *
54
-	 * @param string $tagName tag name
55
-	 * @param bool $userVisible whether the tag is visible by users
56
-	 * @param bool $userAssignable whether the tag is assignable by users
57
-	 *
58
-	 * @return \OCP\SystemTag\ISystemTag system tag
59
-	 *
60
-	 * @throws \OCP\SystemTag\TagNotFoundException if tag does not exist
61
-	 *
62
-	 * @since 9.0.0
63
-	 */
64
-	public function getTag($tagName, $userVisible, $userAssignable);
51
+    /**
52
+     * Returns the tag object matching the given attributes.
53
+     *
54
+     * @param string $tagName tag name
55
+     * @param bool $userVisible whether the tag is visible by users
56
+     * @param bool $userAssignable whether the tag is assignable by users
57
+     *
58
+     * @return \OCP\SystemTag\ISystemTag system tag
59
+     *
60
+     * @throws \OCP\SystemTag\TagNotFoundException if tag does not exist
61
+     *
62
+     * @since 9.0.0
63
+     */
64
+    public function getTag($tagName, $userVisible, $userAssignable);
65 65
 
66
-	/**
67
-	 * Creates the tag object using the given attributes.
68
-	 *
69
-	 * @param string $tagName tag name
70
-	 * @param bool $userVisible whether the tag is visible by users
71
-	 * @param bool $userAssignable whether the tag is assignable by users
72
-	 *
73
-	 * @return \OCP\SystemTag\ISystemTag system tag
74
-	 *
75
-	 * @throws \OCP\SystemTag\TagAlreadyExistsException if tag already exists
76
-	 *
77
-	 * @since 9.0.0
78
-	 */
79
-	public function createTag($tagName, $userVisible, $userAssignable);
66
+    /**
67
+     * Creates the tag object using the given attributes.
68
+     *
69
+     * @param string $tagName tag name
70
+     * @param bool $userVisible whether the tag is visible by users
71
+     * @param bool $userAssignable whether the tag is assignable by users
72
+     *
73
+     * @return \OCP\SystemTag\ISystemTag system tag
74
+     *
75
+     * @throws \OCP\SystemTag\TagAlreadyExistsException if tag already exists
76
+     *
77
+     * @since 9.0.0
78
+     */
79
+    public function createTag($tagName, $userVisible, $userAssignable);
80 80
 
81
-	/**
82
-	 * Returns all known tags, optionally filtered by visibility.
83
-	 *
84
-	 * @param bool|null $visibilityFilter filter by visibility if non-null
85
-	 * @param string $nameSearchPattern optional search pattern for the tag name
86
-	 *
87
-	 * @return \OCP\SystemTag\ISystemTag[] array of system tags or empty array if none found
88
-	 *
89
-	 * @since 9.0.0
90
-	 */
91
-	public function getAllTags($visibilityFilter = null, $nameSearchPattern = null);
81
+    /**
82
+     * Returns all known tags, optionally filtered by visibility.
83
+     *
84
+     * @param bool|null $visibilityFilter filter by visibility if non-null
85
+     * @param string $nameSearchPattern optional search pattern for the tag name
86
+     *
87
+     * @return \OCP\SystemTag\ISystemTag[] array of system tags or empty array if none found
88
+     *
89
+     * @since 9.0.0
90
+     */
91
+    public function getAllTags($visibilityFilter = null, $nameSearchPattern = null);
92 92
 
93
-	/**
94
-	 * Updates the given tag
95
-	 *
96
-	 * @param string $tagId tag id
97
-	 * @param string $newName the new tag name
98
-	 * @param bool $userVisible whether the tag is visible by users
99
-	 * @param bool $userAssignable whether the tag is assignable by users
100
-	 *
101
-	 * @throws \OCP\SystemTag\TagNotFoundException if tag with the given id does not exist
102
-	 * @throws \OCP\SystemTag\TagAlreadyExistsException if there is already another tag
103
-	 * with the same attributes
104
-	 *
105
-	 * @since 9.0.0
106
-	 */
107
-	public function updateTag($tagId, $newName, $userVisible, $userAssignable);
93
+    /**
94
+     * Updates the given tag
95
+     *
96
+     * @param string $tagId tag id
97
+     * @param string $newName the new tag name
98
+     * @param bool $userVisible whether the tag is visible by users
99
+     * @param bool $userAssignable whether the tag is assignable by users
100
+     *
101
+     * @throws \OCP\SystemTag\TagNotFoundException if tag with the given id does not exist
102
+     * @throws \OCP\SystemTag\TagAlreadyExistsException if there is already another tag
103
+     * with the same attributes
104
+     *
105
+     * @since 9.0.0
106
+     */
107
+    public function updateTag($tagId, $newName, $userVisible, $userAssignable);
108 108
 
109
-	/**
110
-	 * Delete the given tags from the database and all their relationships.
111
-	 *
112
-	 * @param string|array $tagIds array of tag ids
113
-	 *
114
-	 * @throws \OCP\SystemTag\TagNotFoundException if at least one tag did not exist
115
-	 *
116
-	 * @since 9.0.0
117
-	 */
118
-	public function deleteTags($tagIds);
109
+    /**
110
+     * Delete the given tags from the database and all their relationships.
111
+     *
112
+     * @param string|array $tagIds array of tag ids
113
+     *
114
+     * @throws \OCP\SystemTag\TagNotFoundException if at least one tag did not exist
115
+     *
116
+     * @since 9.0.0
117
+     */
118
+    public function deleteTags($tagIds);
119 119
 
120
-	/**
121
-	 * Checks whether the given user is allowed to assign/unassign the tag with the
122
-	 * given id.
123
-	 *
124
-	 * @param ISystemTag $tag tag to check permission for
125
-	 * @param IUser $user user to check permission for
126
-	 *
127
-	 * @return true if the user is allowed to assign/unassign the tag, false otherwise
128
-	 *
129
-	 * @since 9.1.0
130
-	 */
131
-	public function canUserAssignTag(ISystemTag $tag, IUser $user);
120
+    /**
121
+     * Checks whether the given user is allowed to assign/unassign the tag with the
122
+     * given id.
123
+     *
124
+     * @param ISystemTag $tag tag to check permission for
125
+     * @param IUser $user user to check permission for
126
+     *
127
+     * @return true if the user is allowed to assign/unassign the tag, false otherwise
128
+     *
129
+     * @since 9.1.0
130
+     */
131
+    public function canUserAssignTag(ISystemTag $tag, IUser $user);
132 132
 
133
-	/**
134
-	 * Checks whether the given user is allowed to see the tag with the given id.
135
-	 *
136
-	 * @param ISystemTag $tag tag to check permission for
137
-	 * @param IUser $user user to check permission for
138
-	 *
139
-	 * @return true if the user can see the tag, false otherwise
140
-	 *
141
-	 * @since 9.1.0
142
-	 */
143
-	public function canUserSeeTag(ISystemTag $tag, IUser $userId);
133
+    /**
134
+     * Checks whether the given user is allowed to see the tag with the given id.
135
+     *
136
+     * @param ISystemTag $tag tag to check permission for
137
+     * @param IUser $user user to check permission for
138
+     *
139
+     * @return true if the user can see the tag, false otherwise
140
+     *
141
+     * @since 9.1.0
142
+     */
143
+    public function canUserSeeTag(ISystemTag $tag, IUser $userId);
144 144
 
145
-	/**
146
-	 * Set groups that can assign a given tag.
147
-	 *
148
-	 * @param ISystemTag $tag tag for group assignment
149
-	 * @param string[] $groupIds group ids of groups that can assign/unassign the tag
150
-	 *
151
-	 * @since 9.1.0
152
-	 */
153
-	public function setTagGroups(ISystemTag $tag, $groupIds);
145
+    /**
146
+     * Set groups that can assign a given tag.
147
+     *
148
+     * @param ISystemTag $tag tag for group assignment
149
+     * @param string[] $groupIds group ids of groups that can assign/unassign the tag
150
+     *
151
+     * @since 9.1.0
152
+     */
153
+    public function setTagGroups(ISystemTag $tag, $groupIds);
154 154
 
155
-	/**
156
-	 * Get groups that can assign a given tag.
157
-	 *
158
-	 * @param ISystemTag $tag tag for group assignment
159
-	 *
160
-	 * @return string[] group ids of groups that can assign/unassign the tag
161
-	 *
162
-	 * @since 9.1.0
163
-	 */
164
-	public function getTagGroups(ISystemTag $tag);
155
+    /**
156
+     * Get groups that can assign a given tag.
157
+     *
158
+     * @param ISystemTag $tag tag for group assignment
159
+     *
160
+     * @return string[] group ids of groups that can assign/unassign the tag
161
+     *
162
+     * @since 9.1.0
163
+     */
164
+    public function getTagGroups(ISystemTag $tag);
165 165
 }
Please login to merge, or discard this patch.
lib/public/Util.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -544,7 +544,7 @@
 block discarded – undo
544 544
 	 * @param array $input The array to work on
545 545
 	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
546 546
 	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
547
-	 * @return array
547
+	 * @return string
548 548
 	 * @since 4.5.0
549 549
 	 */
550 550
 	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
Please login to merge, or discard this patch.
Spacing   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -58,11 +58,11 @@  discard block
 block discarded – undo
58 58
  */
59 59
 class Util {
60 60
 	// consts for Logging
61
-	const DEBUG=0;
62
-	const INFO=1;
63
-	const WARN=2;
64
-	const ERROR=3;
65
-	const FATAL=4;
61
+	const DEBUG = 0;
62
+	const INFO = 1;
63
+	const WARN = 2;
64
+	const ERROR = 3;
65
+	const FATAL = 4;
66 66
 
67 67
 	/** \OCP\Share\IManager */
68 68
 	private static $shareManager;
@@ -118,11 +118,11 @@  discard block
 block discarded – undo
118 118
 		$message->setSubject($subject);
119 119
 		$message->setPlainBody($mailtext);
120 120
 		$message->setFrom([$fromaddress => $fromname]);
121
-		if($html === 1) {
121
+		if ($html === 1) {
122 122
 			$message->setHtmlBody($altbody);
123 123
 		}
124 124
 
125
-		if($altbody === '') {
125
+		if ($altbody === '') {
126 126
 			$message->setHtmlBody($mailtext);
127 127
 			$message->setPlainBody('');
128 128
 		} else {
@@ -130,14 +130,14 @@  discard block
 block discarded – undo
130 130
 			$message->setPlainBody($altbody);
131 131
 		}
132 132
 
133
-		if(!empty($ccaddress)) {
134
-			if(!empty($ccname)) {
133
+		if (!empty($ccaddress)) {
134
+			if (!empty($ccname)) {
135 135
 				$message->setCc([$ccaddress => $ccname]);
136 136
 			} else {
137 137
 				$message->setCc([$ccaddress]);
138 138
 			}
139 139
 		}
140
-		if(!empty($bcc)) {
140
+		if (!empty($bcc)) {
141 141
 			$message->setBcc([$bcc]);
142 142
 		}
143 143
 
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
 	 * @since 4.0.0
153 153
 	 * @deprecated 13.0.0 use log of \OCP\ILogger
154 154
 	 */
155
-	public static function writeLog( $app, $message, $level ) {
155
+	public static function writeLog($app, $message, $level) {
156 156
 		$context = ['app' => $app];
157 157
 		\OC::$server->getLogger()->log($level, $message, $context);
158 158
 	}
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 	 * @since ....0.0 - parameter $level was added in 7.0.0
166 166
 	 * @deprecated 8.2.0 use logException of \OCP\ILogger
167 167
 	 */
168
-	public static function logException( $app, \Exception $ex, $level = \OCP\Util::FATAL ) {
168
+	public static function logException($app, \Exception $ex, $level = \OCP\Util::FATAL) {
169 169
 		\OC::$server->getLogger()->logException($ex, ['app' => $app]);
170 170
 	}
171 171
 
@@ -206,8 +206,8 @@  discard block
 block discarded – undo
206 206
 	 * @param string $file
207 207
 	 * @since 4.0.0
208 208
 	 */
209
-	public static function addStyle( $application, $file = null ) {
210
-		\OC_Util::addStyle( $application, $file );
209
+	public static function addStyle($application, $file = null) {
210
+		\OC_Util::addStyle($application, $file);
211 211
 	}
212 212
 
213 213
 	/**
@@ -216,8 +216,8 @@  discard block
 block discarded – undo
216 216
 	 * @param string $file
217 217
 	 * @since 4.0.0
218 218
 	 */
219
-	public static function addScript( $application, $file = null ) {
220
-		\OC_Util::addScript( $application, $file );
219
+	public static function addScript($application, $file = null) {
220
+		\OC_Util::addScript($application, $file);
221 221
 	}
222 222
 
223 223
 	/**
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
 	 * @param string $text the text content for the element
240 240
 	 * @since 4.0.0
241 241
 	 */
242
-	public static function addHeader($tag, $attributes, $text=null) {
242
+	public static function addHeader($tag, $attributes, $text = null) {
243 243
 		\OC_Util::addHeader($tag, $attributes, $text);
244 244
 	}
245 245
 
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 	 * @since 4.0.0
255 255
 	 * @suppress PhanDeprecatedFunction
256 256
 	 */
257
-	public static function formatDate($timestamp, $dateOnly=false, $timeZone = null) {
257
+	public static function formatDate($timestamp, $dateOnly = false, $timeZone = null) {
258 258
 		return \OC_Util::formatDate($timestamp, $dateOnly, $timeZone);
259 259
 	}
260 260
 
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 	 * @return string the url
279 279
 	 * @since 4.0.0 - parameter $args was added in 4.5.0
280 280
 	 */
281
-	public static function linkToAbsolute( $app, $file, $args = array() ) {
281
+	public static function linkToAbsolute($app, $file, $args = array()) {
282 282
 		$urlGenerator = \OC::$server->getURLGenerator();
283 283
 		return $urlGenerator->getAbsoluteURL(
284 284
 			$urlGenerator->linkTo($app, $file, $args)
@@ -291,11 +291,11 @@  discard block
 block discarded – undo
291 291
 	 * @return string the url
292 292
 	 * @since 4.0.0
293 293
 	 */
294
-	public static function linkToRemote( $service ) {
294
+	public static function linkToRemote($service) {
295 295
 		$urlGenerator = \OC::$server->getURLGenerator();
296
-		$remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
296
+		$remoteBase = $urlGenerator->linkTo('', 'remote.php').'/'.$service;
297 297
 		return $urlGenerator->getAbsoluteURL(
298
-			$remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
298
+			$remoteBase.(($service[strlen($service) - 1] != '/') ? '/' : '')
299 299
 		);
300 300
 	}
301 301
 
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
 	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkToRoute($route, $parameters)
319 319
 	 * @since 5.0.0
320 320
 	 */
321
-	public static function linkToRoute( $route, $parameters = array() ) {
321
+	public static function linkToRoute($route, $parameters = array()) {
322 322
 		return \OC::$server->getURLGenerator()->linkToRoute($route, $parameters);
323 323
 	}
324 324
 
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
 	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkTo($app, $file, $args)
333 333
 	 * @since 4.0.0 - parameter $args was added in 4.5.0
334 334
 	 */
335
-	public static function linkTo( $app, $file, $args = array() ) {
335
+	public static function linkTo($app, $file, $args = array()) {
336 336
 		return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
337 337
 	}
338 338
 
@@ -431,7 +431,7 @@  discard block
 block discarded – undo
431 431
 	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->imagePath($app, $image)
432 432
 	 * @since 4.0.0
433 433
 	 */
434
-	public static function imagePath( $app, $image ) {
434
+	public static function imagePath($app, $image) {
435 435
 		return \OC::$server->getURLGenerator()->imagePath($app, $image);
436 436
 	}
437 437
 
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
 	 * @since 4.5.0
503 503
 	 */
504 504
 	public static function callRegister() {
505
-		if(self::$token === '') {
505
+		if (self::$token === '') {
506 506
 			self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
507 507
 		}
508 508
 		return self::$token;
@@ -514,7 +514,7 @@  discard block
 block discarded – undo
514 514
 	 * @deprecated 9.0.0 Use annotations based on the app framework.
515 515
 	 */
516 516
 	public static function callCheck() {
517
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
517
+		if (!\OC::$server->getRequest()->passesStrictCookieCheck()) {
518 518
 			header('Location: '.\OC::$WEBROOT);
519 519
 			exit();
520 520
 		}
@@ -706,7 +706,7 @@  discard block
 block discarded – undo
706 706
 	 */
707 707
 	public static function needUpgrade() {
708 708
 		if (!isset(self::$needUpgradeCache)) {
709
-			self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getSystemConfig());
709
+			self::$needUpgradeCache = \OC_Util::needUpgrade(\OC::$server->getSystemConfig());
710 710
 		}		
711 711
 		return self::$needUpgradeCache;
712 712
 	}
Please login to merge, or discard this patch.
Indentation   +651 added lines, -651 removed lines patch added patch discarded remove patch
@@ -57,657 +57,657 @@
 block discarded – undo
57 57
  * @since 4.0.0
58 58
  */
59 59
 class Util {
60
-	// consts for Logging
61
-	const DEBUG=0;
62
-	const INFO=1;
63
-	const WARN=2;
64
-	const ERROR=3;
65
-	const FATAL=4;
66
-
67
-	/** \OCP\Share\IManager */
68
-	private static $shareManager;
69
-
70
-	/**
71
-	 * get the current installed version of ownCloud
72
-	 * @return array
73
-	 * @since 4.0.0
74
-	 */
75
-	public static function getVersion() {
76
-		return \OC_Util::getVersion();
77
-	}
60
+    // consts for Logging
61
+    const DEBUG=0;
62
+    const INFO=1;
63
+    const WARN=2;
64
+    const ERROR=3;
65
+    const FATAL=4;
66
+
67
+    /** \OCP\Share\IManager */
68
+    private static $shareManager;
69
+
70
+    /**
71
+     * get the current installed version of ownCloud
72
+     * @return array
73
+     * @since 4.0.0
74
+     */
75
+    public static function getVersion() {
76
+        return \OC_Util::getVersion();
77
+    }
78 78
 	
79
-	/**
80
-	 * Set current update channel
81
-	 * @param string $channel
82
-	 * @since 8.1.0
83
-	 */
84
-	public static function setChannel($channel) {
85
-		\OC::$server->getConfig()->setSystemValue('updater.release.channel', $channel);
86
-	}
79
+    /**
80
+     * Set current update channel
81
+     * @param string $channel
82
+     * @since 8.1.0
83
+     */
84
+    public static function setChannel($channel) {
85
+        \OC::$server->getConfig()->setSystemValue('updater.release.channel', $channel);
86
+    }
87 87
 	
88
-	/**
89
-	 * Get current update channel
90
-	 * @return string
91
-	 * @since 8.1.0
92
-	 */
93
-	public static function getChannel() {
94
-		return \OC_Util::getChannel();
95
-	}
96
-
97
-	/**
98
-	 * send an email
99
-	 * @param string $toaddress
100
-	 * @param string $toname
101
-	 * @param string $subject
102
-	 * @param string $mailtext
103
-	 * @param string $fromaddress
104
-	 * @param string $fromname
105
-	 * @param int $html
106
-	 * @param string $altbody
107
-	 * @param string $ccaddress
108
-	 * @param string $ccname
109
-	 * @param string $bcc
110
-	 * @deprecated 8.1.0 Use \OCP\Mail\IMailer instead
111
-	 * @since 4.0.0
112
-	 */
113
-	public static function sendMail($toaddress, $toname, $subject, $mailtext, $fromaddress, $fromname,
114
-		$html = 0, $altbody = '', $ccaddress = '', $ccname = '', $bcc = '') {
115
-		$mailer = \OC::$server->getMailer();
116
-		$message = $mailer->createMessage();
117
-		$message->setTo([$toaddress => $toname]);
118
-		$message->setSubject($subject);
119
-		$message->setPlainBody($mailtext);
120
-		$message->setFrom([$fromaddress => $fromname]);
121
-		if($html === 1) {
122
-			$message->setHtmlBody($altbody);
123
-		}
124
-
125
-		if($altbody === '') {
126
-			$message->setHtmlBody($mailtext);
127
-			$message->setPlainBody('');
128
-		} else {
129
-			$message->setHtmlBody($mailtext);
130
-			$message->setPlainBody($altbody);
131
-		}
132
-
133
-		if(!empty($ccaddress)) {
134
-			if(!empty($ccname)) {
135
-				$message->setCc([$ccaddress => $ccname]);
136
-			} else {
137
-				$message->setCc([$ccaddress]);
138
-			}
139
-		}
140
-		if(!empty($bcc)) {
141
-			$message->setBcc([$bcc]);
142
-		}
143
-
144
-		$mailer->send($message);
145
-	}
146
-
147
-	/**
148
-	 * write a message in the log
149
-	 * @param string $app
150
-	 * @param string $message
151
-	 * @param int $level
152
-	 * @since 4.0.0
153
-	 * @deprecated 13.0.0 use log of \OCP\ILogger
154
-	 */
155
-	public static function writeLog( $app, $message, $level ) {
156
-		$context = ['app' => $app];
157
-		\OC::$server->getLogger()->log($level, $message, $context);
158
-	}
159
-
160
-	/**
161
-	 * write exception into the log
162
-	 * @param string $app app name
163
-	 * @param \Exception $ex exception to log
164
-	 * @param int $level log level, defaults to \OCP\Util::FATAL
165
-	 * @since ....0.0 - parameter $level was added in 7.0.0
166
-	 * @deprecated 8.2.0 use logException of \OCP\ILogger
167
-	 */
168
-	public static function logException( $app, \Exception $ex, $level = \OCP\Util::FATAL ) {
169
-		\OC::$server->getLogger()->logException($ex, ['app' => $app]);
170
-	}
171
-
172
-	/**
173
-	 * check if sharing is disabled for the current user
174
-	 *
175
-	 * @return boolean
176
-	 * @since 7.0.0
177
-	 * @deprecated 9.1.0 Use \OC::$server->getShareManager()->sharingDisabledForUser
178
-	 */
179
-	public static function isSharingDisabledForUser() {
180
-		if (self::$shareManager === null) {
181
-			self::$shareManager = \OC::$server->getShareManager();
182
-		}
183
-
184
-		$user = \OC::$server->getUserSession()->getUser();
185
-		if ($user !== null) {
186
-			$user = $user->getUID();
187
-		}
188
-
189
-		return self::$shareManager->sharingDisabledForUser($user);
190
-	}
191
-
192
-	/**
193
-	 * get l10n object
194
-	 * @param string $application
195
-	 * @param string|null $language
196
-	 * @return \OCP\IL10N
197
-	 * @since 6.0.0 - parameter $language was added in 8.0.0
198
-	 */
199
-	public static function getL10N($application, $language = null) {
200
-		return \OC::$server->getL10N($application, $language);
201
-	}
202
-
203
-	/**
204
-	 * add a css file
205
-	 * @param string $application
206
-	 * @param string $file
207
-	 * @since 4.0.0
208
-	 */
209
-	public static function addStyle( $application, $file = null ) {
210
-		\OC_Util::addStyle( $application, $file );
211
-	}
212
-
213
-	/**
214
-	 * add a javascript file
215
-	 * @param string $application
216
-	 * @param string $file
217
-	 * @since 4.0.0
218
-	 */
219
-	public static function addScript( $application, $file = null ) {
220
-		\OC_Util::addScript( $application, $file );
221
-	}
222
-
223
-	/**
224
-	 * Add a translation JS file
225
-	 * @param string $application application id
226
-	 * @param string $languageCode language code, defaults to the current locale
227
-	 * @since 8.0.0
228
-	 */
229
-	public static function addTranslations($application, $languageCode = null) {
230
-		\OC_Util::addTranslations($application, $languageCode);
231
-	}
232
-
233
-	/**
234
-	 * Add a custom element to the header
235
-	 * If $text is null then the element will be written as empty element.
236
-	 * So use "" to get a closing tag.
237
-	 * @param string $tag tag name of the element
238
-	 * @param array $attributes array of attributes for the element
239
-	 * @param string $text the text content for the element
240
-	 * @since 4.0.0
241
-	 */
242
-	public static function addHeader($tag, $attributes, $text=null) {
243
-		\OC_Util::addHeader($tag, $attributes, $text);
244
-	}
245
-
246
-	/**
247
-	 * formats a timestamp in the "right" way
248
-	 * @param int $timestamp $timestamp
249
-	 * @param bool $dateOnly option to omit time from the result
250
-	 * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
251
-	 * @return string timestamp
252
-	 *
253
-	 * @deprecated 8.0.0 Use \OC::$server->query('DateTimeFormatter') instead
254
-	 * @since 4.0.0
255
-	 * @suppress PhanDeprecatedFunction
256
-	 */
257
-	public static function formatDate($timestamp, $dateOnly=false, $timeZone = null) {
258
-		return \OC_Util::formatDate($timestamp, $dateOnly, $timeZone);
259
-	}
260
-
261
-	/**
262
-	 * check if some encrypted files are stored
263
-	 * @return bool
264
-	 *
265
-	 * @deprecated 8.1.0 No longer required
266
-	 * @since 6.0.0
267
-	 */
268
-	public static function encryptedFiles() {
269
-		return false;
270
-	}
271
-
272
-	/**
273
-	 * Creates an absolute url to the given app and file.
274
-	 * @param string $app app
275
-	 * @param string $file file
276
-	 * @param array $args array with param=>value, will be appended to the returned url
277
-	 * 	The value of $args will be urlencoded
278
-	 * @return string the url
279
-	 * @since 4.0.0 - parameter $args was added in 4.5.0
280
-	 */
281
-	public static function linkToAbsolute( $app, $file, $args = array() ) {
282
-		$urlGenerator = \OC::$server->getURLGenerator();
283
-		return $urlGenerator->getAbsoluteURL(
284
-			$urlGenerator->linkTo($app, $file, $args)
285
-		);
286
-	}
287
-
288
-	/**
289
-	 * Creates an absolute url for remote use.
290
-	 * @param string $service id
291
-	 * @return string the url
292
-	 * @since 4.0.0
293
-	 */
294
-	public static function linkToRemote( $service ) {
295
-		$urlGenerator = \OC::$server->getURLGenerator();
296
-		$remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
297
-		return $urlGenerator->getAbsoluteURL(
298
-			$remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
299
-		);
300
-	}
301
-
302
-	/**
303
-	 * Creates an absolute url for public use
304
-	 * @param string $service id
305
-	 * @return string the url
306
-	 * @since 4.5.0
307
-	 */
308
-	public static function linkToPublic($service) {
309
-		return \OC_Helper::linkToPublic($service);
310
-	}
311
-
312
-	/**
313
-	 * Creates an url using a defined route
314
-	 * @param string $route
315
-	 * @param array $parameters
316
-	 * @internal param array $args with param=>value, will be appended to the returned url
317
-	 * @return string the url
318
-	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkToRoute($route, $parameters)
319
-	 * @since 5.0.0
320
-	 */
321
-	public static function linkToRoute( $route, $parameters = array() ) {
322
-		return \OC::$server->getURLGenerator()->linkToRoute($route, $parameters);
323
-	}
324
-
325
-	/**
326
-	 * Creates an url to the given app and file
327
-	 * @param string $app app
328
-	 * @param string $file file
329
-	 * @param array $args array with param=>value, will be appended to the returned url
330
-	 * 	The value of $args will be urlencoded
331
-	 * @return string the url
332
-	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkTo($app, $file, $args)
333
-	 * @since 4.0.0 - parameter $args was added in 4.5.0
334
-	 */
335
-	public static function linkTo( $app, $file, $args = array() ) {
336
-		return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
337
-	}
338
-
339
-	/**
340
-	 * Returns the server host, even if the website uses one or more reverse proxy
341
-	 * @return string the server host
342
-	 * @deprecated 8.1.0 Use \OCP\IRequest::getServerHost
343
-	 * @since 4.0.0
344
-	 */
345
-	public static function getServerHost() {
346
-		return \OC::$server->getRequest()->getServerHost();
347
-	}
348
-
349
-	/**
350
-	 * Returns the server host name without an eventual port number
351
-	 * @return string the server hostname
352
-	 * @since 5.0.0
353
-	 */
354
-	public static function getServerHostName() {
355
-		$host_name = \OC::$server->getRequest()->getServerHost();
356
-		// strip away port number (if existing)
357
-		$colon_pos = strpos($host_name, ':');
358
-		if ($colon_pos != FALSE) {
359
-			$host_name = substr($host_name, 0, $colon_pos);
360
-		}
361
-		return $host_name;
362
-	}
363
-
364
-	/**
365
-	 * Returns the default email address
366
-	 * @param string $user_part the user part of the address
367
-	 * @return string the default email address
368
-	 *
369
-	 * Assembles a default email address (using the server hostname
370
-	 * and the given user part, and returns it
371
-	 * Example: when given lostpassword-noreply as $user_part param,
372
-	 *     and is currently accessed via http(s)://example.com/,
373
-	 *     it would return '[email protected]'
374
-	 *
375
-	 * If the configuration value 'mail_from_address' is set in
376
-	 * config.php, this value will override the $user_part that
377
-	 * is passed to this function
378
-	 * @since 5.0.0
379
-	 */
380
-	public static function getDefaultEmailAddress($user_part) {
381
-		$config = \OC::$server->getConfig();
382
-		$user_part = $config->getSystemValue('mail_from_address', $user_part);
383
-		$host_name = self::getServerHostName();
384
-		$host_name = $config->getSystemValue('mail_domain', $host_name);
385
-		$defaultEmailAddress = $user_part.'@'.$host_name;
386
-
387
-		$mailer = \OC::$server->getMailer();
388
-		if ($mailer->validateMailAddress($defaultEmailAddress)) {
389
-			return $defaultEmailAddress;
390
-		}
391
-
392
-		// in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
393
-		return $user_part.'@localhost.localdomain';
394
-	}
395
-
396
-	/**
397
-	 * Returns the server protocol. It respects reverse proxy servers and load balancers
398
-	 * @return string the server protocol
399
-	 * @deprecated 8.1.0 Use \OCP\IRequest::getServerProtocol
400
-	 * @since 4.5.0
401
-	 */
402
-	public static function getServerProtocol() {
403
-		return \OC::$server->getRequest()->getServerProtocol();
404
-	}
405
-
406
-	/**
407
-	 * Returns the request uri, even if the website uses one or more reverse proxies
408
-	 * @return string the request uri
409
-	 * @deprecated 8.1.0 Use \OCP\IRequest::getRequestUri
410
-	 * @since 5.0.0
411
-	 */
412
-	public static function getRequestUri() {
413
-		return \OC::$server->getRequest()->getRequestUri();
414
-	}
415
-
416
-	/**
417
-	 * Returns the script name, even if the website uses one or more reverse proxies
418
-	 * @return string the script name
419
-	 * @deprecated 8.1.0 Use \OCP\IRequest::getScriptName
420
-	 * @since 5.0.0
421
-	 */
422
-	public static function getScriptName() {
423
-		return \OC::$server->getRequest()->getScriptName();
424
-	}
425
-
426
-	/**
427
-	 * Creates path to an image
428
-	 * @param string $app app
429
-	 * @param string $image image name
430
-	 * @return string the url
431
-	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->imagePath($app, $image)
432
-	 * @since 4.0.0
433
-	 */
434
-	public static function imagePath( $app, $image ) {
435
-		return \OC::$server->getURLGenerator()->imagePath($app, $image);
436
-	}
437
-
438
-	/**
439
-	 * Make a human file size (2048 to 2 kB)
440
-	 * @param int $bytes file size in bytes
441
-	 * @return string a human readable file size
442
-	 * @since 4.0.0
443
-	 */
444
-	public static function humanFileSize($bytes) {
445
-		return \OC_Helper::humanFileSize($bytes);
446
-	}
447
-
448
-	/**
449
-	 * Make a computer file size (2 kB to 2048)
450
-	 * @param string $str file size in a fancy format
451
-	 * @return float a file size in bytes
452
-	 *
453
-	 * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
454
-	 * @since 4.0.0
455
-	 */
456
-	public static function computerFileSize($str) {
457
-		return \OC_Helper::computerFileSize($str);
458
-	}
459
-
460
-	/**
461
-	 * connects a function to a hook
462
-	 *
463
-	 * @param string $signalClass class name of emitter
464
-	 * @param string $signalName name of signal
465
-	 * @param string|object $slotClass class name of slot
466
-	 * @param string $slotName name of slot
467
-	 * @return bool
468
-	 *
469
-	 * This function makes it very easy to connect to use hooks.
470
-	 *
471
-	 * TODO: write example
472
-	 * @since 4.0.0
473
-	 */
474
-	static public function connectHook($signalClass, $signalName, $slotClass, $slotName) {
475
-		return \OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName);
476
-	}
477
-
478
-	/**
479
-	 * Emits a signal. To get data from the slot use references!
480
-	 * @param string $signalclass class name of emitter
481
-	 * @param string $signalname name of signal
482
-	 * @param array $params default: array() array with additional data
483
-	 * @return bool true if slots exists or false if not
484
-	 *
485
-	 * TODO: write example
486
-	 * @since 4.0.0
487
-	 */
488
-	static public function emitHook($signalclass, $signalname, $params = array()) {
489
-		return \OC_Hook::emit($signalclass, $signalname, $params);
490
-	}
491
-
492
-	/**
493
-	 * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
494
-	 * multiple OC_Template elements which invoke `callRegister`. If the value
495
-	 * would not be cached these unit-tests would fail.
496
-	 * @var string
497
-	 */
498
-	private static $token = '';
499
-
500
-	/**
501
-	 * Register an get/post call. This is important to prevent CSRF attacks
502
-	 * @since 4.5.0
503
-	 */
504
-	public static function callRegister() {
505
-		if(self::$token === '') {
506
-			self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
507
-		}
508
-		return self::$token;
509
-	}
510
-
511
-	/**
512
-	 * Check an ajax get/post call if the request token is valid. exit if not.
513
-	 * @since 4.5.0
514
-	 * @deprecated 9.0.0 Use annotations based on the app framework.
515
-	 */
516
-	public static function callCheck() {
517
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
518
-			header('Location: '.\OC::$WEBROOT);
519
-			exit();
520
-		}
521
-
522
-		if (!\OC::$server->getRequest()->passesCSRFCheck()) {
523
-			exit();
524
-		}
525
-	}
526
-
527
-	/**
528
-	 * Used to sanitize HTML
529
-	 *
530
-	 * This function is used to sanitize HTML and should be applied on any
531
-	 * string or array of strings before displaying it on a web page.
532
-	 *
533
-	 * @param string|array $value
534
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
535
-	 * @since 4.5.0
536
-	 */
537
-	public static function sanitizeHTML($value) {
538
-		return \OC_Util::sanitizeHTML($value);
539
-	}
540
-
541
-	/**
542
-	 * Public function to encode url parameters
543
-	 *
544
-	 * This function is used to encode path to file before output.
545
-	 * Encoding is done according to RFC 3986 with one exception:
546
-	 * Character '/' is preserved as is.
547
-	 *
548
-	 * @param string $component part of URI to encode
549
-	 * @return string
550
-	 * @since 6.0.0
551
-	 */
552
-	public static function encodePath($component) {
553
-		return \OC_Util::encodePath($component);
554
-	}
555
-
556
-	/**
557
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
558
-	 *
559
-	 * @param array $input The array to work on
560
-	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
561
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
562
-	 * @return array
563
-	 * @since 4.5.0
564
-	 */
565
-	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
566
-		return \OC_Helper::mb_array_change_key_case($input, $case, $encoding);
567
-	}
568
-
569
-	/**
570
-	 * replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
571
-	 *
572
-	 * @param string $string The input string. Opposite to the PHP build-in function does not accept an array.
573
-	 * @param string $replacement The replacement string.
574
-	 * @param int $start If start is positive, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string.
575
-	 * @param int $length Length of the part to be replaced
576
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
577
-	 * @return string
578
-	 * @since 4.5.0
579
-	 * @deprecated 8.2.0 Use substr_replace() instead.
580
-	 */
581
-	public static function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = 'UTF-8') {
582
-		return substr_replace($string, $replacement, $start, $length);
583
-	}
584
-
585
-	/**
586
-	 * Replace all occurrences of the search string with the replacement string
587
-	 *
588
-	 * @param string $search The value being searched for, otherwise known as the needle. String.
589
-	 * @param string $replace The replacement string.
590
-	 * @param string $subject The string or array being searched and replaced on, otherwise known as the haystack.
591
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
592
-	 * @param int $count If passed, this will be set to the number of replacements performed.
593
-	 * @return string
594
-	 * @since 4.5.0
595
-	 * @deprecated 8.2.0 Use str_replace() instead.
596
-	 */
597
-	public static function mb_str_replace($search, $replace, $subject, $encoding = 'UTF-8', &$count = null) {
598
-		return str_replace($search, $replace, $subject, $count);
599
-	}
600
-
601
-	/**
602
-	 * performs a search in a nested array
603
-	 *
604
-	 * @param array $haystack the array to be searched
605
-	 * @param string $needle the search string
606
-	 * @param mixed $index optional, only search this key name
607
-	 * @return mixed the key of the matching field, otherwise false
608
-	 * @since 4.5.0
609
-	 */
610
-	public static function recursiveArraySearch($haystack, $needle, $index = null) {
611
-		return \OC_Helper::recursiveArraySearch($haystack, $needle, $index);
612
-	}
613
-
614
-	/**
615
-	 * calculates the maximum upload size respecting system settings, free space and user quota
616
-	 *
617
-	 * @param string $dir the current folder where the user currently operates
618
-	 * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
619
-	 * @return int number of bytes representing
620
-	 * @since 5.0.0
621
-	 */
622
-	public static function maxUploadFilesize($dir, $free = null) {
623
-		return \OC_Helper::maxUploadFilesize($dir, $free);
624
-	}
625
-
626
-	/**
627
-	 * Calculate free space left within user quota
628
-	 * @param string $dir the current folder where the user currently operates
629
-	 * @return int number of bytes representing
630
-	 * @since 7.0.0
631
-	 */
632
-	public static function freeSpace($dir) {
633
-		return \OC_Helper::freeSpace($dir);
634
-	}
635
-
636
-	/**
637
-	 * Calculate PHP upload limit
638
-	 *
639
-	 * @return int number of bytes representing
640
-	 * @since 7.0.0
641
-	 */
642
-	public static function uploadLimit() {
643
-		return \OC_Helper::uploadLimit();
644
-	}
645
-
646
-	/**
647
-	 * Returns whether the given file name is valid
648
-	 * @param string $file file name to check
649
-	 * @return bool true if the file name is valid, false otherwise
650
-	 * @deprecated 8.1.0 use \OC\Files\View::verifyPath()
651
-	 * @since 7.0.0
652
-	 * @suppress PhanDeprecatedFunction
653
-	 */
654
-	public static function isValidFileName($file) {
655
-		return \OC_Util::isValidFileName($file);
656
-	}
657
-
658
-	/**
659
-	 * Generates a cryptographic secure pseudo-random string
660
-	 * @param int $length of the random string
661
-	 * @return string
662
-	 * @deprecated 8.0.0 Use \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate($length); instead
663
-	 * @since 7.0.0
664
-	 */
665
-	public static function generateRandomBytes($length = 30) {
666
-		return \OC::$server->getSecureRandom()->generate($length, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
667
-	}
668
-
669
-	/**
670
-	 * Compare two strings to provide a natural sort
671
-	 * @param string $a first string to compare
672
-	 * @param string $b second string to compare
673
-	 * @return int -1 if $b comes before $a, 1 if $a comes before $b
674
-	 * or 0 if the strings are identical
675
-	 * @since 7.0.0
676
-	 */
677
-	public static function naturalSortCompare($a, $b) {
678
-		return \OC\NaturalSort::getInstance()->compare($a, $b);
679
-	}
680
-
681
-	/**
682
-	 * check if a password is required for each public link
683
-	 * @return boolean
684
-	 * @since 7.0.0
685
-	 */
686
-	public static function isPublicLinkPasswordRequired() {
687
-		return \OC_Util::isPublicLinkPasswordRequired();
688
-	}
689
-
690
-	/**
691
-	 * check if share API enforces a default expire date
692
-	 * @return boolean
693
-	 * @since 8.0.0
694
-	 */
695
-	public static function isDefaultExpireDateEnforced() {
696
-		return \OC_Util::isDefaultExpireDateEnforced();
697
-	}
698
-
699
-	protected static $needUpgradeCache = null;
700
-
701
-	/**
702
-	 * Checks whether the current version needs upgrade.
703
-	 *
704
-	 * @return bool true if upgrade is needed, false otherwise
705
-	 * @since 7.0.0
706
-	 */
707
-	public static function needUpgrade() {
708
-		if (!isset(self::$needUpgradeCache)) {
709
-			self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getSystemConfig());
710
-		}		
711
-		return self::$needUpgradeCache;
712
-	}
88
+    /**
89
+     * Get current update channel
90
+     * @return string
91
+     * @since 8.1.0
92
+     */
93
+    public static function getChannel() {
94
+        return \OC_Util::getChannel();
95
+    }
96
+
97
+    /**
98
+     * send an email
99
+     * @param string $toaddress
100
+     * @param string $toname
101
+     * @param string $subject
102
+     * @param string $mailtext
103
+     * @param string $fromaddress
104
+     * @param string $fromname
105
+     * @param int $html
106
+     * @param string $altbody
107
+     * @param string $ccaddress
108
+     * @param string $ccname
109
+     * @param string $bcc
110
+     * @deprecated 8.1.0 Use \OCP\Mail\IMailer instead
111
+     * @since 4.0.0
112
+     */
113
+    public static function sendMail($toaddress, $toname, $subject, $mailtext, $fromaddress, $fromname,
114
+        $html = 0, $altbody = '', $ccaddress = '', $ccname = '', $bcc = '') {
115
+        $mailer = \OC::$server->getMailer();
116
+        $message = $mailer->createMessage();
117
+        $message->setTo([$toaddress => $toname]);
118
+        $message->setSubject($subject);
119
+        $message->setPlainBody($mailtext);
120
+        $message->setFrom([$fromaddress => $fromname]);
121
+        if($html === 1) {
122
+            $message->setHtmlBody($altbody);
123
+        }
124
+
125
+        if($altbody === '') {
126
+            $message->setHtmlBody($mailtext);
127
+            $message->setPlainBody('');
128
+        } else {
129
+            $message->setHtmlBody($mailtext);
130
+            $message->setPlainBody($altbody);
131
+        }
132
+
133
+        if(!empty($ccaddress)) {
134
+            if(!empty($ccname)) {
135
+                $message->setCc([$ccaddress => $ccname]);
136
+            } else {
137
+                $message->setCc([$ccaddress]);
138
+            }
139
+        }
140
+        if(!empty($bcc)) {
141
+            $message->setBcc([$bcc]);
142
+        }
143
+
144
+        $mailer->send($message);
145
+    }
146
+
147
+    /**
148
+     * write a message in the log
149
+     * @param string $app
150
+     * @param string $message
151
+     * @param int $level
152
+     * @since 4.0.0
153
+     * @deprecated 13.0.0 use log of \OCP\ILogger
154
+     */
155
+    public static function writeLog( $app, $message, $level ) {
156
+        $context = ['app' => $app];
157
+        \OC::$server->getLogger()->log($level, $message, $context);
158
+    }
159
+
160
+    /**
161
+     * write exception into the log
162
+     * @param string $app app name
163
+     * @param \Exception $ex exception to log
164
+     * @param int $level log level, defaults to \OCP\Util::FATAL
165
+     * @since ....0.0 - parameter $level was added in 7.0.0
166
+     * @deprecated 8.2.0 use logException of \OCP\ILogger
167
+     */
168
+    public static function logException( $app, \Exception $ex, $level = \OCP\Util::FATAL ) {
169
+        \OC::$server->getLogger()->logException($ex, ['app' => $app]);
170
+    }
171
+
172
+    /**
173
+     * check if sharing is disabled for the current user
174
+     *
175
+     * @return boolean
176
+     * @since 7.0.0
177
+     * @deprecated 9.1.0 Use \OC::$server->getShareManager()->sharingDisabledForUser
178
+     */
179
+    public static function isSharingDisabledForUser() {
180
+        if (self::$shareManager === null) {
181
+            self::$shareManager = \OC::$server->getShareManager();
182
+        }
183
+
184
+        $user = \OC::$server->getUserSession()->getUser();
185
+        if ($user !== null) {
186
+            $user = $user->getUID();
187
+        }
188
+
189
+        return self::$shareManager->sharingDisabledForUser($user);
190
+    }
191
+
192
+    /**
193
+     * get l10n object
194
+     * @param string $application
195
+     * @param string|null $language
196
+     * @return \OCP\IL10N
197
+     * @since 6.0.0 - parameter $language was added in 8.0.0
198
+     */
199
+    public static function getL10N($application, $language = null) {
200
+        return \OC::$server->getL10N($application, $language);
201
+    }
202
+
203
+    /**
204
+     * add a css file
205
+     * @param string $application
206
+     * @param string $file
207
+     * @since 4.0.0
208
+     */
209
+    public static function addStyle( $application, $file = null ) {
210
+        \OC_Util::addStyle( $application, $file );
211
+    }
212
+
213
+    /**
214
+     * add a javascript file
215
+     * @param string $application
216
+     * @param string $file
217
+     * @since 4.0.0
218
+     */
219
+    public static function addScript( $application, $file = null ) {
220
+        \OC_Util::addScript( $application, $file );
221
+    }
222
+
223
+    /**
224
+     * Add a translation JS file
225
+     * @param string $application application id
226
+     * @param string $languageCode language code, defaults to the current locale
227
+     * @since 8.0.0
228
+     */
229
+    public static function addTranslations($application, $languageCode = null) {
230
+        \OC_Util::addTranslations($application, $languageCode);
231
+    }
232
+
233
+    /**
234
+     * Add a custom element to the header
235
+     * If $text is null then the element will be written as empty element.
236
+     * So use "" to get a closing tag.
237
+     * @param string $tag tag name of the element
238
+     * @param array $attributes array of attributes for the element
239
+     * @param string $text the text content for the element
240
+     * @since 4.0.0
241
+     */
242
+    public static function addHeader($tag, $attributes, $text=null) {
243
+        \OC_Util::addHeader($tag, $attributes, $text);
244
+    }
245
+
246
+    /**
247
+     * formats a timestamp in the "right" way
248
+     * @param int $timestamp $timestamp
249
+     * @param bool $dateOnly option to omit time from the result
250
+     * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
251
+     * @return string timestamp
252
+     *
253
+     * @deprecated 8.0.0 Use \OC::$server->query('DateTimeFormatter') instead
254
+     * @since 4.0.0
255
+     * @suppress PhanDeprecatedFunction
256
+     */
257
+    public static function formatDate($timestamp, $dateOnly=false, $timeZone = null) {
258
+        return \OC_Util::formatDate($timestamp, $dateOnly, $timeZone);
259
+    }
260
+
261
+    /**
262
+     * check if some encrypted files are stored
263
+     * @return bool
264
+     *
265
+     * @deprecated 8.1.0 No longer required
266
+     * @since 6.0.0
267
+     */
268
+    public static function encryptedFiles() {
269
+        return false;
270
+    }
271
+
272
+    /**
273
+     * Creates an absolute url to the given app and file.
274
+     * @param string $app app
275
+     * @param string $file file
276
+     * @param array $args array with param=>value, will be appended to the returned url
277
+     * 	The value of $args will be urlencoded
278
+     * @return string the url
279
+     * @since 4.0.0 - parameter $args was added in 4.5.0
280
+     */
281
+    public static function linkToAbsolute( $app, $file, $args = array() ) {
282
+        $urlGenerator = \OC::$server->getURLGenerator();
283
+        return $urlGenerator->getAbsoluteURL(
284
+            $urlGenerator->linkTo($app, $file, $args)
285
+        );
286
+    }
287
+
288
+    /**
289
+     * Creates an absolute url for remote use.
290
+     * @param string $service id
291
+     * @return string the url
292
+     * @since 4.0.0
293
+     */
294
+    public static function linkToRemote( $service ) {
295
+        $urlGenerator = \OC::$server->getURLGenerator();
296
+        $remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
297
+        return $urlGenerator->getAbsoluteURL(
298
+            $remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
299
+        );
300
+    }
301
+
302
+    /**
303
+     * Creates an absolute url for public use
304
+     * @param string $service id
305
+     * @return string the url
306
+     * @since 4.5.0
307
+     */
308
+    public static function linkToPublic($service) {
309
+        return \OC_Helper::linkToPublic($service);
310
+    }
311
+
312
+    /**
313
+     * Creates an url using a defined route
314
+     * @param string $route
315
+     * @param array $parameters
316
+     * @internal param array $args with param=>value, will be appended to the returned url
317
+     * @return string the url
318
+     * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkToRoute($route, $parameters)
319
+     * @since 5.0.0
320
+     */
321
+    public static function linkToRoute( $route, $parameters = array() ) {
322
+        return \OC::$server->getURLGenerator()->linkToRoute($route, $parameters);
323
+    }
324
+
325
+    /**
326
+     * Creates an url to the given app and file
327
+     * @param string $app app
328
+     * @param string $file file
329
+     * @param array $args array with param=>value, will be appended to the returned url
330
+     * 	The value of $args will be urlencoded
331
+     * @return string the url
332
+     * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkTo($app, $file, $args)
333
+     * @since 4.0.0 - parameter $args was added in 4.5.0
334
+     */
335
+    public static function linkTo( $app, $file, $args = array() ) {
336
+        return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
337
+    }
338
+
339
+    /**
340
+     * Returns the server host, even if the website uses one or more reverse proxy
341
+     * @return string the server host
342
+     * @deprecated 8.1.0 Use \OCP\IRequest::getServerHost
343
+     * @since 4.0.0
344
+     */
345
+    public static function getServerHost() {
346
+        return \OC::$server->getRequest()->getServerHost();
347
+    }
348
+
349
+    /**
350
+     * Returns the server host name without an eventual port number
351
+     * @return string the server hostname
352
+     * @since 5.0.0
353
+     */
354
+    public static function getServerHostName() {
355
+        $host_name = \OC::$server->getRequest()->getServerHost();
356
+        // strip away port number (if existing)
357
+        $colon_pos = strpos($host_name, ':');
358
+        if ($colon_pos != FALSE) {
359
+            $host_name = substr($host_name, 0, $colon_pos);
360
+        }
361
+        return $host_name;
362
+    }
363
+
364
+    /**
365
+     * Returns the default email address
366
+     * @param string $user_part the user part of the address
367
+     * @return string the default email address
368
+     *
369
+     * Assembles a default email address (using the server hostname
370
+     * and the given user part, and returns it
371
+     * Example: when given lostpassword-noreply as $user_part param,
372
+     *     and is currently accessed via http(s)://example.com/,
373
+     *     it would return '[email protected]'
374
+     *
375
+     * If the configuration value 'mail_from_address' is set in
376
+     * config.php, this value will override the $user_part that
377
+     * is passed to this function
378
+     * @since 5.0.0
379
+     */
380
+    public static function getDefaultEmailAddress($user_part) {
381
+        $config = \OC::$server->getConfig();
382
+        $user_part = $config->getSystemValue('mail_from_address', $user_part);
383
+        $host_name = self::getServerHostName();
384
+        $host_name = $config->getSystemValue('mail_domain', $host_name);
385
+        $defaultEmailAddress = $user_part.'@'.$host_name;
386
+
387
+        $mailer = \OC::$server->getMailer();
388
+        if ($mailer->validateMailAddress($defaultEmailAddress)) {
389
+            return $defaultEmailAddress;
390
+        }
391
+
392
+        // in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
393
+        return $user_part.'@localhost.localdomain';
394
+    }
395
+
396
+    /**
397
+     * Returns the server protocol. It respects reverse proxy servers and load balancers
398
+     * @return string the server protocol
399
+     * @deprecated 8.1.0 Use \OCP\IRequest::getServerProtocol
400
+     * @since 4.5.0
401
+     */
402
+    public static function getServerProtocol() {
403
+        return \OC::$server->getRequest()->getServerProtocol();
404
+    }
405
+
406
+    /**
407
+     * Returns the request uri, even if the website uses one or more reverse proxies
408
+     * @return string the request uri
409
+     * @deprecated 8.1.0 Use \OCP\IRequest::getRequestUri
410
+     * @since 5.0.0
411
+     */
412
+    public static function getRequestUri() {
413
+        return \OC::$server->getRequest()->getRequestUri();
414
+    }
415
+
416
+    /**
417
+     * Returns the script name, even if the website uses one or more reverse proxies
418
+     * @return string the script name
419
+     * @deprecated 8.1.0 Use \OCP\IRequest::getScriptName
420
+     * @since 5.0.0
421
+     */
422
+    public static function getScriptName() {
423
+        return \OC::$server->getRequest()->getScriptName();
424
+    }
425
+
426
+    /**
427
+     * Creates path to an image
428
+     * @param string $app app
429
+     * @param string $image image name
430
+     * @return string the url
431
+     * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->imagePath($app, $image)
432
+     * @since 4.0.0
433
+     */
434
+    public static function imagePath( $app, $image ) {
435
+        return \OC::$server->getURLGenerator()->imagePath($app, $image);
436
+    }
437
+
438
+    /**
439
+     * Make a human file size (2048 to 2 kB)
440
+     * @param int $bytes file size in bytes
441
+     * @return string a human readable file size
442
+     * @since 4.0.0
443
+     */
444
+    public static function humanFileSize($bytes) {
445
+        return \OC_Helper::humanFileSize($bytes);
446
+    }
447
+
448
+    /**
449
+     * Make a computer file size (2 kB to 2048)
450
+     * @param string $str file size in a fancy format
451
+     * @return float a file size in bytes
452
+     *
453
+     * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
454
+     * @since 4.0.0
455
+     */
456
+    public static function computerFileSize($str) {
457
+        return \OC_Helper::computerFileSize($str);
458
+    }
459
+
460
+    /**
461
+     * connects a function to a hook
462
+     *
463
+     * @param string $signalClass class name of emitter
464
+     * @param string $signalName name of signal
465
+     * @param string|object $slotClass class name of slot
466
+     * @param string $slotName name of slot
467
+     * @return bool
468
+     *
469
+     * This function makes it very easy to connect to use hooks.
470
+     *
471
+     * TODO: write example
472
+     * @since 4.0.0
473
+     */
474
+    static public function connectHook($signalClass, $signalName, $slotClass, $slotName) {
475
+        return \OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName);
476
+    }
477
+
478
+    /**
479
+     * Emits a signal. To get data from the slot use references!
480
+     * @param string $signalclass class name of emitter
481
+     * @param string $signalname name of signal
482
+     * @param array $params default: array() array with additional data
483
+     * @return bool true if slots exists or false if not
484
+     *
485
+     * TODO: write example
486
+     * @since 4.0.0
487
+     */
488
+    static public function emitHook($signalclass, $signalname, $params = array()) {
489
+        return \OC_Hook::emit($signalclass, $signalname, $params);
490
+    }
491
+
492
+    /**
493
+     * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
494
+     * multiple OC_Template elements which invoke `callRegister`. If the value
495
+     * would not be cached these unit-tests would fail.
496
+     * @var string
497
+     */
498
+    private static $token = '';
499
+
500
+    /**
501
+     * Register an get/post call. This is important to prevent CSRF attacks
502
+     * @since 4.5.0
503
+     */
504
+    public static function callRegister() {
505
+        if(self::$token === '') {
506
+            self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
507
+        }
508
+        return self::$token;
509
+    }
510
+
511
+    /**
512
+     * Check an ajax get/post call if the request token is valid. exit if not.
513
+     * @since 4.5.0
514
+     * @deprecated 9.0.0 Use annotations based on the app framework.
515
+     */
516
+    public static function callCheck() {
517
+        if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
518
+            header('Location: '.\OC::$WEBROOT);
519
+            exit();
520
+        }
521
+
522
+        if (!\OC::$server->getRequest()->passesCSRFCheck()) {
523
+            exit();
524
+        }
525
+    }
526
+
527
+    /**
528
+     * Used to sanitize HTML
529
+     *
530
+     * This function is used to sanitize HTML and should be applied on any
531
+     * string or array of strings before displaying it on a web page.
532
+     *
533
+     * @param string|array $value
534
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
535
+     * @since 4.5.0
536
+     */
537
+    public static function sanitizeHTML($value) {
538
+        return \OC_Util::sanitizeHTML($value);
539
+    }
540
+
541
+    /**
542
+     * Public function to encode url parameters
543
+     *
544
+     * This function is used to encode path to file before output.
545
+     * Encoding is done according to RFC 3986 with one exception:
546
+     * Character '/' is preserved as is.
547
+     *
548
+     * @param string $component part of URI to encode
549
+     * @return string
550
+     * @since 6.0.0
551
+     */
552
+    public static function encodePath($component) {
553
+        return \OC_Util::encodePath($component);
554
+    }
555
+
556
+    /**
557
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
558
+     *
559
+     * @param array $input The array to work on
560
+     * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
561
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
562
+     * @return array
563
+     * @since 4.5.0
564
+     */
565
+    public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
566
+        return \OC_Helper::mb_array_change_key_case($input, $case, $encoding);
567
+    }
568
+
569
+    /**
570
+     * replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
571
+     *
572
+     * @param string $string The input string. Opposite to the PHP build-in function does not accept an array.
573
+     * @param string $replacement The replacement string.
574
+     * @param int $start If start is positive, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string.
575
+     * @param int $length Length of the part to be replaced
576
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
577
+     * @return string
578
+     * @since 4.5.0
579
+     * @deprecated 8.2.0 Use substr_replace() instead.
580
+     */
581
+    public static function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = 'UTF-8') {
582
+        return substr_replace($string, $replacement, $start, $length);
583
+    }
584
+
585
+    /**
586
+     * Replace all occurrences of the search string with the replacement string
587
+     *
588
+     * @param string $search The value being searched for, otherwise known as the needle. String.
589
+     * @param string $replace The replacement string.
590
+     * @param string $subject The string or array being searched and replaced on, otherwise known as the haystack.
591
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
592
+     * @param int $count If passed, this will be set to the number of replacements performed.
593
+     * @return string
594
+     * @since 4.5.0
595
+     * @deprecated 8.2.0 Use str_replace() instead.
596
+     */
597
+    public static function mb_str_replace($search, $replace, $subject, $encoding = 'UTF-8', &$count = null) {
598
+        return str_replace($search, $replace, $subject, $count);
599
+    }
600
+
601
+    /**
602
+     * performs a search in a nested array
603
+     *
604
+     * @param array $haystack the array to be searched
605
+     * @param string $needle the search string
606
+     * @param mixed $index optional, only search this key name
607
+     * @return mixed the key of the matching field, otherwise false
608
+     * @since 4.5.0
609
+     */
610
+    public static function recursiveArraySearch($haystack, $needle, $index = null) {
611
+        return \OC_Helper::recursiveArraySearch($haystack, $needle, $index);
612
+    }
613
+
614
+    /**
615
+     * calculates the maximum upload size respecting system settings, free space and user quota
616
+     *
617
+     * @param string $dir the current folder where the user currently operates
618
+     * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
619
+     * @return int number of bytes representing
620
+     * @since 5.0.0
621
+     */
622
+    public static function maxUploadFilesize($dir, $free = null) {
623
+        return \OC_Helper::maxUploadFilesize($dir, $free);
624
+    }
625
+
626
+    /**
627
+     * Calculate free space left within user quota
628
+     * @param string $dir the current folder where the user currently operates
629
+     * @return int number of bytes representing
630
+     * @since 7.0.0
631
+     */
632
+    public static function freeSpace($dir) {
633
+        return \OC_Helper::freeSpace($dir);
634
+    }
635
+
636
+    /**
637
+     * Calculate PHP upload limit
638
+     *
639
+     * @return int number of bytes representing
640
+     * @since 7.0.0
641
+     */
642
+    public static function uploadLimit() {
643
+        return \OC_Helper::uploadLimit();
644
+    }
645
+
646
+    /**
647
+     * Returns whether the given file name is valid
648
+     * @param string $file file name to check
649
+     * @return bool true if the file name is valid, false otherwise
650
+     * @deprecated 8.1.0 use \OC\Files\View::verifyPath()
651
+     * @since 7.0.0
652
+     * @suppress PhanDeprecatedFunction
653
+     */
654
+    public static function isValidFileName($file) {
655
+        return \OC_Util::isValidFileName($file);
656
+    }
657
+
658
+    /**
659
+     * Generates a cryptographic secure pseudo-random string
660
+     * @param int $length of the random string
661
+     * @return string
662
+     * @deprecated 8.0.0 Use \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate($length); instead
663
+     * @since 7.0.0
664
+     */
665
+    public static function generateRandomBytes($length = 30) {
666
+        return \OC::$server->getSecureRandom()->generate($length, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
667
+    }
668
+
669
+    /**
670
+     * Compare two strings to provide a natural sort
671
+     * @param string $a first string to compare
672
+     * @param string $b second string to compare
673
+     * @return int -1 if $b comes before $a, 1 if $a comes before $b
674
+     * or 0 if the strings are identical
675
+     * @since 7.0.0
676
+     */
677
+    public static function naturalSortCompare($a, $b) {
678
+        return \OC\NaturalSort::getInstance()->compare($a, $b);
679
+    }
680
+
681
+    /**
682
+     * check if a password is required for each public link
683
+     * @return boolean
684
+     * @since 7.0.0
685
+     */
686
+    public static function isPublicLinkPasswordRequired() {
687
+        return \OC_Util::isPublicLinkPasswordRequired();
688
+    }
689
+
690
+    /**
691
+     * check if share API enforces a default expire date
692
+     * @return boolean
693
+     * @since 8.0.0
694
+     */
695
+    public static function isDefaultExpireDateEnforced() {
696
+        return \OC_Util::isDefaultExpireDateEnforced();
697
+    }
698
+
699
+    protected static $needUpgradeCache = null;
700
+
701
+    /**
702
+     * Checks whether the current version needs upgrade.
703
+     *
704
+     * @return bool true if upgrade is needed, false otherwise
705
+     * @since 7.0.0
706
+     */
707
+    public static function needUpgrade() {
708
+        if (!isset(self::$needUpgradeCache)) {
709
+            self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getSystemConfig());
710
+        }		
711
+        return self::$needUpgradeCache;
712
+    }
713 713
 }
Please login to merge, or discard this patch.
lib/private/Files/View.php 3 patches
Doc Comments   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 	 * and does not take the chroot into account )
201 201
 	 *
202 202
 	 * @param string $path
203
-	 * @return \OCP\Files\Mount\IMountPoint
203
+	 * @return Mount\MountPoint|null
204 204
 	 */
205 205
 	public function getMount($path) {
206 206
 		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
@@ -963,7 +963,7 @@  discard block
 block discarded – undo
963 963
 
964 964
 	/**
965 965
 	 * @param string $path
966
-	 * @return bool|string
966
+	 * @return string|false
967 967
 	 * @throws \OCP\Files\InvalidPathException
968 968
 	 */
969 969
 	public function toTmpFile($path) {
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
 	 * @param string $path
1079 1079
 	 * @param array $hooks (optional)
1080 1080
 	 * @param mixed $extraParam (optional)
1081
-	 * @return mixed
1081
+	 * @return string
1082 1082
 	 * @throws \Exception
1083 1083
 	 *
1084 1084
 	 * This method takes requests for basic filesystem functions (e.g. reading & writing
@@ -2086,7 +2086,7 @@  discard block
 block discarded – undo
2086 2086
 
2087 2087
 	/**
2088 2088
 	 * @param string $filename
2089
-	 * @return array
2089
+	 * @return string[]
2090 2090
 	 * @throws \OC\User\NoUserException
2091 2091
 	 * @throws NotFoundException
2092 2092
 	 */
Please login to merge, or discard this patch.
Spacing   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -128,9 +128,9 @@  discard block
 block discarded – undo
128 128
 			$path = '/';
129 129
 		}
130 130
 		if ($path[0] !== '/') {
131
-			$path = '/' . $path;
131
+			$path = '/'.$path;
132 132
 		}
133
-		return $this->fakeRoot . $path;
133
+		return $this->fakeRoot.$path;
134 134
 	}
135 135
 
136 136
 	/**
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 	public function chroot($fakeRoot) {
143 143
 		if (!$fakeRoot == '') {
144 144
 			if ($fakeRoot[0] !== '/') {
145
-				$fakeRoot = '/' . $fakeRoot;
145
+				$fakeRoot = '/'.$fakeRoot;
146 146
 			}
147 147
 		}
148 148
 		$this->fakeRoot = $fakeRoot;
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
 		}
175 175
 
176 176
 		// missing slashes can cause wrong matches!
177
-		$root = rtrim($this->fakeRoot, '/') . '/';
177
+		$root = rtrim($this->fakeRoot, '/').'/';
178 178
 
179 179
 		if (strpos($path, $root) !== 0) {
180 180
 			return null;
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
 		if ($mount instanceof MoveableMount) {
281 281
 			// cut of /user/files to get the relative path to data/user/files
282 282
 			$pathParts = explode('/', $path, 4);
283
-			$relPath = '/' . $pathParts[3];
283
+			$relPath = '/'.$pathParts[3];
284 284
 			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
285 285
 			\OC_Hook::emit(
286 286
 				Filesystem::CLASSNAME, "umount",
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
 		}
683 683
 		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
684 684
 		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
685
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
685
+		$mount = Filesystem::getMountManager()->find($absolutePath.$postFix);
686 686
 		if ($mount and $mount->getInternalPath($absolutePath) === '') {
687 687
 			return $this->removeMount($mount, $absolutePath);
688 688
 		}
@@ -802,7 +802,7 @@  discard block
 block discarded – undo
802 802
 								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
803 803
 							}
804 804
 						}
805
-					} catch(\Exception $e) {
805
+					} catch (\Exception $e) {
806 806
 						throw $e;
807 807
 					} finally {
808 808
 						$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
@@ -826,7 +826,7 @@  discard block
 block discarded – undo
826 826
 						}
827 827
 					}
828 828
 				}
829
-			} catch(\Exception $e) {
829
+			} catch (\Exception $e) {
830 830
 				throw $e;
831 831
 			} finally {
832 832
 				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
@@ -959,7 +959,7 @@  discard block
 block discarded – undo
959 959
 				$hooks[] = 'write';
960 960
 				break;
961 961
 			default:
962
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
962
+				\OCP\Util::writeLog('core', 'invalid mode ('.$mode.') for '.$path, \OCP\Util::ERROR);
963 963
 		}
964 964
 
965 965
 		if ($mode !== 'r' && $mode !== 'w') {
@@ -1063,7 +1063,7 @@  discard block
 block discarded – undo
1063 1063
 					array(Filesystem::signal_param_path => $this->getHookPath($path))
1064 1064
 				);
1065 1065
 			}
1066
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1066
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1067 1067
 			if ($storage) {
1068 1068
 				$result = $storage->hash($type, $internalPath, $raw);
1069 1069
 				return $result;
@@ -1118,7 +1118,7 @@  discard block
 block discarded – undo
1118 1118
 
1119 1119
 			$run = $this->runHooks($hooks, $path);
1120 1120
 			/** @var \OC\Files\Storage\Storage $storage */
1121
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1121
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1122 1122
 			if ($run and $storage) {
1123 1123
 				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1124 1124
 					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
@@ -1157,7 +1157,7 @@  discard block
 block discarded – undo
1157 1157
 					$unlockLater = true;
1158 1158
 					// make sure our unlocking callback will still be called if connection is aborted
1159 1159
 					ignore_user_abort(true);
1160
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1160
+					$result = CallbackWrapper::wrap($result, null, null, function() use ($hooks, $path) {
1161 1161
 						if (in_array('write', $hooks)) {
1162 1162
 							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1163 1163
 						} else if (in_array('read', $hooks)) {
@@ -1218,7 +1218,7 @@  discard block
 block discarded – undo
1218 1218
 			return true;
1219 1219
 		}
1220 1220
 
1221
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1221
+		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot.'/');
1222 1222
 	}
1223 1223
 
1224 1224
 	/**
@@ -1237,7 +1237,7 @@  discard block
 block discarded – undo
1237 1237
 				if ($hook != 'read') {
1238 1238
 					\OC_Hook::emit(
1239 1239
 						Filesystem::CLASSNAME,
1240
-						$prefix . $hook,
1240
+						$prefix.$hook,
1241 1241
 						array(
1242 1242
 							Filesystem::signal_param_run => &$run,
1243 1243
 							Filesystem::signal_param_path => $path
@@ -1246,7 +1246,7 @@  discard block
 block discarded – undo
1246 1246
 				} elseif (!$post) {
1247 1247
 					\OC_Hook::emit(
1248 1248
 						Filesystem::CLASSNAME,
1249
-						$prefix . $hook,
1249
+						$prefix.$hook,
1250 1250
 						array(
1251 1251
 							Filesystem::signal_param_path => $path
1252 1252
 						)
@@ -1341,7 +1341,7 @@  discard block
 block discarded – undo
1341 1341
 			return $this->getPartFileInfo($path);
1342 1342
 		}
1343 1343
 		$relativePath = $path;
1344
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1344
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1345 1345
 
1346 1346
 		$mount = Filesystem::getMountManager()->find($path);
1347 1347
 		$storage = $mount->getStorage();
@@ -1365,7 +1365,7 @@  discard block
 block discarded – undo
1365 1365
 					//add the sizes of other mount points to the folder
1366 1366
 					$extOnly = ($includeMountPoints === 'ext');
1367 1367
 					$mounts = Filesystem::getMountManager()->findIn($path);
1368
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1368
+					$info->setSubMounts(array_filter($mounts, function(IMountPoint $mount) use ($extOnly) {
1369 1369
 						$subStorage = $mount->getStorage();
1370 1370
 						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1371 1371
 					}));
@@ -1412,12 +1412,12 @@  discard block
 block discarded – undo
1412 1412
 			/**
1413 1413
 			 * @var \OC\Files\FileInfo[] $files
1414 1414
 			 */
1415
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1415
+			$files = array_map(function(ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1416 1416
 				if ($sharingDisabled) {
1417 1417
 					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1418 1418
 				}
1419 1419
 				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1420
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1420
+				return new FileInfo($path.'/'.$content['name'], $storage, $content['path'], $content, $mount, $owner);
1421 1421
 			}, $contents);
1422 1422
 
1423 1423
 			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
@@ -1442,8 +1442,8 @@  discard block
 block discarded – undo
1442 1442
 							// sometimes when the storage is not available it can be any exception
1443 1443
 							\OCP\Util::writeLog(
1444 1444
 								'core',
1445
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1446
-								get_class($e) . ': ' . $e->getMessage(),
1445
+								'Exception while scanning storage "'.$subStorage->getId().'": '.
1446
+								get_class($e).': '.$e->getMessage(),
1447 1447
 								\OCP\Util::ERROR
1448 1448
 							);
1449 1449
 							continue;
@@ -1480,7 +1480,7 @@  discard block
 block discarded – undo
1480 1480
 									break;
1481 1481
 								}
1482 1482
 							}
1483
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1483
+							$rootEntry['path'] = substr(Filesystem::normalizePath($path.'/'.$rootEntry['name']), strlen($user) + 2); // full path without /$user/
1484 1484
 
1485 1485
 							// if sharing was disabled for the user we remove the share permissions
1486 1486
 							if (\OCP\Util::isSharingDisabledForUser()) {
@@ -1488,14 +1488,14 @@  discard block
 block discarded – undo
1488 1488
 							}
1489 1489
 
1490 1490
 							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1491
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1491
+							$files[] = new FileInfo($path.'/'.$rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1492 1492
 						}
1493 1493
 					}
1494 1494
 				}
1495 1495
 			}
1496 1496
 
1497 1497
 			if ($mimetype_filter) {
1498
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1498
+				$files = array_filter($files, function(FileInfo $file) use ($mimetype_filter) {
1499 1499
 					if (strpos($mimetype_filter, '/')) {
1500 1500
 						return $file->getMimetype() === $mimetype_filter;
1501 1501
 					} else {
@@ -1524,7 +1524,7 @@  discard block
 block discarded – undo
1524 1524
 		if ($data instanceof FileInfo) {
1525 1525
 			$data = $data->getData();
1526 1526
 		}
1527
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1527
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1528 1528
 		/**
1529 1529
 		 * @var \OC\Files\Storage\Storage $storage
1530 1530
 		 * @var string $internalPath
@@ -1551,7 +1551,7 @@  discard block
 block discarded – undo
1551 1551
 	 * @return FileInfo[]
1552 1552
 	 */
1553 1553
 	public function search($query) {
1554
-		return $this->searchCommon('search', array('%' . $query . '%'));
1554
+		return $this->searchCommon('search', array('%'.$query.'%'));
1555 1555
 	}
1556 1556
 
1557 1557
 	/**
@@ -1602,10 +1602,10 @@  discard block
 block discarded – undo
1602 1602
 
1603 1603
 			$results = call_user_func_array(array($cache, $method), $args);
1604 1604
 			foreach ($results as $result) {
1605
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1605
+				if (substr($mountPoint.$result['path'], 0, $rootLength + 1) === $this->fakeRoot.'/') {
1606 1606
 					$internalPath = $result['path'];
1607
-					$path = $mountPoint . $result['path'];
1608
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1607
+					$path = $mountPoint.$result['path'];
1608
+					$result['path'] = substr($mountPoint.$result['path'], $rootLength);
1609 1609
 					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1610 1610
 					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1611 1611
 				}
@@ -1623,8 +1623,8 @@  discard block
 block discarded – undo
1623 1623
 					if ($results) {
1624 1624
 						foreach ($results as $result) {
1625 1625
 							$internalPath = $result['path'];
1626
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1627
-							$path = rtrim($mountPoint . $internalPath, '/');
1626
+							$result['path'] = rtrim($relativeMountPoint.$result['path'], '/');
1627
+							$path = rtrim($mountPoint.$internalPath, '/');
1628 1628
 							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1629 1629
 							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1630 1630
 						}
@@ -1645,7 +1645,7 @@  discard block
 block discarded – undo
1645 1645
 	public function getOwner($path) {
1646 1646
 		$info = $this->getFileInfo($path);
1647 1647
 		if (!$info) {
1648
-			throw new NotFoundException($path . ' not found while trying to get owner');
1648
+			throw new NotFoundException($path.' not found while trying to get owner');
1649 1649
 		}
1650 1650
 		return $info->getOwner()->getUID();
1651 1651
 	}
@@ -1679,7 +1679,7 @@  discard block
 block discarded – undo
1679 1679
 	 * @return string
1680 1680
 	 */
1681 1681
 	public function getPath($id) {
1682
-		$id = (int)$id;
1682
+		$id = (int) $id;
1683 1683
 		$manager = Filesystem::getMountManager();
1684 1684
 		$mounts = $manager->findIn($this->fakeRoot);
1685 1685
 		$mounts[] = $manager->find($this->fakeRoot);
@@ -1694,7 +1694,7 @@  discard block
 block discarded – undo
1694 1694
 				$cache = $mount->getStorage()->getCache();
1695 1695
 				$internalPath = $cache->getPathById($id);
1696 1696
 				if (is_string($internalPath)) {
1697
-					$fullPath = $mount->getMountPoint() . $internalPath;
1697
+					$fullPath = $mount->getMountPoint().$internalPath;
1698 1698
 					if (!is_null($path = $this->getRelativePath($fullPath))) {
1699 1699
 						return $path;
1700 1700
 					}
@@ -1737,10 +1737,10 @@  discard block
 block discarded – undo
1737 1737
 		}
1738 1738
 
1739 1739
 		// note: cannot use the view because the target is already locked
1740
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1740
+		$fileId = (int) $targetStorage->getCache()->getId($targetInternalPath);
1741 1741
 		if ($fileId === -1) {
1742 1742
 			// target might not exist, need to check parent instead
1743
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1743
+			$fileId = (int) $targetStorage->getCache()->getId(dirname($targetInternalPath));
1744 1744
 		}
1745 1745
 
1746 1746
 		// check if any of the parents were shared by the current owner (include collections)
@@ -1840,7 +1840,7 @@  discard block
 block discarded – undo
1840 1840
 		$resultPath = '';
1841 1841
 		foreach ($parts as $part) {
1842 1842
 			if ($part) {
1843
-				$resultPath .= '/' . $part;
1843
+				$resultPath .= '/'.$part;
1844 1844
 				$result[] = $resultPath;
1845 1845
 			}
1846 1846
 		}
@@ -2103,16 +2103,16 @@  discard block
 block discarded – undo
2103 2103
 	public function getUidAndFilename($filename) {
2104 2104
 		$info = $this->getFileInfo($filename);
2105 2105
 		if (!$info instanceof \OCP\Files\FileInfo) {
2106
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2106
+			throw new NotFoundException($this->getAbsolutePath($filename).' not found');
2107 2107
 		}
2108 2108
 		$uid = $info->getOwner()->getUID();
2109 2109
 		if ($uid != \OCP\User::getUser()) {
2110 2110
 			Filesystem::initMountPoints($uid);
2111
-			$ownerView = new View('/' . $uid . '/files');
2111
+			$ownerView = new View('/'.$uid.'/files');
2112 2112
 			try {
2113 2113
 				$filename = $ownerView->getPath($info['fileid']);
2114 2114
 			} catch (NotFoundException $e) {
2115
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2115
+				throw new NotFoundException('File with id '.$info['fileid'].' not found for user '.$uid);
2116 2116
 			}
2117 2117
 		}
2118 2118
 		return [$uid, $filename];
@@ -2129,7 +2129,7 @@  discard block
 block discarded – undo
2129 2129
 		$directoryParts = array_filter($directoryParts);
2130 2130
 		foreach ($directoryParts as $key => $part) {
2131 2131
 			$currentPathElements = array_slice($directoryParts, 0, $key);
2132
-			$currentPath = '/' . implode('/', $currentPathElements);
2132
+			$currentPath = '/'.implode('/', $currentPathElements);
2133 2133
 			if ($this->is_file($currentPath)) {
2134 2134
 				return false;
2135 2135
 			}
Please login to merge, or discard this patch.
Indentation   +2078 added lines, -2078 removed lines patch added patch discarded remove patch
@@ -82,2082 +82,2082 @@
 block discarded – undo
82 82
  * \OC\Files\Storage\Storage object
83 83
  */
84 84
 class View {
85
-	/** @var string */
86
-	private $fakeRoot = '';
87
-
88
-	/**
89
-	 * @var \OCP\Lock\ILockingProvider
90
-	 */
91
-	protected $lockingProvider;
92
-
93
-	private $lockingEnabled;
94
-
95
-	private $updaterEnabled = true;
96
-
97
-	/** @var \OC\User\Manager */
98
-	private $userManager;
99
-
100
-	/** @var \OCP\ILogger */
101
-	private $logger;
102
-
103
-	/**
104
-	 * @param string $root
105
-	 * @throws \Exception If $root contains an invalid path
106
-	 */
107
-	public function __construct($root = '') {
108
-		if (is_null($root)) {
109
-			throw new \InvalidArgumentException('Root can\'t be null');
110
-		}
111
-		if (!Filesystem::isValidPath($root)) {
112
-			throw new \Exception();
113
-		}
114
-
115
-		$this->fakeRoot = $root;
116
-		$this->lockingProvider = \OC::$server->getLockingProvider();
117
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
118
-		$this->userManager = \OC::$server->getUserManager();
119
-		$this->logger = \OC::$server->getLogger();
120
-	}
121
-
122
-	public function getAbsolutePath($path = '/') {
123
-		if ($path === null) {
124
-			return null;
125
-		}
126
-		$this->assertPathLength($path);
127
-		if ($path === '') {
128
-			$path = '/';
129
-		}
130
-		if ($path[0] !== '/') {
131
-			$path = '/' . $path;
132
-		}
133
-		return $this->fakeRoot . $path;
134
-	}
135
-
136
-	/**
137
-	 * change the root to a fake root
138
-	 *
139
-	 * @param string $fakeRoot
140
-	 * @return boolean|null
141
-	 */
142
-	public function chroot($fakeRoot) {
143
-		if (!$fakeRoot == '') {
144
-			if ($fakeRoot[0] !== '/') {
145
-				$fakeRoot = '/' . $fakeRoot;
146
-			}
147
-		}
148
-		$this->fakeRoot = $fakeRoot;
149
-	}
150
-
151
-	/**
152
-	 * get the fake root
153
-	 *
154
-	 * @return string
155
-	 */
156
-	public function getRoot() {
157
-		return $this->fakeRoot;
158
-	}
159
-
160
-	/**
161
-	 * get path relative to the root of the view
162
-	 *
163
-	 * @param string $path
164
-	 * @return string
165
-	 */
166
-	public function getRelativePath($path) {
167
-		$this->assertPathLength($path);
168
-		if ($this->fakeRoot == '') {
169
-			return $path;
170
-		}
171
-
172
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
173
-			return '/';
174
-		}
175
-
176
-		// missing slashes can cause wrong matches!
177
-		$root = rtrim($this->fakeRoot, '/') . '/';
178
-
179
-		if (strpos($path, $root) !== 0) {
180
-			return null;
181
-		} else {
182
-			$path = substr($path, strlen($this->fakeRoot));
183
-			if (strlen($path) === 0) {
184
-				return '/';
185
-			} else {
186
-				return $path;
187
-			}
188
-		}
189
-	}
190
-
191
-	/**
192
-	 * get the mountpoint of the storage object for a path
193
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
194
-	 * returned mountpoint is relative to the absolute root of the filesystem
195
-	 * and does not take the chroot into account )
196
-	 *
197
-	 * @param string $path
198
-	 * @return string
199
-	 */
200
-	public function getMountPoint($path) {
201
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
202
-	}
203
-
204
-	/**
205
-	 * get the mountpoint of the storage object for a path
206
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
207
-	 * returned mountpoint is relative to the absolute root of the filesystem
208
-	 * and does not take the chroot into account )
209
-	 *
210
-	 * @param string $path
211
-	 * @return \OCP\Files\Mount\IMountPoint
212
-	 */
213
-	public function getMount($path) {
214
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
215
-	}
216
-
217
-	/**
218
-	 * resolve a path to a storage and internal path
219
-	 *
220
-	 * @param string $path
221
-	 * @return array an array consisting of the storage and the internal path
222
-	 */
223
-	public function resolvePath($path) {
224
-		$a = $this->getAbsolutePath($path);
225
-		$p = Filesystem::normalizePath($a);
226
-		return Filesystem::resolvePath($p);
227
-	}
228
-
229
-	/**
230
-	 * return the path to a local version of the file
231
-	 * we need this because we can't know if a file is stored local or not from
232
-	 * outside the filestorage and for some purposes a local file is needed
233
-	 *
234
-	 * @param string $path
235
-	 * @return string
236
-	 */
237
-	public function getLocalFile($path) {
238
-		$parent = substr($path, 0, strrpos($path, '/'));
239
-		$path = $this->getAbsolutePath($path);
240
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
241
-		if (Filesystem::isValidPath($parent) and $storage) {
242
-			return $storage->getLocalFile($internalPath);
243
-		} else {
244
-			return null;
245
-		}
246
-	}
247
-
248
-	/**
249
-	 * @param string $path
250
-	 * @return string
251
-	 */
252
-	public function getLocalFolder($path) {
253
-		$parent = substr($path, 0, strrpos($path, '/'));
254
-		$path = $this->getAbsolutePath($path);
255
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
256
-		if (Filesystem::isValidPath($parent) and $storage) {
257
-			return $storage->getLocalFolder($internalPath);
258
-		} else {
259
-			return null;
260
-		}
261
-	}
262
-
263
-	/**
264
-	 * the following functions operate with arguments and return values identical
265
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
266
-	 * for \OC\Files\Storage\Storage via basicOperation().
267
-	 */
268
-	public function mkdir($path) {
269
-		return $this->basicOperation('mkdir', $path, array('create', 'write'));
270
-	}
271
-
272
-	/**
273
-	 * remove mount point
274
-	 *
275
-	 * @param \OC\Files\Mount\MoveableMount $mount
276
-	 * @param string $path relative to data/
277
-	 * @return boolean
278
-	 */
279
-	protected function removeMount($mount, $path) {
280
-		if ($mount instanceof MoveableMount) {
281
-			// cut of /user/files to get the relative path to data/user/files
282
-			$pathParts = explode('/', $path, 4);
283
-			$relPath = '/' . $pathParts[3];
284
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
285
-			\OC_Hook::emit(
286
-				Filesystem::CLASSNAME, "umount",
287
-				array(Filesystem::signal_param_path => $relPath)
288
-			);
289
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
290
-			$result = $mount->removeMount();
291
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
292
-			if ($result) {
293
-				\OC_Hook::emit(
294
-					Filesystem::CLASSNAME, "post_umount",
295
-					array(Filesystem::signal_param_path => $relPath)
296
-				);
297
-			}
298
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
299
-			return $result;
300
-		} else {
301
-			// do not allow deleting the storage's root / the mount point
302
-			// because for some storages it might delete the whole contents
303
-			// but isn't supposed to work that way
304
-			return false;
305
-		}
306
-	}
307
-
308
-	public function disableCacheUpdate() {
309
-		$this->updaterEnabled = false;
310
-	}
311
-
312
-	public function enableCacheUpdate() {
313
-		$this->updaterEnabled = true;
314
-	}
315
-
316
-	protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
317
-		if ($this->updaterEnabled) {
318
-			if (is_null($time)) {
319
-				$time = time();
320
-			}
321
-			$storage->getUpdater()->update($internalPath, $time);
322
-		}
323
-	}
324
-
325
-	protected function removeUpdate(Storage $storage, $internalPath) {
326
-		if ($this->updaterEnabled) {
327
-			$storage->getUpdater()->remove($internalPath);
328
-		}
329
-	}
330
-
331
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
332
-		if ($this->updaterEnabled) {
333
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
334
-		}
335
-	}
336
-
337
-	/**
338
-	 * @param string $path
339
-	 * @return bool|mixed
340
-	 */
341
-	public function rmdir($path) {
342
-		$absolutePath = $this->getAbsolutePath($path);
343
-		$mount = Filesystem::getMountManager()->find($absolutePath);
344
-		if ($mount->getInternalPath($absolutePath) === '') {
345
-			return $this->removeMount($mount, $absolutePath);
346
-		}
347
-		if ($this->is_dir($path)) {
348
-			$result = $this->basicOperation('rmdir', $path, array('delete'));
349
-		} else {
350
-			$result = false;
351
-		}
352
-
353
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
354
-			$storage = $mount->getStorage();
355
-			$internalPath = $mount->getInternalPath($absolutePath);
356
-			$storage->getUpdater()->remove($internalPath);
357
-		}
358
-		return $result;
359
-	}
360
-
361
-	/**
362
-	 * @param string $path
363
-	 * @return resource
364
-	 */
365
-	public function opendir($path) {
366
-		return $this->basicOperation('opendir', $path, array('read'));
367
-	}
368
-
369
-	/**
370
-	 * @param string $path
371
-	 * @return bool|mixed
372
-	 */
373
-	public function is_dir($path) {
374
-		if ($path == '/') {
375
-			return true;
376
-		}
377
-		return $this->basicOperation('is_dir', $path);
378
-	}
379
-
380
-	/**
381
-	 * @param string $path
382
-	 * @return bool|mixed
383
-	 */
384
-	public function is_file($path) {
385
-		if ($path == '/') {
386
-			return false;
387
-		}
388
-		return $this->basicOperation('is_file', $path);
389
-	}
390
-
391
-	/**
392
-	 * @param string $path
393
-	 * @return mixed
394
-	 */
395
-	public function stat($path) {
396
-		return $this->basicOperation('stat', $path);
397
-	}
398
-
399
-	/**
400
-	 * @param string $path
401
-	 * @return mixed
402
-	 */
403
-	public function filetype($path) {
404
-		return $this->basicOperation('filetype', $path);
405
-	}
406
-
407
-	/**
408
-	 * @param string $path
409
-	 * @return mixed
410
-	 */
411
-	public function filesize($path) {
412
-		return $this->basicOperation('filesize', $path);
413
-	}
414
-
415
-	/**
416
-	 * @param string $path
417
-	 * @return bool|mixed
418
-	 * @throws \OCP\Files\InvalidPathException
419
-	 */
420
-	public function readfile($path) {
421
-		$this->assertPathLength($path);
422
-		@ob_end_clean();
423
-		$handle = $this->fopen($path, 'rb');
424
-		if ($handle) {
425
-			$chunkSize = 8192; // 8 kB chunks
426
-			while (!feof($handle)) {
427
-				echo fread($handle, $chunkSize);
428
-				flush();
429
-			}
430
-			fclose($handle);
431
-			$size = $this->filesize($path);
432
-			return $size;
433
-		}
434
-		return false;
435
-	}
436
-
437
-	/**
438
-	 * @param string $path
439
-	 * @param int $from
440
-	 * @param int $to
441
-	 * @return bool|mixed
442
-	 * @throws \OCP\Files\InvalidPathException
443
-	 * @throws \OCP\Files\UnseekableException
444
-	 */
445
-	public function readfilePart($path, $from, $to) {
446
-		$this->assertPathLength($path);
447
-		@ob_end_clean();
448
-		$handle = $this->fopen($path, 'rb');
449
-		if ($handle) {
450
-			$chunkSize = 8192; // 8 kB chunks
451
-			$startReading = true;
452
-
453
-			if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
454
-				// forward file handle via chunked fread because fseek seem to have failed
455
-
456
-				$end = $from + 1;
457
-				while (!feof($handle) && ftell($handle) < $end) {
458
-					$len = $from - ftell($handle);
459
-					if ($len > $chunkSize) {
460
-						$len = $chunkSize;
461
-					}
462
-					$result = fread($handle, $len);
463
-
464
-					if ($result === false) {
465
-						$startReading = false;
466
-						break;
467
-					}
468
-				}
469
-			}
470
-
471
-			if ($startReading) {
472
-				$end = $to + 1;
473
-				while (!feof($handle) && ftell($handle) < $end) {
474
-					$len = $end - ftell($handle);
475
-					if ($len > $chunkSize) {
476
-						$len = $chunkSize;
477
-					}
478
-					echo fread($handle, $len);
479
-					flush();
480
-				}
481
-				$size = ftell($handle) - $from;
482
-				return $size;
483
-			}
484
-
485
-			throw new \OCP\Files\UnseekableException('fseek error');
486
-		}
487
-		return false;
488
-	}
489
-
490
-	/**
491
-	 * @param string $path
492
-	 * @return mixed
493
-	 */
494
-	public function isCreatable($path) {
495
-		return $this->basicOperation('isCreatable', $path);
496
-	}
497
-
498
-	/**
499
-	 * @param string $path
500
-	 * @return mixed
501
-	 */
502
-	public function isReadable($path) {
503
-		return $this->basicOperation('isReadable', $path);
504
-	}
505
-
506
-	/**
507
-	 * @param string $path
508
-	 * @return mixed
509
-	 */
510
-	public function isUpdatable($path) {
511
-		return $this->basicOperation('isUpdatable', $path);
512
-	}
513
-
514
-	/**
515
-	 * @param string $path
516
-	 * @return bool|mixed
517
-	 */
518
-	public function isDeletable($path) {
519
-		$absolutePath = $this->getAbsolutePath($path);
520
-		$mount = Filesystem::getMountManager()->find($absolutePath);
521
-		if ($mount->getInternalPath($absolutePath) === '') {
522
-			return $mount instanceof MoveableMount;
523
-		}
524
-		return $this->basicOperation('isDeletable', $path);
525
-	}
526
-
527
-	/**
528
-	 * @param string $path
529
-	 * @return mixed
530
-	 */
531
-	public function isSharable($path) {
532
-		return $this->basicOperation('isSharable', $path);
533
-	}
534
-
535
-	/**
536
-	 * @param string $path
537
-	 * @return bool|mixed
538
-	 */
539
-	public function file_exists($path) {
540
-		if ($path == '/') {
541
-			return true;
542
-		}
543
-		return $this->basicOperation('file_exists', $path);
544
-	}
545
-
546
-	/**
547
-	 * @param string $path
548
-	 * @return mixed
549
-	 */
550
-	public function filemtime($path) {
551
-		return $this->basicOperation('filemtime', $path);
552
-	}
553
-
554
-	/**
555
-	 * @param string $path
556
-	 * @param int|string $mtime
557
-	 * @return bool
558
-	 */
559
-	public function touch($path, $mtime = null) {
560
-		if (!is_null($mtime) and !is_numeric($mtime)) {
561
-			$mtime = strtotime($mtime);
562
-		}
563
-
564
-		$hooks = array('touch');
565
-
566
-		if (!$this->file_exists($path)) {
567
-			$hooks[] = 'create';
568
-			$hooks[] = 'write';
569
-		}
570
-		$result = $this->basicOperation('touch', $path, $hooks, $mtime);
571
-		if (!$result) {
572
-			// If create file fails because of permissions on external storage like SMB folders,
573
-			// check file exists and return false if not.
574
-			if (!$this->file_exists($path)) {
575
-				return false;
576
-			}
577
-			if (is_null($mtime)) {
578
-				$mtime = time();
579
-			}
580
-			//if native touch fails, we emulate it by changing the mtime in the cache
581
-			$this->putFileInfo($path, array('mtime' => floor($mtime)));
582
-		}
583
-		return true;
584
-	}
585
-
586
-	/**
587
-	 * @param string $path
588
-	 * @return mixed
589
-	 */
590
-	public function file_get_contents($path) {
591
-		return $this->basicOperation('file_get_contents', $path, array('read'));
592
-	}
593
-
594
-	/**
595
-	 * @param bool $exists
596
-	 * @param string $path
597
-	 * @param bool $run
598
-	 */
599
-	protected function emit_file_hooks_pre($exists, $path, &$run) {
600
-		if (!$exists) {
601
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
602
-				Filesystem::signal_param_path => $this->getHookPath($path),
603
-				Filesystem::signal_param_run => &$run,
604
-			));
605
-		} else {
606
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
607
-				Filesystem::signal_param_path => $this->getHookPath($path),
608
-				Filesystem::signal_param_run => &$run,
609
-			));
610
-		}
611
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
612
-			Filesystem::signal_param_path => $this->getHookPath($path),
613
-			Filesystem::signal_param_run => &$run,
614
-		));
615
-	}
616
-
617
-	/**
618
-	 * @param bool $exists
619
-	 * @param string $path
620
-	 */
621
-	protected function emit_file_hooks_post($exists, $path) {
622
-		if (!$exists) {
623
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
624
-				Filesystem::signal_param_path => $this->getHookPath($path),
625
-			));
626
-		} else {
627
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
628
-				Filesystem::signal_param_path => $this->getHookPath($path),
629
-			));
630
-		}
631
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
632
-			Filesystem::signal_param_path => $this->getHookPath($path),
633
-		));
634
-	}
635
-
636
-	/**
637
-	 * @param string $path
638
-	 * @param mixed $data
639
-	 * @return bool|mixed
640
-	 * @throws \Exception
641
-	 */
642
-	public function file_put_contents($path, $data) {
643
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
644
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
645
-			if (Filesystem::isValidPath($path)
646
-				and !Filesystem::isFileBlacklisted($path)
647
-			) {
648
-				$path = $this->getRelativePath($absolutePath);
649
-
650
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
651
-
652
-				$exists = $this->file_exists($path);
653
-				$run = true;
654
-				if ($this->shouldEmitHooks($path)) {
655
-					$this->emit_file_hooks_pre($exists, $path, $run);
656
-				}
657
-				if (!$run) {
658
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
659
-					return false;
660
-				}
661
-
662
-				$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
663
-
664
-				/** @var \OC\Files\Storage\Storage $storage */
665
-				list($storage, $internalPath) = $this->resolvePath($path);
666
-				$target = $storage->fopen($internalPath, 'w');
667
-				if ($target) {
668
-					list (, $result) = \OC_Helper::streamCopy($data, $target);
669
-					fclose($target);
670
-					fclose($data);
671
-
672
-					$this->writeUpdate($storage, $internalPath);
673
-
674
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
675
-
676
-					if ($this->shouldEmitHooks($path) && $result !== false) {
677
-						$this->emit_file_hooks_post($exists, $path);
678
-					}
679
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
680
-					return $result;
681
-				} else {
682
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
683
-					return false;
684
-				}
685
-			} else {
686
-				return false;
687
-			}
688
-		} else {
689
-			$hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
690
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
691
-		}
692
-	}
693
-
694
-	/**
695
-	 * @param string $path
696
-	 * @return bool|mixed
697
-	 */
698
-	public function unlink($path) {
699
-		if ($path === '' || $path === '/') {
700
-			// do not allow deleting the root
701
-			return false;
702
-		}
703
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
704
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
705
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
706
-		if ($mount and $mount->getInternalPath($absolutePath) === '') {
707
-			return $this->removeMount($mount, $absolutePath);
708
-		}
709
-		if ($this->is_dir($path)) {
710
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
711
-		} else {
712
-			$result = $this->basicOperation('unlink', $path, ['delete']);
713
-		}
714
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
715
-			$storage = $mount->getStorage();
716
-			$internalPath = $mount->getInternalPath($absolutePath);
717
-			$storage->getUpdater()->remove($internalPath);
718
-			return true;
719
-		} else {
720
-			return $result;
721
-		}
722
-	}
723
-
724
-	/**
725
-	 * @param string $directory
726
-	 * @return bool|mixed
727
-	 */
728
-	public function deleteAll($directory) {
729
-		return $this->rmdir($directory);
730
-	}
731
-
732
-	/**
733
-	 * Rename/move a file or folder from the source path to target path.
734
-	 *
735
-	 * @param string $path1 source path
736
-	 * @param string $path2 target path
737
-	 *
738
-	 * @return bool|mixed
739
-	 */
740
-	public function rename($path1, $path2) {
741
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
742
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
743
-		$result = false;
744
-		if (
745
-			Filesystem::isValidPath($path2)
746
-			and Filesystem::isValidPath($path1)
747
-			and !Filesystem::isFileBlacklisted($path2)
748
-		) {
749
-			$path1 = $this->getRelativePath($absolutePath1);
750
-			$path2 = $this->getRelativePath($absolutePath2);
751
-			$exists = $this->file_exists($path2);
752
-
753
-			if ($path1 == null or $path2 == null) {
754
-				return false;
755
-			}
756
-
757
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
758
-			try {
759
-				$this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
760
-
761
-				$run = true;
762
-				if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
763
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
764
-					$this->emit_file_hooks_pre($exists, $path2, $run);
765
-				} elseif ($this->shouldEmitHooks($path1)) {
766
-					\OC_Hook::emit(
767
-						Filesystem::CLASSNAME, Filesystem::signal_rename,
768
-						array(
769
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
770
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
771
-							Filesystem::signal_param_run => &$run
772
-						)
773
-					);
774
-				}
775
-				if ($run) {
776
-					$this->verifyPath(dirname($path2), basename($path2));
777
-
778
-					$manager = Filesystem::getMountManager();
779
-					$mount1 = $this->getMount($path1);
780
-					$mount2 = $this->getMount($path2);
781
-					$storage1 = $mount1->getStorage();
782
-					$storage2 = $mount2->getStorage();
783
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
784
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
785
-
786
-					$this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
787
-					try {
788
-						$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
789
-
790
-						if ($internalPath1 === '') {
791
-							if ($mount1 instanceof MoveableMount) {
792
-								if ($this->isTargetAllowed($absolutePath2)) {
793
-									/**
794
-									 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
795
-									 */
796
-									$sourceMountPoint = $mount1->getMountPoint();
797
-									$result = $mount1->moveMount($absolutePath2);
798
-									$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
799
-								} else {
800
-									$result = false;
801
-								}
802
-							} else {
803
-								$result = false;
804
-							}
805
-							// moving a file/folder within the same mount point
806
-						} elseif ($storage1 === $storage2) {
807
-							if ($storage1) {
808
-								$result = $storage1->rename($internalPath1, $internalPath2);
809
-							} else {
810
-								$result = false;
811
-							}
812
-							// moving a file/folder between storages (from $storage1 to $storage2)
813
-						} else {
814
-							$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
815
-						}
816
-
817
-						if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
818
-							// if it was a rename from a part file to a regular file it was a write and not a rename operation
819
-							$this->writeUpdate($storage2, $internalPath2);
820
-						} else if ($result) {
821
-							if ($internalPath1 !== '') { // don't do a cache update for moved mounts
822
-								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
823
-							}
824
-						}
825
-					} catch(\Exception $e) {
826
-						throw $e;
827
-					} finally {
828
-						$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
829
-						$this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
830
-					}
831
-
832
-					if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
833
-						if ($this->shouldEmitHooks()) {
834
-							$this->emit_file_hooks_post($exists, $path2);
835
-						}
836
-					} elseif ($result) {
837
-						if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
838
-							\OC_Hook::emit(
839
-								Filesystem::CLASSNAME,
840
-								Filesystem::signal_post_rename,
841
-								array(
842
-									Filesystem::signal_param_oldpath => $this->getHookPath($path1),
843
-									Filesystem::signal_param_newpath => $this->getHookPath($path2)
844
-								)
845
-							);
846
-						}
847
-					}
848
-				}
849
-			} catch(\Exception $e) {
850
-				throw $e;
851
-			} finally {
852
-				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
853
-				$this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
854
-			}
855
-		}
856
-		return $result;
857
-	}
858
-
859
-	/**
860
-	 * Copy a file/folder from the source path to target path
861
-	 *
862
-	 * @param string $path1 source path
863
-	 * @param string $path2 target path
864
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
865
-	 *
866
-	 * @return bool|mixed
867
-	 */
868
-	public function copy($path1, $path2, $preserveMtime = false) {
869
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
870
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
871
-		$result = false;
872
-		if (
873
-			Filesystem::isValidPath($path2)
874
-			and Filesystem::isValidPath($path1)
875
-			and !Filesystem::isFileBlacklisted($path2)
876
-		) {
877
-			$path1 = $this->getRelativePath($absolutePath1);
878
-			$path2 = $this->getRelativePath($absolutePath2);
879
-
880
-			if ($path1 == null or $path2 == null) {
881
-				return false;
882
-			}
883
-			$run = true;
884
-
885
-			$this->lockFile($path2, ILockingProvider::LOCK_SHARED);
886
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED);
887
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
888
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
889
-
890
-			try {
891
-
892
-				$exists = $this->file_exists($path2);
893
-				if ($this->shouldEmitHooks()) {
894
-					\OC_Hook::emit(
895
-						Filesystem::CLASSNAME,
896
-						Filesystem::signal_copy,
897
-						array(
898
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
899
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
900
-							Filesystem::signal_param_run => &$run
901
-						)
902
-					);
903
-					$this->emit_file_hooks_pre($exists, $path2, $run);
904
-				}
905
-				if ($run) {
906
-					$mount1 = $this->getMount($path1);
907
-					$mount2 = $this->getMount($path2);
908
-					$storage1 = $mount1->getStorage();
909
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
910
-					$storage2 = $mount2->getStorage();
911
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
912
-
913
-					$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
914
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
915
-
916
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
917
-						if ($storage1) {
918
-							$result = $storage1->copy($internalPath1, $internalPath2);
919
-						} else {
920
-							$result = false;
921
-						}
922
-					} else {
923
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
924
-					}
925
-
926
-					$this->writeUpdate($storage2, $internalPath2);
927
-
928
-					$this->changeLock($path2, ILockingProvider::LOCK_SHARED);
929
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
930
-
931
-					if ($this->shouldEmitHooks() && $result !== false) {
932
-						\OC_Hook::emit(
933
-							Filesystem::CLASSNAME,
934
-							Filesystem::signal_post_copy,
935
-							array(
936
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
937
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
938
-							)
939
-						);
940
-						$this->emit_file_hooks_post($exists, $path2);
941
-					}
942
-
943
-				}
944
-			} catch (\Exception $e) {
945
-				$this->unlockFile($path2, $lockTypePath2);
946
-				$this->unlockFile($path1, $lockTypePath1);
947
-				throw $e;
948
-			}
949
-
950
-			$this->unlockFile($path2, $lockTypePath2);
951
-			$this->unlockFile($path1, $lockTypePath1);
952
-
953
-		}
954
-		return $result;
955
-	}
956
-
957
-	/**
958
-	 * @param string $path
959
-	 * @param string $mode 'r' or 'w'
960
-	 * @return resource
961
-	 */
962
-	public function fopen($path, $mode) {
963
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
964
-		$hooks = array();
965
-		switch ($mode) {
966
-			case 'r':
967
-				$hooks[] = 'read';
968
-				break;
969
-			case 'r+':
970
-			case 'w+':
971
-			case 'x+':
972
-			case 'a+':
973
-				$hooks[] = 'read';
974
-				$hooks[] = 'write';
975
-				break;
976
-			case 'w':
977
-			case 'x':
978
-			case 'a':
979
-				$hooks[] = 'write';
980
-				break;
981
-			default:
982
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
983
-		}
984
-
985
-		if ($mode !== 'r' && $mode !== 'w') {
986
-			\OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
987
-		}
988
-
989
-		return $this->basicOperation('fopen', $path, $hooks, $mode);
990
-	}
991
-
992
-	/**
993
-	 * @param string $path
994
-	 * @return bool|string
995
-	 * @throws \OCP\Files\InvalidPathException
996
-	 */
997
-	public function toTmpFile($path) {
998
-		$this->assertPathLength($path);
999
-		if (Filesystem::isValidPath($path)) {
1000
-			$source = $this->fopen($path, 'r');
1001
-			if ($source) {
1002
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
1003
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1004
-				file_put_contents($tmpFile, $source);
1005
-				return $tmpFile;
1006
-			} else {
1007
-				return false;
1008
-			}
1009
-		} else {
1010
-			return false;
1011
-		}
1012
-	}
1013
-
1014
-	/**
1015
-	 * @param string $tmpFile
1016
-	 * @param string $path
1017
-	 * @return bool|mixed
1018
-	 * @throws \OCP\Files\InvalidPathException
1019
-	 */
1020
-	public function fromTmpFile($tmpFile, $path) {
1021
-		$this->assertPathLength($path);
1022
-		if (Filesystem::isValidPath($path)) {
1023
-
1024
-			// Get directory that the file is going into
1025
-			$filePath = dirname($path);
1026
-
1027
-			// Create the directories if any
1028
-			if (!$this->file_exists($filePath)) {
1029
-				$result = $this->createParentDirectories($filePath);
1030
-				if ($result === false) {
1031
-					return false;
1032
-				}
1033
-			}
1034
-
1035
-			$source = fopen($tmpFile, 'r');
1036
-			if ($source) {
1037
-				$result = $this->file_put_contents($path, $source);
1038
-				// $this->file_put_contents() might have already closed
1039
-				// the resource, so we check it, before trying to close it
1040
-				// to avoid messages in the error log.
1041
-				if (is_resource($source)) {
1042
-					fclose($source);
1043
-				}
1044
-				unlink($tmpFile);
1045
-				return $result;
1046
-			} else {
1047
-				return false;
1048
-			}
1049
-		} else {
1050
-			return false;
1051
-		}
1052
-	}
1053
-
1054
-
1055
-	/**
1056
-	 * @param string $path
1057
-	 * @return mixed
1058
-	 * @throws \OCP\Files\InvalidPathException
1059
-	 */
1060
-	public function getMimeType($path) {
1061
-		$this->assertPathLength($path);
1062
-		return $this->basicOperation('getMimeType', $path);
1063
-	}
1064
-
1065
-	/**
1066
-	 * @param string $type
1067
-	 * @param string $path
1068
-	 * @param bool $raw
1069
-	 * @return bool|null|string
1070
-	 */
1071
-	public function hash($type, $path, $raw = false) {
1072
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1073
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1074
-		if (Filesystem::isValidPath($path)) {
1075
-			$path = $this->getRelativePath($absolutePath);
1076
-			if ($path == null) {
1077
-				return false;
1078
-			}
1079
-			if ($this->shouldEmitHooks($path)) {
1080
-				\OC_Hook::emit(
1081
-					Filesystem::CLASSNAME,
1082
-					Filesystem::signal_read,
1083
-					array(Filesystem::signal_param_path => $this->getHookPath($path))
1084
-				);
1085
-			}
1086
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1087
-			if ($storage) {
1088
-				$result = $storage->hash($type, $internalPath, $raw);
1089
-				return $result;
1090
-			}
1091
-		}
1092
-		return null;
1093
-	}
1094
-
1095
-	/**
1096
-	 * @param string $path
1097
-	 * @return mixed
1098
-	 * @throws \OCP\Files\InvalidPathException
1099
-	 */
1100
-	public function free_space($path = '/') {
1101
-		$this->assertPathLength($path);
1102
-		$result = $this->basicOperation('free_space', $path);
1103
-		if ($result === null) {
1104
-			throw new InvalidPathException();
1105
-		}
1106
-		return $result;
1107
-	}
1108
-
1109
-	/**
1110
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1111
-	 *
1112
-	 * @param string $operation
1113
-	 * @param string $path
1114
-	 * @param array $hooks (optional)
1115
-	 * @param mixed $extraParam (optional)
1116
-	 * @return mixed
1117
-	 * @throws \Exception
1118
-	 *
1119
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1120
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1121
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1122
-	 */
1123
-	private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1124
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1125
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1126
-		if (Filesystem::isValidPath($path)
1127
-			and !Filesystem::isFileBlacklisted($path)
1128
-		) {
1129
-			$path = $this->getRelativePath($absolutePath);
1130
-			if ($path == null) {
1131
-				return false;
1132
-			}
1133
-
1134
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1135
-				// always a shared lock during pre-hooks so the hook can read the file
1136
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1137
-			}
1138
-
1139
-			$run = $this->runHooks($hooks, $path);
1140
-			/** @var \OC\Files\Storage\Storage $storage */
1141
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1142
-			if ($run and $storage) {
1143
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1144
-					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1145
-				}
1146
-				try {
1147
-					if (!is_null($extraParam)) {
1148
-						$result = $storage->$operation($internalPath, $extraParam);
1149
-					} else {
1150
-						$result = $storage->$operation($internalPath);
1151
-					}
1152
-				} catch (\Exception $e) {
1153
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1154
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1155
-					} else if (in_array('read', $hooks)) {
1156
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1157
-					}
1158
-					throw $e;
1159
-				}
1160
-
1161
-				if ($result && in_array('delete', $hooks) and $result) {
1162
-					$this->removeUpdate($storage, $internalPath);
1163
-				}
1164
-				if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1165
-					$this->writeUpdate($storage, $internalPath);
1166
-				}
1167
-				if ($result && in_array('touch', $hooks)) {
1168
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1169
-				}
1170
-
1171
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1172
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1173
-				}
1174
-
1175
-				$unlockLater = false;
1176
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1177
-					$unlockLater = true;
1178
-					// make sure our unlocking callback will still be called if connection is aborted
1179
-					ignore_user_abort(true);
1180
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1181
-						if (in_array('write', $hooks)) {
1182
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1183
-						} else if (in_array('read', $hooks)) {
1184
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1185
-						}
1186
-					});
1187
-				}
1188
-
1189
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1190
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1191
-						$this->runHooks($hooks, $path, true);
1192
-					}
1193
-				}
1194
-
1195
-				if (!$unlockLater
1196
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1197
-				) {
1198
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1199
-				}
1200
-				return $result;
1201
-			} else {
1202
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1203
-			}
1204
-		}
1205
-		return null;
1206
-	}
1207
-
1208
-	/**
1209
-	 * get the path relative to the default root for hook usage
1210
-	 *
1211
-	 * @param string $path
1212
-	 * @return string
1213
-	 */
1214
-	private function getHookPath($path) {
1215
-		if (!Filesystem::getView()) {
1216
-			return $path;
1217
-		}
1218
-		return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1219
-	}
1220
-
1221
-	private function shouldEmitHooks($path = '') {
1222
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1223
-			return false;
1224
-		}
1225
-		if (!Filesystem::$loaded) {
1226
-			return false;
1227
-		}
1228
-		$defaultRoot = Filesystem::getRoot();
1229
-		if ($defaultRoot === null) {
1230
-			return false;
1231
-		}
1232
-		if ($this->fakeRoot === $defaultRoot) {
1233
-			return true;
1234
-		}
1235
-		$fullPath = $this->getAbsolutePath($path);
1236
-
1237
-		if ($fullPath === $defaultRoot) {
1238
-			return true;
1239
-		}
1240
-
1241
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1242
-	}
1243
-
1244
-	/**
1245
-	 * @param string[] $hooks
1246
-	 * @param string $path
1247
-	 * @param bool $post
1248
-	 * @return bool
1249
-	 */
1250
-	private function runHooks($hooks, $path, $post = false) {
1251
-		$relativePath = $path;
1252
-		$path = $this->getHookPath($path);
1253
-		$prefix = ($post) ? 'post_' : '';
1254
-		$run = true;
1255
-		if ($this->shouldEmitHooks($relativePath)) {
1256
-			foreach ($hooks as $hook) {
1257
-				if ($hook != 'read') {
1258
-					\OC_Hook::emit(
1259
-						Filesystem::CLASSNAME,
1260
-						$prefix . $hook,
1261
-						array(
1262
-							Filesystem::signal_param_run => &$run,
1263
-							Filesystem::signal_param_path => $path
1264
-						)
1265
-					);
1266
-				} elseif (!$post) {
1267
-					\OC_Hook::emit(
1268
-						Filesystem::CLASSNAME,
1269
-						$prefix . $hook,
1270
-						array(
1271
-							Filesystem::signal_param_path => $path
1272
-						)
1273
-					);
1274
-				}
1275
-			}
1276
-		}
1277
-		return $run;
1278
-	}
1279
-
1280
-	/**
1281
-	 * check if a file or folder has been updated since $time
1282
-	 *
1283
-	 * @param string $path
1284
-	 * @param int $time
1285
-	 * @return bool
1286
-	 */
1287
-	public function hasUpdated($path, $time) {
1288
-		return $this->basicOperation('hasUpdated', $path, array(), $time);
1289
-	}
1290
-
1291
-	/**
1292
-	 * @param string $ownerId
1293
-	 * @return \OC\User\User
1294
-	 */
1295
-	private function getUserObjectForOwner($ownerId) {
1296
-		$owner = $this->userManager->get($ownerId);
1297
-		if ($owner instanceof IUser) {
1298
-			return $owner;
1299
-		} else {
1300
-			return new User($ownerId, null);
1301
-		}
1302
-	}
1303
-
1304
-	/**
1305
-	 * Get file info from cache
1306
-	 *
1307
-	 * If the file is not in cached it will be scanned
1308
-	 * If the file has changed on storage the cache will be updated
1309
-	 *
1310
-	 * @param \OC\Files\Storage\Storage $storage
1311
-	 * @param string $internalPath
1312
-	 * @param string $relativePath
1313
-	 * @return ICacheEntry|bool
1314
-	 */
1315
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1316
-		$cache = $storage->getCache($internalPath);
1317
-		$data = $cache->get($internalPath);
1318
-		$watcher = $storage->getWatcher($internalPath);
1319
-
1320
-		try {
1321
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1322
-			if (!$data || $data['size'] === -1) {
1323
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1324
-				if (!$storage->file_exists($internalPath)) {
1325
-					$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1326
-					return false;
1327
-				}
1328
-				$scanner = $storage->getScanner($internalPath);
1329
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1330
-				$data = $cache->get($internalPath);
1331
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1332
-			} else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1333
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1334
-				$watcher->update($internalPath, $data);
1335
-				$storage->getPropagator()->propagateChange($internalPath, time());
1336
-				$data = $cache->get($internalPath);
1337
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1338
-			}
1339
-		} catch (LockedException $e) {
1340
-			// if the file is locked we just use the old cache info
1341
-		}
1342
-
1343
-		return $data;
1344
-	}
1345
-
1346
-	/**
1347
-	 * get the filesystem info
1348
-	 *
1349
-	 * @param string $path
1350
-	 * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1351
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1352
-	 * defaults to true
1353
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1354
-	 */
1355
-	public function getFileInfo($path, $includeMountPoints = true) {
1356
-		$this->assertPathLength($path);
1357
-		if (!Filesystem::isValidPath($path)) {
1358
-			return false;
1359
-		}
1360
-		if (Cache\Scanner::isPartialFile($path)) {
1361
-			return $this->getPartFileInfo($path);
1362
-		}
1363
-		$relativePath = $path;
1364
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1365
-
1366
-		$mount = Filesystem::getMountManager()->find($path);
1367
-		$storage = $mount->getStorage();
1368
-		$internalPath = $mount->getInternalPath($path);
1369
-		if ($storage) {
1370
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1371
-
1372
-			if (!$data instanceof ICacheEntry) {
1373
-				return false;
1374
-			}
1375
-
1376
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1377
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1378
-			}
1379
-
1380
-			$owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1381
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1382
-
1383
-			if ($data and isset($data['fileid'])) {
1384
-				if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1385
-					//add the sizes of other mount points to the folder
1386
-					$extOnly = ($includeMountPoints === 'ext');
1387
-					$mounts = Filesystem::getMountManager()->findIn($path);
1388
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1389
-						$subStorage = $mount->getStorage();
1390
-						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1391
-					}));
1392
-				}
1393
-			}
1394
-
1395
-			return $info;
1396
-		}
1397
-
1398
-		return false;
1399
-	}
1400
-
1401
-	/**
1402
-	 * get the content of a directory
1403
-	 *
1404
-	 * @param string $directory path under datadirectory
1405
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1406
-	 * @return FileInfo[]
1407
-	 */
1408
-	public function getDirectoryContent($directory, $mimetype_filter = '') {
1409
-		$this->assertPathLength($directory);
1410
-		if (!Filesystem::isValidPath($directory)) {
1411
-			return [];
1412
-		}
1413
-		$path = $this->getAbsolutePath($directory);
1414
-		$path = Filesystem::normalizePath($path);
1415
-		$mount = $this->getMount($directory);
1416
-		$storage = $mount->getStorage();
1417
-		$internalPath = $mount->getInternalPath($path);
1418
-		if ($storage) {
1419
-			$cache = $storage->getCache($internalPath);
1420
-			$user = \OC_User::getUser();
1421
-
1422
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1423
-
1424
-			if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1425
-				return [];
1426
-			}
1427
-
1428
-			$folderId = $data['fileid'];
1429
-			$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1430
-
1431
-			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1432
-			/**
1433
-			 * @var \OC\Files\FileInfo[] $files
1434
-			 */
1435
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1436
-				if ($sharingDisabled) {
1437
-					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1438
-				}
1439
-				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1440
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1441
-			}, $contents);
1442
-
1443
-			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1444
-			$mounts = Filesystem::getMountManager()->findIn($path);
1445
-			$dirLength = strlen($path);
1446
-			foreach ($mounts as $mount) {
1447
-				$mountPoint = $mount->getMountPoint();
1448
-				$subStorage = $mount->getStorage();
1449
-				if ($subStorage) {
1450
-					$subCache = $subStorage->getCache('');
1451
-
1452
-					$rootEntry = $subCache->get('');
1453
-					if (!$rootEntry) {
1454
-						$subScanner = $subStorage->getScanner('');
1455
-						try {
1456
-							$subScanner->scanFile('');
1457
-						} catch (\OCP\Files\StorageNotAvailableException $e) {
1458
-							continue;
1459
-						} catch (\OCP\Files\StorageInvalidException $e) {
1460
-							continue;
1461
-						} catch (\Exception $e) {
1462
-							// sometimes when the storage is not available it can be any exception
1463
-							\OCP\Util::writeLog(
1464
-								'core',
1465
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1466
-								get_class($e) . ': ' . $e->getMessage(),
1467
-								\OCP\Util::ERROR
1468
-							);
1469
-							continue;
1470
-						}
1471
-						$rootEntry = $subCache->get('');
1472
-					}
1473
-
1474
-					if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1475
-						$relativePath = trim(substr($mountPoint, $dirLength), '/');
1476
-						if ($pos = strpos($relativePath, '/')) {
1477
-							//mountpoint inside subfolder add size to the correct folder
1478
-							$entryName = substr($relativePath, 0, $pos);
1479
-							foreach ($files as &$entry) {
1480
-								if ($entry->getName() === $entryName) {
1481
-									$entry->addSubEntry($rootEntry, $mountPoint);
1482
-								}
1483
-							}
1484
-						} else { //mountpoint in this folder, add an entry for it
1485
-							$rootEntry['name'] = $relativePath;
1486
-							$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1487
-							$permissions = $rootEntry['permissions'];
1488
-							// do not allow renaming/deleting the mount point if they are not shared files/folders
1489
-							// for shared files/folders we use the permissions given by the owner
1490
-							if ($mount instanceof MoveableMount) {
1491
-								$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1492
-							} else {
1493
-								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1494
-							}
1495
-
1496
-							//remove any existing entry with the same name
1497
-							foreach ($files as $i => $file) {
1498
-								if ($file['name'] === $rootEntry['name']) {
1499
-									unset($files[$i]);
1500
-									break;
1501
-								}
1502
-							}
1503
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1504
-
1505
-							// if sharing was disabled for the user we remove the share permissions
1506
-							if (\OCP\Util::isSharingDisabledForUser()) {
1507
-								$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1508
-							}
1509
-
1510
-							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1511
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1512
-						}
1513
-					}
1514
-				}
1515
-			}
1516
-
1517
-			if ($mimetype_filter) {
1518
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1519
-					if (strpos($mimetype_filter, '/')) {
1520
-						return $file->getMimetype() === $mimetype_filter;
1521
-					} else {
1522
-						return $file->getMimePart() === $mimetype_filter;
1523
-					}
1524
-				});
1525
-			}
1526
-
1527
-			return $files;
1528
-		} else {
1529
-			return [];
1530
-		}
1531
-	}
1532
-
1533
-	/**
1534
-	 * change file metadata
1535
-	 *
1536
-	 * @param string $path
1537
-	 * @param array|\OCP\Files\FileInfo $data
1538
-	 * @return int
1539
-	 *
1540
-	 * returns the fileid of the updated file
1541
-	 */
1542
-	public function putFileInfo($path, $data) {
1543
-		$this->assertPathLength($path);
1544
-		if ($data instanceof FileInfo) {
1545
-			$data = $data->getData();
1546
-		}
1547
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1548
-		/**
1549
-		 * @var \OC\Files\Storage\Storage $storage
1550
-		 * @var string $internalPath
1551
-		 */
1552
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
1553
-		if ($storage) {
1554
-			$cache = $storage->getCache($path);
1555
-
1556
-			if (!$cache->inCache($internalPath)) {
1557
-				$scanner = $storage->getScanner($internalPath);
1558
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1559
-			}
1560
-
1561
-			return $cache->put($internalPath, $data);
1562
-		} else {
1563
-			return -1;
1564
-		}
1565
-	}
1566
-
1567
-	/**
1568
-	 * search for files with the name matching $query
1569
-	 *
1570
-	 * @param string $query
1571
-	 * @return FileInfo[]
1572
-	 */
1573
-	public function search($query) {
1574
-		return $this->searchCommon('search', array('%' . $query . '%'));
1575
-	}
1576
-
1577
-	/**
1578
-	 * search for files with the name matching $query
1579
-	 *
1580
-	 * @param string $query
1581
-	 * @return FileInfo[]
1582
-	 */
1583
-	public function searchRaw($query) {
1584
-		return $this->searchCommon('search', array($query));
1585
-	}
1586
-
1587
-	/**
1588
-	 * search for files by mimetype
1589
-	 *
1590
-	 * @param string $mimetype
1591
-	 * @return FileInfo[]
1592
-	 */
1593
-	public function searchByMime($mimetype) {
1594
-		return $this->searchCommon('searchByMime', array($mimetype));
1595
-	}
1596
-
1597
-	/**
1598
-	 * search for files by tag
1599
-	 *
1600
-	 * @param string|int $tag name or tag id
1601
-	 * @param string $userId owner of the tags
1602
-	 * @return FileInfo[]
1603
-	 */
1604
-	public function searchByTag($tag, $userId) {
1605
-		return $this->searchCommon('searchByTag', array($tag, $userId));
1606
-	}
1607
-
1608
-	/**
1609
-	 * @param string $method cache method
1610
-	 * @param array $args
1611
-	 * @return FileInfo[]
1612
-	 */
1613
-	private function searchCommon($method, $args) {
1614
-		$files = array();
1615
-		$rootLength = strlen($this->fakeRoot);
1616
-
1617
-		$mount = $this->getMount('');
1618
-		$mountPoint = $mount->getMountPoint();
1619
-		$storage = $mount->getStorage();
1620
-		if ($storage) {
1621
-			$cache = $storage->getCache('');
1622
-
1623
-			$results = call_user_func_array(array($cache, $method), $args);
1624
-			foreach ($results as $result) {
1625
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1626
-					$internalPath = $result['path'];
1627
-					$path = $mountPoint . $result['path'];
1628
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1629
-					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1630
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1631
-				}
1632
-			}
1633
-
1634
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1635
-			foreach ($mounts as $mount) {
1636
-				$mountPoint = $mount->getMountPoint();
1637
-				$storage = $mount->getStorage();
1638
-				if ($storage) {
1639
-					$cache = $storage->getCache('');
1640
-
1641
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1642
-					$results = call_user_func_array(array($cache, $method), $args);
1643
-					if ($results) {
1644
-						foreach ($results as $result) {
1645
-							$internalPath = $result['path'];
1646
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1647
-							$path = rtrim($mountPoint . $internalPath, '/');
1648
-							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1649
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1650
-						}
1651
-					}
1652
-				}
1653
-			}
1654
-		}
1655
-		return $files;
1656
-	}
1657
-
1658
-	/**
1659
-	 * Get the owner for a file or folder
1660
-	 *
1661
-	 * @param string $path
1662
-	 * @return string the user id of the owner
1663
-	 * @throws NotFoundException
1664
-	 */
1665
-	public function getOwner($path) {
1666
-		$info = $this->getFileInfo($path);
1667
-		if (!$info) {
1668
-			throw new NotFoundException($path . ' not found while trying to get owner');
1669
-		}
1670
-		return $info->getOwner()->getUID();
1671
-	}
1672
-
1673
-	/**
1674
-	 * get the ETag for a file or folder
1675
-	 *
1676
-	 * @param string $path
1677
-	 * @return string
1678
-	 */
1679
-	public function getETag($path) {
1680
-		/**
1681
-		 * @var Storage\Storage $storage
1682
-		 * @var string $internalPath
1683
-		 */
1684
-		list($storage, $internalPath) = $this->resolvePath($path);
1685
-		if ($storage) {
1686
-			return $storage->getETag($internalPath);
1687
-		} else {
1688
-			return null;
1689
-		}
1690
-	}
1691
-
1692
-	/**
1693
-	 * Get the path of a file by id, relative to the view
1694
-	 *
1695
-	 * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1696
-	 *
1697
-	 * @param int $id
1698
-	 * @throws NotFoundException
1699
-	 * @return string
1700
-	 */
1701
-	public function getPath($id) {
1702
-		$id = (int)$id;
1703
-		$manager = Filesystem::getMountManager();
1704
-		$mounts = $manager->findIn($this->fakeRoot);
1705
-		$mounts[] = $manager->find($this->fakeRoot);
1706
-		// reverse the array so we start with the storage this view is in
1707
-		// which is the most likely to contain the file we're looking for
1708
-		$mounts = array_reverse($mounts);
1709
-		foreach ($mounts as $mount) {
1710
-			/**
1711
-			 * @var \OC\Files\Mount\MountPoint $mount
1712
-			 */
1713
-			if ($mount->getStorage()) {
1714
-				$cache = $mount->getStorage()->getCache();
1715
-				$internalPath = $cache->getPathById($id);
1716
-				if (is_string($internalPath)) {
1717
-					$fullPath = $mount->getMountPoint() . $internalPath;
1718
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1719
-						return $path;
1720
-					}
1721
-				}
1722
-			}
1723
-		}
1724
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1725
-	}
1726
-
1727
-	/**
1728
-	 * @param string $path
1729
-	 * @throws InvalidPathException
1730
-	 */
1731
-	private function assertPathLength($path) {
1732
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1733
-		// Check for the string length - performed using isset() instead of strlen()
1734
-		// because isset() is about 5x-40x faster.
1735
-		if (isset($path[$maxLen])) {
1736
-			$pathLen = strlen($path);
1737
-			throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1738
-		}
1739
-	}
1740
-
1741
-	/**
1742
-	 * check if it is allowed to move a mount point to a given target.
1743
-	 * It is not allowed to move a mount point into a different mount point or
1744
-	 * into an already shared folder
1745
-	 *
1746
-	 * @param string $target path
1747
-	 * @return boolean
1748
-	 */
1749
-	private function isTargetAllowed($target) {
1750
-
1751
-		list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1752
-		if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1753
-			\OCP\Util::writeLog('files',
1754
-				'It is not allowed to move one mount point into another one',
1755
-				\OCP\Util::DEBUG);
1756
-			return false;
1757
-		}
1758
-
1759
-		// note: cannot use the view because the target is already locked
1760
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1761
-		if ($fileId === -1) {
1762
-			// target might not exist, need to check parent instead
1763
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1764
-		}
1765
-
1766
-		// check if any of the parents were shared by the current owner (include collections)
1767
-		$shares = \OCP\Share::getItemShared(
1768
-			'folder',
1769
-			$fileId,
1770
-			\OCP\Share::FORMAT_NONE,
1771
-			null,
1772
-			true
1773
-		);
1774
-
1775
-		if (count($shares) > 0) {
1776
-			\OCP\Util::writeLog('files',
1777
-				'It is not allowed to move one mount point into a shared folder',
1778
-				\OCP\Util::DEBUG);
1779
-			return false;
1780
-		}
1781
-
1782
-		return true;
1783
-	}
1784
-
1785
-	/**
1786
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1787
-	 *
1788
-	 * @param string $path
1789
-	 * @return \OCP\Files\FileInfo
1790
-	 */
1791
-	private function getPartFileInfo($path) {
1792
-		$mount = $this->getMount($path);
1793
-		$storage = $mount->getStorage();
1794
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1795
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1796
-		return new FileInfo(
1797
-			$this->getAbsolutePath($path),
1798
-			$storage,
1799
-			$internalPath,
1800
-			[
1801
-				'fileid' => null,
1802
-				'mimetype' => $storage->getMimeType($internalPath),
1803
-				'name' => basename($path),
1804
-				'etag' => null,
1805
-				'size' => $storage->filesize($internalPath),
1806
-				'mtime' => $storage->filemtime($internalPath),
1807
-				'encrypted' => false,
1808
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1809
-			],
1810
-			$mount,
1811
-			$owner
1812
-		);
1813
-	}
1814
-
1815
-	/**
1816
-	 * @param string $path
1817
-	 * @param string $fileName
1818
-	 * @throws InvalidPathException
1819
-	 */
1820
-	public function verifyPath($path, $fileName) {
1821
-		try {
1822
-			/** @type \OCP\Files\Storage $storage */
1823
-			list($storage, $internalPath) = $this->resolvePath($path);
1824
-			$storage->verifyPath($internalPath, $fileName);
1825
-		} catch (ReservedWordException $ex) {
1826
-			$l = \OC::$server->getL10N('lib');
1827
-			throw new InvalidPathException($l->t('File name is a reserved word'));
1828
-		} catch (InvalidCharacterInPathException $ex) {
1829
-			$l = \OC::$server->getL10N('lib');
1830
-			throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1831
-		} catch (FileNameTooLongException $ex) {
1832
-			$l = \OC::$server->getL10N('lib');
1833
-			throw new InvalidPathException($l->t('File name is too long'));
1834
-		} catch (InvalidDirectoryException $ex) {
1835
-			$l = \OC::$server->getL10N('lib');
1836
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1837
-		} catch (EmptyFileNameException $ex) {
1838
-			$l = \OC::$server->getL10N('lib');
1839
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1840
-		}
1841
-	}
1842
-
1843
-	/**
1844
-	 * get all parent folders of $path
1845
-	 *
1846
-	 * @param string $path
1847
-	 * @return string[]
1848
-	 */
1849
-	private function getParents($path) {
1850
-		$path = trim($path, '/');
1851
-		if (!$path) {
1852
-			return [];
1853
-		}
1854
-
1855
-		$parts = explode('/', $path);
1856
-
1857
-		// remove the single file
1858
-		array_pop($parts);
1859
-		$result = array('/');
1860
-		$resultPath = '';
1861
-		foreach ($parts as $part) {
1862
-			if ($part) {
1863
-				$resultPath .= '/' . $part;
1864
-				$result[] = $resultPath;
1865
-			}
1866
-		}
1867
-		return $result;
1868
-	}
1869
-
1870
-	/**
1871
-	 * Returns the mount point for which to lock
1872
-	 *
1873
-	 * @param string $absolutePath absolute path
1874
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1875
-	 * is mounted directly on the given path, false otherwise
1876
-	 * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1877
-	 */
1878
-	private function getMountForLock($absolutePath, $useParentMount = false) {
1879
-		$results = [];
1880
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1881
-		if (!$mount) {
1882
-			return $results;
1883
-		}
1884
-
1885
-		if ($useParentMount) {
1886
-			// find out if something is mounted directly on the path
1887
-			$internalPath = $mount->getInternalPath($absolutePath);
1888
-			if ($internalPath === '') {
1889
-				// resolve the parent mount instead
1890
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1891
-			}
1892
-		}
1893
-
1894
-		return $mount;
1895
-	}
1896
-
1897
-	/**
1898
-	 * Lock the given path
1899
-	 *
1900
-	 * @param string $path the path of the file to lock, relative to the view
1901
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1902
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1903
-	 *
1904
-	 * @return bool False if the path is excluded from locking, true otherwise
1905
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1906
-	 */
1907
-	private function lockPath($path, $type, $lockMountPoint = false) {
1908
-		$absolutePath = $this->getAbsolutePath($path);
1909
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1910
-		if (!$this->shouldLockFile($absolutePath)) {
1911
-			return false;
1912
-		}
1913
-
1914
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1915
-		if ($mount) {
1916
-			try {
1917
-				$storage = $mount->getStorage();
1918
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1919
-					$storage->acquireLock(
1920
-						$mount->getInternalPath($absolutePath),
1921
-						$type,
1922
-						$this->lockingProvider
1923
-					);
1924
-				}
1925
-			} catch (\OCP\Lock\LockedException $e) {
1926
-				// rethrow with the a human-readable path
1927
-				throw new \OCP\Lock\LockedException(
1928
-					$this->getPathRelativeToFiles($absolutePath),
1929
-					$e
1930
-				);
1931
-			}
1932
-		}
1933
-
1934
-		return true;
1935
-	}
1936
-
1937
-	/**
1938
-	 * Change the lock type
1939
-	 *
1940
-	 * @param string $path the path of the file to lock, relative to the view
1941
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1942
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1943
-	 *
1944
-	 * @return bool False if the path is excluded from locking, true otherwise
1945
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1946
-	 */
1947
-	public function changeLock($path, $type, $lockMountPoint = false) {
1948
-		$path = Filesystem::normalizePath($path);
1949
-		$absolutePath = $this->getAbsolutePath($path);
1950
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1951
-		if (!$this->shouldLockFile($absolutePath)) {
1952
-			return false;
1953
-		}
1954
-
1955
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1956
-		if ($mount) {
1957
-			try {
1958
-				$storage = $mount->getStorage();
1959
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1960
-					$storage->changeLock(
1961
-						$mount->getInternalPath($absolutePath),
1962
-						$type,
1963
-						$this->lockingProvider
1964
-					);
1965
-				}
1966
-			} catch (\OCP\Lock\LockedException $e) {
1967
-				try {
1968
-					// rethrow with the a human-readable path
1969
-					throw new \OCP\Lock\LockedException(
1970
-						$this->getPathRelativeToFiles($absolutePath),
1971
-						$e
1972
-					);
1973
-				} catch (\InvalidArgumentException $e) {
1974
-					throw new \OCP\Lock\LockedException(
1975
-						$absolutePath,
1976
-						$e
1977
-					);
1978
-				}
1979
-			}
1980
-		}
1981
-
1982
-		return true;
1983
-	}
1984
-
1985
-	/**
1986
-	 * Unlock the given path
1987
-	 *
1988
-	 * @param string $path the path of the file to unlock, relative to the view
1989
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1990
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1991
-	 *
1992
-	 * @return bool False if the path is excluded from locking, true otherwise
1993
-	 */
1994
-	private function unlockPath($path, $type, $lockMountPoint = false) {
1995
-		$absolutePath = $this->getAbsolutePath($path);
1996
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1997
-		if (!$this->shouldLockFile($absolutePath)) {
1998
-			return false;
1999
-		}
2000
-
2001
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2002
-		if ($mount) {
2003
-			$storage = $mount->getStorage();
2004
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2005
-				$storage->releaseLock(
2006
-					$mount->getInternalPath($absolutePath),
2007
-					$type,
2008
-					$this->lockingProvider
2009
-				);
2010
-			}
2011
-		}
2012
-
2013
-		return true;
2014
-	}
2015
-
2016
-	/**
2017
-	 * Lock a path and all its parents up to the root of the view
2018
-	 *
2019
-	 * @param string $path the path of the file to lock relative to the view
2020
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2021
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2022
-	 *
2023
-	 * @return bool False if the path is excluded from locking, true otherwise
2024
-	 */
2025
-	public function lockFile($path, $type, $lockMountPoint = false) {
2026
-		$absolutePath = $this->getAbsolutePath($path);
2027
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2028
-		if (!$this->shouldLockFile($absolutePath)) {
2029
-			return false;
2030
-		}
2031
-
2032
-		$this->lockPath($path, $type, $lockMountPoint);
2033
-
2034
-		$parents = $this->getParents($path);
2035
-		foreach ($parents as $parent) {
2036
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2037
-		}
2038
-
2039
-		return true;
2040
-	}
2041
-
2042
-	/**
2043
-	 * Unlock a path and all its parents up to the root of the view
2044
-	 *
2045
-	 * @param string $path the path of the file to lock relative to the view
2046
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2047
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2048
-	 *
2049
-	 * @return bool False if the path is excluded from locking, true otherwise
2050
-	 */
2051
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2052
-		$absolutePath = $this->getAbsolutePath($path);
2053
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2054
-		if (!$this->shouldLockFile($absolutePath)) {
2055
-			return false;
2056
-		}
2057
-
2058
-		$this->unlockPath($path, $type, $lockMountPoint);
2059
-
2060
-		$parents = $this->getParents($path);
2061
-		foreach ($parents as $parent) {
2062
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2063
-		}
2064
-
2065
-		return true;
2066
-	}
2067
-
2068
-	/**
2069
-	 * Only lock files in data/user/files/
2070
-	 *
2071
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2072
-	 * @return bool
2073
-	 */
2074
-	protected function shouldLockFile($path) {
2075
-		$path = Filesystem::normalizePath($path);
2076
-
2077
-		$pathSegments = explode('/', $path);
2078
-		if (isset($pathSegments[2])) {
2079
-			// E.g.: /username/files/path-to-file
2080
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2081
-		}
2082
-
2083
-		return strpos($path, '/appdata_') !== 0;
2084
-	}
2085
-
2086
-	/**
2087
-	 * Shortens the given absolute path to be relative to
2088
-	 * "$user/files".
2089
-	 *
2090
-	 * @param string $absolutePath absolute path which is under "files"
2091
-	 *
2092
-	 * @return string path relative to "files" with trimmed slashes or null
2093
-	 * if the path was NOT relative to files
2094
-	 *
2095
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2096
-	 * @since 8.1.0
2097
-	 */
2098
-	public function getPathRelativeToFiles($absolutePath) {
2099
-		$path = Filesystem::normalizePath($absolutePath);
2100
-		$parts = explode('/', trim($path, '/'), 3);
2101
-		// "$user", "files", "path/to/dir"
2102
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2103
-			$this->logger->error(
2104
-				'$absolutePath must be relative to "files", value is "%s"',
2105
-				[
2106
-					$absolutePath
2107
-				]
2108
-			);
2109
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2110
-		}
2111
-		if (isset($parts[2])) {
2112
-			return $parts[2];
2113
-		}
2114
-		return '';
2115
-	}
2116
-
2117
-	/**
2118
-	 * @param string $filename
2119
-	 * @return array
2120
-	 * @throws \OC\User\NoUserException
2121
-	 * @throws NotFoundException
2122
-	 */
2123
-	public function getUidAndFilename($filename) {
2124
-		$info = $this->getFileInfo($filename);
2125
-		if (!$info instanceof \OCP\Files\FileInfo) {
2126
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2127
-		}
2128
-		$uid = $info->getOwner()->getUID();
2129
-		if ($uid != \OCP\User::getUser()) {
2130
-			Filesystem::initMountPoints($uid);
2131
-			$ownerView = new View('/' . $uid . '/files');
2132
-			try {
2133
-				$filename = $ownerView->getPath($info['fileid']);
2134
-			} catch (NotFoundException $e) {
2135
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2136
-			}
2137
-		}
2138
-		return [$uid, $filename];
2139
-	}
2140
-
2141
-	/**
2142
-	 * Creates parent non-existing folders
2143
-	 *
2144
-	 * @param string $filePath
2145
-	 * @return bool
2146
-	 */
2147
-	private function createParentDirectories($filePath) {
2148
-		$directoryParts = explode('/', $filePath);
2149
-		$directoryParts = array_filter($directoryParts);
2150
-		foreach ($directoryParts as $key => $part) {
2151
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2152
-			$currentPath = '/' . implode('/', $currentPathElements);
2153
-			if ($this->is_file($currentPath)) {
2154
-				return false;
2155
-			}
2156
-			if (!$this->file_exists($currentPath)) {
2157
-				$this->mkdir($currentPath);
2158
-			}
2159
-		}
2160
-
2161
-		return true;
2162
-	}
85
+    /** @var string */
86
+    private $fakeRoot = '';
87
+
88
+    /**
89
+     * @var \OCP\Lock\ILockingProvider
90
+     */
91
+    protected $lockingProvider;
92
+
93
+    private $lockingEnabled;
94
+
95
+    private $updaterEnabled = true;
96
+
97
+    /** @var \OC\User\Manager */
98
+    private $userManager;
99
+
100
+    /** @var \OCP\ILogger */
101
+    private $logger;
102
+
103
+    /**
104
+     * @param string $root
105
+     * @throws \Exception If $root contains an invalid path
106
+     */
107
+    public function __construct($root = '') {
108
+        if (is_null($root)) {
109
+            throw new \InvalidArgumentException('Root can\'t be null');
110
+        }
111
+        if (!Filesystem::isValidPath($root)) {
112
+            throw new \Exception();
113
+        }
114
+
115
+        $this->fakeRoot = $root;
116
+        $this->lockingProvider = \OC::$server->getLockingProvider();
117
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
118
+        $this->userManager = \OC::$server->getUserManager();
119
+        $this->logger = \OC::$server->getLogger();
120
+    }
121
+
122
+    public function getAbsolutePath($path = '/') {
123
+        if ($path === null) {
124
+            return null;
125
+        }
126
+        $this->assertPathLength($path);
127
+        if ($path === '') {
128
+            $path = '/';
129
+        }
130
+        if ($path[0] !== '/') {
131
+            $path = '/' . $path;
132
+        }
133
+        return $this->fakeRoot . $path;
134
+    }
135
+
136
+    /**
137
+     * change the root to a fake root
138
+     *
139
+     * @param string $fakeRoot
140
+     * @return boolean|null
141
+     */
142
+    public function chroot($fakeRoot) {
143
+        if (!$fakeRoot == '') {
144
+            if ($fakeRoot[0] !== '/') {
145
+                $fakeRoot = '/' . $fakeRoot;
146
+            }
147
+        }
148
+        $this->fakeRoot = $fakeRoot;
149
+    }
150
+
151
+    /**
152
+     * get the fake root
153
+     *
154
+     * @return string
155
+     */
156
+    public function getRoot() {
157
+        return $this->fakeRoot;
158
+    }
159
+
160
+    /**
161
+     * get path relative to the root of the view
162
+     *
163
+     * @param string $path
164
+     * @return string
165
+     */
166
+    public function getRelativePath($path) {
167
+        $this->assertPathLength($path);
168
+        if ($this->fakeRoot == '') {
169
+            return $path;
170
+        }
171
+
172
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
173
+            return '/';
174
+        }
175
+
176
+        // missing slashes can cause wrong matches!
177
+        $root = rtrim($this->fakeRoot, '/') . '/';
178
+
179
+        if (strpos($path, $root) !== 0) {
180
+            return null;
181
+        } else {
182
+            $path = substr($path, strlen($this->fakeRoot));
183
+            if (strlen($path) === 0) {
184
+                return '/';
185
+            } else {
186
+                return $path;
187
+            }
188
+        }
189
+    }
190
+
191
+    /**
192
+     * get the mountpoint of the storage object for a path
193
+     * ( note: because a storage is not always mounted inside the fakeroot, the
194
+     * returned mountpoint is relative to the absolute root of the filesystem
195
+     * and does not take the chroot into account )
196
+     *
197
+     * @param string $path
198
+     * @return string
199
+     */
200
+    public function getMountPoint($path) {
201
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
202
+    }
203
+
204
+    /**
205
+     * get the mountpoint of the storage object for a path
206
+     * ( note: because a storage is not always mounted inside the fakeroot, the
207
+     * returned mountpoint is relative to the absolute root of the filesystem
208
+     * and does not take the chroot into account )
209
+     *
210
+     * @param string $path
211
+     * @return \OCP\Files\Mount\IMountPoint
212
+     */
213
+    public function getMount($path) {
214
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
215
+    }
216
+
217
+    /**
218
+     * resolve a path to a storage and internal path
219
+     *
220
+     * @param string $path
221
+     * @return array an array consisting of the storage and the internal path
222
+     */
223
+    public function resolvePath($path) {
224
+        $a = $this->getAbsolutePath($path);
225
+        $p = Filesystem::normalizePath($a);
226
+        return Filesystem::resolvePath($p);
227
+    }
228
+
229
+    /**
230
+     * return the path to a local version of the file
231
+     * we need this because we can't know if a file is stored local or not from
232
+     * outside the filestorage and for some purposes a local file is needed
233
+     *
234
+     * @param string $path
235
+     * @return string
236
+     */
237
+    public function getLocalFile($path) {
238
+        $parent = substr($path, 0, strrpos($path, '/'));
239
+        $path = $this->getAbsolutePath($path);
240
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
241
+        if (Filesystem::isValidPath($parent) and $storage) {
242
+            return $storage->getLocalFile($internalPath);
243
+        } else {
244
+            return null;
245
+        }
246
+    }
247
+
248
+    /**
249
+     * @param string $path
250
+     * @return string
251
+     */
252
+    public function getLocalFolder($path) {
253
+        $parent = substr($path, 0, strrpos($path, '/'));
254
+        $path = $this->getAbsolutePath($path);
255
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
256
+        if (Filesystem::isValidPath($parent) and $storage) {
257
+            return $storage->getLocalFolder($internalPath);
258
+        } else {
259
+            return null;
260
+        }
261
+    }
262
+
263
+    /**
264
+     * the following functions operate with arguments and return values identical
265
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
266
+     * for \OC\Files\Storage\Storage via basicOperation().
267
+     */
268
+    public function mkdir($path) {
269
+        return $this->basicOperation('mkdir', $path, array('create', 'write'));
270
+    }
271
+
272
+    /**
273
+     * remove mount point
274
+     *
275
+     * @param \OC\Files\Mount\MoveableMount $mount
276
+     * @param string $path relative to data/
277
+     * @return boolean
278
+     */
279
+    protected function removeMount($mount, $path) {
280
+        if ($mount instanceof MoveableMount) {
281
+            // cut of /user/files to get the relative path to data/user/files
282
+            $pathParts = explode('/', $path, 4);
283
+            $relPath = '/' . $pathParts[3];
284
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
285
+            \OC_Hook::emit(
286
+                Filesystem::CLASSNAME, "umount",
287
+                array(Filesystem::signal_param_path => $relPath)
288
+            );
289
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
290
+            $result = $mount->removeMount();
291
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
292
+            if ($result) {
293
+                \OC_Hook::emit(
294
+                    Filesystem::CLASSNAME, "post_umount",
295
+                    array(Filesystem::signal_param_path => $relPath)
296
+                );
297
+            }
298
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
299
+            return $result;
300
+        } else {
301
+            // do not allow deleting the storage's root / the mount point
302
+            // because for some storages it might delete the whole contents
303
+            // but isn't supposed to work that way
304
+            return false;
305
+        }
306
+    }
307
+
308
+    public function disableCacheUpdate() {
309
+        $this->updaterEnabled = false;
310
+    }
311
+
312
+    public function enableCacheUpdate() {
313
+        $this->updaterEnabled = true;
314
+    }
315
+
316
+    protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
317
+        if ($this->updaterEnabled) {
318
+            if (is_null($time)) {
319
+                $time = time();
320
+            }
321
+            $storage->getUpdater()->update($internalPath, $time);
322
+        }
323
+    }
324
+
325
+    protected function removeUpdate(Storage $storage, $internalPath) {
326
+        if ($this->updaterEnabled) {
327
+            $storage->getUpdater()->remove($internalPath);
328
+        }
329
+    }
330
+
331
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
332
+        if ($this->updaterEnabled) {
333
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
334
+        }
335
+    }
336
+
337
+    /**
338
+     * @param string $path
339
+     * @return bool|mixed
340
+     */
341
+    public function rmdir($path) {
342
+        $absolutePath = $this->getAbsolutePath($path);
343
+        $mount = Filesystem::getMountManager()->find($absolutePath);
344
+        if ($mount->getInternalPath($absolutePath) === '') {
345
+            return $this->removeMount($mount, $absolutePath);
346
+        }
347
+        if ($this->is_dir($path)) {
348
+            $result = $this->basicOperation('rmdir', $path, array('delete'));
349
+        } else {
350
+            $result = false;
351
+        }
352
+
353
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
354
+            $storage = $mount->getStorage();
355
+            $internalPath = $mount->getInternalPath($absolutePath);
356
+            $storage->getUpdater()->remove($internalPath);
357
+        }
358
+        return $result;
359
+    }
360
+
361
+    /**
362
+     * @param string $path
363
+     * @return resource
364
+     */
365
+    public function opendir($path) {
366
+        return $this->basicOperation('opendir', $path, array('read'));
367
+    }
368
+
369
+    /**
370
+     * @param string $path
371
+     * @return bool|mixed
372
+     */
373
+    public function is_dir($path) {
374
+        if ($path == '/') {
375
+            return true;
376
+        }
377
+        return $this->basicOperation('is_dir', $path);
378
+    }
379
+
380
+    /**
381
+     * @param string $path
382
+     * @return bool|mixed
383
+     */
384
+    public function is_file($path) {
385
+        if ($path == '/') {
386
+            return false;
387
+        }
388
+        return $this->basicOperation('is_file', $path);
389
+    }
390
+
391
+    /**
392
+     * @param string $path
393
+     * @return mixed
394
+     */
395
+    public function stat($path) {
396
+        return $this->basicOperation('stat', $path);
397
+    }
398
+
399
+    /**
400
+     * @param string $path
401
+     * @return mixed
402
+     */
403
+    public function filetype($path) {
404
+        return $this->basicOperation('filetype', $path);
405
+    }
406
+
407
+    /**
408
+     * @param string $path
409
+     * @return mixed
410
+     */
411
+    public function filesize($path) {
412
+        return $this->basicOperation('filesize', $path);
413
+    }
414
+
415
+    /**
416
+     * @param string $path
417
+     * @return bool|mixed
418
+     * @throws \OCP\Files\InvalidPathException
419
+     */
420
+    public function readfile($path) {
421
+        $this->assertPathLength($path);
422
+        @ob_end_clean();
423
+        $handle = $this->fopen($path, 'rb');
424
+        if ($handle) {
425
+            $chunkSize = 8192; // 8 kB chunks
426
+            while (!feof($handle)) {
427
+                echo fread($handle, $chunkSize);
428
+                flush();
429
+            }
430
+            fclose($handle);
431
+            $size = $this->filesize($path);
432
+            return $size;
433
+        }
434
+        return false;
435
+    }
436
+
437
+    /**
438
+     * @param string $path
439
+     * @param int $from
440
+     * @param int $to
441
+     * @return bool|mixed
442
+     * @throws \OCP\Files\InvalidPathException
443
+     * @throws \OCP\Files\UnseekableException
444
+     */
445
+    public function readfilePart($path, $from, $to) {
446
+        $this->assertPathLength($path);
447
+        @ob_end_clean();
448
+        $handle = $this->fopen($path, 'rb');
449
+        if ($handle) {
450
+            $chunkSize = 8192; // 8 kB chunks
451
+            $startReading = true;
452
+
453
+            if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
454
+                // forward file handle via chunked fread because fseek seem to have failed
455
+
456
+                $end = $from + 1;
457
+                while (!feof($handle) && ftell($handle) < $end) {
458
+                    $len = $from - ftell($handle);
459
+                    if ($len > $chunkSize) {
460
+                        $len = $chunkSize;
461
+                    }
462
+                    $result = fread($handle, $len);
463
+
464
+                    if ($result === false) {
465
+                        $startReading = false;
466
+                        break;
467
+                    }
468
+                }
469
+            }
470
+
471
+            if ($startReading) {
472
+                $end = $to + 1;
473
+                while (!feof($handle) && ftell($handle) < $end) {
474
+                    $len = $end - ftell($handle);
475
+                    if ($len > $chunkSize) {
476
+                        $len = $chunkSize;
477
+                    }
478
+                    echo fread($handle, $len);
479
+                    flush();
480
+                }
481
+                $size = ftell($handle) - $from;
482
+                return $size;
483
+            }
484
+
485
+            throw new \OCP\Files\UnseekableException('fseek error');
486
+        }
487
+        return false;
488
+    }
489
+
490
+    /**
491
+     * @param string $path
492
+     * @return mixed
493
+     */
494
+    public function isCreatable($path) {
495
+        return $this->basicOperation('isCreatable', $path);
496
+    }
497
+
498
+    /**
499
+     * @param string $path
500
+     * @return mixed
501
+     */
502
+    public function isReadable($path) {
503
+        return $this->basicOperation('isReadable', $path);
504
+    }
505
+
506
+    /**
507
+     * @param string $path
508
+     * @return mixed
509
+     */
510
+    public function isUpdatable($path) {
511
+        return $this->basicOperation('isUpdatable', $path);
512
+    }
513
+
514
+    /**
515
+     * @param string $path
516
+     * @return bool|mixed
517
+     */
518
+    public function isDeletable($path) {
519
+        $absolutePath = $this->getAbsolutePath($path);
520
+        $mount = Filesystem::getMountManager()->find($absolutePath);
521
+        if ($mount->getInternalPath($absolutePath) === '') {
522
+            return $mount instanceof MoveableMount;
523
+        }
524
+        return $this->basicOperation('isDeletable', $path);
525
+    }
526
+
527
+    /**
528
+     * @param string $path
529
+     * @return mixed
530
+     */
531
+    public function isSharable($path) {
532
+        return $this->basicOperation('isSharable', $path);
533
+    }
534
+
535
+    /**
536
+     * @param string $path
537
+     * @return bool|mixed
538
+     */
539
+    public function file_exists($path) {
540
+        if ($path == '/') {
541
+            return true;
542
+        }
543
+        return $this->basicOperation('file_exists', $path);
544
+    }
545
+
546
+    /**
547
+     * @param string $path
548
+     * @return mixed
549
+     */
550
+    public function filemtime($path) {
551
+        return $this->basicOperation('filemtime', $path);
552
+    }
553
+
554
+    /**
555
+     * @param string $path
556
+     * @param int|string $mtime
557
+     * @return bool
558
+     */
559
+    public function touch($path, $mtime = null) {
560
+        if (!is_null($mtime) and !is_numeric($mtime)) {
561
+            $mtime = strtotime($mtime);
562
+        }
563
+
564
+        $hooks = array('touch');
565
+
566
+        if (!$this->file_exists($path)) {
567
+            $hooks[] = 'create';
568
+            $hooks[] = 'write';
569
+        }
570
+        $result = $this->basicOperation('touch', $path, $hooks, $mtime);
571
+        if (!$result) {
572
+            // If create file fails because of permissions on external storage like SMB folders,
573
+            // check file exists and return false if not.
574
+            if (!$this->file_exists($path)) {
575
+                return false;
576
+            }
577
+            if (is_null($mtime)) {
578
+                $mtime = time();
579
+            }
580
+            //if native touch fails, we emulate it by changing the mtime in the cache
581
+            $this->putFileInfo($path, array('mtime' => floor($mtime)));
582
+        }
583
+        return true;
584
+    }
585
+
586
+    /**
587
+     * @param string $path
588
+     * @return mixed
589
+     */
590
+    public function file_get_contents($path) {
591
+        return $this->basicOperation('file_get_contents', $path, array('read'));
592
+    }
593
+
594
+    /**
595
+     * @param bool $exists
596
+     * @param string $path
597
+     * @param bool $run
598
+     */
599
+    protected function emit_file_hooks_pre($exists, $path, &$run) {
600
+        if (!$exists) {
601
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
602
+                Filesystem::signal_param_path => $this->getHookPath($path),
603
+                Filesystem::signal_param_run => &$run,
604
+            ));
605
+        } else {
606
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
607
+                Filesystem::signal_param_path => $this->getHookPath($path),
608
+                Filesystem::signal_param_run => &$run,
609
+            ));
610
+        }
611
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
612
+            Filesystem::signal_param_path => $this->getHookPath($path),
613
+            Filesystem::signal_param_run => &$run,
614
+        ));
615
+    }
616
+
617
+    /**
618
+     * @param bool $exists
619
+     * @param string $path
620
+     */
621
+    protected function emit_file_hooks_post($exists, $path) {
622
+        if (!$exists) {
623
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
624
+                Filesystem::signal_param_path => $this->getHookPath($path),
625
+            ));
626
+        } else {
627
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
628
+                Filesystem::signal_param_path => $this->getHookPath($path),
629
+            ));
630
+        }
631
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
632
+            Filesystem::signal_param_path => $this->getHookPath($path),
633
+        ));
634
+    }
635
+
636
+    /**
637
+     * @param string $path
638
+     * @param mixed $data
639
+     * @return bool|mixed
640
+     * @throws \Exception
641
+     */
642
+    public function file_put_contents($path, $data) {
643
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
644
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
645
+            if (Filesystem::isValidPath($path)
646
+                and !Filesystem::isFileBlacklisted($path)
647
+            ) {
648
+                $path = $this->getRelativePath($absolutePath);
649
+
650
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
651
+
652
+                $exists = $this->file_exists($path);
653
+                $run = true;
654
+                if ($this->shouldEmitHooks($path)) {
655
+                    $this->emit_file_hooks_pre($exists, $path, $run);
656
+                }
657
+                if (!$run) {
658
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
659
+                    return false;
660
+                }
661
+
662
+                $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
663
+
664
+                /** @var \OC\Files\Storage\Storage $storage */
665
+                list($storage, $internalPath) = $this->resolvePath($path);
666
+                $target = $storage->fopen($internalPath, 'w');
667
+                if ($target) {
668
+                    list (, $result) = \OC_Helper::streamCopy($data, $target);
669
+                    fclose($target);
670
+                    fclose($data);
671
+
672
+                    $this->writeUpdate($storage, $internalPath);
673
+
674
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
675
+
676
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
677
+                        $this->emit_file_hooks_post($exists, $path);
678
+                    }
679
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
680
+                    return $result;
681
+                } else {
682
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
683
+                    return false;
684
+                }
685
+            } else {
686
+                return false;
687
+            }
688
+        } else {
689
+            $hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
690
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
691
+        }
692
+    }
693
+
694
+    /**
695
+     * @param string $path
696
+     * @return bool|mixed
697
+     */
698
+    public function unlink($path) {
699
+        if ($path === '' || $path === '/') {
700
+            // do not allow deleting the root
701
+            return false;
702
+        }
703
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
704
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
705
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
706
+        if ($mount and $mount->getInternalPath($absolutePath) === '') {
707
+            return $this->removeMount($mount, $absolutePath);
708
+        }
709
+        if ($this->is_dir($path)) {
710
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
711
+        } else {
712
+            $result = $this->basicOperation('unlink', $path, ['delete']);
713
+        }
714
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
715
+            $storage = $mount->getStorage();
716
+            $internalPath = $mount->getInternalPath($absolutePath);
717
+            $storage->getUpdater()->remove($internalPath);
718
+            return true;
719
+        } else {
720
+            return $result;
721
+        }
722
+    }
723
+
724
+    /**
725
+     * @param string $directory
726
+     * @return bool|mixed
727
+     */
728
+    public function deleteAll($directory) {
729
+        return $this->rmdir($directory);
730
+    }
731
+
732
+    /**
733
+     * Rename/move a file or folder from the source path to target path.
734
+     *
735
+     * @param string $path1 source path
736
+     * @param string $path2 target path
737
+     *
738
+     * @return bool|mixed
739
+     */
740
+    public function rename($path1, $path2) {
741
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
742
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
743
+        $result = false;
744
+        if (
745
+            Filesystem::isValidPath($path2)
746
+            and Filesystem::isValidPath($path1)
747
+            and !Filesystem::isFileBlacklisted($path2)
748
+        ) {
749
+            $path1 = $this->getRelativePath($absolutePath1);
750
+            $path2 = $this->getRelativePath($absolutePath2);
751
+            $exists = $this->file_exists($path2);
752
+
753
+            if ($path1 == null or $path2 == null) {
754
+                return false;
755
+            }
756
+
757
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
758
+            try {
759
+                $this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
760
+
761
+                $run = true;
762
+                if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
763
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
764
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
765
+                } elseif ($this->shouldEmitHooks($path1)) {
766
+                    \OC_Hook::emit(
767
+                        Filesystem::CLASSNAME, Filesystem::signal_rename,
768
+                        array(
769
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
770
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
771
+                            Filesystem::signal_param_run => &$run
772
+                        )
773
+                    );
774
+                }
775
+                if ($run) {
776
+                    $this->verifyPath(dirname($path2), basename($path2));
777
+
778
+                    $manager = Filesystem::getMountManager();
779
+                    $mount1 = $this->getMount($path1);
780
+                    $mount2 = $this->getMount($path2);
781
+                    $storage1 = $mount1->getStorage();
782
+                    $storage2 = $mount2->getStorage();
783
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
784
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
785
+
786
+                    $this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
787
+                    try {
788
+                        $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
789
+
790
+                        if ($internalPath1 === '') {
791
+                            if ($mount1 instanceof MoveableMount) {
792
+                                if ($this->isTargetAllowed($absolutePath2)) {
793
+                                    /**
794
+                                     * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
795
+                                     */
796
+                                    $sourceMountPoint = $mount1->getMountPoint();
797
+                                    $result = $mount1->moveMount($absolutePath2);
798
+                                    $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
799
+                                } else {
800
+                                    $result = false;
801
+                                }
802
+                            } else {
803
+                                $result = false;
804
+                            }
805
+                            // moving a file/folder within the same mount point
806
+                        } elseif ($storage1 === $storage2) {
807
+                            if ($storage1) {
808
+                                $result = $storage1->rename($internalPath1, $internalPath2);
809
+                            } else {
810
+                                $result = false;
811
+                            }
812
+                            // moving a file/folder between storages (from $storage1 to $storage2)
813
+                        } else {
814
+                            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
815
+                        }
816
+
817
+                        if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
818
+                            // if it was a rename from a part file to a regular file it was a write and not a rename operation
819
+                            $this->writeUpdate($storage2, $internalPath2);
820
+                        } else if ($result) {
821
+                            if ($internalPath1 !== '') { // don't do a cache update for moved mounts
822
+                                $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
823
+                            }
824
+                        }
825
+                    } catch(\Exception $e) {
826
+                        throw $e;
827
+                    } finally {
828
+                        $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
829
+                        $this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
830
+                    }
831
+
832
+                    if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
833
+                        if ($this->shouldEmitHooks()) {
834
+                            $this->emit_file_hooks_post($exists, $path2);
835
+                        }
836
+                    } elseif ($result) {
837
+                        if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
838
+                            \OC_Hook::emit(
839
+                                Filesystem::CLASSNAME,
840
+                                Filesystem::signal_post_rename,
841
+                                array(
842
+                                    Filesystem::signal_param_oldpath => $this->getHookPath($path1),
843
+                                    Filesystem::signal_param_newpath => $this->getHookPath($path2)
844
+                                )
845
+                            );
846
+                        }
847
+                    }
848
+                }
849
+            } catch(\Exception $e) {
850
+                throw $e;
851
+            } finally {
852
+                $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
853
+                $this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
854
+            }
855
+        }
856
+        return $result;
857
+    }
858
+
859
+    /**
860
+     * Copy a file/folder from the source path to target path
861
+     *
862
+     * @param string $path1 source path
863
+     * @param string $path2 target path
864
+     * @param bool $preserveMtime whether to preserve mtime on the copy
865
+     *
866
+     * @return bool|mixed
867
+     */
868
+    public function copy($path1, $path2, $preserveMtime = false) {
869
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
870
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
871
+        $result = false;
872
+        if (
873
+            Filesystem::isValidPath($path2)
874
+            and Filesystem::isValidPath($path1)
875
+            and !Filesystem::isFileBlacklisted($path2)
876
+        ) {
877
+            $path1 = $this->getRelativePath($absolutePath1);
878
+            $path2 = $this->getRelativePath($absolutePath2);
879
+
880
+            if ($path1 == null or $path2 == null) {
881
+                return false;
882
+            }
883
+            $run = true;
884
+
885
+            $this->lockFile($path2, ILockingProvider::LOCK_SHARED);
886
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED);
887
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
888
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
889
+
890
+            try {
891
+
892
+                $exists = $this->file_exists($path2);
893
+                if ($this->shouldEmitHooks()) {
894
+                    \OC_Hook::emit(
895
+                        Filesystem::CLASSNAME,
896
+                        Filesystem::signal_copy,
897
+                        array(
898
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
899
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
900
+                            Filesystem::signal_param_run => &$run
901
+                        )
902
+                    );
903
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
904
+                }
905
+                if ($run) {
906
+                    $mount1 = $this->getMount($path1);
907
+                    $mount2 = $this->getMount($path2);
908
+                    $storage1 = $mount1->getStorage();
909
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
910
+                    $storage2 = $mount2->getStorage();
911
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
912
+
913
+                    $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
914
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
915
+
916
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
917
+                        if ($storage1) {
918
+                            $result = $storage1->copy($internalPath1, $internalPath2);
919
+                        } else {
920
+                            $result = false;
921
+                        }
922
+                    } else {
923
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
924
+                    }
925
+
926
+                    $this->writeUpdate($storage2, $internalPath2);
927
+
928
+                    $this->changeLock($path2, ILockingProvider::LOCK_SHARED);
929
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
930
+
931
+                    if ($this->shouldEmitHooks() && $result !== false) {
932
+                        \OC_Hook::emit(
933
+                            Filesystem::CLASSNAME,
934
+                            Filesystem::signal_post_copy,
935
+                            array(
936
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
937
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
938
+                            )
939
+                        );
940
+                        $this->emit_file_hooks_post($exists, $path2);
941
+                    }
942
+
943
+                }
944
+            } catch (\Exception $e) {
945
+                $this->unlockFile($path2, $lockTypePath2);
946
+                $this->unlockFile($path1, $lockTypePath1);
947
+                throw $e;
948
+            }
949
+
950
+            $this->unlockFile($path2, $lockTypePath2);
951
+            $this->unlockFile($path1, $lockTypePath1);
952
+
953
+        }
954
+        return $result;
955
+    }
956
+
957
+    /**
958
+     * @param string $path
959
+     * @param string $mode 'r' or 'w'
960
+     * @return resource
961
+     */
962
+    public function fopen($path, $mode) {
963
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
964
+        $hooks = array();
965
+        switch ($mode) {
966
+            case 'r':
967
+                $hooks[] = 'read';
968
+                break;
969
+            case 'r+':
970
+            case 'w+':
971
+            case 'x+':
972
+            case 'a+':
973
+                $hooks[] = 'read';
974
+                $hooks[] = 'write';
975
+                break;
976
+            case 'w':
977
+            case 'x':
978
+            case 'a':
979
+                $hooks[] = 'write';
980
+                break;
981
+            default:
982
+                \OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
983
+        }
984
+
985
+        if ($mode !== 'r' && $mode !== 'w') {
986
+            \OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
987
+        }
988
+
989
+        return $this->basicOperation('fopen', $path, $hooks, $mode);
990
+    }
991
+
992
+    /**
993
+     * @param string $path
994
+     * @return bool|string
995
+     * @throws \OCP\Files\InvalidPathException
996
+     */
997
+    public function toTmpFile($path) {
998
+        $this->assertPathLength($path);
999
+        if (Filesystem::isValidPath($path)) {
1000
+            $source = $this->fopen($path, 'r');
1001
+            if ($source) {
1002
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
1003
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1004
+                file_put_contents($tmpFile, $source);
1005
+                return $tmpFile;
1006
+            } else {
1007
+                return false;
1008
+            }
1009
+        } else {
1010
+            return false;
1011
+        }
1012
+    }
1013
+
1014
+    /**
1015
+     * @param string $tmpFile
1016
+     * @param string $path
1017
+     * @return bool|mixed
1018
+     * @throws \OCP\Files\InvalidPathException
1019
+     */
1020
+    public function fromTmpFile($tmpFile, $path) {
1021
+        $this->assertPathLength($path);
1022
+        if (Filesystem::isValidPath($path)) {
1023
+
1024
+            // Get directory that the file is going into
1025
+            $filePath = dirname($path);
1026
+
1027
+            // Create the directories if any
1028
+            if (!$this->file_exists($filePath)) {
1029
+                $result = $this->createParentDirectories($filePath);
1030
+                if ($result === false) {
1031
+                    return false;
1032
+                }
1033
+            }
1034
+
1035
+            $source = fopen($tmpFile, 'r');
1036
+            if ($source) {
1037
+                $result = $this->file_put_contents($path, $source);
1038
+                // $this->file_put_contents() might have already closed
1039
+                // the resource, so we check it, before trying to close it
1040
+                // to avoid messages in the error log.
1041
+                if (is_resource($source)) {
1042
+                    fclose($source);
1043
+                }
1044
+                unlink($tmpFile);
1045
+                return $result;
1046
+            } else {
1047
+                return false;
1048
+            }
1049
+        } else {
1050
+            return false;
1051
+        }
1052
+    }
1053
+
1054
+
1055
+    /**
1056
+     * @param string $path
1057
+     * @return mixed
1058
+     * @throws \OCP\Files\InvalidPathException
1059
+     */
1060
+    public function getMimeType($path) {
1061
+        $this->assertPathLength($path);
1062
+        return $this->basicOperation('getMimeType', $path);
1063
+    }
1064
+
1065
+    /**
1066
+     * @param string $type
1067
+     * @param string $path
1068
+     * @param bool $raw
1069
+     * @return bool|null|string
1070
+     */
1071
+    public function hash($type, $path, $raw = false) {
1072
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1073
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1074
+        if (Filesystem::isValidPath($path)) {
1075
+            $path = $this->getRelativePath($absolutePath);
1076
+            if ($path == null) {
1077
+                return false;
1078
+            }
1079
+            if ($this->shouldEmitHooks($path)) {
1080
+                \OC_Hook::emit(
1081
+                    Filesystem::CLASSNAME,
1082
+                    Filesystem::signal_read,
1083
+                    array(Filesystem::signal_param_path => $this->getHookPath($path))
1084
+                );
1085
+            }
1086
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1087
+            if ($storage) {
1088
+                $result = $storage->hash($type, $internalPath, $raw);
1089
+                return $result;
1090
+            }
1091
+        }
1092
+        return null;
1093
+    }
1094
+
1095
+    /**
1096
+     * @param string $path
1097
+     * @return mixed
1098
+     * @throws \OCP\Files\InvalidPathException
1099
+     */
1100
+    public function free_space($path = '/') {
1101
+        $this->assertPathLength($path);
1102
+        $result = $this->basicOperation('free_space', $path);
1103
+        if ($result === null) {
1104
+            throw new InvalidPathException();
1105
+        }
1106
+        return $result;
1107
+    }
1108
+
1109
+    /**
1110
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1111
+     *
1112
+     * @param string $operation
1113
+     * @param string $path
1114
+     * @param array $hooks (optional)
1115
+     * @param mixed $extraParam (optional)
1116
+     * @return mixed
1117
+     * @throws \Exception
1118
+     *
1119
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1120
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1121
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1122
+     */
1123
+    private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1124
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1125
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1126
+        if (Filesystem::isValidPath($path)
1127
+            and !Filesystem::isFileBlacklisted($path)
1128
+        ) {
1129
+            $path = $this->getRelativePath($absolutePath);
1130
+            if ($path == null) {
1131
+                return false;
1132
+            }
1133
+
1134
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1135
+                // always a shared lock during pre-hooks so the hook can read the file
1136
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1137
+            }
1138
+
1139
+            $run = $this->runHooks($hooks, $path);
1140
+            /** @var \OC\Files\Storage\Storage $storage */
1141
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1142
+            if ($run and $storage) {
1143
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1144
+                    $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1145
+                }
1146
+                try {
1147
+                    if (!is_null($extraParam)) {
1148
+                        $result = $storage->$operation($internalPath, $extraParam);
1149
+                    } else {
1150
+                        $result = $storage->$operation($internalPath);
1151
+                    }
1152
+                } catch (\Exception $e) {
1153
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1154
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1155
+                    } else if (in_array('read', $hooks)) {
1156
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1157
+                    }
1158
+                    throw $e;
1159
+                }
1160
+
1161
+                if ($result && in_array('delete', $hooks) and $result) {
1162
+                    $this->removeUpdate($storage, $internalPath);
1163
+                }
1164
+                if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1165
+                    $this->writeUpdate($storage, $internalPath);
1166
+                }
1167
+                if ($result && in_array('touch', $hooks)) {
1168
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1169
+                }
1170
+
1171
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1172
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1173
+                }
1174
+
1175
+                $unlockLater = false;
1176
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1177
+                    $unlockLater = true;
1178
+                    // make sure our unlocking callback will still be called if connection is aborted
1179
+                    ignore_user_abort(true);
1180
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1181
+                        if (in_array('write', $hooks)) {
1182
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1183
+                        } else if (in_array('read', $hooks)) {
1184
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1185
+                        }
1186
+                    });
1187
+                }
1188
+
1189
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1190
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1191
+                        $this->runHooks($hooks, $path, true);
1192
+                    }
1193
+                }
1194
+
1195
+                if (!$unlockLater
1196
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1197
+                ) {
1198
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1199
+                }
1200
+                return $result;
1201
+            } else {
1202
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1203
+            }
1204
+        }
1205
+        return null;
1206
+    }
1207
+
1208
+    /**
1209
+     * get the path relative to the default root for hook usage
1210
+     *
1211
+     * @param string $path
1212
+     * @return string
1213
+     */
1214
+    private function getHookPath($path) {
1215
+        if (!Filesystem::getView()) {
1216
+            return $path;
1217
+        }
1218
+        return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1219
+    }
1220
+
1221
+    private function shouldEmitHooks($path = '') {
1222
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1223
+            return false;
1224
+        }
1225
+        if (!Filesystem::$loaded) {
1226
+            return false;
1227
+        }
1228
+        $defaultRoot = Filesystem::getRoot();
1229
+        if ($defaultRoot === null) {
1230
+            return false;
1231
+        }
1232
+        if ($this->fakeRoot === $defaultRoot) {
1233
+            return true;
1234
+        }
1235
+        $fullPath = $this->getAbsolutePath($path);
1236
+
1237
+        if ($fullPath === $defaultRoot) {
1238
+            return true;
1239
+        }
1240
+
1241
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1242
+    }
1243
+
1244
+    /**
1245
+     * @param string[] $hooks
1246
+     * @param string $path
1247
+     * @param bool $post
1248
+     * @return bool
1249
+     */
1250
+    private function runHooks($hooks, $path, $post = false) {
1251
+        $relativePath = $path;
1252
+        $path = $this->getHookPath($path);
1253
+        $prefix = ($post) ? 'post_' : '';
1254
+        $run = true;
1255
+        if ($this->shouldEmitHooks($relativePath)) {
1256
+            foreach ($hooks as $hook) {
1257
+                if ($hook != 'read') {
1258
+                    \OC_Hook::emit(
1259
+                        Filesystem::CLASSNAME,
1260
+                        $prefix . $hook,
1261
+                        array(
1262
+                            Filesystem::signal_param_run => &$run,
1263
+                            Filesystem::signal_param_path => $path
1264
+                        )
1265
+                    );
1266
+                } elseif (!$post) {
1267
+                    \OC_Hook::emit(
1268
+                        Filesystem::CLASSNAME,
1269
+                        $prefix . $hook,
1270
+                        array(
1271
+                            Filesystem::signal_param_path => $path
1272
+                        )
1273
+                    );
1274
+                }
1275
+            }
1276
+        }
1277
+        return $run;
1278
+    }
1279
+
1280
+    /**
1281
+     * check if a file or folder has been updated since $time
1282
+     *
1283
+     * @param string $path
1284
+     * @param int $time
1285
+     * @return bool
1286
+     */
1287
+    public function hasUpdated($path, $time) {
1288
+        return $this->basicOperation('hasUpdated', $path, array(), $time);
1289
+    }
1290
+
1291
+    /**
1292
+     * @param string $ownerId
1293
+     * @return \OC\User\User
1294
+     */
1295
+    private function getUserObjectForOwner($ownerId) {
1296
+        $owner = $this->userManager->get($ownerId);
1297
+        if ($owner instanceof IUser) {
1298
+            return $owner;
1299
+        } else {
1300
+            return new User($ownerId, null);
1301
+        }
1302
+    }
1303
+
1304
+    /**
1305
+     * Get file info from cache
1306
+     *
1307
+     * If the file is not in cached it will be scanned
1308
+     * If the file has changed on storage the cache will be updated
1309
+     *
1310
+     * @param \OC\Files\Storage\Storage $storage
1311
+     * @param string $internalPath
1312
+     * @param string $relativePath
1313
+     * @return ICacheEntry|bool
1314
+     */
1315
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1316
+        $cache = $storage->getCache($internalPath);
1317
+        $data = $cache->get($internalPath);
1318
+        $watcher = $storage->getWatcher($internalPath);
1319
+
1320
+        try {
1321
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1322
+            if (!$data || $data['size'] === -1) {
1323
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1324
+                if (!$storage->file_exists($internalPath)) {
1325
+                    $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1326
+                    return false;
1327
+                }
1328
+                $scanner = $storage->getScanner($internalPath);
1329
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1330
+                $data = $cache->get($internalPath);
1331
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1332
+            } else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1333
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1334
+                $watcher->update($internalPath, $data);
1335
+                $storage->getPropagator()->propagateChange($internalPath, time());
1336
+                $data = $cache->get($internalPath);
1337
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1338
+            }
1339
+        } catch (LockedException $e) {
1340
+            // if the file is locked we just use the old cache info
1341
+        }
1342
+
1343
+        return $data;
1344
+    }
1345
+
1346
+    /**
1347
+     * get the filesystem info
1348
+     *
1349
+     * @param string $path
1350
+     * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1351
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1352
+     * defaults to true
1353
+     * @return \OC\Files\FileInfo|false False if file does not exist
1354
+     */
1355
+    public function getFileInfo($path, $includeMountPoints = true) {
1356
+        $this->assertPathLength($path);
1357
+        if (!Filesystem::isValidPath($path)) {
1358
+            return false;
1359
+        }
1360
+        if (Cache\Scanner::isPartialFile($path)) {
1361
+            return $this->getPartFileInfo($path);
1362
+        }
1363
+        $relativePath = $path;
1364
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1365
+
1366
+        $mount = Filesystem::getMountManager()->find($path);
1367
+        $storage = $mount->getStorage();
1368
+        $internalPath = $mount->getInternalPath($path);
1369
+        if ($storage) {
1370
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1371
+
1372
+            if (!$data instanceof ICacheEntry) {
1373
+                return false;
1374
+            }
1375
+
1376
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1377
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1378
+            }
1379
+
1380
+            $owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1381
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1382
+
1383
+            if ($data and isset($data['fileid'])) {
1384
+                if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1385
+                    //add the sizes of other mount points to the folder
1386
+                    $extOnly = ($includeMountPoints === 'ext');
1387
+                    $mounts = Filesystem::getMountManager()->findIn($path);
1388
+                    $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1389
+                        $subStorage = $mount->getStorage();
1390
+                        return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1391
+                    }));
1392
+                }
1393
+            }
1394
+
1395
+            return $info;
1396
+        }
1397
+
1398
+        return false;
1399
+    }
1400
+
1401
+    /**
1402
+     * get the content of a directory
1403
+     *
1404
+     * @param string $directory path under datadirectory
1405
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1406
+     * @return FileInfo[]
1407
+     */
1408
+    public function getDirectoryContent($directory, $mimetype_filter = '') {
1409
+        $this->assertPathLength($directory);
1410
+        if (!Filesystem::isValidPath($directory)) {
1411
+            return [];
1412
+        }
1413
+        $path = $this->getAbsolutePath($directory);
1414
+        $path = Filesystem::normalizePath($path);
1415
+        $mount = $this->getMount($directory);
1416
+        $storage = $mount->getStorage();
1417
+        $internalPath = $mount->getInternalPath($path);
1418
+        if ($storage) {
1419
+            $cache = $storage->getCache($internalPath);
1420
+            $user = \OC_User::getUser();
1421
+
1422
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1423
+
1424
+            if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1425
+                return [];
1426
+            }
1427
+
1428
+            $folderId = $data['fileid'];
1429
+            $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1430
+
1431
+            $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1432
+            /**
1433
+             * @var \OC\Files\FileInfo[] $files
1434
+             */
1435
+            $files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1436
+                if ($sharingDisabled) {
1437
+                    $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1438
+                }
1439
+                $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1440
+                return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1441
+            }, $contents);
1442
+
1443
+            //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1444
+            $mounts = Filesystem::getMountManager()->findIn($path);
1445
+            $dirLength = strlen($path);
1446
+            foreach ($mounts as $mount) {
1447
+                $mountPoint = $mount->getMountPoint();
1448
+                $subStorage = $mount->getStorage();
1449
+                if ($subStorage) {
1450
+                    $subCache = $subStorage->getCache('');
1451
+
1452
+                    $rootEntry = $subCache->get('');
1453
+                    if (!$rootEntry) {
1454
+                        $subScanner = $subStorage->getScanner('');
1455
+                        try {
1456
+                            $subScanner->scanFile('');
1457
+                        } catch (\OCP\Files\StorageNotAvailableException $e) {
1458
+                            continue;
1459
+                        } catch (\OCP\Files\StorageInvalidException $e) {
1460
+                            continue;
1461
+                        } catch (\Exception $e) {
1462
+                            // sometimes when the storage is not available it can be any exception
1463
+                            \OCP\Util::writeLog(
1464
+                                'core',
1465
+                                'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1466
+                                get_class($e) . ': ' . $e->getMessage(),
1467
+                                \OCP\Util::ERROR
1468
+                            );
1469
+                            continue;
1470
+                        }
1471
+                        $rootEntry = $subCache->get('');
1472
+                    }
1473
+
1474
+                    if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1475
+                        $relativePath = trim(substr($mountPoint, $dirLength), '/');
1476
+                        if ($pos = strpos($relativePath, '/')) {
1477
+                            //mountpoint inside subfolder add size to the correct folder
1478
+                            $entryName = substr($relativePath, 0, $pos);
1479
+                            foreach ($files as &$entry) {
1480
+                                if ($entry->getName() === $entryName) {
1481
+                                    $entry->addSubEntry($rootEntry, $mountPoint);
1482
+                                }
1483
+                            }
1484
+                        } else { //mountpoint in this folder, add an entry for it
1485
+                            $rootEntry['name'] = $relativePath;
1486
+                            $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1487
+                            $permissions = $rootEntry['permissions'];
1488
+                            // do not allow renaming/deleting the mount point if they are not shared files/folders
1489
+                            // for shared files/folders we use the permissions given by the owner
1490
+                            if ($mount instanceof MoveableMount) {
1491
+                                $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1492
+                            } else {
1493
+                                $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1494
+                            }
1495
+
1496
+                            //remove any existing entry with the same name
1497
+                            foreach ($files as $i => $file) {
1498
+                                if ($file['name'] === $rootEntry['name']) {
1499
+                                    unset($files[$i]);
1500
+                                    break;
1501
+                                }
1502
+                            }
1503
+                            $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1504
+
1505
+                            // if sharing was disabled for the user we remove the share permissions
1506
+                            if (\OCP\Util::isSharingDisabledForUser()) {
1507
+                                $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1508
+                            }
1509
+
1510
+                            $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1511
+                            $files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1512
+                        }
1513
+                    }
1514
+                }
1515
+            }
1516
+
1517
+            if ($mimetype_filter) {
1518
+                $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1519
+                    if (strpos($mimetype_filter, '/')) {
1520
+                        return $file->getMimetype() === $mimetype_filter;
1521
+                    } else {
1522
+                        return $file->getMimePart() === $mimetype_filter;
1523
+                    }
1524
+                });
1525
+            }
1526
+
1527
+            return $files;
1528
+        } else {
1529
+            return [];
1530
+        }
1531
+    }
1532
+
1533
+    /**
1534
+     * change file metadata
1535
+     *
1536
+     * @param string $path
1537
+     * @param array|\OCP\Files\FileInfo $data
1538
+     * @return int
1539
+     *
1540
+     * returns the fileid of the updated file
1541
+     */
1542
+    public function putFileInfo($path, $data) {
1543
+        $this->assertPathLength($path);
1544
+        if ($data instanceof FileInfo) {
1545
+            $data = $data->getData();
1546
+        }
1547
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1548
+        /**
1549
+         * @var \OC\Files\Storage\Storage $storage
1550
+         * @var string $internalPath
1551
+         */
1552
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
1553
+        if ($storage) {
1554
+            $cache = $storage->getCache($path);
1555
+
1556
+            if (!$cache->inCache($internalPath)) {
1557
+                $scanner = $storage->getScanner($internalPath);
1558
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1559
+            }
1560
+
1561
+            return $cache->put($internalPath, $data);
1562
+        } else {
1563
+            return -1;
1564
+        }
1565
+    }
1566
+
1567
+    /**
1568
+     * search for files with the name matching $query
1569
+     *
1570
+     * @param string $query
1571
+     * @return FileInfo[]
1572
+     */
1573
+    public function search($query) {
1574
+        return $this->searchCommon('search', array('%' . $query . '%'));
1575
+    }
1576
+
1577
+    /**
1578
+     * search for files with the name matching $query
1579
+     *
1580
+     * @param string $query
1581
+     * @return FileInfo[]
1582
+     */
1583
+    public function searchRaw($query) {
1584
+        return $this->searchCommon('search', array($query));
1585
+    }
1586
+
1587
+    /**
1588
+     * search for files by mimetype
1589
+     *
1590
+     * @param string $mimetype
1591
+     * @return FileInfo[]
1592
+     */
1593
+    public function searchByMime($mimetype) {
1594
+        return $this->searchCommon('searchByMime', array($mimetype));
1595
+    }
1596
+
1597
+    /**
1598
+     * search for files by tag
1599
+     *
1600
+     * @param string|int $tag name or tag id
1601
+     * @param string $userId owner of the tags
1602
+     * @return FileInfo[]
1603
+     */
1604
+    public function searchByTag($tag, $userId) {
1605
+        return $this->searchCommon('searchByTag', array($tag, $userId));
1606
+    }
1607
+
1608
+    /**
1609
+     * @param string $method cache method
1610
+     * @param array $args
1611
+     * @return FileInfo[]
1612
+     */
1613
+    private function searchCommon($method, $args) {
1614
+        $files = array();
1615
+        $rootLength = strlen($this->fakeRoot);
1616
+
1617
+        $mount = $this->getMount('');
1618
+        $mountPoint = $mount->getMountPoint();
1619
+        $storage = $mount->getStorage();
1620
+        if ($storage) {
1621
+            $cache = $storage->getCache('');
1622
+
1623
+            $results = call_user_func_array(array($cache, $method), $args);
1624
+            foreach ($results as $result) {
1625
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1626
+                    $internalPath = $result['path'];
1627
+                    $path = $mountPoint . $result['path'];
1628
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1629
+                    $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1630
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1631
+                }
1632
+            }
1633
+
1634
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1635
+            foreach ($mounts as $mount) {
1636
+                $mountPoint = $mount->getMountPoint();
1637
+                $storage = $mount->getStorage();
1638
+                if ($storage) {
1639
+                    $cache = $storage->getCache('');
1640
+
1641
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1642
+                    $results = call_user_func_array(array($cache, $method), $args);
1643
+                    if ($results) {
1644
+                        foreach ($results as $result) {
1645
+                            $internalPath = $result['path'];
1646
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1647
+                            $path = rtrim($mountPoint . $internalPath, '/');
1648
+                            $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1649
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1650
+                        }
1651
+                    }
1652
+                }
1653
+            }
1654
+        }
1655
+        return $files;
1656
+    }
1657
+
1658
+    /**
1659
+     * Get the owner for a file or folder
1660
+     *
1661
+     * @param string $path
1662
+     * @return string the user id of the owner
1663
+     * @throws NotFoundException
1664
+     */
1665
+    public function getOwner($path) {
1666
+        $info = $this->getFileInfo($path);
1667
+        if (!$info) {
1668
+            throw new NotFoundException($path . ' not found while trying to get owner');
1669
+        }
1670
+        return $info->getOwner()->getUID();
1671
+    }
1672
+
1673
+    /**
1674
+     * get the ETag for a file or folder
1675
+     *
1676
+     * @param string $path
1677
+     * @return string
1678
+     */
1679
+    public function getETag($path) {
1680
+        /**
1681
+         * @var Storage\Storage $storage
1682
+         * @var string $internalPath
1683
+         */
1684
+        list($storage, $internalPath) = $this->resolvePath($path);
1685
+        if ($storage) {
1686
+            return $storage->getETag($internalPath);
1687
+        } else {
1688
+            return null;
1689
+        }
1690
+    }
1691
+
1692
+    /**
1693
+     * Get the path of a file by id, relative to the view
1694
+     *
1695
+     * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1696
+     *
1697
+     * @param int $id
1698
+     * @throws NotFoundException
1699
+     * @return string
1700
+     */
1701
+    public function getPath($id) {
1702
+        $id = (int)$id;
1703
+        $manager = Filesystem::getMountManager();
1704
+        $mounts = $manager->findIn($this->fakeRoot);
1705
+        $mounts[] = $manager->find($this->fakeRoot);
1706
+        // reverse the array so we start with the storage this view is in
1707
+        // which is the most likely to contain the file we're looking for
1708
+        $mounts = array_reverse($mounts);
1709
+        foreach ($mounts as $mount) {
1710
+            /**
1711
+             * @var \OC\Files\Mount\MountPoint $mount
1712
+             */
1713
+            if ($mount->getStorage()) {
1714
+                $cache = $mount->getStorage()->getCache();
1715
+                $internalPath = $cache->getPathById($id);
1716
+                if (is_string($internalPath)) {
1717
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1718
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1719
+                        return $path;
1720
+                    }
1721
+                }
1722
+            }
1723
+        }
1724
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1725
+    }
1726
+
1727
+    /**
1728
+     * @param string $path
1729
+     * @throws InvalidPathException
1730
+     */
1731
+    private function assertPathLength($path) {
1732
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1733
+        // Check for the string length - performed using isset() instead of strlen()
1734
+        // because isset() is about 5x-40x faster.
1735
+        if (isset($path[$maxLen])) {
1736
+            $pathLen = strlen($path);
1737
+            throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1738
+        }
1739
+    }
1740
+
1741
+    /**
1742
+     * check if it is allowed to move a mount point to a given target.
1743
+     * It is not allowed to move a mount point into a different mount point or
1744
+     * into an already shared folder
1745
+     *
1746
+     * @param string $target path
1747
+     * @return boolean
1748
+     */
1749
+    private function isTargetAllowed($target) {
1750
+
1751
+        list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1752
+        if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1753
+            \OCP\Util::writeLog('files',
1754
+                'It is not allowed to move one mount point into another one',
1755
+                \OCP\Util::DEBUG);
1756
+            return false;
1757
+        }
1758
+
1759
+        // note: cannot use the view because the target is already locked
1760
+        $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1761
+        if ($fileId === -1) {
1762
+            // target might not exist, need to check parent instead
1763
+            $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1764
+        }
1765
+
1766
+        // check if any of the parents were shared by the current owner (include collections)
1767
+        $shares = \OCP\Share::getItemShared(
1768
+            'folder',
1769
+            $fileId,
1770
+            \OCP\Share::FORMAT_NONE,
1771
+            null,
1772
+            true
1773
+        );
1774
+
1775
+        if (count($shares) > 0) {
1776
+            \OCP\Util::writeLog('files',
1777
+                'It is not allowed to move one mount point into a shared folder',
1778
+                \OCP\Util::DEBUG);
1779
+            return false;
1780
+        }
1781
+
1782
+        return true;
1783
+    }
1784
+
1785
+    /**
1786
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1787
+     *
1788
+     * @param string $path
1789
+     * @return \OCP\Files\FileInfo
1790
+     */
1791
+    private function getPartFileInfo($path) {
1792
+        $mount = $this->getMount($path);
1793
+        $storage = $mount->getStorage();
1794
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1795
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1796
+        return new FileInfo(
1797
+            $this->getAbsolutePath($path),
1798
+            $storage,
1799
+            $internalPath,
1800
+            [
1801
+                'fileid' => null,
1802
+                'mimetype' => $storage->getMimeType($internalPath),
1803
+                'name' => basename($path),
1804
+                'etag' => null,
1805
+                'size' => $storage->filesize($internalPath),
1806
+                'mtime' => $storage->filemtime($internalPath),
1807
+                'encrypted' => false,
1808
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1809
+            ],
1810
+            $mount,
1811
+            $owner
1812
+        );
1813
+    }
1814
+
1815
+    /**
1816
+     * @param string $path
1817
+     * @param string $fileName
1818
+     * @throws InvalidPathException
1819
+     */
1820
+    public function verifyPath($path, $fileName) {
1821
+        try {
1822
+            /** @type \OCP\Files\Storage $storage */
1823
+            list($storage, $internalPath) = $this->resolvePath($path);
1824
+            $storage->verifyPath($internalPath, $fileName);
1825
+        } catch (ReservedWordException $ex) {
1826
+            $l = \OC::$server->getL10N('lib');
1827
+            throw new InvalidPathException($l->t('File name is a reserved word'));
1828
+        } catch (InvalidCharacterInPathException $ex) {
1829
+            $l = \OC::$server->getL10N('lib');
1830
+            throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1831
+        } catch (FileNameTooLongException $ex) {
1832
+            $l = \OC::$server->getL10N('lib');
1833
+            throw new InvalidPathException($l->t('File name is too long'));
1834
+        } catch (InvalidDirectoryException $ex) {
1835
+            $l = \OC::$server->getL10N('lib');
1836
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1837
+        } catch (EmptyFileNameException $ex) {
1838
+            $l = \OC::$server->getL10N('lib');
1839
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1840
+        }
1841
+    }
1842
+
1843
+    /**
1844
+     * get all parent folders of $path
1845
+     *
1846
+     * @param string $path
1847
+     * @return string[]
1848
+     */
1849
+    private function getParents($path) {
1850
+        $path = trim($path, '/');
1851
+        if (!$path) {
1852
+            return [];
1853
+        }
1854
+
1855
+        $parts = explode('/', $path);
1856
+
1857
+        // remove the single file
1858
+        array_pop($parts);
1859
+        $result = array('/');
1860
+        $resultPath = '';
1861
+        foreach ($parts as $part) {
1862
+            if ($part) {
1863
+                $resultPath .= '/' . $part;
1864
+                $result[] = $resultPath;
1865
+            }
1866
+        }
1867
+        return $result;
1868
+    }
1869
+
1870
+    /**
1871
+     * Returns the mount point for which to lock
1872
+     *
1873
+     * @param string $absolutePath absolute path
1874
+     * @param bool $useParentMount true to return parent mount instead of whatever
1875
+     * is mounted directly on the given path, false otherwise
1876
+     * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1877
+     */
1878
+    private function getMountForLock($absolutePath, $useParentMount = false) {
1879
+        $results = [];
1880
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1881
+        if (!$mount) {
1882
+            return $results;
1883
+        }
1884
+
1885
+        if ($useParentMount) {
1886
+            // find out if something is mounted directly on the path
1887
+            $internalPath = $mount->getInternalPath($absolutePath);
1888
+            if ($internalPath === '') {
1889
+                // resolve the parent mount instead
1890
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1891
+            }
1892
+        }
1893
+
1894
+        return $mount;
1895
+    }
1896
+
1897
+    /**
1898
+     * Lock the given path
1899
+     *
1900
+     * @param string $path the path of the file to lock, relative to the view
1901
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1902
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1903
+     *
1904
+     * @return bool False if the path is excluded from locking, true otherwise
1905
+     * @throws \OCP\Lock\LockedException if the path is already locked
1906
+     */
1907
+    private function lockPath($path, $type, $lockMountPoint = false) {
1908
+        $absolutePath = $this->getAbsolutePath($path);
1909
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1910
+        if (!$this->shouldLockFile($absolutePath)) {
1911
+            return false;
1912
+        }
1913
+
1914
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1915
+        if ($mount) {
1916
+            try {
1917
+                $storage = $mount->getStorage();
1918
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1919
+                    $storage->acquireLock(
1920
+                        $mount->getInternalPath($absolutePath),
1921
+                        $type,
1922
+                        $this->lockingProvider
1923
+                    );
1924
+                }
1925
+            } catch (\OCP\Lock\LockedException $e) {
1926
+                // rethrow with the a human-readable path
1927
+                throw new \OCP\Lock\LockedException(
1928
+                    $this->getPathRelativeToFiles($absolutePath),
1929
+                    $e
1930
+                );
1931
+            }
1932
+        }
1933
+
1934
+        return true;
1935
+    }
1936
+
1937
+    /**
1938
+     * Change the lock type
1939
+     *
1940
+     * @param string $path the path of the file to lock, relative to the view
1941
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1942
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1943
+     *
1944
+     * @return bool False if the path is excluded from locking, true otherwise
1945
+     * @throws \OCP\Lock\LockedException if the path is already locked
1946
+     */
1947
+    public function changeLock($path, $type, $lockMountPoint = false) {
1948
+        $path = Filesystem::normalizePath($path);
1949
+        $absolutePath = $this->getAbsolutePath($path);
1950
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1951
+        if (!$this->shouldLockFile($absolutePath)) {
1952
+            return false;
1953
+        }
1954
+
1955
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1956
+        if ($mount) {
1957
+            try {
1958
+                $storage = $mount->getStorage();
1959
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1960
+                    $storage->changeLock(
1961
+                        $mount->getInternalPath($absolutePath),
1962
+                        $type,
1963
+                        $this->lockingProvider
1964
+                    );
1965
+                }
1966
+            } catch (\OCP\Lock\LockedException $e) {
1967
+                try {
1968
+                    // rethrow with the a human-readable path
1969
+                    throw new \OCP\Lock\LockedException(
1970
+                        $this->getPathRelativeToFiles($absolutePath),
1971
+                        $e
1972
+                    );
1973
+                } catch (\InvalidArgumentException $e) {
1974
+                    throw new \OCP\Lock\LockedException(
1975
+                        $absolutePath,
1976
+                        $e
1977
+                    );
1978
+                }
1979
+            }
1980
+        }
1981
+
1982
+        return true;
1983
+    }
1984
+
1985
+    /**
1986
+     * Unlock the given path
1987
+     *
1988
+     * @param string $path the path of the file to unlock, relative to the view
1989
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1990
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1991
+     *
1992
+     * @return bool False if the path is excluded from locking, true otherwise
1993
+     */
1994
+    private function unlockPath($path, $type, $lockMountPoint = false) {
1995
+        $absolutePath = $this->getAbsolutePath($path);
1996
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1997
+        if (!$this->shouldLockFile($absolutePath)) {
1998
+            return false;
1999
+        }
2000
+
2001
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2002
+        if ($mount) {
2003
+            $storage = $mount->getStorage();
2004
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2005
+                $storage->releaseLock(
2006
+                    $mount->getInternalPath($absolutePath),
2007
+                    $type,
2008
+                    $this->lockingProvider
2009
+                );
2010
+            }
2011
+        }
2012
+
2013
+        return true;
2014
+    }
2015
+
2016
+    /**
2017
+     * Lock a path and all its parents up to the root of the view
2018
+     *
2019
+     * @param string $path the path of the file to lock relative to the view
2020
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2021
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2022
+     *
2023
+     * @return bool False if the path is excluded from locking, true otherwise
2024
+     */
2025
+    public function lockFile($path, $type, $lockMountPoint = false) {
2026
+        $absolutePath = $this->getAbsolutePath($path);
2027
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2028
+        if (!$this->shouldLockFile($absolutePath)) {
2029
+            return false;
2030
+        }
2031
+
2032
+        $this->lockPath($path, $type, $lockMountPoint);
2033
+
2034
+        $parents = $this->getParents($path);
2035
+        foreach ($parents as $parent) {
2036
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2037
+        }
2038
+
2039
+        return true;
2040
+    }
2041
+
2042
+    /**
2043
+     * Unlock a path and all its parents up to the root of the view
2044
+     *
2045
+     * @param string $path the path of the file to lock relative to the view
2046
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2047
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2048
+     *
2049
+     * @return bool False if the path is excluded from locking, true otherwise
2050
+     */
2051
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2052
+        $absolutePath = $this->getAbsolutePath($path);
2053
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2054
+        if (!$this->shouldLockFile($absolutePath)) {
2055
+            return false;
2056
+        }
2057
+
2058
+        $this->unlockPath($path, $type, $lockMountPoint);
2059
+
2060
+        $parents = $this->getParents($path);
2061
+        foreach ($parents as $parent) {
2062
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2063
+        }
2064
+
2065
+        return true;
2066
+    }
2067
+
2068
+    /**
2069
+     * Only lock files in data/user/files/
2070
+     *
2071
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2072
+     * @return bool
2073
+     */
2074
+    protected function shouldLockFile($path) {
2075
+        $path = Filesystem::normalizePath($path);
2076
+
2077
+        $pathSegments = explode('/', $path);
2078
+        if (isset($pathSegments[2])) {
2079
+            // E.g.: /username/files/path-to-file
2080
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2081
+        }
2082
+
2083
+        return strpos($path, '/appdata_') !== 0;
2084
+    }
2085
+
2086
+    /**
2087
+     * Shortens the given absolute path to be relative to
2088
+     * "$user/files".
2089
+     *
2090
+     * @param string $absolutePath absolute path which is under "files"
2091
+     *
2092
+     * @return string path relative to "files" with trimmed slashes or null
2093
+     * if the path was NOT relative to files
2094
+     *
2095
+     * @throws \InvalidArgumentException if the given path was not under "files"
2096
+     * @since 8.1.0
2097
+     */
2098
+    public function getPathRelativeToFiles($absolutePath) {
2099
+        $path = Filesystem::normalizePath($absolutePath);
2100
+        $parts = explode('/', trim($path, '/'), 3);
2101
+        // "$user", "files", "path/to/dir"
2102
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2103
+            $this->logger->error(
2104
+                '$absolutePath must be relative to "files", value is "%s"',
2105
+                [
2106
+                    $absolutePath
2107
+                ]
2108
+            );
2109
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2110
+        }
2111
+        if (isset($parts[2])) {
2112
+            return $parts[2];
2113
+        }
2114
+        return '';
2115
+    }
2116
+
2117
+    /**
2118
+     * @param string $filename
2119
+     * @return array
2120
+     * @throws \OC\User\NoUserException
2121
+     * @throws NotFoundException
2122
+     */
2123
+    public function getUidAndFilename($filename) {
2124
+        $info = $this->getFileInfo($filename);
2125
+        if (!$info instanceof \OCP\Files\FileInfo) {
2126
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2127
+        }
2128
+        $uid = $info->getOwner()->getUID();
2129
+        if ($uid != \OCP\User::getUser()) {
2130
+            Filesystem::initMountPoints($uid);
2131
+            $ownerView = new View('/' . $uid . '/files');
2132
+            try {
2133
+                $filename = $ownerView->getPath($info['fileid']);
2134
+            } catch (NotFoundException $e) {
2135
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2136
+            }
2137
+        }
2138
+        return [$uid, $filename];
2139
+    }
2140
+
2141
+    /**
2142
+     * Creates parent non-existing folders
2143
+     *
2144
+     * @param string $filePath
2145
+     * @return bool
2146
+     */
2147
+    private function createParentDirectories($filePath) {
2148
+        $directoryParts = explode('/', $filePath);
2149
+        $directoryParts = array_filter($directoryParts);
2150
+        foreach ($directoryParts as $key => $part) {
2151
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2152
+            $currentPath = '/' . implode('/', $currentPathElements);
2153
+            if ($this->is_file($currentPath)) {
2154
+                return false;
2155
+            }
2156
+            if (!$this->file_exists($currentPath)) {
2157
+                $this->mkdir($currentPath);
2158
+            }
2159
+        }
2160
+
2161
+        return true;
2162
+    }
2163 2163
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Helper.php 3 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -303,6 +303,7 @@
 block discarded – undo
303 303
 	 * get default share folder
304 304
 	 *
305 305
 	 * @param \OC\Files\View
306
+	 * @param View $view
306 307
 	 * @return string
307 308
 	 */
308 309
 	public static function getShareFolder($view = null) {
Please login to merge, or discard this patch.
Indentation   +237 added lines, -237 removed lines patch added patch discarded remove patch
@@ -36,242 +36,242 @@
 block discarded – undo
36 36
 
37 37
 class Helper {
38 38
 
39
-	public static function registerHooks() {
40
-		\OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\OCA\Files_Sharing\Updater', 'renameHook');
41
-		\OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren');
42
-
43
-		\OCP\Util::connectHook('OC_User', 'post_deleteUser', '\OCA\Files_Sharing\Hooks', 'deleteUser');
44
-	}
45
-
46
-	/**
47
-	 * Sets up the filesystem and user for public sharing
48
-	 * @param string $token string share token
49
-	 * @param string $relativePath optional path relative to the share
50
-	 * @param string $password optional password
51
-	 * @return array
52
-	 */
53
-	public static function setupFromToken($token, $relativePath = null, $password = null) {
54
-		\OC_User::setIncognitoMode(true);
55
-
56
-		$shareManager = \OC::$server->getShareManager();
57
-
58
-		try {
59
-			$share = $shareManager->getShareByToken($token);
60
-		} catch (ShareNotFound $e) {
61
-			\OC_Response::setStatus(404);
62
-			\OCP\Util::writeLog('core-preview', 'Passed token parameter is not valid', \OCP\Util::DEBUG);
63
-			exit;
64
-		}
65
-
66
-		\OCP\JSON::checkUserExists($share->getShareOwner());
67
-		\OC_Util::tearDownFS();
68
-		\OC_Util::setupFS($share->getShareOwner());
69
-
70
-
71
-		try {
72
-			$path = Filesystem::getPath($share->getNodeId());
73
-		} catch (NotFoundException $e) {
74
-			\OCP\Util::writeLog('share', 'could not resolve linkItem', \OCP\Util::DEBUG);
75
-			\OC_Response::setStatus(404);
76
-			\OCP\JSON::error(array('success' => false));
77
-			exit();
78
-		}
79
-
80
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK && $share->getPassword() !== null) {
81
-			if (!self::authenticate($share, $password)) {
82
-				\OC_Response::setStatus(403);
83
-				\OCP\JSON::error(array('success' => false));
84
-				exit();
85
-			}
86
-		}
87
-
88
-		$basePath = $path;
89
-
90
-		if ($relativePath !== null && Filesystem::isReadable($basePath . $relativePath)) {
91
-			$path .= Filesystem::normalizePath($relativePath);
92
-		}
93
-
94
-		return array(
95
-			'share' => $share,
96
-			'basePath' => $basePath,
97
-			'realPath' => $path
98
-		);
99
-	}
100
-
101
-	/**
102
-	 * Authenticate link item with the given password
103
-	 * or with the session if no password was given.
104
-	 * @param \OCP\Share\IShare $share
105
-	 * @param string $password optional password
106
-	 *
107
-	 * @return boolean true if authorized, false otherwise
108
-	 */
109
-	public static function authenticate($share, $password = null) {
110
-		$shareManager = \OC::$server->getShareManager();
111
-
112
-		if ($password !== null) {
113
-			if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
-				if ($shareManager->checkPassword($share, $password)) {
115
-					\OC::$server->getSession()->set('public_link_authenticated', (string)$share->getId());
116
-					return true;
117
-				}
118
-			}
119
-		} else {
120
-			// not authenticated ?
121
-			if (\OC::$server->getSession()->exists('public_link_authenticated')
122
-				&& \OC::$server->getSession()->get('public_link_authenticated') !== (string)$share->getId()) {
123
-				return true;
124
-			}
125
-		}
126
-		return false;
127
-	}
128
-
129
-	public static function getSharesFromItem($target) {
130
-		$result = array();
131
-		$owner = Filesystem::getOwner($target);
132
-		Filesystem::initMountPoints($owner);
133
-		$info = Filesystem::getFileInfo($target);
134
-		$ownerView = new View('/'.$owner.'/files');
135
-		if ( $owner !== User::getUser() ) {
136
-			$path = $ownerView->getPath($info['fileid']);
137
-		} else {
138
-			$path = $target;
139
-		}
140
-
141
-
142
-		$ids = array();
143
-		while ($path !== dirname($path)) {
144
-			$info = $ownerView->getFileInfo($path);
145
-			if ($info instanceof \OC\Files\FileInfo) {
146
-				$ids[] = $info['fileid'];
147
-			} else {
148
-				\OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
149
-			}
150
-			$path = dirname($path);
151
-		}
152
-
153
-		if (!empty($ids)) {
154
-
155
-			$idList = array_chunk($ids, 99, true);
156
-
157
-			foreach ($idList as $subList) {
158
-				$statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
159
-				$query = \OCP\DB::prepare($statement);
160
-				$r = $query->execute();
161
-				$result = array_merge($result, $r->fetchAll());
162
-			}
163
-		}
164
-
165
-		return $result;
166
-	}
167
-
168
-	/**
169
-	 * get the UID of the owner of the file and the path to the file relative to
170
-	 * owners files folder
171
-	 *
172
-	 * @param $filename
173
-	 * @return array
174
-	 * @throws \OC\User\NoUserException
175
-	 */
176
-	public static function getUidAndFilename($filename) {
177
-		$uid = Filesystem::getOwner($filename);
178
-		$userManager = \OC::$server->getUserManager();
179
-		// if the user with the UID doesn't exists, e.g. because the UID points
180
-		// to a remote user with a federated cloud ID we use the current logged-in
181
-		// user. We need a valid local user to create the share
182
-		if (!$userManager->userExists($uid)) {
183
-			$uid = User::getUser();
184
-		}
185
-		Filesystem::initMountPoints($uid);
186
-		if ( $uid !== User::getUser() ) {
187
-			$info = Filesystem::getFileInfo($filename);
188
-			$ownerView = new View('/'.$uid.'/files');
189
-			try {
190
-				$filename = $ownerView->getPath($info['fileid']);
191
-			} catch (NotFoundException $e) {
192
-				$filename = null;
193
-			}
194
-		}
195
-		return [$uid, $filename];
196
-	}
197
-
198
-	/**
199
-	 * Format a path to be relative to the /user/files/ directory
200
-	 * @param string $path the absolute path
201
-	 * @return string e.g. turns '/admin/files/test.txt' into 'test.txt'
202
-	 */
203
-	public static function stripUserFilesPath($path) {
204
-		$trimmed = ltrim($path, '/');
205
-		$split = explode('/', $trimmed);
206
-
207
-		// it is not a file relative to data/user/files
208
-		if (count($split) < 3 || $split[1] !== 'files') {
209
-			return false;
210
-		}
211
-
212
-		$sliced = array_slice($split, 2);
213
-		$relPath = implode('/', $sliced);
214
-
215
-		return $relPath;
216
-	}
217
-
218
-	/**
219
-	 * check if file name already exists and generate unique target
220
-	 *
221
-	 * @param string $path
222
-	 * @param array $excludeList
223
-	 * @param View $view
224
-	 * @return string $path
225
-	 */
226
-	public static function generateUniqueTarget($path, $excludeList, $view) {
227
-		$pathinfo = pathinfo($path);
228
-		$ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
229
-		$name = $pathinfo['filename'];
230
-		$dir = $pathinfo['dirname'];
231
-		$i = 2;
232
-		while ($view->file_exists($path) || in_array($path, $excludeList)) {
233
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
234
-			$i++;
235
-		}
236
-
237
-		return $path;
238
-	}
239
-
240
-	/**
241
-	 * get default share folder
242
-	 *
243
-	 * @param \OC\Files\View
244
-	 * @return string
245
-	 */
246
-	public static function getShareFolder($view = null) {
247
-		if ($view === null) {
248
-			$view = Filesystem::getView();
249
-		}
250
-		$shareFolder = \OC::$server->getConfig()->getSystemValue('share_folder', '/');
251
-		$shareFolder = Filesystem::normalizePath($shareFolder);
252
-
253
-		if (!$view->file_exists($shareFolder)) {
254
-			$dir = '';
255
-			$subdirs = explode('/', $shareFolder);
256
-			foreach ($subdirs as $subdir) {
257
-				$dir = $dir . '/' . $subdir;
258
-				if (!$view->is_dir($dir)) {
259
-					$view->mkdir($dir);
260
-				}
261
-			}
262
-		}
263
-
264
-		return $shareFolder;
265
-
266
-	}
267
-
268
-	/**
269
-	 * set default share folder
270
-	 *
271
-	 * @param string $shareFolder
272
-	 */
273
-	public static function setShareFolder($shareFolder) {
274
-		\OC::$server->getConfig()->setSystemValue('share_folder', $shareFolder);
275
-	}
39
+    public static function registerHooks() {
40
+        \OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\OCA\Files_Sharing\Updater', 'renameHook');
41
+        \OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren');
42
+
43
+        \OCP\Util::connectHook('OC_User', 'post_deleteUser', '\OCA\Files_Sharing\Hooks', 'deleteUser');
44
+    }
45
+
46
+    /**
47
+     * Sets up the filesystem and user for public sharing
48
+     * @param string $token string share token
49
+     * @param string $relativePath optional path relative to the share
50
+     * @param string $password optional password
51
+     * @return array
52
+     */
53
+    public static function setupFromToken($token, $relativePath = null, $password = null) {
54
+        \OC_User::setIncognitoMode(true);
55
+
56
+        $shareManager = \OC::$server->getShareManager();
57
+
58
+        try {
59
+            $share = $shareManager->getShareByToken($token);
60
+        } catch (ShareNotFound $e) {
61
+            \OC_Response::setStatus(404);
62
+            \OCP\Util::writeLog('core-preview', 'Passed token parameter is not valid', \OCP\Util::DEBUG);
63
+            exit;
64
+        }
65
+
66
+        \OCP\JSON::checkUserExists($share->getShareOwner());
67
+        \OC_Util::tearDownFS();
68
+        \OC_Util::setupFS($share->getShareOwner());
69
+
70
+
71
+        try {
72
+            $path = Filesystem::getPath($share->getNodeId());
73
+        } catch (NotFoundException $e) {
74
+            \OCP\Util::writeLog('share', 'could not resolve linkItem', \OCP\Util::DEBUG);
75
+            \OC_Response::setStatus(404);
76
+            \OCP\JSON::error(array('success' => false));
77
+            exit();
78
+        }
79
+
80
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK && $share->getPassword() !== null) {
81
+            if (!self::authenticate($share, $password)) {
82
+                \OC_Response::setStatus(403);
83
+                \OCP\JSON::error(array('success' => false));
84
+                exit();
85
+            }
86
+        }
87
+
88
+        $basePath = $path;
89
+
90
+        if ($relativePath !== null && Filesystem::isReadable($basePath . $relativePath)) {
91
+            $path .= Filesystem::normalizePath($relativePath);
92
+        }
93
+
94
+        return array(
95
+            'share' => $share,
96
+            'basePath' => $basePath,
97
+            'realPath' => $path
98
+        );
99
+    }
100
+
101
+    /**
102
+     * Authenticate link item with the given password
103
+     * or with the session if no password was given.
104
+     * @param \OCP\Share\IShare $share
105
+     * @param string $password optional password
106
+     *
107
+     * @return boolean true if authorized, false otherwise
108
+     */
109
+    public static function authenticate($share, $password = null) {
110
+        $shareManager = \OC::$server->getShareManager();
111
+
112
+        if ($password !== null) {
113
+            if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
+                if ($shareManager->checkPassword($share, $password)) {
115
+                    \OC::$server->getSession()->set('public_link_authenticated', (string)$share->getId());
116
+                    return true;
117
+                }
118
+            }
119
+        } else {
120
+            // not authenticated ?
121
+            if (\OC::$server->getSession()->exists('public_link_authenticated')
122
+                && \OC::$server->getSession()->get('public_link_authenticated') !== (string)$share->getId()) {
123
+                return true;
124
+            }
125
+        }
126
+        return false;
127
+    }
128
+
129
+    public static function getSharesFromItem($target) {
130
+        $result = array();
131
+        $owner = Filesystem::getOwner($target);
132
+        Filesystem::initMountPoints($owner);
133
+        $info = Filesystem::getFileInfo($target);
134
+        $ownerView = new View('/'.$owner.'/files');
135
+        if ( $owner !== User::getUser() ) {
136
+            $path = $ownerView->getPath($info['fileid']);
137
+        } else {
138
+            $path = $target;
139
+        }
140
+
141
+
142
+        $ids = array();
143
+        while ($path !== dirname($path)) {
144
+            $info = $ownerView->getFileInfo($path);
145
+            if ($info instanceof \OC\Files\FileInfo) {
146
+                $ids[] = $info['fileid'];
147
+            } else {
148
+                \OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
149
+            }
150
+            $path = dirname($path);
151
+        }
152
+
153
+        if (!empty($ids)) {
154
+
155
+            $idList = array_chunk($ids, 99, true);
156
+
157
+            foreach ($idList as $subList) {
158
+                $statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
159
+                $query = \OCP\DB::prepare($statement);
160
+                $r = $query->execute();
161
+                $result = array_merge($result, $r->fetchAll());
162
+            }
163
+        }
164
+
165
+        return $result;
166
+    }
167
+
168
+    /**
169
+     * get the UID of the owner of the file and the path to the file relative to
170
+     * owners files folder
171
+     *
172
+     * @param $filename
173
+     * @return array
174
+     * @throws \OC\User\NoUserException
175
+     */
176
+    public static function getUidAndFilename($filename) {
177
+        $uid = Filesystem::getOwner($filename);
178
+        $userManager = \OC::$server->getUserManager();
179
+        // if the user with the UID doesn't exists, e.g. because the UID points
180
+        // to a remote user with a federated cloud ID we use the current logged-in
181
+        // user. We need a valid local user to create the share
182
+        if (!$userManager->userExists($uid)) {
183
+            $uid = User::getUser();
184
+        }
185
+        Filesystem::initMountPoints($uid);
186
+        if ( $uid !== User::getUser() ) {
187
+            $info = Filesystem::getFileInfo($filename);
188
+            $ownerView = new View('/'.$uid.'/files');
189
+            try {
190
+                $filename = $ownerView->getPath($info['fileid']);
191
+            } catch (NotFoundException $e) {
192
+                $filename = null;
193
+            }
194
+        }
195
+        return [$uid, $filename];
196
+    }
197
+
198
+    /**
199
+     * Format a path to be relative to the /user/files/ directory
200
+     * @param string $path the absolute path
201
+     * @return string e.g. turns '/admin/files/test.txt' into 'test.txt'
202
+     */
203
+    public static function stripUserFilesPath($path) {
204
+        $trimmed = ltrim($path, '/');
205
+        $split = explode('/', $trimmed);
206
+
207
+        // it is not a file relative to data/user/files
208
+        if (count($split) < 3 || $split[1] !== 'files') {
209
+            return false;
210
+        }
211
+
212
+        $sliced = array_slice($split, 2);
213
+        $relPath = implode('/', $sliced);
214
+
215
+        return $relPath;
216
+    }
217
+
218
+    /**
219
+     * check if file name already exists and generate unique target
220
+     *
221
+     * @param string $path
222
+     * @param array $excludeList
223
+     * @param View $view
224
+     * @return string $path
225
+     */
226
+    public static function generateUniqueTarget($path, $excludeList, $view) {
227
+        $pathinfo = pathinfo($path);
228
+        $ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
229
+        $name = $pathinfo['filename'];
230
+        $dir = $pathinfo['dirname'];
231
+        $i = 2;
232
+        while ($view->file_exists($path) || in_array($path, $excludeList)) {
233
+            $path = Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
234
+            $i++;
235
+        }
236
+
237
+        return $path;
238
+    }
239
+
240
+    /**
241
+     * get default share folder
242
+     *
243
+     * @param \OC\Files\View
244
+     * @return string
245
+     */
246
+    public static function getShareFolder($view = null) {
247
+        if ($view === null) {
248
+            $view = Filesystem::getView();
249
+        }
250
+        $shareFolder = \OC::$server->getConfig()->getSystemValue('share_folder', '/');
251
+        $shareFolder = Filesystem::normalizePath($shareFolder);
252
+
253
+        if (!$view->file_exists($shareFolder)) {
254
+            $dir = '';
255
+            $subdirs = explode('/', $shareFolder);
256
+            foreach ($subdirs as $subdir) {
257
+                $dir = $dir . '/' . $subdir;
258
+                if (!$view->is_dir($dir)) {
259
+                    $view->mkdir($dir);
260
+                }
261
+            }
262
+        }
263
+
264
+        return $shareFolder;
265
+
266
+    }
267
+
268
+    /**
269
+     * set default share folder
270
+     *
271
+     * @param string $shareFolder
272
+     */
273
+    public static function setShareFolder($shareFolder) {
274
+        \OC::$server->getConfig()->setSystemValue('share_folder', $shareFolder);
275
+    }
276 276
 
277 277
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 
88 88
 		$basePath = $path;
89 89
 
90
-		if ($relativePath !== null && Filesystem::isReadable($basePath . $relativePath)) {
90
+		if ($relativePath !== null && Filesystem::isReadable($basePath.$relativePath)) {
91 91
 			$path .= Filesystem::normalizePath($relativePath);
92 92
 		}
93 93
 
@@ -112,14 +112,14 @@  discard block
 block discarded – undo
112 112
 		if ($password !== null) {
113 113
 			if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114 114
 				if ($shareManager->checkPassword($share, $password)) {
115
-					\OC::$server->getSession()->set('public_link_authenticated', (string)$share->getId());
115
+					\OC::$server->getSession()->set('public_link_authenticated', (string) $share->getId());
116 116
 					return true;
117 117
 				}
118 118
 			}
119 119
 		} else {
120 120
 			// not authenticated ?
121 121
 			if (\OC::$server->getSession()->exists('public_link_authenticated')
122
-				&& \OC::$server->getSession()->get('public_link_authenticated') !== (string)$share->getId()) {
122
+				&& \OC::$server->getSession()->get('public_link_authenticated') !== (string) $share->getId()) {
123 123
 				return true;
124 124
 			}
125 125
 		}
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 		Filesystem::initMountPoints($owner);
133 133
 		$info = Filesystem::getFileInfo($target);
134 134
 		$ownerView = new View('/'.$owner.'/files');
135
-		if ( $owner !== User::getUser() ) {
135
+		if ($owner !== User::getUser()) {
136 136
 			$path = $ownerView->getPath($info['fileid']);
137 137
 		} else {
138 138
 			$path = $target;
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 			if ($info instanceof \OC\Files\FileInfo) {
146 146
 				$ids[] = $info['fileid'];
147 147
 			} else {
148
-				\OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
148
+				\OCP\Util::writeLog('sharing', 'No fileinfo available for: '.$path, \OCP\Util::WARN);
149 149
 			}
150 150
 			$path = dirname($path);
151 151
 		}
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 			$idList = array_chunk($ids, 99, true);
156 156
 
157 157
 			foreach ($idList as $subList) {
158
-				$statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
158
+				$statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (".implode(',', $subList).") AND `share_type` IN (0, 1, 2)";
159 159
 				$query = \OCP\DB::prepare($statement);
160 160
 				$r = $query->execute();
161 161
 				$result = array_merge($result, $r->fetchAll());
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 			$uid = User::getUser();
184 184
 		}
185 185
 		Filesystem::initMountPoints($uid);
186
-		if ( $uid !== User::getUser() ) {
186
+		if ($uid !== User::getUser()) {
187 187
 			$info = Filesystem::getFileInfo($filename);
188 188
 			$ownerView = new View('/'.$uid.'/files');
189 189
 			try {
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
 		$dir = $pathinfo['dirname'];
231 231
 		$i = 2;
232 232
 		while ($view->file_exists($path) || in_array($path, $excludeList)) {
233
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
233
+			$path = Filesystem::normalizePath($dir.'/'.$name.' ('.$i.')'.$ext);
234 234
 			$i++;
235 235
 		}
236 236
 
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 			$dir = '';
255 255
 			$subdirs = explode('/', $shareFolder);
256 256
 			foreach ($subdirs as $subdir) {
257
-				$dir = $dir . '/' . $subdir;
257
+				$dir = $dir.'/'.$subdir;
258 258
 				if (!$view->is_dir($dir)) {
259 259
 					$view->mkdir($dir);
260 260
 				}
Please login to merge, or discard this patch.
apps/dav/lib/SystemTag/SystemTagsObjectMappingCollection.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -89,6 +89,9 @@
 block discarded – undo
89 89
 		$this->user = $user;
90 90
 	}
91 91
 
92
+	/**
93
+	 * @param string $tagId
94
+	 */
92 95
 	function createFile($tagId, $data = null) {
93 96
 		try {
94 97
 			$tags = $this->tagManager->getTagsByIds([$tagId]);
Please login to merge, or discard this patch.
Indentation   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -39,169 +39,169 @@
 block discarded – undo
39 39
  */
40 40
 class SystemTagsObjectMappingCollection implements ICollection {
41 41
 
42
-	/**
43
-	 * @var string
44
-	 */
45
-	private $objectId;
46
-
47
-	/**
48
-	 * @var string
49
-	 */
50
-	private $objectType;
51
-
52
-	/**
53
-	 * @var ISystemTagManager
54
-	 */
55
-	private $tagManager;
56
-
57
-	/**
58
-	 * @var ISystemTagObjectMapper
59
-	 */
60
-	private $tagMapper;
61
-
62
-	/**
63
-	 * User
64
-	 *
65
-	 * @var IUser
66
-	 */
67
-	private $user;
68
-
69
-
70
-	/**
71
-	 * Constructor
72
-	 *
73
-	 * @param string $objectId object id
74
-	 * @param string $objectType object type
75
-	 * @param IUser $user user
76
-	 * @param ISystemTagManager $tagManager tag manager
77
-	 * @param ISystemTagObjectMapper $tagMapper tag mapper
78
-	 */
79
-	public function __construct(
80
-		$objectId,
81
-		$objectType,
82
-		IUser $user,
83
-		ISystemTagManager $tagManager,
84
-		ISystemTagObjectMapper $tagMapper
85
-	) {
86
-		$this->tagManager = $tagManager;
87
-		$this->tagMapper = $tagMapper;
88
-		$this->objectId = $objectId;
89
-		$this->objectType = $objectType;
90
-		$this->user = $user;
91
-	}
92
-
93
-	function createFile($tagId, $data = null) {
94
-		try {
95
-			$tags = $this->tagManager->getTagsByIds([$tagId]);
96
-			$tag = current($tags);
97
-			if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
-				throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
99
-			}
100
-			if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
-				throw new Forbidden('No permission to assign tag ' . $tagId);
102
-			}
103
-
104
-			$this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105
-		} catch (TagNotFoundException $e) {
106
-			throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
107
-		}
108
-	}
109
-
110
-	function createDirectory($name) {
111
-		throw new Forbidden('Permission denied to create collections');
112
-	}
113
-
114
-	function getChild($tagId) {
115
-		try {
116
-			if ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true)) {
117
-				$tag = $this->tagManager->getTagsByIds([$tagId]);
118
-				$tag = current($tag);
119
-				if ($this->tagManager->canUserSeeTag($tag, $this->user)) {
120
-					return $this->makeNode($tag);
121
-				}
122
-			}
123
-			throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
124
-		} catch (\InvalidArgumentException $e) {
125
-			throw new BadRequest('Invalid tag id', 0, $e);
126
-		} catch (TagNotFoundException $e) {
127
-			throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
128
-		}
129
-	}
130
-
131
-	function getChildren() {
132
-		$tagIds = current($this->tagMapper->getTagIdsForObjects([$this->objectId], $this->objectType));
133
-		if (empty($tagIds)) {
134
-			return [];
135
-		}
136
-		$tags = $this->tagManager->getTagsByIds($tagIds);
137
-
138
-		// filter out non-visible tags
139
-		$tags = array_filter($tags, function($tag) {
140
-			return $this->tagManager->canUserSeeTag($tag, $this->user);
141
-		});
142
-
143
-		return array_values(array_map(function($tag) {
144
-			return $this->makeNode($tag);
145
-		}, $tags));
146
-	}
147
-
148
-	function childExists($tagId) {
149
-		try {
150
-			$result = ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true));
151
-
152
-			if ($result) {
153
-				$tags = $this->tagManager->getTagsByIds([$tagId]);
154
-				$tag = current($tags);
155
-				if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
156
-					return false;
157
-				}
158
-			}
159
-
160
-			return $result;
161
-		} catch (\InvalidArgumentException $e) {
162
-			throw new BadRequest('Invalid tag id', 0, $e);
163
-		} catch (TagNotFoundException $e) {
164
-			return false;
165
-		}
166
-	}
167
-
168
-	function delete() {
169
-		throw new Forbidden('Permission denied to delete this collection');
170
-	}
171
-
172
-	function getName() {
173
-		return $this->objectId;
174
-	}
175
-
176
-	function setName($name) {
177
-		throw new Forbidden('Permission denied to rename this collection');
178
-	}
179
-
180
-	/**
181
-	 * Returns the last modification time, as a unix timestamp
182
-	 *
183
-	 * @return int
184
-	 */
185
-	function getLastModified() {
186
-		return null;
187
-	}
188
-
189
-	/**
190
-	 * Create a sabre node for the mapping of the 
191
-	 * given system tag to the collection's object
192
-	 *
193
-	 * @param ISystemTag $tag
194
-	 *
195
-	 * @return SystemTagMappingNode
196
-	 */
197
-	private function makeNode(ISystemTag $tag) {
198
-		return new SystemTagMappingNode(
199
-			$tag,
200
-			$this->objectId,
201
-			$this->objectType,
202
-			$this->user,
203
-			$this->tagManager,
204
-			$this->tagMapper
205
-		);
206
-	}
42
+    /**
43
+     * @var string
44
+     */
45
+    private $objectId;
46
+
47
+    /**
48
+     * @var string
49
+     */
50
+    private $objectType;
51
+
52
+    /**
53
+     * @var ISystemTagManager
54
+     */
55
+    private $tagManager;
56
+
57
+    /**
58
+     * @var ISystemTagObjectMapper
59
+     */
60
+    private $tagMapper;
61
+
62
+    /**
63
+     * User
64
+     *
65
+     * @var IUser
66
+     */
67
+    private $user;
68
+
69
+
70
+    /**
71
+     * Constructor
72
+     *
73
+     * @param string $objectId object id
74
+     * @param string $objectType object type
75
+     * @param IUser $user user
76
+     * @param ISystemTagManager $tagManager tag manager
77
+     * @param ISystemTagObjectMapper $tagMapper tag mapper
78
+     */
79
+    public function __construct(
80
+        $objectId,
81
+        $objectType,
82
+        IUser $user,
83
+        ISystemTagManager $tagManager,
84
+        ISystemTagObjectMapper $tagMapper
85
+    ) {
86
+        $this->tagManager = $tagManager;
87
+        $this->tagMapper = $tagMapper;
88
+        $this->objectId = $objectId;
89
+        $this->objectType = $objectType;
90
+        $this->user = $user;
91
+    }
92
+
93
+    function createFile($tagId, $data = null) {
94
+        try {
95
+            $tags = $this->tagManager->getTagsByIds([$tagId]);
96
+            $tag = current($tags);
97
+            if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
+                throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
99
+            }
100
+            if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
+                throw new Forbidden('No permission to assign tag ' . $tagId);
102
+            }
103
+
104
+            $this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105
+        } catch (TagNotFoundException $e) {
106
+            throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
107
+        }
108
+    }
109
+
110
+    function createDirectory($name) {
111
+        throw new Forbidden('Permission denied to create collections');
112
+    }
113
+
114
+    function getChild($tagId) {
115
+        try {
116
+            if ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true)) {
117
+                $tag = $this->tagManager->getTagsByIds([$tagId]);
118
+                $tag = current($tag);
119
+                if ($this->tagManager->canUserSeeTag($tag, $this->user)) {
120
+                    return $this->makeNode($tag);
121
+                }
122
+            }
123
+            throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
124
+        } catch (\InvalidArgumentException $e) {
125
+            throw new BadRequest('Invalid tag id', 0, $e);
126
+        } catch (TagNotFoundException $e) {
127
+            throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
128
+        }
129
+    }
130
+
131
+    function getChildren() {
132
+        $tagIds = current($this->tagMapper->getTagIdsForObjects([$this->objectId], $this->objectType));
133
+        if (empty($tagIds)) {
134
+            return [];
135
+        }
136
+        $tags = $this->tagManager->getTagsByIds($tagIds);
137
+
138
+        // filter out non-visible tags
139
+        $tags = array_filter($tags, function($tag) {
140
+            return $this->tagManager->canUserSeeTag($tag, $this->user);
141
+        });
142
+
143
+        return array_values(array_map(function($tag) {
144
+            return $this->makeNode($tag);
145
+        }, $tags));
146
+    }
147
+
148
+    function childExists($tagId) {
149
+        try {
150
+            $result = ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true));
151
+
152
+            if ($result) {
153
+                $tags = $this->tagManager->getTagsByIds([$tagId]);
154
+                $tag = current($tags);
155
+                if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
156
+                    return false;
157
+                }
158
+            }
159
+
160
+            return $result;
161
+        } catch (\InvalidArgumentException $e) {
162
+            throw new BadRequest('Invalid tag id', 0, $e);
163
+        } catch (TagNotFoundException $e) {
164
+            return false;
165
+        }
166
+    }
167
+
168
+    function delete() {
169
+        throw new Forbidden('Permission denied to delete this collection');
170
+    }
171
+
172
+    function getName() {
173
+        return $this->objectId;
174
+    }
175
+
176
+    function setName($name) {
177
+        throw new Forbidden('Permission denied to rename this collection');
178
+    }
179
+
180
+    /**
181
+     * Returns the last modification time, as a unix timestamp
182
+     *
183
+     * @return int
184
+     */
185
+    function getLastModified() {
186
+        return null;
187
+    }
188
+
189
+    /**
190
+     * Create a sabre node for the mapping of the 
191
+     * given system tag to the collection's object
192
+     *
193
+     * @param ISystemTag $tag
194
+     *
195
+     * @return SystemTagMappingNode
196
+     */
197
+    private function makeNode(ISystemTag $tag) {
198
+        return new SystemTagMappingNode(
199
+            $tag,
200
+            $this->objectId,
201
+            $this->objectType,
202
+            $this->user,
203
+            $this->tagManager,
204
+            $this->tagMapper
205
+        );
206
+    }
207 207
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -95,15 +95,15 @@  discard block
 block discarded – undo
95 95
 			$tags = $this->tagManager->getTagsByIds([$tagId]);
96 96
 			$tag = current($tags);
97 97
 			if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
-				throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
98
+				throw new PreconditionFailed('Tag with id '.$tagId.' does not exist, cannot assign');
99 99
 			}
100 100
 			if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
-				throw new Forbidden('No permission to assign tag ' . $tagId);
101
+				throw new Forbidden('No permission to assign tag '.$tagId);
102 102
 			}
103 103
 
104 104
 			$this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105 105
 		} catch (TagNotFoundException $e) {
106
-			throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
106
+			throw new PreconditionFailed('Tag with id '.$tagId.' does not exist, cannot assign');
107 107
 		}
108 108
 	}
109 109
 
@@ -120,11 +120,11 @@  discard block
 block discarded – undo
120 120
 					return $this->makeNode($tag);
121 121
 				}
122 122
 			}
123
-			throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
123
+			throw new NotFound('Tag with id '.$tagId.' not present for object '.$this->objectId);
124 124
 		} catch (\InvalidArgumentException $e) {
125 125
 			throw new BadRequest('Invalid tag id', 0, $e);
126 126
 		} catch (TagNotFoundException $e) {
127
-			throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
127
+			throw new NotFound('Tag with id '.$tagId.' not found', 0, $e);
128 128
 		}
129 129
 	}
130 130
 
Please login to merge, or discard this patch.
lib/private/DB/Migrator.php 3 patches
Doc Comments   +8 added lines patch added patch discarded remove patch
@@ -273,6 +273,10 @@  discard block
 block discarded – undo
273 273
 		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
274 274
 	}
275 275
 
276
+	/**
277
+	 * @param integer $step
278
+	 * @param integer $max
279
+	 */
276 280
 	protected function emit($sql, $step, $max) {
277 281
 		if ($this->noEmit) {
278 282
 			return;
@@ -283,6 +287,10 @@  discard block
 block discarded – undo
283 287
 		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
284 288
 	}
285 289
 
290
+	/**
291
+	 * @param integer $step
292
+	 * @param integer $max
293
+	 */
286 294
 	private function emitCheckStep($tableName, $step, $max) {
287 295
 		if(is_null($this->dispatcher)) {
288 296
 			return;
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 	 * @return string
138 138
 	 */
139 139
 	protected function generateTemporaryTableName($name) {
140
-		return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
140
+		return $this->config->getSystemValue('dbtableprefix', 'oc_').$name.'_'.$this->random->generate(13, ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
141 141
 	}
142 142
 
143 143
 	/**
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
 				$indexName = $index->getName();
189 189
 			} else {
190 190
 				// avoid conflicts in index names
191
-				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
191
+				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_').$this->random->generate(13, ISecureRandom::CHAR_LOWER);
192 192
 			}
193 193
 			$newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
194 194
 		}
@@ -268,15 +268,15 @@  discard block
 block discarded – undo
268 268
 		$quotedSource = $this->connection->quoteIdentifier($sourceName);
269 269
 		$quotedTarget = $this->connection->quoteIdentifier($targetName);
270 270
 
271
-		$this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
272
-		$this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
271
+		$this->connection->exec('CREATE TABLE '.$quotedTarget.' (LIKE '.$quotedSource.')');
272
+		$this->connection->exec('INSERT INTO '.$quotedTarget.' SELECT * FROM '.$quotedSource);
273 273
 	}
274 274
 
275 275
 	/**
276 276
 	 * @param string $name
277 277
 	 */
278 278
 	protected function dropTable($name) {
279
-		$this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
279
+		$this->connection->exec('DROP TABLE '.$this->connection->quoteIdentifier($name));
280 280
 	}
281 281
 
282 282
 	/**
@@ -284,30 +284,30 @@  discard block
 block discarded – undo
284 284
 	 * @return string
285 285
 	 */
286 286
 	protected function convertStatementToScript($statement) {
287
-		$script = $statement . ';';
287
+		$script = $statement.';';
288 288
 		$script .= PHP_EOL;
289 289
 		$script .= PHP_EOL;
290 290
 		return $script;
291 291
 	}
292 292
 
293 293
 	protected function getFilterExpression() {
294
-		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
294
+		return '/^'.preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')).'/';
295 295
 	}
296 296
 
297 297
 	protected function emit($sql, $step, $max) {
298 298
 		if ($this->noEmit) {
299 299
 			return;
300 300
 		}
301
-		if(is_null($this->dispatcher)) {
301
+		if (is_null($this->dispatcher)) {
302 302
 			return;
303 303
 		}
304
-		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
304
+		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step + 1, $max]));
305 305
 	}
306 306
 
307 307
 	private function emitCheckStep($tableName, $step, $max) {
308
-		if(is_null($this->dispatcher)) {
308
+		if (is_null($this->dispatcher)) {
309 309
 			return;
310 310
 		}
311
-		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
311
+		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step + 1, $max]));
312 312
 	}
313 313
 }
Please login to merge, or discard this patch.
Indentation   +268 added lines, -268 removed lines patch added patch discarded remove patch
@@ -43,272 +43,272 @@
 block discarded – undo
43 43
 
44 44
 class Migrator {
45 45
 
46
-	/** @var \Doctrine\DBAL\Connection */
47
-	protected $connection;
48
-
49
-	/** @var ISecureRandom */
50
-	private $random;
51
-
52
-	/** @var IConfig */
53
-	protected $config;
54
-
55
-	/** @var EventDispatcher  */
56
-	private $dispatcher;
57
-
58
-	/** @var bool */
59
-	private $noEmit = false;
60
-
61
-	/**
62
-	 * @param \Doctrine\DBAL\Connection|Connection $connection
63
-	 * @param ISecureRandom $random
64
-	 * @param IConfig $config
65
-	 * @param EventDispatcher $dispatcher
66
-	 */
67
-	public function __construct(\Doctrine\DBAL\Connection $connection,
68
-								ISecureRandom $random,
69
-								IConfig $config,
70
-								EventDispatcher $dispatcher = null) {
71
-		$this->connection = $connection;
72
-		$this->random = $random;
73
-		$this->config = $config;
74
-		$this->dispatcher = $dispatcher;
75
-	}
76
-
77
-	/**
78
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
79
-	 */
80
-	public function migrate(Schema $targetSchema) {
81
-		$this->noEmit = true;
82
-		$this->applySchema($targetSchema);
83
-	}
84
-
85
-	/**
86
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
87
-	 * @return string
88
-	 */
89
-	public function generateChangeScript(Schema $targetSchema) {
90
-		$schemaDiff = $this->getDiff($targetSchema, $this->connection);
91
-
92
-		$script = '';
93
-		$sqls = $schemaDiff->toSql($this->connection->getDatabasePlatform());
94
-		foreach ($sqls as $sql) {
95
-			$script .= $this->convertStatementToScript($sql);
96
-		}
97
-
98
-		return $script;
99
-	}
100
-
101
-	/**
102
-	 * @param Schema $targetSchema
103
-	 * @throws \OC\DB\MigrationException
104
-	 */
105
-	public function checkMigrate(Schema $targetSchema) {
106
-		$this->noEmit = true;
107
-		/**@var \Doctrine\DBAL\Schema\Table[] $tables */
108
-		$tables = $targetSchema->getTables();
109
-		$filterExpression = $this->getFilterExpression();
110
-		$this->connection->getConfiguration()->
111
-			setFilterSchemaAssetsExpression($filterExpression);
112
-		$existingTables = $this->connection->getSchemaManager()->listTableNames();
113
-
114
-		$step = 0;
115
-		foreach ($tables as $table) {
116
-			if (strpos($table->getName(), '.')) {
117
-				list(, $tableName) = explode('.', $table->getName());
118
-			} else {
119
-				$tableName = $table->getName();
120
-			}
121
-			$this->emitCheckStep($tableName, $step++, count($tables));
122
-			// don't need to check for new tables
123
-			if (array_search($tableName, $existingTables) !== false) {
124
-				$this->checkTableMigrate($table);
125
-			}
126
-		}
127
-	}
128
-
129
-	/**
130
-	 * Create a unique name for the temporary table
131
-	 *
132
-	 * @param string $name
133
-	 * @return string
134
-	 */
135
-	protected function generateTemporaryTableName($name) {
136
-		return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
137
-	}
138
-
139
-	/**
140
-	 * Check the migration of a table on a copy so we can detect errors before messing with the real table
141
-	 *
142
-	 * @param \Doctrine\DBAL\Schema\Table $table
143
-	 * @throws \OC\DB\MigrationException
144
-	 */
145
-	protected function checkTableMigrate(Table $table) {
146
-		$name = $table->getName();
147
-		$tmpName = $this->generateTemporaryTableName($name);
148
-
149
-		$this->copyTable($name, $tmpName);
150
-
151
-		//create the migration schema for the temporary table
152
-		$tmpTable = $this->renameTableSchema($table, $tmpName);
153
-		$schemaConfig = new SchemaConfig();
154
-		$schemaConfig->setName($this->connection->getDatabase());
155
-		$schema = new Schema(array($tmpTable), array(), $schemaConfig);
156
-
157
-		try {
158
-			$this->applySchema($schema);
159
-			$this->dropTable($tmpName);
160
-		} catch (DBALException $e) {
161
-			// pgsql needs to commit it's failed transaction before doing anything else
162
-			if ($this->connection->isTransactionActive()) {
163
-				$this->connection->commit();
164
-			}
165
-			$this->dropTable($tmpName);
166
-			throw new MigrationException($table->getName(), $e->getMessage());
167
-		}
168
-	}
169
-
170
-	/**
171
-	 * @param \Doctrine\DBAL\Schema\Table $table
172
-	 * @param string $newName
173
-	 * @return \Doctrine\DBAL\Schema\Table
174
-	 */
175
-	protected function renameTableSchema(Table $table, $newName) {
176
-		/**
177
-		 * @var \Doctrine\DBAL\Schema\Index[] $indexes
178
-		 */
179
-		$indexes = $table->getIndexes();
180
-		$newIndexes = array();
181
-		foreach ($indexes as $index) {
182
-			if ($index->isPrimary()) {
183
-				// do not rename primary key
184
-				$indexName = $index->getName();
185
-			} else {
186
-				// avoid conflicts in index names
187
-				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
188
-			}
189
-			$newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
190
-		}
191
-
192
-		// foreign keys are not supported so we just set it to an empty array
193
-		return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions());
194
-	}
195
-
196
-	public function createSchema() {
197
-		$filterExpression = $this->getFilterExpression();
198
-		$this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
199
-		return $this->connection->getSchemaManager()->createSchema();
200
-	}
201
-
202
-	/**
203
-	 * @param Schema $targetSchema
204
-	 * @param \Doctrine\DBAL\Connection $connection
205
-	 * @return \Doctrine\DBAL\Schema\SchemaDiff
206
-	 * @throws DBALException
207
-	 */
208
-	protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
209
-		// adjust varchar columns with a length higher then getVarcharMaxLength to clob
210
-		foreach ($targetSchema->getTables() as $table) {
211
-			foreach ($table->getColumns() as $column) {
212
-				if ($column->getType() instanceof StringType) {
213
-					if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
214
-						$column->setType(Type::getType('text'));
215
-						$column->setLength(null);
216
-					}
217
-				}
218
-			}
219
-		}
220
-
221
-		$filterExpression = $this->getFilterExpression();
222
-		$this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
223
-		$sourceSchema = $connection->getSchemaManager()->createSchema();
224
-
225
-		// remove tables we don't know about
226
-		/** @var $table \Doctrine\DBAL\Schema\Table */
227
-		foreach ($sourceSchema->getTables() as $table) {
228
-			if (!$targetSchema->hasTable($table->getName())) {
229
-				$sourceSchema->dropTable($table->getName());
230
-			}
231
-		}
232
-		// remove sequences we don't know about
233
-		foreach ($sourceSchema->getSequences() as $table) {
234
-			if (!$targetSchema->hasSequence($table->getName())) {
235
-				$sourceSchema->dropSequence($table->getName());
236
-			}
237
-		}
238
-
239
-		$comparator = new Comparator();
240
-		return $comparator->compare($sourceSchema, $targetSchema);
241
-	}
242
-
243
-	/**
244
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
245
-	 * @param \Doctrine\DBAL\Connection $connection
246
-	 */
247
-	protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $connection = null) {
248
-		if (is_null($connection)) {
249
-			$connection = $this->connection;
250
-		}
251
-
252
-		$schemaDiff = $this->getDiff($targetSchema, $connection);
253
-
254
-		$connection->beginTransaction();
255
-		$sqls = $schemaDiff->toSql($connection->getDatabasePlatform());
256
-		$step = 0;
257
-		foreach ($sqls as $sql) {
258
-			$this->emit($sql, $step++, count($sqls));
259
-			$connection->query($sql);
260
-		}
261
-		$connection->commit();
262
-	}
263
-
264
-	/**
265
-	 * @param string $sourceName
266
-	 * @param string $targetName
267
-	 */
268
-	protected function copyTable($sourceName, $targetName) {
269
-		$quotedSource = $this->connection->quoteIdentifier($sourceName);
270
-		$quotedTarget = $this->connection->quoteIdentifier($targetName);
271
-
272
-		$this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
273
-		$this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
274
-	}
275
-
276
-	/**
277
-	 * @param string $name
278
-	 */
279
-	protected function dropTable($name) {
280
-		$this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
281
-	}
282
-
283
-	/**
284
-	 * @param $statement
285
-	 * @return string
286
-	 */
287
-	protected function convertStatementToScript($statement) {
288
-		$script = $statement . ';';
289
-		$script .= PHP_EOL;
290
-		$script .= PHP_EOL;
291
-		return $script;
292
-	}
293
-
294
-	protected function getFilterExpression() {
295
-		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
296
-	}
297
-
298
-	protected function emit($sql, $step, $max) {
299
-		if ($this->noEmit) {
300
-			return;
301
-		}
302
-		if(is_null($this->dispatcher)) {
303
-			return;
304
-		}
305
-		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
306
-	}
307
-
308
-	private function emitCheckStep($tableName, $step, $max) {
309
-		if(is_null($this->dispatcher)) {
310
-			return;
311
-		}
312
-		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
313
-	}
46
+    /** @var \Doctrine\DBAL\Connection */
47
+    protected $connection;
48
+
49
+    /** @var ISecureRandom */
50
+    private $random;
51
+
52
+    /** @var IConfig */
53
+    protected $config;
54
+
55
+    /** @var EventDispatcher  */
56
+    private $dispatcher;
57
+
58
+    /** @var bool */
59
+    private $noEmit = false;
60
+
61
+    /**
62
+     * @param \Doctrine\DBAL\Connection|Connection $connection
63
+     * @param ISecureRandom $random
64
+     * @param IConfig $config
65
+     * @param EventDispatcher $dispatcher
66
+     */
67
+    public function __construct(\Doctrine\DBAL\Connection $connection,
68
+                                ISecureRandom $random,
69
+                                IConfig $config,
70
+                                EventDispatcher $dispatcher = null) {
71
+        $this->connection = $connection;
72
+        $this->random = $random;
73
+        $this->config = $config;
74
+        $this->dispatcher = $dispatcher;
75
+    }
76
+
77
+    /**
78
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
79
+     */
80
+    public function migrate(Schema $targetSchema) {
81
+        $this->noEmit = true;
82
+        $this->applySchema($targetSchema);
83
+    }
84
+
85
+    /**
86
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
87
+     * @return string
88
+     */
89
+    public function generateChangeScript(Schema $targetSchema) {
90
+        $schemaDiff = $this->getDiff($targetSchema, $this->connection);
91
+
92
+        $script = '';
93
+        $sqls = $schemaDiff->toSql($this->connection->getDatabasePlatform());
94
+        foreach ($sqls as $sql) {
95
+            $script .= $this->convertStatementToScript($sql);
96
+        }
97
+
98
+        return $script;
99
+    }
100
+
101
+    /**
102
+     * @param Schema $targetSchema
103
+     * @throws \OC\DB\MigrationException
104
+     */
105
+    public function checkMigrate(Schema $targetSchema) {
106
+        $this->noEmit = true;
107
+        /**@var \Doctrine\DBAL\Schema\Table[] $tables */
108
+        $tables = $targetSchema->getTables();
109
+        $filterExpression = $this->getFilterExpression();
110
+        $this->connection->getConfiguration()->
111
+            setFilterSchemaAssetsExpression($filterExpression);
112
+        $existingTables = $this->connection->getSchemaManager()->listTableNames();
113
+
114
+        $step = 0;
115
+        foreach ($tables as $table) {
116
+            if (strpos($table->getName(), '.')) {
117
+                list(, $tableName) = explode('.', $table->getName());
118
+            } else {
119
+                $tableName = $table->getName();
120
+            }
121
+            $this->emitCheckStep($tableName, $step++, count($tables));
122
+            // don't need to check for new tables
123
+            if (array_search($tableName, $existingTables) !== false) {
124
+                $this->checkTableMigrate($table);
125
+            }
126
+        }
127
+    }
128
+
129
+    /**
130
+     * Create a unique name for the temporary table
131
+     *
132
+     * @param string $name
133
+     * @return string
134
+     */
135
+    protected function generateTemporaryTableName($name) {
136
+        return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
137
+    }
138
+
139
+    /**
140
+     * Check the migration of a table on a copy so we can detect errors before messing with the real table
141
+     *
142
+     * @param \Doctrine\DBAL\Schema\Table $table
143
+     * @throws \OC\DB\MigrationException
144
+     */
145
+    protected function checkTableMigrate(Table $table) {
146
+        $name = $table->getName();
147
+        $tmpName = $this->generateTemporaryTableName($name);
148
+
149
+        $this->copyTable($name, $tmpName);
150
+
151
+        //create the migration schema for the temporary table
152
+        $tmpTable = $this->renameTableSchema($table, $tmpName);
153
+        $schemaConfig = new SchemaConfig();
154
+        $schemaConfig->setName($this->connection->getDatabase());
155
+        $schema = new Schema(array($tmpTable), array(), $schemaConfig);
156
+
157
+        try {
158
+            $this->applySchema($schema);
159
+            $this->dropTable($tmpName);
160
+        } catch (DBALException $e) {
161
+            // pgsql needs to commit it's failed transaction before doing anything else
162
+            if ($this->connection->isTransactionActive()) {
163
+                $this->connection->commit();
164
+            }
165
+            $this->dropTable($tmpName);
166
+            throw new MigrationException($table->getName(), $e->getMessage());
167
+        }
168
+    }
169
+
170
+    /**
171
+     * @param \Doctrine\DBAL\Schema\Table $table
172
+     * @param string $newName
173
+     * @return \Doctrine\DBAL\Schema\Table
174
+     */
175
+    protected function renameTableSchema(Table $table, $newName) {
176
+        /**
177
+         * @var \Doctrine\DBAL\Schema\Index[] $indexes
178
+         */
179
+        $indexes = $table->getIndexes();
180
+        $newIndexes = array();
181
+        foreach ($indexes as $index) {
182
+            if ($index->isPrimary()) {
183
+                // do not rename primary key
184
+                $indexName = $index->getName();
185
+            } else {
186
+                // avoid conflicts in index names
187
+                $indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
188
+            }
189
+            $newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
190
+        }
191
+
192
+        // foreign keys are not supported so we just set it to an empty array
193
+        return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions());
194
+    }
195
+
196
+    public function createSchema() {
197
+        $filterExpression = $this->getFilterExpression();
198
+        $this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
199
+        return $this->connection->getSchemaManager()->createSchema();
200
+    }
201
+
202
+    /**
203
+     * @param Schema $targetSchema
204
+     * @param \Doctrine\DBAL\Connection $connection
205
+     * @return \Doctrine\DBAL\Schema\SchemaDiff
206
+     * @throws DBALException
207
+     */
208
+    protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
209
+        // adjust varchar columns with a length higher then getVarcharMaxLength to clob
210
+        foreach ($targetSchema->getTables() as $table) {
211
+            foreach ($table->getColumns() as $column) {
212
+                if ($column->getType() instanceof StringType) {
213
+                    if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
214
+                        $column->setType(Type::getType('text'));
215
+                        $column->setLength(null);
216
+                    }
217
+                }
218
+            }
219
+        }
220
+
221
+        $filterExpression = $this->getFilterExpression();
222
+        $this->connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
223
+        $sourceSchema = $connection->getSchemaManager()->createSchema();
224
+
225
+        // remove tables we don't know about
226
+        /** @var $table \Doctrine\DBAL\Schema\Table */
227
+        foreach ($sourceSchema->getTables() as $table) {
228
+            if (!$targetSchema->hasTable($table->getName())) {
229
+                $sourceSchema->dropTable($table->getName());
230
+            }
231
+        }
232
+        // remove sequences we don't know about
233
+        foreach ($sourceSchema->getSequences() as $table) {
234
+            if (!$targetSchema->hasSequence($table->getName())) {
235
+                $sourceSchema->dropSequence($table->getName());
236
+            }
237
+        }
238
+
239
+        $comparator = new Comparator();
240
+        return $comparator->compare($sourceSchema, $targetSchema);
241
+    }
242
+
243
+    /**
244
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
245
+     * @param \Doctrine\DBAL\Connection $connection
246
+     */
247
+    protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $connection = null) {
248
+        if (is_null($connection)) {
249
+            $connection = $this->connection;
250
+        }
251
+
252
+        $schemaDiff = $this->getDiff($targetSchema, $connection);
253
+
254
+        $connection->beginTransaction();
255
+        $sqls = $schemaDiff->toSql($connection->getDatabasePlatform());
256
+        $step = 0;
257
+        foreach ($sqls as $sql) {
258
+            $this->emit($sql, $step++, count($sqls));
259
+            $connection->query($sql);
260
+        }
261
+        $connection->commit();
262
+    }
263
+
264
+    /**
265
+     * @param string $sourceName
266
+     * @param string $targetName
267
+     */
268
+    protected function copyTable($sourceName, $targetName) {
269
+        $quotedSource = $this->connection->quoteIdentifier($sourceName);
270
+        $quotedTarget = $this->connection->quoteIdentifier($targetName);
271
+
272
+        $this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
273
+        $this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
274
+    }
275
+
276
+    /**
277
+     * @param string $name
278
+     */
279
+    protected function dropTable($name) {
280
+        $this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
281
+    }
282
+
283
+    /**
284
+     * @param $statement
285
+     * @return string
286
+     */
287
+    protected function convertStatementToScript($statement) {
288
+        $script = $statement . ';';
289
+        $script .= PHP_EOL;
290
+        $script .= PHP_EOL;
291
+        return $script;
292
+    }
293
+
294
+    protected function getFilterExpression() {
295
+        return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
296
+    }
297
+
298
+    protected function emit($sql, $step, $max) {
299
+        if ($this->noEmit) {
300
+            return;
301
+        }
302
+        if(is_null($this->dispatcher)) {
303
+            return;
304
+        }
305
+        $this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
306
+    }
307
+
308
+    private function emitCheckStep($tableName, $step, $max) {
309
+        if(is_null($this->dispatcher)) {
310
+            return;
311
+        }
312
+        $this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
313
+    }
314 314
 }
Please login to merge, or discard this patch.