Completed
Pull Request — master (#6025)
by Thomas
12:42
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.
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.
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.
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/AppFramework/Db/Mapper.php 3 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -308,6 +308,7 @@  discard block
 block discarded – undo
308 308
 	 * @param array $params the parameters of the sql query
309 309
 	 * @param int $limit the maximum number of rows
310 310
 	 * @param int $offset from which row we want to start
311
+	 * @param string $msg
311 312
 	 * @return string formatted error message string
312 313
 	 * @since 9.1.0
313 314
 	 */
@@ -360,7 +361,7 @@  discard block
 block discarded – undo
360 361
 	 * Returns an db result and throws exceptions when there are more or less
361 362
 	 * results
362 363
 	 * @param string $sql the sql query
363
-	 * @param array $params the parameters of the sql query
364
+	 * @param string[] $params the parameters of the sql query
364 365
 	 * @param int $limit the maximum number of rows
365 366
 	 * @param int $offset from which row we want to start
366 367
 	 * @throws DoesNotExistException if the item does not exist
Please login to merge, or discard this patch.
Indentation   +321 added lines, -321 removed lines patch added patch discarded remove patch
@@ -37,327 +37,327 @@
 block discarded – undo
37 37
  */
38 38
 abstract class Mapper {
39 39
 
40
-	protected $tableName;
41
-	protected $entityClass;
42
-	protected $db;
43
-
44
-	/**
45
-	 * @param IDBConnection $db Instance of the Db abstraction layer
46
-	 * @param string $tableName the name of the table. set this to allow entity
47
-	 * @param string $entityClass the name of the entity that the sql should be
48
-	 * mapped to queries without using sql
49
-	 * @since 7.0.0
50
-	 */
51
-	public function __construct(IDBConnection $db, $tableName, $entityClass=null){
52
-		$this->db = $db;
53
-		$this->tableName = '*PREFIX*' . $tableName;
54
-
55
-		// if not given set the entity name to the class without the mapper part
56
-		// cache it here for later use since reflection is slow
57
-		if($entityClass === null) {
58
-			$this->entityClass = str_replace('Mapper', '', get_class($this));
59
-		} else {
60
-			$this->entityClass = $entityClass;
61
-		}
62
-	}
63
-
64
-
65
-	/**
66
-	 * @return string the table name
67
-	 * @since 7.0.0
68
-	 */
69
-	public function getTableName(){
70
-		return $this->tableName;
71
-	}
72
-
73
-
74
-	/**
75
-	 * Deletes an entity from the table
76
-	 * @param Entity $entity the entity that should be deleted
77
-	 * @return Entity the deleted entity
78
-	 * @since 7.0.0 - return value added in 8.1.0
79
-	 */
80
-	public function delete(Entity $entity){
81
-		$sql = 'DELETE FROM `' . $this->tableName . '` WHERE `id` = ?';
82
-		$stmt = $this->execute($sql, [$entity->getId()]);
83
-		$stmt->closeCursor();
84
-		return $entity;
85
-	}
86
-
87
-
88
-	/**
89
-	 * Creates a new entry in the db from an entity
90
-	 * @param Entity $entity the entity that should be created
91
-	 * @return Entity the saved entity with the set id
92
-	 * @since 7.0.0
93
-	 */
94
-	public function insert(Entity $entity){
95
-		// get updated fields to save, fields have to be set using a setter to
96
-		// be saved
97
-		$properties = $entity->getUpdatedFields();
98
-		$values = '';
99
-		$columns = '';
100
-		$params = [];
101
-
102
-		// build the fields
103
-		$i = 0;
104
-		foreach($properties as $property => $updated) {
105
-			$column = $entity->propertyToColumn($property);
106
-			$getter = 'get' . ucfirst($property);
107
-
108
-			$columns .= '`' . $column . '`';
109
-			$values .= '?';
110
-
111
-			// only append colon if there are more entries
112
-			if($i < count($properties)-1){
113
-				$columns .= ',';
114
-				$values .= ',';
115
-			}
116
-
117
-			$params[] = $entity->$getter();
118
-			$i++;
119
-
120
-		}
121
-
122
-		$sql = 'INSERT INTO `' . $this->tableName . '`(' .
123
-				$columns . ') VALUES(' . $values . ')';
124
-
125
-		$stmt = $this->execute($sql, $params);
126
-
127
-		$entity->setId((int) $this->db->lastInsertId($this->tableName));
128
-
129
-		$stmt->closeCursor();
130
-
131
-		return $entity;
132
-	}
133
-
134
-
135
-
136
-	/**
137
-	 * Updates an entry in the db from an entity
138
-	 * @throws \InvalidArgumentException if entity has no id
139
-	 * @param Entity $entity the entity that should be created
140
-	 * @return Entity the saved entity with the set id
141
-	 * @since 7.0.0 - return value was added in 8.0.0
142
-	 */
143
-	public function update(Entity $entity){
144
-		// if entity wasn't changed it makes no sense to run a db query
145
-		$properties = $entity->getUpdatedFields();
146
-		if(count($properties) === 0) {
147
-			return $entity;
148
-		}
149
-
150
-		// entity needs an id
151
-		$id = $entity->getId();
152
-		if($id === null){
153
-			throw new \InvalidArgumentException(
154
-				'Entity which should be updated has no id');
155
-		}
156
-
157
-		// get updated fields to save, fields have to be set using a setter to
158
-		// be saved
159
-		// do not update the id field
160
-		unset($properties['id']);
161
-
162
-		$columns = '';
163
-		$params = [];
164
-
165
-		// build the fields
166
-		$i = 0;
167
-		foreach($properties as $property => $updated) {
168
-
169
-			$column = $entity->propertyToColumn($property);
170
-			$getter = 'get' . ucfirst($property);
171
-
172
-			$columns .= '`' . $column . '` = ?';
173
-
174
-			// only append colon if there are more entries
175
-			if($i < count($properties)-1){
176
-				$columns .= ',';
177
-			}
178
-
179
-			$params[] = $entity->$getter();
180
-			$i++;
181
-		}
182
-
183
-		$sql = 'UPDATE `' . $this->tableName . '` SET ' .
184
-				$columns . ' WHERE `id` = ?';
185
-		$params[] = $id;
186
-
187
-		$stmt = $this->execute($sql, $params);
188
-		$stmt->closeCursor();
189
-
190
-		return $entity;
191
-	}
192
-
193
-	/**
194
-	 * Checks if an array is associative
195
-	 * @param array $array
196
-	 * @return bool true if associative
197
-	 * @since 8.1.0
198
-	 */
199
-	private function isAssocArray(array $array) {
200
-		return array_values($array) !== $array;
201
-	}
202
-
203
-	/**
204
-	 * Returns the correct PDO constant based on the value type
205
-	 * @param $value
206
-	 * @return int PDO constant
207
-	 * @since 8.1.0
208
-	 */
209
-	private function getPDOType($value) {
210
-		switch (gettype($value)) {
211
-			case 'integer':
212
-				return \PDO::PARAM_INT;
213
-			case 'boolean':
214
-				return \PDO::PARAM_BOOL;
215
-			default:
216
-				return \PDO::PARAM_STR;
217
-		}
218
-	}
219
-
220
-
221
-	/**
222
-	 * Runs an sql query
223
-	 * @param string $sql the prepare string
224
-	 * @param array $params the params which should replace the ? in the sql query
225
-	 * @param int $limit the maximum number of rows
226
-	 * @param int $offset from which row we want to start
227
-	 * @return \PDOStatement the database query result
228
-	 * @since 7.0.0
229
-	 */
230
-	protected function execute($sql, array $params=[], $limit=null, $offset=null){
231
-		$query = $this->db->prepare($sql, $limit, $offset);
232
-
233
-		if ($this->isAssocArray($params)) {
234
-			foreach ($params as $key => $param) {
235
-				$pdoConstant = $this->getPDOType($param);
236
-				$query->bindValue($key, $param, $pdoConstant);
237
-			}
238
-		} else {
239
-			$index = 1;  // bindParam is 1 indexed
240
-			foreach ($params as $param) {
241
-				$pdoConstant = $this->getPDOType($param);
242
-				$query->bindValue($index, $param, $pdoConstant);
243
-				$index++;
244
-			}
245
-		}
246
-
247
-		$result = $query->execute();
248
-
249
-		return $query;
250
-	}
251
-
252
-
253
-	/**
254
-	 * Returns an db result and throws exceptions when there are more or less
255
-	 * results
256
-	 * @see findEntity
257
-	 * @param string $sql the sql query
258
-	 * @param array $params the parameters of the sql query
259
-	 * @param int $limit the maximum number of rows
260
-	 * @param int $offset from which row we want to start
261
-	 * @throws DoesNotExistException if the item does not exist
262
-	 * @throws MultipleObjectsReturnedException if more than one item exist
263
-	 * @return array the result as row
264
-	 * @since 7.0.0
265
-	 */
266
-	protected function findOneQuery($sql, array $params=[], $limit=null, $offset=null){
267
-		$stmt = $this->execute($sql, $params, $limit, $offset);
268
-		$row = $stmt->fetch();
269
-
270
-		if($row === false || $row === null){
271
-			$stmt->closeCursor();
272
-			$msg = $this->buildDebugMessage(
273
-				'Did expect one result but found none when executing', $sql, $params, $limit, $offset
274
-			);
275
-			throw new DoesNotExistException($msg);
276
-		}
277
-		$row2 = $stmt->fetch();
278
-		$stmt->closeCursor();
279
-		//MDB2 returns null, PDO and doctrine false when no row is available
280
-		if( ! ($row2 === false || $row2 === null )) {
281
-			$msg = $this->buildDebugMessage(
282
-				'Did not expect more than one result when executing', $sql, $params, $limit, $offset
283
-			);
284
-			throw new MultipleObjectsReturnedException($msg);
285
-		} else {
286
-			return $row;
287
-		}
288
-	}
289
-
290
-	/**
291
-	 * Builds an error message by prepending the $msg to an error message which
292
-	 * has the parameters
293
-	 * @see findEntity
294
-	 * @param string $sql the sql query
295
-	 * @param array $params the parameters of the sql query
296
-	 * @param int $limit the maximum number of rows
297
-	 * @param int $offset from which row we want to start
298
-	 * @return string formatted error message string
299
-	 * @since 9.1.0
300
-	 */
301
-	private function buildDebugMessage($msg, $sql, array $params=[], $limit=null, $offset=null) {
302
-		return $msg .
303
-					': query "' .	$sql . '"; ' .
304
-					'parameters ' . print_r($params, true) . '; ' .
305
-					'limit "' . $limit . '"; '.
306
-					'offset "' . $offset . '"';
307
-	}
308
-
309
-
310
-	/**
311
-	 * Creates an entity from a row. Automatically determines the entity class
312
-	 * from the current mapper name (MyEntityMapper -> MyEntity)
313
-	 * @param array $row the row which should be converted to an entity
314
-	 * @return Entity the entity
315
-	 * @since 7.0.0
316
-	 */
317
-	protected function mapRowToEntity($row) {
318
-		return call_user_func($this->entityClass .'::fromRow', $row);
319
-	}
320
-
321
-
322
-	/**
323
-	 * Runs a sql query and returns an array of entities
324
-	 * @param string $sql the prepare string
325
-	 * @param array $params the params which should replace the ? in the sql query
326
-	 * @param int $limit the maximum number of rows
327
-	 * @param int $offset from which row we want to start
328
-	 * @return array all fetched entities
329
-	 * @since 7.0.0
330
-	 */
331
-	protected function findEntities($sql, array $params=[], $limit=null, $offset=null) {
332
-		$stmt = $this->execute($sql, $params, $limit, $offset);
333
-
334
-		$entities = [];
335
-
336
-		while($row = $stmt->fetch()){
337
-			$entities[] = $this->mapRowToEntity($row);
338
-		}
339
-
340
-		$stmt->closeCursor();
341
-
342
-		return $entities;
343
-	}
344
-
345
-
346
-	/**
347
-	 * Returns an db result and throws exceptions when there are more or less
348
-	 * results
349
-	 * @param string $sql the sql query
350
-	 * @param array $params the parameters of the sql query
351
-	 * @param int $limit the maximum number of rows
352
-	 * @param int $offset from which row we want to start
353
-	 * @throws DoesNotExistException if the item does not exist
354
-	 * @throws MultipleObjectsReturnedException if more than one item exist
355
-	 * @return Entity the entity
356
-	 * @since 7.0.0
357
-	 */
358
-	protected function findEntity($sql, array $params=[], $limit=null, $offset=null){
359
-		return $this->mapRowToEntity($this->findOneQuery($sql, $params, $limit, $offset));
360
-	}
40
+    protected $tableName;
41
+    protected $entityClass;
42
+    protected $db;
43
+
44
+    /**
45
+     * @param IDBConnection $db Instance of the Db abstraction layer
46
+     * @param string $tableName the name of the table. set this to allow entity
47
+     * @param string $entityClass the name of the entity that the sql should be
48
+     * mapped to queries without using sql
49
+     * @since 7.0.0
50
+     */
51
+    public function __construct(IDBConnection $db, $tableName, $entityClass=null){
52
+        $this->db = $db;
53
+        $this->tableName = '*PREFIX*' . $tableName;
54
+
55
+        // if not given set the entity name to the class without the mapper part
56
+        // cache it here for later use since reflection is slow
57
+        if($entityClass === null) {
58
+            $this->entityClass = str_replace('Mapper', '', get_class($this));
59
+        } else {
60
+            $this->entityClass = $entityClass;
61
+        }
62
+    }
63
+
64
+
65
+    /**
66
+     * @return string the table name
67
+     * @since 7.0.0
68
+     */
69
+    public function getTableName(){
70
+        return $this->tableName;
71
+    }
72
+
73
+
74
+    /**
75
+     * Deletes an entity from the table
76
+     * @param Entity $entity the entity that should be deleted
77
+     * @return Entity the deleted entity
78
+     * @since 7.0.0 - return value added in 8.1.0
79
+     */
80
+    public function delete(Entity $entity){
81
+        $sql = 'DELETE FROM `' . $this->tableName . '` WHERE `id` = ?';
82
+        $stmt = $this->execute($sql, [$entity->getId()]);
83
+        $stmt->closeCursor();
84
+        return $entity;
85
+    }
86
+
87
+
88
+    /**
89
+     * Creates a new entry in the db from an entity
90
+     * @param Entity $entity the entity that should be created
91
+     * @return Entity the saved entity with the set id
92
+     * @since 7.0.0
93
+     */
94
+    public function insert(Entity $entity){
95
+        // get updated fields to save, fields have to be set using a setter to
96
+        // be saved
97
+        $properties = $entity->getUpdatedFields();
98
+        $values = '';
99
+        $columns = '';
100
+        $params = [];
101
+
102
+        // build the fields
103
+        $i = 0;
104
+        foreach($properties as $property => $updated) {
105
+            $column = $entity->propertyToColumn($property);
106
+            $getter = 'get' . ucfirst($property);
107
+
108
+            $columns .= '`' . $column . '`';
109
+            $values .= '?';
110
+
111
+            // only append colon if there are more entries
112
+            if($i < count($properties)-1){
113
+                $columns .= ',';
114
+                $values .= ',';
115
+            }
116
+
117
+            $params[] = $entity->$getter();
118
+            $i++;
119
+
120
+        }
121
+
122
+        $sql = 'INSERT INTO `' . $this->tableName . '`(' .
123
+                $columns . ') VALUES(' . $values . ')';
124
+
125
+        $stmt = $this->execute($sql, $params);
126
+
127
+        $entity->setId((int) $this->db->lastInsertId($this->tableName));
128
+
129
+        $stmt->closeCursor();
130
+
131
+        return $entity;
132
+    }
133
+
134
+
135
+
136
+    /**
137
+     * Updates an entry in the db from an entity
138
+     * @throws \InvalidArgumentException if entity has no id
139
+     * @param Entity $entity the entity that should be created
140
+     * @return Entity the saved entity with the set id
141
+     * @since 7.0.0 - return value was added in 8.0.0
142
+     */
143
+    public function update(Entity $entity){
144
+        // if entity wasn't changed it makes no sense to run a db query
145
+        $properties = $entity->getUpdatedFields();
146
+        if(count($properties) === 0) {
147
+            return $entity;
148
+        }
149
+
150
+        // entity needs an id
151
+        $id = $entity->getId();
152
+        if($id === null){
153
+            throw new \InvalidArgumentException(
154
+                'Entity which should be updated has no id');
155
+        }
156
+
157
+        // get updated fields to save, fields have to be set using a setter to
158
+        // be saved
159
+        // do not update the id field
160
+        unset($properties['id']);
161
+
162
+        $columns = '';
163
+        $params = [];
164
+
165
+        // build the fields
166
+        $i = 0;
167
+        foreach($properties as $property => $updated) {
168
+
169
+            $column = $entity->propertyToColumn($property);
170
+            $getter = 'get' . ucfirst($property);
171
+
172
+            $columns .= '`' . $column . '` = ?';
173
+
174
+            // only append colon if there are more entries
175
+            if($i < count($properties)-1){
176
+                $columns .= ',';
177
+            }
178
+
179
+            $params[] = $entity->$getter();
180
+            $i++;
181
+        }
182
+
183
+        $sql = 'UPDATE `' . $this->tableName . '` SET ' .
184
+                $columns . ' WHERE `id` = ?';
185
+        $params[] = $id;
186
+
187
+        $stmt = $this->execute($sql, $params);
188
+        $stmt->closeCursor();
189
+
190
+        return $entity;
191
+    }
192
+
193
+    /**
194
+     * Checks if an array is associative
195
+     * @param array $array
196
+     * @return bool true if associative
197
+     * @since 8.1.0
198
+     */
199
+    private function isAssocArray(array $array) {
200
+        return array_values($array) !== $array;
201
+    }
202
+
203
+    /**
204
+     * Returns the correct PDO constant based on the value type
205
+     * @param $value
206
+     * @return int PDO constant
207
+     * @since 8.1.0
208
+     */
209
+    private function getPDOType($value) {
210
+        switch (gettype($value)) {
211
+            case 'integer':
212
+                return \PDO::PARAM_INT;
213
+            case 'boolean':
214
+                return \PDO::PARAM_BOOL;
215
+            default:
216
+                return \PDO::PARAM_STR;
217
+        }
218
+    }
219
+
220
+
221
+    /**
222
+     * Runs an sql query
223
+     * @param string $sql the prepare string
224
+     * @param array $params the params which should replace the ? in the sql query
225
+     * @param int $limit the maximum number of rows
226
+     * @param int $offset from which row we want to start
227
+     * @return \PDOStatement the database query result
228
+     * @since 7.0.0
229
+     */
230
+    protected function execute($sql, array $params=[], $limit=null, $offset=null){
231
+        $query = $this->db->prepare($sql, $limit, $offset);
232
+
233
+        if ($this->isAssocArray($params)) {
234
+            foreach ($params as $key => $param) {
235
+                $pdoConstant = $this->getPDOType($param);
236
+                $query->bindValue($key, $param, $pdoConstant);
237
+            }
238
+        } else {
239
+            $index = 1;  // bindParam is 1 indexed
240
+            foreach ($params as $param) {
241
+                $pdoConstant = $this->getPDOType($param);
242
+                $query->bindValue($index, $param, $pdoConstant);
243
+                $index++;
244
+            }
245
+        }
246
+
247
+        $result = $query->execute();
248
+
249
+        return $query;
250
+    }
251
+
252
+
253
+    /**
254
+     * Returns an db result and throws exceptions when there are more or less
255
+     * results
256
+     * @see findEntity
257
+     * @param string $sql the sql query
258
+     * @param array $params the parameters of the sql query
259
+     * @param int $limit the maximum number of rows
260
+     * @param int $offset from which row we want to start
261
+     * @throws DoesNotExistException if the item does not exist
262
+     * @throws MultipleObjectsReturnedException if more than one item exist
263
+     * @return array the result as row
264
+     * @since 7.0.0
265
+     */
266
+    protected function findOneQuery($sql, array $params=[], $limit=null, $offset=null){
267
+        $stmt = $this->execute($sql, $params, $limit, $offset);
268
+        $row = $stmt->fetch();
269
+
270
+        if($row === false || $row === null){
271
+            $stmt->closeCursor();
272
+            $msg = $this->buildDebugMessage(
273
+                'Did expect one result but found none when executing', $sql, $params, $limit, $offset
274
+            );
275
+            throw new DoesNotExistException($msg);
276
+        }
277
+        $row2 = $stmt->fetch();
278
+        $stmt->closeCursor();
279
+        //MDB2 returns null, PDO and doctrine false when no row is available
280
+        if( ! ($row2 === false || $row2 === null )) {
281
+            $msg = $this->buildDebugMessage(
282
+                'Did not expect more than one result when executing', $sql, $params, $limit, $offset
283
+            );
284
+            throw new MultipleObjectsReturnedException($msg);
285
+        } else {
286
+            return $row;
287
+        }
288
+    }
289
+
290
+    /**
291
+     * Builds an error message by prepending the $msg to an error message which
292
+     * has the parameters
293
+     * @see findEntity
294
+     * @param string $sql the sql query
295
+     * @param array $params the parameters of the sql query
296
+     * @param int $limit the maximum number of rows
297
+     * @param int $offset from which row we want to start
298
+     * @return string formatted error message string
299
+     * @since 9.1.0
300
+     */
301
+    private function buildDebugMessage($msg, $sql, array $params=[], $limit=null, $offset=null) {
302
+        return $msg .
303
+                    ': query "' .	$sql . '"; ' .
304
+                    'parameters ' . print_r($params, true) . '; ' .
305
+                    'limit "' . $limit . '"; '.
306
+                    'offset "' . $offset . '"';
307
+    }
308
+
309
+
310
+    /**
311
+     * Creates an entity from a row. Automatically determines the entity class
312
+     * from the current mapper name (MyEntityMapper -> MyEntity)
313
+     * @param array $row the row which should be converted to an entity
314
+     * @return Entity the entity
315
+     * @since 7.0.0
316
+     */
317
+    protected function mapRowToEntity($row) {
318
+        return call_user_func($this->entityClass .'::fromRow', $row);
319
+    }
320
+
321
+
322
+    /**
323
+     * Runs a sql query and returns an array of entities
324
+     * @param string $sql the prepare string
325
+     * @param array $params the params which should replace the ? in the sql query
326
+     * @param int $limit the maximum number of rows
327
+     * @param int $offset from which row we want to start
328
+     * @return array all fetched entities
329
+     * @since 7.0.0
330
+     */
331
+    protected function findEntities($sql, array $params=[], $limit=null, $offset=null) {
332
+        $stmt = $this->execute($sql, $params, $limit, $offset);
333
+
334
+        $entities = [];
335
+
336
+        while($row = $stmt->fetch()){
337
+            $entities[] = $this->mapRowToEntity($row);
338
+        }
339
+
340
+        $stmt->closeCursor();
341
+
342
+        return $entities;
343
+    }
344
+
345
+
346
+    /**
347
+     * Returns an db result and throws exceptions when there are more or less
348
+     * results
349
+     * @param string $sql the sql query
350
+     * @param array $params the parameters of the sql query
351
+     * @param int $limit the maximum number of rows
352
+     * @param int $offset from which row we want to start
353
+     * @throws DoesNotExistException if the item does not exist
354
+     * @throws MultipleObjectsReturnedException if more than one item exist
355
+     * @return Entity the entity
356
+     * @since 7.0.0
357
+     */
358
+    protected function findEntity($sql, array $params=[], $limit=null, $offset=null){
359
+        return $this->mapRowToEntity($this->findOneQuery($sql, $params, $limit, $offset));
360
+    }
361 361
 
362 362
 
363 363
 }
Please login to merge, or discard this patch.
Spacing   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -48,13 +48,13 @@  discard block
 block discarded – undo
48 48
 	 * mapped to queries without using sql
49 49
 	 * @since 7.0.0
50 50
 	 */
51
-	public function __construct(IDBConnection $db, $tableName, $entityClass=null){
51
+	public function __construct(IDBConnection $db, $tableName, $entityClass = null) {
52 52
 		$this->db = $db;
53
-		$this->tableName = '*PREFIX*' . $tableName;
53
+		$this->tableName = '*PREFIX*'.$tableName;
54 54
 
55 55
 		// if not given set the entity name to the class without the mapper part
56 56
 		// cache it here for later use since reflection is slow
57
-		if($entityClass === null) {
57
+		if ($entityClass === null) {
58 58
 			$this->entityClass = str_replace('Mapper', '', get_class($this));
59 59
 		} else {
60 60
 			$this->entityClass = $entityClass;
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
 	 * @return string the table name
67 67
 	 * @since 7.0.0
68 68
 	 */
69
-	public function getTableName(){
69
+	public function getTableName() {
70 70
 		return $this->tableName;
71 71
 	}
72 72
 
@@ -77,8 +77,8 @@  discard block
 block discarded – undo
77 77
 	 * @return Entity the deleted entity
78 78
 	 * @since 7.0.0 - return value added in 8.1.0
79 79
 	 */
80
-	public function delete(Entity $entity){
81
-		$sql = 'DELETE FROM `' . $this->tableName . '` WHERE `id` = ?';
80
+	public function delete(Entity $entity) {
81
+		$sql = 'DELETE FROM `'.$this->tableName.'` WHERE `id` = ?';
82 82
 		$stmt = $this->execute($sql, [$entity->getId()]);
83 83
 		$stmt->closeCursor();
84 84
 		return $entity;
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 	 * @return Entity the saved entity with the set id
92 92
 	 * @since 7.0.0
93 93
 	 */
94
-	public function insert(Entity $entity){
94
+	public function insert(Entity $entity) {
95 95
 		// get updated fields to save, fields have to be set using a setter to
96 96
 		// be saved
97 97
 		$properties = $entity->getUpdatedFields();
@@ -101,15 +101,15 @@  discard block
 block discarded – undo
101 101
 
102 102
 		// build the fields
103 103
 		$i = 0;
104
-		foreach($properties as $property => $updated) {
104
+		foreach ($properties as $property => $updated) {
105 105
 			$column = $entity->propertyToColumn($property);
106
-			$getter = 'get' . ucfirst($property);
106
+			$getter = 'get'.ucfirst($property);
107 107
 
108
-			$columns .= '`' . $column . '`';
108
+			$columns .= '`'.$column.'`';
109 109
 			$values .= '?';
110 110
 
111 111
 			// only append colon if there are more entries
112
-			if($i < count($properties)-1){
112
+			if ($i < count($properties) - 1) {
113 113
 				$columns .= ',';
114 114
 				$values .= ',';
115 115
 			}
@@ -119,8 +119,8 @@  discard block
 block discarded – undo
119 119
 
120 120
 		}
121 121
 
122
-		$sql = 'INSERT INTO `' . $this->tableName . '`(' .
123
-				$columns . ') VALUES(' . $values . ')';
122
+		$sql = 'INSERT INTO `'.$this->tableName.'`('.
123
+				$columns.') VALUES('.$values.')';
124 124
 
125 125
 		$stmt = $this->execute($sql, $params);
126 126
 
@@ -140,16 +140,16 @@  discard block
 block discarded – undo
140 140
 	 * @return Entity the saved entity with the set id
141 141
 	 * @since 7.0.0 - return value was added in 8.0.0
142 142
 	 */
143
-	public function update(Entity $entity){
143
+	public function update(Entity $entity) {
144 144
 		// if entity wasn't changed it makes no sense to run a db query
145 145
 		$properties = $entity->getUpdatedFields();
146
-		if(count($properties) === 0) {
146
+		if (count($properties) === 0) {
147 147
 			return $entity;
148 148
 		}
149 149
 
150 150
 		// entity needs an id
151 151
 		$id = $entity->getId();
152
-		if($id === null){
152
+		if ($id === null) {
153 153
 			throw new \InvalidArgumentException(
154 154
 				'Entity which should be updated has no id');
155 155
 		}
@@ -164,15 +164,15 @@  discard block
 block discarded – undo
164 164
 
165 165
 		// build the fields
166 166
 		$i = 0;
167
-		foreach($properties as $property => $updated) {
167
+		foreach ($properties as $property => $updated) {
168 168
 
169 169
 			$column = $entity->propertyToColumn($property);
170
-			$getter = 'get' . ucfirst($property);
170
+			$getter = 'get'.ucfirst($property);
171 171
 
172
-			$columns .= '`' . $column . '` = ?';
172
+			$columns .= '`'.$column.'` = ?';
173 173
 
174 174
 			// only append colon if there are more entries
175
-			if($i < count($properties)-1){
175
+			if ($i < count($properties) - 1) {
176 176
 				$columns .= ',';
177 177
 			}
178 178
 
@@ -180,8 +180,8 @@  discard block
 block discarded – undo
180 180
 			$i++;
181 181
 		}
182 182
 
183
-		$sql = 'UPDATE `' . $this->tableName . '` SET ' .
184
-				$columns . ' WHERE `id` = ?';
183
+		$sql = 'UPDATE `'.$this->tableName.'` SET '.
184
+				$columns.' WHERE `id` = ?';
185 185
 		$params[] = $id;
186 186
 
187 187
 		$stmt = $this->execute($sql, $params);
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
 	 * @return \PDOStatement the database query result
228 228
 	 * @since 7.0.0
229 229
 	 */
230
-	protected function execute($sql, array $params=[], $limit=null, $offset=null){
230
+	protected function execute($sql, array $params = [], $limit = null, $offset = null) {
231 231
 		$query = $this->db->prepare($sql, $limit, $offset);
232 232
 
233 233
 		if ($this->isAssocArray($params)) {
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
 				$query->bindValue($key, $param, $pdoConstant);
237 237
 			}
238 238
 		} else {
239
-			$index = 1;  // bindParam is 1 indexed
239
+			$index = 1; // bindParam is 1 indexed
240 240
 			foreach ($params as $param) {
241 241
 				$pdoConstant = $this->getPDOType($param);
242 242
 				$query->bindValue($index, $param, $pdoConstant);
@@ -263,11 +263,11 @@  discard block
 block discarded – undo
263 263
 	 * @return array the result as row
264 264
 	 * @since 7.0.0
265 265
 	 */
266
-	protected function findOneQuery($sql, array $params=[], $limit=null, $offset=null){
266
+	protected function findOneQuery($sql, array $params = [], $limit = null, $offset = null) {
267 267
 		$stmt = $this->execute($sql, $params, $limit, $offset);
268 268
 		$row = $stmt->fetch();
269 269
 
270
-		if($row === false || $row === null){
270
+		if ($row === false || $row === null) {
271 271
 			$stmt->closeCursor();
272 272
 			$msg = $this->buildDebugMessage(
273 273
 				'Did expect one result but found none when executing', $sql, $params, $limit, $offset
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
 		$row2 = $stmt->fetch();
278 278
 		$stmt->closeCursor();
279 279
 		//MDB2 returns null, PDO and doctrine false when no row is available
280
-		if( ! ($row2 === false || $row2 === null )) {
280
+		if (!($row2 === false || $row2 === null)) {
281 281
 			$msg = $this->buildDebugMessage(
282 282
 				'Did not expect more than one result when executing', $sql, $params, $limit, $offset
283 283
 			);
@@ -298,12 +298,12 @@  discard block
 block discarded – undo
298 298
 	 * @return string formatted error message string
299 299
 	 * @since 9.1.0
300 300
 	 */
301
-	private function buildDebugMessage($msg, $sql, array $params=[], $limit=null, $offset=null) {
302
-		return $msg .
303
-					': query "' .	$sql . '"; ' .
304
-					'parameters ' . print_r($params, true) . '; ' .
305
-					'limit "' . $limit . '"; '.
306
-					'offset "' . $offset . '"';
301
+	private function buildDebugMessage($msg, $sql, array $params = [], $limit = null, $offset = null) {
302
+		return $msg.
303
+					': query "'.$sql.'"; '.
304
+					'parameters '.print_r($params, true).'; '.
305
+					'limit "'.$limit.'"; '.
306
+					'offset "'.$offset.'"';
307 307
 	}
308 308
 
309 309
 
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
 	 * @since 7.0.0
316 316
 	 */
317 317
 	protected function mapRowToEntity($row) {
318
-		return call_user_func($this->entityClass .'::fromRow', $row);
318
+		return call_user_func($this->entityClass.'::fromRow', $row);
319 319
 	}
320 320
 
321 321
 
@@ -328,12 +328,12 @@  discard block
 block discarded – undo
328 328
 	 * @return array all fetched entities
329 329
 	 * @since 7.0.0
330 330
 	 */
331
-	protected function findEntities($sql, array $params=[], $limit=null, $offset=null) {
331
+	protected function findEntities($sql, array $params = [], $limit = null, $offset = null) {
332 332
 		$stmt = $this->execute($sql, $params, $limit, $offset);
333 333
 
334 334
 		$entities = [];
335 335
 
336
-		while($row = $stmt->fetch()){
336
+		while ($row = $stmt->fetch()) {
337 337
 			$entities[] = $this->mapRowToEntity($row);
338 338
 		}
339 339
 
@@ -355,7 +355,7 @@  discard block
 block discarded – undo
355 355
 	 * @return Entity the entity
356 356
 	 * @since 7.0.0
357 357
 	 */
358
-	protected function findEntity($sql, array $params=[], $limit=null, $offset=null){
358
+	protected function findEntity($sql, array $params = [], $limit = null, $offset = null) {
359 359
 		return $this->mapRowToEntity($this->findOneQuery($sql, $params, $limit, $offset));
360 360
 	}
361 361
 
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.
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 -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 -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.
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.
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   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -125,9 +125,9 @@  discard block
 block discarded – undo
125 125
 			$path = '/';
126 126
 		}
127 127
 		if ($path[0] !== '/') {
128
-			$path = '/' . $path;
128
+			$path = '/'.$path;
129 129
 		}
130
-		return $this->fakeRoot . $path;
130
+		return $this->fakeRoot.$path;
131 131
 	}
132 132
 
133 133
 	/**
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
 	public function chroot($fakeRoot) {
140 140
 		if (!$fakeRoot == '') {
141 141
 			if ($fakeRoot[0] !== '/') {
142
-				$fakeRoot = '/' . $fakeRoot;
142
+				$fakeRoot = '/'.$fakeRoot;
143 143
 			}
144 144
 		}
145 145
 		$this->fakeRoot = $fakeRoot;
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 		}
172 172
 
173 173
 		// missing slashes can cause wrong matches!
174
-		$root = rtrim($this->fakeRoot, '/') . '/';
174
+		$root = rtrim($this->fakeRoot, '/').'/';
175 175
 
176 176
 		if (strpos($path, $root) !== 0) {
177 177
 			return null;
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
 		if ($mount instanceof MoveableMount) {
278 278
 			// cut of /user/files to get the relative path to data/user/files
279 279
 			$pathParts = explode('/', $path, 4);
280
-			$relPath = '/' . $pathParts[3];
280
+			$relPath = '/'.$pathParts[3];
281 281
 			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
282 282
 			\OC_Hook::emit(
283 283
 				Filesystem::CLASSNAME, "umount",
@@ -688,7 +688,7 @@  discard block
 block discarded – undo
688 688
 		}
689 689
 		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
690 690
 		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
691
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
691
+		$mount = Filesystem::getMountManager()->find($absolutePath.$postFix);
692 692
 		if ($mount and $mount->getInternalPath($absolutePath) === '') {
693 693
 			return $this->removeMount($mount, $absolutePath);
694 694
 		}
@@ -954,7 +954,7 @@  discard block
 block discarded – undo
954 954
 				$hooks[] = 'write';
955 955
 				break;
956 956
 			default:
957
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
957
+				\OCP\Util::writeLog('core', 'invalid mode ('.$mode.') for '.$path, \OCP\Util::ERROR);
958 958
 		}
959 959
 
960 960
 		if ($mode !== 'r' && $mode !== 'w') {
@@ -1058,7 +1058,7 @@  discard block
 block discarded – undo
1058 1058
 					array(Filesystem::signal_param_path => $this->getHookPath($path))
1059 1059
 				);
1060 1060
 			}
1061
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1061
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1062 1062
 			if ($storage) {
1063 1063
 				$result = $storage->hash($type, $internalPath, $raw);
1064 1064
 				return $result;
@@ -1109,7 +1109,7 @@  discard block
 block discarded – undo
1109 1109
 
1110 1110
 			$run = $this->runHooks($hooks, $path);
1111 1111
 			/** @var \OC\Files\Storage\Storage $storage */
1112
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1112
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1113 1113
 			if ($run and $storage) {
1114 1114
 				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1115 1115
 					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
@@ -1148,7 +1148,7 @@  discard block
 block discarded – undo
1148 1148
 					$unlockLater = true;
1149 1149
 					// make sure our unlocking callback will still be called if connection is aborted
1150 1150
 					ignore_user_abort(true);
1151
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1151
+					$result = CallbackWrapper::wrap($result, null, null, function() use ($hooks, $path) {
1152 1152
 						if (in_array('write', $hooks)) {
1153 1153
 							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1154 1154
 						} else if (in_array('read', $hooks)) {
@@ -1209,7 +1209,7 @@  discard block
 block discarded – undo
1209 1209
 			return true;
1210 1210
 		}
1211 1211
 
1212
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1212
+		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot.'/');
1213 1213
 	}
1214 1214
 
1215 1215
 	/**
@@ -1228,7 +1228,7 @@  discard block
 block discarded – undo
1228 1228
 				if ($hook != 'read') {
1229 1229
 					\OC_Hook::emit(
1230 1230
 						Filesystem::CLASSNAME,
1231
-						$prefix . $hook,
1231
+						$prefix.$hook,
1232 1232
 						array(
1233 1233
 							Filesystem::signal_param_run => &$run,
1234 1234
 							Filesystem::signal_param_path => $path
@@ -1237,7 +1237,7 @@  discard block
 block discarded – undo
1237 1237
 				} elseif (!$post) {
1238 1238
 					\OC_Hook::emit(
1239 1239
 						Filesystem::CLASSNAME,
1240
-						$prefix . $hook,
1240
+						$prefix.$hook,
1241 1241
 						array(
1242 1242
 							Filesystem::signal_param_path => $path
1243 1243
 						)
@@ -1332,7 +1332,7 @@  discard block
 block discarded – undo
1332 1332
 			return $this->getPartFileInfo($path);
1333 1333
 		}
1334 1334
 		$relativePath = $path;
1335
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1335
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1336 1336
 
1337 1337
 		$mount = Filesystem::getMountManager()->find($path);
1338 1338
 		$storage = $mount->getStorage();
@@ -1356,7 +1356,7 @@  discard block
 block discarded – undo
1356 1356
 					//add the sizes of other mount points to the folder
1357 1357
 					$extOnly = ($includeMountPoints === 'ext');
1358 1358
 					$mounts = Filesystem::getMountManager()->findIn($path);
1359
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1359
+					$info->setSubMounts(array_filter($mounts, function(IMountPoint $mount) use ($extOnly) {
1360 1360
 						$subStorage = $mount->getStorage();
1361 1361
 						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1362 1362
 					}));
@@ -1403,12 +1403,12 @@  discard block
 block discarded – undo
1403 1403
 			/**
1404 1404
 			 * @var \OC\Files\FileInfo[] $files
1405 1405
 			 */
1406
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1406
+			$files = array_map(function(ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1407 1407
 				if ($sharingDisabled) {
1408 1408
 					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1409 1409
 				}
1410 1410
 				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1411
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1411
+				return new FileInfo($path.'/'.$content['name'], $storage, $content['path'], $content, $mount, $owner);
1412 1412
 			}, $contents);
1413 1413
 
1414 1414
 			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
@@ -1433,8 +1433,8 @@  discard block
 block discarded – undo
1433 1433
 							// sometimes when the storage is not available it can be any exception
1434 1434
 							\OCP\Util::writeLog(
1435 1435
 								'core',
1436
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1437
-								get_class($e) . ': ' . $e->getMessage(),
1436
+								'Exception while scanning storage "'.$subStorage->getId().'": '.
1437
+								get_class($e).': '.$e->getMessage(),
1438 1438
 								\OCP\Util::ERROR
1439 1439
 							);
1440 1440
 							continue;
@@ -1471,7 +1471,7 @@  discard block
 block discarded – undo
1471 1471
 									break;
1472 1472
 								}
1473 1473
 							}
1474
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1474
+							$rootEntry['path'] = substr(Filesystem::normalizePath($path.'/'.$rootEntry['name']), strlen($user) + 2); // full path without /$user/
1475 1475
 
1476 1476
 							// if sharing was disabled for the user we remove the share permissions
1477 1477
 							if (\OCP\Util::isSharingDisabledForUser()) {
@@ -1479,14 +1479,14 @@  discard block
 block discarded – undo
1479 1479
 							}
1480 1480
 
1481 1481
 							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1482
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1482
+							$files[] = new FileInfo($path.'/'.$rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1483 1483
 						}
1484 1484
 					}
1485 1485
 				}
1486 1486
 			}
1487 1487
 
1488 1488
 			if ($mimetype_filter) {
1489
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1489
+				$files = array_filter($files, function(FileInfo $file) use ($mimetype_filter) {
1490 1490
 					if (strpos($mimetype_filter, '/')) {
1491 1491
 						return $file->getMimetype() === $mimetype_filter;
1492 1492
 					} else {
@@ -1515,7 +1515,7 @@  discard block
 block discarded – undo
1515 1515
 		if ($data instanceof FileInfo) {
1516 1516
 			$data = $data->getData();
1517 1517
 		}
1518
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1518
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1519 1519
 		/**
1520 1520
 		 * @var \OC\Files\Storage\Storage $storage
1521 1521
 		 * @var string $internalPath
@@ -1542,7 +1542,7 @@  discard block
 block discarded – undo
1542 1542
 	 * @return FileInfo[]
1543 1543
 	 */
1544 1544
 	public function search($query) {
1545
-		return $this->searchCommon('search', array('%' . $query . '%'));
1545
+		return $this->searchCommon('search', array('%'.$query.'%'));
1546 1546
 	}
1547 1547
 
1548 1548
 	/**
@@ -1593,10 +1593,10 @@  discard block
 block discarded – undo
1593 1593
 
1594 1594
 			$results = call_user_func_array(array($cache, $method), $args);
1595 1595
 			foreach ($results as $result) {
1596
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1596
+				if (substr($mountPoint.$result['path'], 0, $rootLength + 1) === $this->fakeRoot.'/') {
1597 1597
 					$internalPath = $result['path'];
1598
-					$path = $mountPoint . $result['path'];
1599
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1598
+					$path = $mountPoint.$result['path'];
1599
+					$result['path'] = substr($mountPoint.$result['path'], $rootLength);
1600 1600
 					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1601 1601
 					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1602 1602
 				}
@@ -1614,8 +1614,8 @@  discard block
 block discarded – undo
1614 1614
 					if ($results) {
1615 1615
 						foreach ($results as $result) {
1616 1616
 							$internalPath = $result['path'];
1617
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1618
-							$path = rtrim($mountPoint . $internalPath, '/');
1617
+							$result['path'] = rtrim($relativeMountPoint.$result['path'], '/');
1618
+							$path = rtrim($mountPoint.$internalPath, '/');
1619 1619
 							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1620 1620
 							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1621 1621
 						}
@@ -1636,7 +1636,7 @@  discard block
 block discarded – undo
1636 1636
 	public function getOwner($path) {
1637 1637
 		$info = $this->getFileInfo($path);
1638 1638
 		if (!$info) {
1639
-			throw new NotFoundException($path . ' not found while trying to get owner');
1639
+			throw new NotFoundException($path.' not found while trying to get owner');
1640 1640
 		}
1641 1641
 		return $info->getOwner()->getUID();
1642 1642
 	}
@@ -1670,7 +1670,7 @@  discard block
 block discarded – undo
1670 1670
 	 * @return string
1671 1671
 	 */
1672 1672
 	public function getPath($id) {
1673
-		$id = (int)$id;
1673
+		$id = (int) $id;
1674 1674
 		$manager = Filesystem::getMountManager();
1675 1675
 		$mounts = $manager->findIn($this->fakeRoot);
1676 1676
 		$mounts[] = $manager->find($this->fakeRoot);
@@ -1685,7 +1685,7 @@  discard block
 block discarded – undo
1685 1685
 				$cache = $mount->getStorage()->getCache();
1686 1686
 				$internalPath = $cache->getPathById($id);
1687 1687
 				if (is_string($internalPath)) {
1688
-					$fullPath = $mount->getMountPoint() . $internalPath;
1688
+					$fullPath = $mount->getMountPoint().$internalPath;
1689 1689
 					if (!is_null($path = $this->getRelativePath($fullPath))) {
1690 1690
 						return $path;
1691 1691
 					}
@@ -1728,10 +1728,10 @@  discard block
 block discarded – undo
1728 1728
 		}
1729 1729
 
1730 1730
 		// note: cannot use the view because the target is already locked
1731
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1731
+		$fileId = (int) $targetStorage->getCache()->getId($targetInternalPath);
1732 1732
 		if ($fileId === -1) {
1733 1733
 			// target might not exist, need to check parent instead
1734
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1734
+			$fileId = (int) $targetStorage->getCache()->getId(dirname($targetInternalPath));
1735 1735
 		}
1736 1736
 
1737 1737
 		// check if any of the parents were shared by the current owner (include collections)
@@ -1831,7 +1831,7 @@  discard block
 block discarded – undo
1831 1831
 		$resultPath = '';
1832 1832
 		foreach ($parts as $part) {
1833 1833
 			if ($part) {
1834
-				$resultPath .= '/' . $part;
1834
+				$resultPath .= '/'.$part;
1835 1835
 				$result[] = $resultPath;
1836 1836
 			}
1837 1837
 		}
@@ -2081,16 +2081,16 @@  discard block
 block discarded – undo
2081 2081
 	public function getUidAndFilename($filename) {
2082 2082
 		$info = $this->getFileInfo($filename);
2083 2083
 		if (!$info instanceof \OCP\Files\FileInfo) {
2084
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2084
+			throw new NotFoundException($this->getAbsolutePath($filename).' not found');
2085 2085
 		}
2086 2086
 		$uid = $info->getOwner()->getUID();
2087 2087
 		if ($uid != \OCP\User::getUser()) {
2088 2088
 			Filesystem::initMountPoints($uid);
2089
-			$ownerView = new View('/' . $uid . '/files');
2089
+			$ownerView = new View('/'.$uid.'/files');
2090 2090
 			try {
2091 2091
 				$filename = $ownerView->getPath($info['fileid']);
2092 2092
 			} catch (NotFoundException $e) {
2093
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2093
+				throw new NotFoundException('File with id '.$info['fileid'].' not found for user '.$uid);
2094 2094
 			}
2095 2095
 		}
2096 2096
 		return [$uid, $filename];
@@ -2107,7 +2107,7 @@  discard block
 block discarded – undo
2107 2107
 		$directoryParts = array_filter($directoryParts);
2108 2108
 		foreach ($directoryParts as $key => $part) {
2109 2109
 			$currentPathElements = array_slice($directoryParts, 0, $key);
2110
-			$currentPath = '/' . implode('/', $currentPathElements);
2110
+			$currentPath = '/'.implode('/', $currentPathElements);
2111 2111
 			if ($this->is_file($currentPath)) {
2112 2112
 				return false;
2113 2113
 			}
Please login to merge, or discard this patch.
Indentation   +2055 added lines, -2055 removed lines patch added patch discarded remove patch
@@ -82,2059 +82,2059 @@
 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
-			if (fseek($handle, $from) === 0) {
451
-				$chunkSize = 8192; // 8 kB chunks
452
-				$end = $to + 1;
453
-				while (!feof($handle) && ftell($handle) < $end) {
454
-					$len = $end - ftell($handle);
455
-					if ($len > $chunkSize) {
456
-						$len = $chunkSize;
457
-					}
458
-					echo fread($handle, $len);
459
-					flush();
460
-				}
461
-				$size = ftell($handle) - $from;
462
-				return $size;
463
-			}
464
-
465
-			throw new \OCP\Files\UnseekableException('fseek error');
466
-		}
467
-		return false;
468
-	}
469
-
470
-	/**
471
-	 * @param string $path
472
-	 * @return mixed
473
-	 */
474
-	public function isCreatable($path) {
475
-		return $this->basicOperation('isCreatable', $path);
476
-	}
477
-
478
-	/**
479
-	 * @param string $path
480
-	 * @return mixed
481
-	 */
482
-	public function isReadable($path) {
483
-		return $this->basicOperation('isReadable', $path);
484
-	}
485
-
486
-	/**
487
-	 * @param string $path
488
-	 * @return mixed
489
-	 */
490
-	public function isUpdatable($path) {
491
-		return $this->basicOperation('isUpdatable', $path);
492
-	}
493
-
494
-	/**
495
-	 * @param string $path
496
-	 * @return bool|mixed
497
-	 */
498
-	public function isDeletable($path) {
499
-		$absolutePath = $this->getAbsolutePath($path);
500
-		$mount = Filesystem::getMountManager()->find($absolutePath);
501
-		if ($mount->getInternalPath($absolutePath) === '') {
502
-			return $mount instanceof MoveableMount;
503
-		}
504
-		return $this->basicOperation('isDeletable', $path);
505
-	}
506
-
507
-	/**
508
-	 * @param string $path
509
-	 * @return mixed
510
-	 */
511
-	public function isSharable($path) {
512
-		return $this->basicOperation('isSharable', $path);
513
-	}
514
-
515
-	/**
516
-	 * @param string $path
517
-	 * @return bool|mixed
518
-	 */
519
-	public function file_exists($path) {
520
-		if ($path == '/') {
521
-			return true;
522
-		}
523
-		return $this->basicOperation('file_exists', $path);
524
-	}
525
-
526
-	/**
527
-	 * @param string $path
528
-	 * @return mixed
529
-	 */
530
-	public function filemtime($path) {
531
-		return $this->basicOperation('filemtime', $path);
532
-	}
533
-
534
-	/**
535
-	 * @param string $path
536
-	 * @param int|string $mtime
537
-	 * @return bool
538
-	 */
539
-	public function touch($path, $mtime = null) {
540
-		if (!is_null($mtime) and !is_numeric($mtime)) {
541
-			$mtime = strtotime($mtime);
542
-		}
543
-
544
-		$hooks = array('touch');
545
-
546
-		if (!$this->file_exists($path)) {
547
-			$hooks[] = 'create';
548
-			$hooks[] = 'write';
549
-		}
550
-		$result = $this->basicOperation('touch', $path, $hooks, $mtime);
551
-		if (!$result) {
552
-			// If create file fails because of permissions on external storage like SMB folders,
553
-			// check file exists and return false if not.
554
-			if (!$this->file_exists($path)) {
555
-				return false;
556
-			}
557
-			if (is_null($mtime)) {
558
-				$mtime = time();
559
-			}
560
-			//if native touch fails, we emulate it by changing the mtime in the cache
561
-			$this->putFileInfo($path, array('mtime' => floor($mtime)));
562
-		}
563
-		return true;
564
-	}
565
-
566
-	/**
567
-	 * @param string $path
568
-	 * @return mixed
569
-	 */
570
-	public function file_get_contents($path) {
571
-		return $this->basicOperation('file_get_contents', $path, array('read'));
572
-	}
573
-
574
-	/**
575
-	 * @param bool $exists
576
-	 * @param string $path
577
-	 * @param bool $run
578
-	 */
579
-	protected function emit_file_hooks_pre($exists, $path, &$run) {
580
-		if (!$exists) {
581
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
582
-				Filesystem::signal_param_path => $this->getHookPath($path),
583
-				Filesystem::signal_param_run => &$run,
584
-			));
585
-		} else {
586
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
587
-				Filesystem::signal_param_path => $this->getHookPath($path),
588
-				Filesystem::signal_param_run => &$run,
589
-			));
590
-		}
591
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
592
-			Filesystem::signal_param_path => $this->getHookPath($path),
593
-			Filesystem::signal_param_run => &$run,
594
-		));
595
-	}
596
-
597
-	/**
598
-	 * @param bool $exists
599
-	 * @param string $path
600
-	 */
601
-	protected function emit_file_hooks_post($exists, $path) {
602
-		if (!$exists) {
603
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
604
-				Filesystem::signal_param_path => $this->getHookPath($path),
605
-			));
606
-		} else {
607
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
608
-				Filesystem::signal_param_path => $this->getHookPath($path),
609
-			));
610
-		}
611
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
612
-			Filesystem::signal_param_path => $this->getHookPath($path),
613
-		));
614
-	}
615
-
616
-	/**
617
-	 * @param string $path
618
-	 * @param mixed $data
619
-	 * @return bool|mixed
620
-	 * @throws \Exception
621
-	 */
622
-	public function file_put_contents($path, $data) {
623
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
624
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
625
-			if (Filesystem::isValidPath($path)
626
-				and !Filesystem::isFileBlacklisted($path)
627
-			) {
628
-				$path = $this->getRelativePath($absolutePath);
629
-
630
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
631
-
632
-				$exists = $this->file_exists($path);
633
-				$run = true;
634
-				if ($this->shouldEmitHooks($path)) {
635
-					$this->emit_file_hooks_pre($exists, $path, $run);
636
-				}
637
-				if (!$run) {
638
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
639
-					return false;
640
-				}
641
-
642
-				$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
643
-
644
-				/** @var \OC\Files\Storage\Storage $storage */
645
-				list($storage, $internalPath) = $this->resolvePath($path);
646
-				$target = $storage->fopen($internalPath, 'w');
647
-				if ($target) {
648
-					list (, $result) = \OC_Helper::streamCopy($data, $target);
649
-					fclose($target);
650
-					fclose($data);
651
-
652
-					$this->writeUpdate($storage, $internalPath);
653
-
654
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
655
-
656
-					if ($this->shouldEmitHooks($path) && $result !== false) {
657
-						$this->emit_file_hooks_post($exists, $path);
658
-					}
659
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
660
-					return $result;
661
-				} else {
662
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
663
-					return false;
664
-				}
665
-			} else {
666
-				return false;
667
-			}
668
-		} else {
669
-			$hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
670
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
671
-		}
672
-	}
673
-
674
-	/**
675
-	 * @param string $path
676
-	 * @return bool|mixed
677
-	 */
678
-	public function unlink($path) {
679
-		if ($path === '' || $path === '/') {
680
-			// do not allow deleting the root
681
-			return false;
682
-		}
683
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
684
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
685
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
686
-		if ($mount and $mount->getInternalPath($absolutePath) === '') {
687
-			return $this->removeMount($mount, $absolutePath);
688
-		}
689
-		if ($this->is_dir($path)) {
690
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
691
-		} else {
692
-			$result = $this->basicOperation('unlink', $path, ['delete']);
693
-		}
694
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
695
-			$storage = $mount->getStorage();
696
-			$internalPath = $mount->getInternalPath($absolutePath);
697
-			$storage->getUpdater()->remove($internalPath);
698
-			return true;
699
-		} else {
700
-			return $result;
701
-		}
702
-	}
703
-
704
-	/**
705
-	 * @param string $directory
706
-	 * @return bool|mixed
707
-	 */
708
-	public function deleteAll($directory) {
709
-		return $this->rmdir($directory);
710
-	}
711
-
712
-	/**
713
-	 * Rename/move a file or folder from the source path to target path.
714
-	 *
715
-	 * @param string $path1 source path
716
-	 * @param string $path2 target path
717
-	 *
718
-	 * @return bool|mixed
719
-	 */
720
-	public function rename($path1, $path2) {
721
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
722
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
723
-		$result = false;
724
-		if (
725
-			Filesystem::isValidPath($path2)
726
-			and Filesystem::isValidPath($path1)
727
-			and !Filesystem::isFileBlacklisted($path2)
728
-		) {
729
-			$path1 = $this->getRelativePath($absolutePath1);
730
-			$path2 = $this->getRelativePath($absolutePath2);
731
-			$exists = $this->file_exists($path2);
732
-
733
-			if ($path1 == null or $path2 == null) {
734
-				return false;
735
-			}
736
-
737
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
738
-			try {
739
-				$this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
740
-			} catch (LockedException $e) {
741
-				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED);
742
-				throw $e;
743
-			}
744
-
745
-			$run = true;
746
-			if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
747
-				// if it was a rename from a part file to a regular file it was a write and not a rename operation
748
-				$this->emit_file_hooks_pre($exists, $path2, $run);
749
-			} elseif ($this->shouldEmitHooks($path1)) {
750
-				\OC_Hook::emit(
751
-					Filesystem::CLASSNAME, Filesystem::signal_rename,
752
-					array(
753
-						Filesystem::signal_param_oldpath => $this->getHookPath($path1),
754
-						Filesystem::signal_param_newpath => $this->getHookPath($path2),
755
-						Filesystem::signal_param_run => &$run
756
-					)
757
-				);
758
-			}
759
-			if ($run) {
760
-				$this->verifyPath(dirname($path2), basename($path2));
761
-
762
-				$manager = Filesystem::getMountManager();
763
-				$mount1 = $this->getMount($path1);
764
-				$mount2 = $this->getMount($path2);
765
-				$storage1 = $mount1->getStorage();
766
-				$storage2 = $mount2->getStorage();
767
-				$internalPath1 = $mount1->getInternalPath($absolutePath1);
768
-				$internalPath2 = $mount2->getInternalPath($absolutePath2);
769
-
770
-				$this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
771
-				$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
772
-
773
-				if ($internalPath1 === '') {
774
-					if ($mount1 instanceof MoveableMount) {
775
-						if ($this->isTargetAllowed($absolutePath2)) {
776
-							/**
777
-							 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
778
-							 */
779
-							$sourceMountPoint = $mount1->getMountPoint();
780
-							$result = $mount1->moveMount($absolutePath2);
781
-							$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
782
-						} else {
783
-							$result = false;
784
-						}
785
-					} else {
786
-						$result = false;
787
-					}
788
-					// moving a file/folder within the same mount point
789
-				} elseif ($storage1 === $storage2) {
790
-					if ($storage1) {
791
-						$result = $storage1->rename($internalPath1, $internalPath2);
792
-					} else {
793
-						$result = false;
794
-					}
795
-					// moving a file/folder between storages (from $storage1 to $storage2)
796
-				} else {
797
-					$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
798
-				}
799
-
800
-				if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
801
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
802
-
803
-					$this->writeUpdate($storage2, $internalPath2);
804
-				} else if ($result) {
805
-					if ($internalPath1 !== '') { // don't do a cache update for moved mounts
806
-						$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
807
-					}
808
-				}
809
-
810
-				$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
811
-				$this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
812
-
813
-				if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
814
-					if ($this->shouldEmitHooks()) {
815
-						$this->emit_file_hooks_post($exists, $path2);
816
-					}
817
-				} elseif ($result) {
818
-					if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
819
-						\OC_Hook::emit(
820
-							Filesystem::CLASSNAME,
821
-							Filesystem::signal_post_rename,
822
-							array(
823
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
824
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
825
-							)
826
-						);
827
-					}
828
-				}
829
-			}
830
-			$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
831
-			$this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
832
-		}
833
-		return $result;
834
-	}
835
-
836
-	/**
837
-	 * Copy a file/folder from the source path to target path
838
-	 *
839
-	 * @param string $path1 source path
840
-	 * @param string $path2 target path
841
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
842
-	 *
843
-	 * @return bool|mixed
844
-	 */
845
-	public function copy($path1, $path2, $preserveMtime = false) {
846
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
847
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
848
-		$result = false;
849
-		if (
850
-			Filesystem::isValidPath($path2)
851
-			and Filesystem::isValidPath($path1)
852
-			and !Filesystem::isFileBlacklisted($path2)
853
-		) {
854
-			$path1 = $this->getRelativePath($absolutePath1);
855
-			$path2 = $this->getRelativePath($absolutePath2);
856
-
857
-			if ($path1 == null or $path2 == null) {
858
-				return false;
859
-			}
860
-			$run = true;
861
-
862
-			$this->lockFile($path2, ILockingProvider::LOCK_SHARED);
863
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED);
864
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
865
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
866
-
867
-			try {
868
-
869
-				$exists = $this->file_exists($path2);
870
-				if ($this->shouldEmitHooks()) {
871
-					\OC_Hook::emit(
872
-						Filesystem::CLASSNAME,
873
-						Filesystem::signal_copy,
874
-						array(
875
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
876
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
877
-							Filesystem::signal_param_run => &$run
878
-						)
879
-					);
880
-					$this->emit_file_hooks_pre($exists, $path2, $run);
881
-				}
882
-				if ($run) {
883
-					$mount1 = $this->getMount($path1);
884
-					$mount2 = $this->getMount($path2);
885
-					$storage1 = $mount1->getStorage();
886
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
887
-					$storage2 = $mount2->getStorage();
888
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
889
-
890
-					$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
891
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
892
-
893
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
894
-						if ($storage1) {
895
-							$result = $storage1->copy($internalPath1, $internalPath2);
896
-						} else {
897
-							$result = false;
898
-						}
899
-					} else {
900
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
901
-					}
902
-
903
-					$this->writeUpdate($storage2, $internalPath2);
904
-
905
-					$this->changeLock($path2, ILockingProvider::LOCK_SHARED);
906
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
907
-
908
-					if ($this->shouldEmitHooks() && $result !== false) {
909
-						\OC_Hook::emit(
910
-							Filesystem::CLASSNAME,
911
-							Filesystem::signal_post_copy,
912
-							array(
913
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
914
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
915
-							)
916
-						);
917
-						$this->emit_file_hooks_post($exists, $path2);
918
-					}
919
-
920
-				}
921
-			} catch (\Exception $e) {
922
-				$this->unlockFile($path2, $lockTypePath2);
923
-				$this->unlockFile($path1, $lockTypePath1);
924
-				throw $e;
925
-			}
926
-
927
-			$this->unlockFile($path2, $lockTypePath2);
928
-			$this->unlockFile($path1, $lockTypePath1);
929
-
930
-		}
931
-		return $result;
932
-	}
933
-
934
-	/**
935
-	 * @param string $path
936
-	 * @param string $mode 'r' or 'w'
937
-	 * @return resource
938
-	 */
939
-	public function fopen($path, $mode) {
940
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
941
-		$hooks = array();
942
-		switch ($mode) {
943
-			case 'r':
944
-				$hooks[] = 'read';
945
-				break;
946
-			case 'r+':
947
-			case 'w+':
948
-			case 'x+':
949
-			case 'a+':
950
-				$hooks[] = 'read';
951
-				$hooks[] = 'write';
952
-				break;
953
-			case 'w':
954
-			case 'x':
955
-			case 'a':
956
-				$hooks[] = 'write';
957
-				break;
958
-			default:
959
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
960
-		}
961
-
962
-		if ($mode !== 'r' && $mode !== 'w') {
963
-			\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');
964
-		}
965
-
966
-		return $this->basicOperation('fopen', $path, $hooks, $mode);
967
-	}
968
-
969
-	/**
970
-	 * @param string $path
971
-	 * @return bool|string
972
-	 * @throws \OCP\Files\InvalidPathException
973
-	 */
974
-	public function toTmpFile($path) {
975
-		$this->assertPathLength($path);
976
-		if (Filesystem::isValidPath($path)) {
977
-			$source = $this->fopen($path, 'r');
978
-			if ($source) {
979
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
980
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
981
-				file_put_contents($tmpFile, $source);
982
-				return $tmpFile;
983
-			} else {
984
-				return false;
985
-			}
986
-		} else {
987
-			return false;
988
-		}
989
-	}
990
-
991
-	/**
992
-	 * @param string $tmpFile
993
-	 * @param string $path
994
-	 * @return bool|mixed
995
-	 * @throws \OCP\Files\InvalidPathException
996
-	 */
997
-	public function fromTmpFile($tmpFile, $path) {
998
-		$this->assertPathLength($path);
999
-		if (Filesystem::isValidPath($path)) {
1000
-
1001
-			// Get directory that the file is going into
1002
-			$filePath = dirname($path);
1003
-
1004
-			// Create the directories if any
1005
-			if (!$this->file_exists($filePath)) {
1006
-				$result = $this->createParentDirectories($filePath);
1007
-				if ($result === false) {
1008
-					return false;
1009
-				}
1010
-			}
1011
-
1012
-			$source = fopen($tmpFile, 'r');
1013
-			if ($source) {
1014
-				$result = $this->file_put_contents($path, $source);
1015
-				// $this->file_put_contents() might have already closed
1016
-				// the resource, so we check it, before trying to close it
1017
-				// to avoid messages in the error log.
1018
-				if (is_resource($source)) {
1019
-					fclose($source);
1020
-				}
1021
-				unlink($tmpFile);
1022
-				return $result;
1023
-			} else {
1024
-				return false;
1025
-			}
1026
-		} else {
1027
-			return false;
1028
-		}
1029
-	}
1030
-
1031
-
1032
-	/**
1033
-	 * @param string $path
1034
-	 * @return mixed
1035
-	 * @throws \OCP\Files\InvalidPathException
1036
-	 */
1037
-	public function getMimeType($path) {
1038
-		$this->assertPathLength($path);
1039
-		return $this->basicOperation('getMimeType', $path);
1040
-	}
1041
-
1042
-	/**
1043
-	 * @param string $type
1044
-	 * @param string $path
1045
-	 * @param bool $raw
1046
-	 * @return bool|null|string
1047
-	 */
1048
-	public function hash($type, $path, $raw = false) {
1049
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1050
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1051
-		if (Filesystem::isValidPath($path)) {
1052
-			$path = $this->getRelativePath($absolutePath);
1053
-			if ($path == null) {
1054
-				return false;
1055
-			}
1056
-			if ($this->shouldEmitHooks($path)) {
1057
-				\OC_Hook::emit(
1058
-					Filesystem::CLASSNAME,
1059
-					Filesystem::signal_read,
1060
-					array(Filesystem::signal_param_path => $this->getHookPath($path))
1061
-				);
1062
-			}
1063
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1064
-			if ($storage) {
1065
-				$result = $storage->hash($type, $internalPath, $raw);
1066
-				return $result;
1067
-			}
1068
-		}
1069
-		return null;
1070
-	}
1071
-
1072
-	/**
1073
-	 * @param string $path
1074
-	 * @return mixed
1075
-	 * @throws \OCP\Files\InvalidPathException
1076
-	 */
1077
-	public function free_space($path = '/') {
1078
-		$this->assertPathLength($path);
1079
-		$result = $this->basicOperation('free_space', $path);
1080
-		if ($result === null) {
1081
-			throw new InvalidPathException();
1082
-		}
1083
-		return $result;
1084
-	}
1085
-
1086
-	/**
1087
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1088
-	 *
1089
-	 * @param string $operation
1090
-	 * @param string $path
1091
-	 * @param array $hooks (optional)
1092
-	 * @param mixed $extraParam (optional)
1093
-	 * @return mixed
1094
-	 * @throws \Exception
1095
-	 *
1096
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1097
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1098
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1099
-	 */
1100
-	private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1101
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1102
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1103
-		if (Filesystem::isValidPath($path)
1104
-			and !Filesystem::isFileBlacklisted($path)
1105
-		) {
1106
-			$path = $this->getRelativePath($absolutePath);
1107
-			if ($path == null) {
1108
-				return false;
1109
-			}
1110
-
1111
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1112
-				// always a shared lock during pre-hooks so the hook can read the file
1113
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1114
-			}
1115
-
1116
-			$run = $this->runHooks($hooks, $path);
1117
-			/** @var \OC\Files\Storage\Storage $storage */
1118
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1119
-			if ($run and $storage) {
1120
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1121
-					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1122
-				}
1123
-				try {
1124
-					if (!is_null($extraParam)) {
1125
-						$result = $storage->$operation($internalPath, $extraParam);
1126
-					} else {
1127
-						$result = $storage->$operation($internalPath);
1128
-					}
1129
-				} catch (\Exception $e) {
1130
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1131
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1132
-					} else if (in_array('read', $hooks)) {
1133
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1134
-					}
1135
-					throw $e;
1136
-				}
1137
-
1138
-				if ($result && in_array('delete', $hooks) and $result) {
1139
-					$this->removeUpdate($storage, $internalPath);
1140
-				}
1141
-				if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1142
-					$this->writeUpdate($storage, $internalPath);
1143
-				}
1144
-				if ($result && in_array('touch', $hooks)) {
1145
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1146
-				}
1147
-
1148
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1149
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1150
-				}
1151
-
1152
-				$unlockLater = false;
1153
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1154
-					$unlockLater = true;
1155
-					// make sure our unlocking callback will still be called if connection is aborted
1156
-					ignore_user_abort(true);
1157
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1158
-						if (in_array('write', $hooks)) {
1159
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1160
-						} else if (in_array('read', $hooks)) {
1161
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1162
-						}
1163
-					});
1164
-				}
1165
-
1166
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1167
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1168
-						$this->runHooks($hooks, $path, true);
1169
-					}
1170
-				}
1171
-
1172
-				if (!$unlockLater
1173
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1174
-				) {
1175
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1176
-				}
1177
-				return $result;
1178
-			} else {
1179
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1180
-			}
1181
-		}
1182
-		return null;
1183
-	}
1184
-
1185
-	/**
1186
-	 * get the path relative to the default root for hook usage
1187
-	 *
1188
-	 * @param string $path
1189
-	 * @return string
1190
-	 */
1191
-	private function getHookPath($path) {
1192
-		if (!Filesystem::getView()) {
1193
-			return $path;
1194
-		}
1195
-		return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1196
-	}
1197
-
1198
-	private function shouldEmitHooks($path = '') {
1199
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1200
-			return false;
1201
-		}
1202
-		if (!Filesystem::$loaded) {
1203
-			return false;
1204
-		}
1205
-		$defaultRoot = Filesystem::getRoot();
1206
-		if ($defaultRoot === null) {
1207
-			return false;
1208
-		}
1209
-		if ($this->fakeRoot === $defaultRoot) {
1210
-			return true;
1211
-		}
1212
-		$fullPath = $this->getAbsolutePath($path);
1213
-
1214
-		if ($fullPath === $defaultRoot) {
1215
-			return true;
1216
-		}
1217
-
1218
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1219
-	}
1220
-
1221
-	/**
1222
-	 * @param string[] $hooks
1223
-	 * @param string $path
1224
-	 * @param bool $post
1225
-	 * @return bool
1226
-	 */
1227
-	private function runHooks($hooks, $path, $post = false) {
1228
-		$relativePath = $path;
1229
-		$path = $this->getHookPath($path);
1230
-		$prefix = ($post) ? 'post_' : '';
1231
-		$run = true;
1232
-		if ($this->shouldEmitHooks($relativePath)) {
1233
-			foreach ($hooks as $hook) {
1234
-				if ($hook != 'read') {
1235
-					\OC_Hook::emit(
1236
-						Filesystem::CLASSNAME,
1237
-						$prefix . $hook,
1238
-						array(
1239
-							Filesystem::signal_param_run => &$run,
1240
-							Filesystem::signal_param_path => $path
1241
-						)
1242
-					);
1243
-				} elseif (!$post) {
1244
-					\OC_Hook::emit(
1245
-						Filesystem::CLASSNAME,
1246
-						$prefix . $hook,
1247
-						array(
1248
-							Filesystem::signal_param_path => $path
1249
-						)
1250
-					);
1251
-				}
1252
-			}
1253
-		}
1254
-		return $run;
1255
-	}
1256
-
1257
-	/**
1258
-	 * check if a file or folder has been updated since $time
1259
-	 *
1260
-	 * @param string $path
1261
-	 * @param int $time
1262
-	 * @return bool
1263
-	 */
1264
-	public function hasUpdated($path, $time) {
1265
-		return $this->basicOperation('hasUpdated', $path, array(), $time);
1266
-	}
1267
-
1268
-	/**
1269
-	 * @param string $ownerId
1270
-	 * @return \OC\User\User
1271
-	 */
1272
-	private function getUserObjectForOwner($ownerId) {
1273
-		$owner = $this->userManager->get($ownerId);
1274
-		if ($owner instanceof IUser) {
1275
-			return $owner;
1276
-		} else {
1277
-			return new User($ownerId, null);
1278
-		}
1279
-	}
1280
-
1281
-	/**
1282
-	 * Get file info from cache
1283
-	 *
1284
-	 * If the file is not in cached it will be scanned
1285
-	 * If the file has changed on storage the cache will be updated
1286
-	 *
1287
-	 * @param \OC\Files\Storage\Storage $storage
1288
-	 * @param string $internalPath
1289
-	 * @param string $relativePath
1290
-	 * @return ICacheEntry|bool
1291
-	 */
1292
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1293
-		$cache = $storage->getCache($internalPath);
1294
-		$data = $cache->get($internalPath);
1295
-		$watcher = $storage->getWatcher($internalPath);
1296
-
1297
-		try {
1298
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1299
-			if (!$data || $data['size'] === -1) {
1300
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1301
-				if (!$storage->file_exists($internalPath)) {
1302
-					$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1303
-					return false;
1304
-				}
1305
-				$scanner = $storage->getScanner($internalPath);
1306
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1307
-				$data = $cache->get($internalPath);
1308
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1309
-			} else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1310
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1311
-				$watcher->update($internalPath, $data);
1312
-				$storage->getPropagator()->propagateChange($internalPath, time());
1313
-				$data = $cache->get($internalPath);
1314
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1315
-			}
1316
-		} catch (LockedException $e) {
1317
-			// if the file is locked we just use the old cache info
1318
-		}
1319
-
1320
-		return $data;
1321
-	}
1322
-
1323
-	/**
1324
-	 * get the filesystem info
1325
-	 *
1326
-	 * @param string $path
1327
-	 * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1328
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1329
-	 * defaults to true
1330
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1331
-	 */
1332
-	public function getFileInfo($path, $includeMountPoints = true) {
1333
-		$this->assertPathLength($path);
1334
-		if (!Filesystem::isValidPath($path)) {
1335
-			return false;
1336
-		}
1337
-		if (Cache\Scanner::isPartialFile($path)) {
1338
-			return $this->getPartFileInfo($path);
1339
-		}
1340
-		$relativePath = $path;
1341
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1342
-
1343
-		$mount = Filesystem::getMountManager()->find($path);
1344
-		$storage = $mount->getStorage();
1345
-		$internalPath = $mount->getInternalPath($path);
1346
-		if ($storage) {
1347
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1348
-
1349
-			if (!$data instanceof ICacheEntry) {
1350
-				return false;
1351
-			}
1352
-
1353
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1354
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1355
-			}
1356
-
1357
-			$owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1358
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1359
-
1360
-			if ($data and isset($data['fileid'])) {
1361
-				if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1362
-					//add the sizes of other mount points to the folder
1363
-					$extOnly = ($includeMountPoints === 'ext');
1364
-					$mounts = Filesystem::getMountManager()->findIn($path);
1365
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1366
-						$subStorage = $mount->getStorage();
1367
-						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1368
-					}));
1369
-				}
1370
-			}
1371
-
1372
-			return $info;
1373
-		}
1374
-
1375
-		return false;
1376
-	}
1377
-
1378
-	/**
1379
-	 * get the content of a directory
1380
-	 *
1381
-	 * @param string $directory path under datadirectory
1382
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1383
-	 * @return FileInfo[]
1384
-	 */
1385
-	public function getDirectoryContent($directory, $mimetype_filter = '') {
1386
-		$this->assertPathLength($directory);
1387
-		if (!Filesystem::isValidPath($directory)) {
1388
-			return [];
1389
-		}
1390
-		$path = $this->getAbsolutePath($directory);
1391
-		$path = Filesystem::normalizePath($path);
1392
-		$mount = $this->getMount($directory);
1393
-		$storage = $mount->getStorage();
1394
-		$internalPath = $mount->getInternalPath($path);
1395
-		if ($storage) {
1396
-			$cache = $storage->getCache($internalPath);
1397
-			$user = \OC_User::getUser();
1398
-
1399
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1400
-
1401
-			if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1402
-				return [];
1403
-			}
1404
-
1405
-			$folderId = $data['fileid'];
1406
-			$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1407
-
1408
-			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1409
-			/**
1410
-			 * @var \OC\Files\FileInfo[] $files
1411
-			 */
1412
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1413
-				if ($sharingDisabled) {
1414
-					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1415
-				}
1416
-				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1417
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1418
-			}, $contents);
1419
-
1420
-			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1421
-			$mounts = Filesystem::getMountManager()->findIn($path);
1422
-			$dirLength = strlen($path);
1423
-			foreach ($mounts as $mount) {
1424
-				$mountPoint = $mount->getMountPoint();
1425
-				$subStorage = $mount->getStorage();
1426
-				if ($subStorage) {
1427
-					$subCache = $subStorage->getCache('');
1428
-
1429
-					$rootEntry = $subCache->get('');
1430
-					if (!$rootEntry) {
1431
-						$subScanner = $subStorage->getScanner('');
1432
-						try {
1433
-							$subScanner->scanFile('');
1434
-						} catch (\OCP\Files\StorageNotAvailableException $e) {
1435
-							continue;
1436
-						} catch (\OCP\Files\StorageInvalidException $e) {
1437
-							continue;
1438
-						} catch (\Exception $e) {
1439
-							// sometimes when the storage is not available it can be any exception
1440
-							\OCP\Util::writeLog(
1441
-								'core',
1442
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1443
-								get_class($e) . ': ' . $e->getMessage(),
1444
-								\OCP\Util::ERROR
1445
-							);
1446
-							continue;
1447
-						}
1448
-						$rootEntry = $subCache->get('');
1449
-					}
1450
-
1451
-					if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1452
-						$relativePath = trim(substr($mountPoint, $dirLength), '/');
1453
-						if ($pos = strpos($relativePath, '/')) {
1454
-							//mountpoint inside subfolder add size to the correct folder
1455
-							$entryName = substr($relativePath, 0, $pos);
1456
-							foreach ($files as &$entry) {
1457
-								if ($entry->getName() === $entryName) {
1458
-									$entry->addSubEntry($rootEntry, $mountPoint);
1459
-								}
1460
-							}
1461
-						} else { //mountpoint in this folder, add an entry for it
1462
-							$rootEntry['name'] = $relativePath;
1463
-							$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1464
-							$permissions = $rootEntry['permissions'];
1465
-							// do not allow renaming/deleting the mount point if they are not shared files/folders
1466
-							// for shared files/folders we use the permissions given by the owner
1467
-							if ($mount instanceof MoveableMount) {
1468
-								$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1469
-							} else {
1470
-								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1471
-							}
1472
-
1473
-							//remove any existing entry with the same name
1474
-							foreach ($files as $i => $file) {
1475
-								if ($file['name'] === $rootEntry['name']) {
1476
-									unset($files[$i]);
1477
-									break;
1478
-								}
1479
-							}
1480
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1481
-
1482
-							// if sharing was disabled for the user we remove the share permissions
1483
-							if (\OCP\Util::isSharingDisabledForUser()) {
1484
-								$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1485
-							}
1486
-
1487
-							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1488
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1489
-						}
1490
-					}
1491
-				}
1492
-			}
1493
-
1494
-			if ($mimetype_filter) {
1495
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1496
-					if (strpos($mimetype_filter, '/')) {
1497
-						return $file->getMimetype() === $mimetype_filter;
1498
-					} else {
1499
-						return $file->getMimePart() === $mimetype_filter;
1500
-					}
1501
-				});
1502
-			}
1503
-
1504
-			return $files;
1505
-		} else {
1506
-			return [];
1507
-		}
1508
-	}
1509
-
1510
-	/**
1511
-	 * change file metadata
1512
-	 *
1513
-	 * @param string $path
1514
-	 * @param array|\OCP\Files\FileInfo $data
1515
-	 * @return int
1516
-	 *
1517
-	 * returns the fileid of the updated file
1518
-	 */
1519
-	public function putFileInfo($path, $data) {
1520
-		$this->assertPathLength($path);
1521
-		if ($data instanceof FileInfo) {
1522
-			$data = $data->getData();
1523
-		}
1524
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1525
-		/**
1526
-		 * @var \OC\Files\Storage\Storage $storage
1527
-		 * @var string $internalPath
1528
-		 */
1529
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
1530
-		if ($storage) {
1531
-			$cache = $storage->getCache($path);
1532
-
1533
-			if (!$cache->inCache($internalPath)) {
1534
-				$scanner = $storage->getScanner($internalPath);
1535
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1536
-			}
1537
-
1538
-			return $cache->put($internalPath, $data);
1539
-		} else {
1540
-			return -1;
1541
-		}
1542
-	}
1543
-
1544
-	/**
1545
-	 * search for files with the name matching $query
1546
-	 *
1547
-	 * @param string $query
1548
-	 * @return FileInfo[]
1549
-	 */
1550
-	public function search($query) {
1551
-		return $this->searchCommon('search', array('%' . $query . '%'));
1552
-	}
1553
-
1554
-	/**
1555
-	 * search for files with the name matching $query
1556
-	 *
1557
-	 * @param string $query
1558
-	 * @return FileInfo[]
1559
-	 */
1560
-	public function searchRaw($query) {
1561
-		return $this->searchCommon('search', array($query));
1562
-	}
1563
-
1564
-	/**
1565
-	 * search for files by mimetype
1566
-	 *
1567
-	 * @param string $mimetype
1568
-	 * @return FileInfo[]
1569
-	 */
1570
-	public function searchByMime($mimetype) {
1571
-		return $this->searchCommon('searchByMime', array($mimetype));
1572
-	}
1573
-
1574
-	/**
1575
-	 * search for files by tag
1576
-	 *
1577
-	 * @param string|int $tag name or tag id
1578
-	 * @param string $userId owner of the tags
1579
-	 * @return FileInfo[]
1580
-	 */
1581
-	public function searchByTag($tag, $userId) {
1582
-		return $this->searchCommon('searchByTag', array($tag, $userId));
1583
-	}
1584
-
1585
-	/**
1586
-	 * @param string $method cache method
1587
-	 * @param array $args
1588
-	 * @return FileInfo[]
1589
-	 */
1590
-	private function searchCommon($method, $args) {
1591
-		$files = array();
1592
-		$rootLength = strlen($this->fakeRoot);
1593
-
1594
-		$mount = $this->getMount('');
1595
-		$mountPoint = $mount->getMountPoint();
1596
-		$storage = $mount->getStorage();
1597
-		if ($storage) {
1598
-			$cache = $storage->getCache('');
1599
-
1600
-			$results = call_user_func_array(array($cache, $method), $args);
1601
-			foreach ($results as $result) {
1602
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1603
-					$internalPath = $result['path'];
1604
-					$path = $mountPoint . $result['path'];
1605
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1606
-					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1607
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1608
-				}
1609
-			}
1610
-
1611
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1612
-			foreach ($mounts as $mount) {
1613
-				$mountPoint = $mount->getMountPoint();
1614
-				$storage = $mount->getStorage();
1615
-				if ($storage) {
1616
-					$cache = $storage->getCache('');
1617
-
1618
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1619
-					$results = call_user_func_array(array($cache, $method), $args);
1620
-					if ($results) {
1621
-						foreach ($results as $result) {
1622
-							$internalPath = $result['path'];
1623
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1624
-							$path = rtrim($mountPoint . $internalPath, '/');
1625
-							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1626
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1627
-						}
1628
-					}
1629
-				}
1630
-			}
1631
-		}
1632
-		return $files;
1633
-	}
1634
-
1635
-	/**
1636
-	 * Get the owner for a file or folder
1637
-	 *
1638
-	 * @param string $path
1639
-	 * @return string the user id of the owner
1640
-	 * @throws NotFoundException
1641
-	 */
1642
-	public function getOwner($path) {
1643
-		$info = $this->getFileInfo($path);
1644
-		if (!$info) {
1645
-			throw new NotFoundException($path . ' not found while trying to get owner');
1646
-		}
1647
-		return $info->getOwner()->getUID();
1648
-	}
1649
-
1650
-	/**
1651
-	 * get the ETag for a file or folder
1652
-	 *
1653
-	 * @param string $path
1654
-	 * @return string
1655
-	 */
1656
-	public function getETag($path) {
1657
-		/**
1658
-		 * @var Storage\Storage $storage
1659
-		 * @var string $internalPath
1660
-		 */
1661
-		list($storage, $internalPath) = $this->resolvePath($path);
1662
-		if ($storage) {
1663
-			return $storage->getETag($internalPath);
1664
-		} else {
1665
-			return null;
1666
-		}
1667
-	}
1668
-
1669
-	/**
1670
-	 * Get the path of a file by id, relative to the view
1671
-	 *
1672
-	 * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1673
-	 *
1674
-	 * @param int $id
1675
-	 * @throws NotFoundException
1676
-	 * @return string
1677
-	 */
1678
-	public function getPath($id) {
1679
-		$id = (int)$id;
1680
-		$manager = Filesystem::getMountManager();
1681
-		$mounts = $manager->findIn($this->fakeRoot);
1682
-		$mounts[] = $manager->find($this->fakeRoot);
1683
-		// reverse the array so we start with the storage this view is in
1684
-		// which is the most likely to contain the file we're looking for
1685
-		$mounts = array_reverse($mounts);
1686
-		foreach ($mounts as $mount) {
1687
-			/**
1688
-			 * @var \OC\Files\Mount\MountPoint $mount
1689
-			 */
1690
-			if ($mount->getStorage()) {
1691
-				$cache = $mount->getStorage()->getCache();
1692
-				$internalPath = $cache->getPathById($id);
1693
-				if (is_string($internalPath)) {
1694
-					$fullPath = $mount->getMountPoint() . $internalPath;
1695
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1696
-						return $path;
1697
-					}
1698
-				}
1699
-			}
1700
-		}
1701
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1702
-	}
1703
-
1704
-	/**
1705
-	 * @param string $path
1706
-	 * @throws InvalidPathException
1707
-	 */
1708
-	private function assertPathLength($path) {
1709
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1710
-		// Check for the string length - performed using isset() instead of strlen()
1711
-		// because isset() is about 5x-40x faster.
1712
-		if (isset($path[$maxLen])) {
1713
-			$pathLen = strlen($path);
1714
-			throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1715
-		}
1716
-	}
1717
-
1718
-	/**
1719
-	 * check if it is allowed to move a mount point to a given target.
1720
-	 * It is not allowed to move a mount point into a different mount point or
1721
-	 * into an already shared folder
1722
-	 *
1723
-	 * @param string $target path
1724
-	 * @return boolean
1725
-	 */
1726
-	private function isTargetAllowed($target) {
1727
-
1728
-		list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1729
-		if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1730
-			\OCP\Util::writeLog('files',
1731
-				'It is not allowed to move one mount point into another one',
1732
-				\OCP\Util::DEBUG);
1733
-			return false;
1734
-		}
1735
-
1736
-		// note: cannot use the view because the target is already locked
1737
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1738
-		if ($fileId === -1) {
1739
-			// target might not exist, need to check parent instead
1740
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1741
-		}
1742
-
1743
-		// check if any of the parents were shared by the current owner (include collections)
1744
-		$shares = \OCP\Share::getItemShared(
1745
-			'folder',
1746
-			$fileId,
1747
-			\OCP\Share::FORMAT_NONE,
1748
-			null,
1749
-			true
1750
-		);
1751
-
1752
-		if (count($shares) > 0) {
1753
-			\OCP\Util::writeLog('files',
1754
-				'It is not allowed to move one mount point into a shared folder',
1755
-				\OCP\Util::DEBUG);
1756
-			return false;
1757
-		}
1758
-
1759
-		return true;
1760
-	}
1761
-
1762
-	/**
1763
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1764
-	 *
1765
-	 * @param string $path
1766
-	 * @return \OCP\Files\FileInfo
1767
-	 */
1768
-	private function getPartFileInfo($path) {
1769
-		$mount = $this->getMount($path);
1770
-		$storage = $mount->getStorage();
1771
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1772
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1773
-		return new FileInfo(
1774
-			$this->getAbsolutePath($path),
1775
-			$storage,
1776
-			$internalPath,
1777
-			[
1778
-				'fileid' => null,
1779
-				'mimetype' => $storage->getMimeType($internalPath),
1780
-				'name' => basename($path),
1781
-				'etag' => null,
1782
-				'size' => $storage->filesize($internalPath),
1783
-				'mtime' => $storage->filemtime($internalPath),
1784
-				'encrypted' => false,
1785
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1786
-			],
1787
-			$mount,
1788
-			$owner
1789
-		);
1790
-	}
1791
-
1792
-	/**
1793
-	 * @param string $path
1794
-	 * @param string $fileName
1795
-	 * @throws InvalidPathException
1796
-	 */
1797
-	public function verifyPath($path, $fileName) {
1798
-		try {
1799
-			/** @type \OCP\Files\Storage $storage */
1800
-			list($storage, $internalPath) = $this->resolvePath($path);
1801
-			$storage->verifyPath($internalPath, $fileName);
1802
-		} catch (ReservedWordException $ex) {
1803
-			$l = \OC::$server->getL10N('lib');
1804
-			throw new InvalidPathException($l->t('File name is a reserved word'));
1805
-		} catch (InvalidCharacterInPathException $ex) {
1806
-			$l = \OC::$server->getL10N('lib');
1807
-			throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1808
-		} catch (FileNameTooLongException $ex) {
1809
-			$l = \OC::$server->getL10N('lib');
1810
-			throw new InvalidPathException($l->t('File name is too long'));
1811
-		} catch (InvalidDirectoryException $ex) {
1812
-			$l = \OC::$server->getL10N('lib');
1813
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1814
-		} catch (EmptyFileNameException $ex) {
1815
-			$l = \OC::$server->getL10N('lib');
1816
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1817
-		}
1818
-	}
1819
-
1820
-	/**
1821
-	 * get all parent folders of $path
1822
-	 *
1823
-	 * @param string $path
1824
-	 * @return string[]
1825
-	 */
1826
-	private function getParents($path) {
1827
-		$path = trim($path, '/');
1828
-		if (!$path) {
1829
-			return [];
1830
-		}
1831
-
1832
-		$parts = explode('/', $path);
1833
-
1834
-		// remove the single file
1835
-		array_pop($parts);
1836
-		$result = array('/');
1837
-		$resultPath = '';
1838
-		foreach ($parts as $part) {
1839
-			if ($part) {
1840
-				$resultPath .= '/' . $part;
1841
-				$result[] = $resultPath;
1842
-			}
1843
-		}
1844
-		return $result;
1845
-	}
1846
-
1847
-	/**
1848
-	 * Returns the mount point for which to lock
1849
-	 *
1850
-	 * @param string $absolutePath absolute path
1851
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1852
-	 * is mounted directly on the given path, false otherwise
1853
-	 * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1854
-	 */
1855
-	private function getMountForLock($absolutePath, $useParentMount = false) {
1856
-		$results = [];
1857
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1858
-		if (!$mount) {
1859
-			return $results;
1860
-		}
1861
-
1862
-		if ($useParentMount) {
1863
-			// find out if something is mounted directly on the path
1864
-			$internalPath = $mount->getInternalPath($absolutePath);
1865
-			if ($internalPath === '') {
1866
-				// resolve the parent mount instead
1867
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1868
-			}
1869
-		}
1870
-
1871
-		return $mount;
1872
-	}
1873
-
1874
-	/**
1875
-	 * Lock the given path
1876
-	 *
1877
-	 * @param string $path the path of the file to lock, relative to the view
1878
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1879
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1880
-	 *
1881
-	 * @return bool False if the path is excluded from locking, true otherwise
1882
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1883
-	 */
1884
-	private function lockPath($path, $type, $lockMountPoint = false) {
1885
-		$absolutePath = $this->getAbsolutePath($path);
1886
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1887
-		if (!$this->shouldLockFile($absolutePath)) {
1888
-			return false;
1889
-		}
1890
-
1891
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1892
-		if ($mount) {
1893
-			try {
1894
-				$storage = $mount->getStorage();
1895
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1896
-					$storage->acquireLock(
1897
-						$mount->getInternalPath($absolutePath),
1898
-						$type,
1899
-						$this->lockingProvider
1900
-					);
1901
-				}
1902
-			} catch (\OCP\Lock\LockedException $e) {
1903
-				// rethrow with the a human-readable path
1904
-				throw new \OCP\Lock\LockedException(
1905
-					$this->getPathRelativeToFiles($absolutePath),
1906
-					$e
1907
-				);
1908
-			}
1909
-		}
1910
-
1911
-		return true;
1912
-	}
1913
-
1914
-	/**
1915
-	 * Change the lock type
1916
-	 *
1917
-	 * @param string $path the path of the file to lock, relative to the view
1918
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1919
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1920
-	 *
1921
-	 * @return bool False if the path is excluded from locking, true otherwise
1922
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1923
-	 */
1924
-	public function changeLock($path, $type, $lockMountPoint = false) {
1925
-		$path = Filesystem::normalizePath($path);
1926
-		$absolutePath = $this->getAbsolutePath($path);
1927
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1928
-		if (!$this->shouldLockFile($absolutePath)) {
1929
-			return false;
1930
-		}
1931
-
1932
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1933
-		if ($mount) {
1934
-			try {
1935
-				$storage = $mount->getStorage();
1936
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1937
-					$storage->changeLock(
1938
-						$mount->getInternalPath($absolutePath),
1939
-						$type,
1940
-						$this->lockingProvider
1941
-					);
1942
-				}
1943
-			} catch (\OCP\Lock\LockedException $e) {
1944
-				try {
1945
-					// rethrow with the a human-readable path
1946
-					throw new \OCP\Lock\LockedException(
1947
-						$this->getPathRelativeToFiles($absolutePath),
1948
-						$e
1949
-					);
1950
-				} catch (\InvalidArgumentException $e) {
1951
-					throw new \OCP\Lock\LockedException(
1952
-						$absolutePath,
1953
-						$e
1954
-					);
1955
-				}
1956
-			}
1957
-		}
1958
-
1959
-		return true;
1960
-	}
1961
-
1962
-	/**
1963
-	 * Unlock the given path
1964
-	 *
1965
-	 * @param string $path the path of the file to unlock, relative to the view
1966
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1967
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1968
-	 *
1969
-	 * @return bool False if the path is excluded from locking, true otherwise
1970
-	 */
1971
-	private function unlockPath($path, $type, $lockMountPoint = false) {
1972
-		$absolutePath = $this->getAbsolutePath($path);
1973
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1974
-		if (!$this->shouldLockFile($absolutePath)) {
1975
-			return false;
1976
-		}
1977
-
1978
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1979
-		if ($mount) {
1980
-			$storage = $mount->getStorage();
1981
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1982
-				$storage->releaseLock(
1983
-					$mount->getInternalPath($absolutePath),
1984
-					$type,
1985
-					$this->lockingProvider
1986
-				);
1987
-			}
1988
-		}
1989
-
1990
-		return true;
1991
-	}
1992
-
1993
-	/**
1994
-	 * Lock a path and all its parents up to the root of the view
1995
-	 *
1996
-	 * @param string $path the path of the file to lock relative to the view
1997
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1998
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1999
-	 *
2000
-	 * @return bool False if the path is excluded from locking, true otherwise
2001
-	 */
2002
-	public function lockFile($path, $type, $lockMountPoint = false) {
2003
-		$absolutePath = $this->getAbsolutePath($path);
2004
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2005
-		if (!$this->shouldLockFile($absolutePath)) {
2006
-			return false;
2007
-		}
2008
-
2009
-		$this->lockPath($path, $type, $lockMountPoint);
2010
-
2011
-		$parents = $this->getParents($path);
2012
-		foreach ($parents as $parent) {
2013
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2014
-		}
2015
-
2016
-		return true;
2017
-	}
2018
-
2019
-	/**
2020
-	 * Unlock a path and all its parents up to the root of the view
2021
-	 *
2022
-	 * @param string $path the path of the file to lock relative to the view
2023
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2024
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2025
-	 *
2026
-	 * @return bool False if the path is excluded from locking, true otherwise
2027
-	 */
2028
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2029
-		$absolutePath = $this->getAbsolutePath($path);
2030
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2031
-		if (!$this->shouldLockFile($absolutePath)) {
2032
-			return false;
2033
-		}
2034
-
2035
-		$this->unlockPath($path, $type, $lockMountPoint);
2036
-
2037
-		$parents = $this->getParents($path);
2038
-		foreach ($parents as $parent) {
2039
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2040
-		}
2041
-
2042
-		return true;
2043
-	}
2044
-
2045
-	/**
2046
-	 * Only lock files in data/user/files/
2047
-	 *
2048
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2049
-	 * @return bool
2050
-	 */
2051
-	protected function shouldLockFile($path) {
2052
-		$path = Filesystem::normalizePath($path);
2053
-
2054
-		$pathSegments = explode('/', $path);
2055
-		if (isset($pathSegments[2])) {
2056
-			// E.g.: /username/files/path-to-file
2057
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2058
-		}
2059
-
2060
-		return strpos($path, '/appdata_') !== 0;
2061
-	}
2062
-
2063
-	/**
2064
-	 * Shortens the given absolute path to be relative to
2065
-	 * "$user/files".
2066
-	 *
2067
-	 * @param string $absolutePath absolute path which is under "files"
2068
-	 *
2069
-	 * @return string path relative to "files" with trimmed slashes or null
2070
-	 * if the path was NOT relative to files
2071
-	 *
2072
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2073
-	 * @since 8.1.0
2074
-	 */
2075
-	public function getPathRelativeToFiles($absolutePath) {
2076
-		$path = Filesystem::normalizePath($absolutePath);
2077
-		$parts = explode('/', trim($path, '/'), 3);
2078
-		// "$user", "files", "path/to/dir"
2079
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2080
-			$this->logger->error(
2081
-				'$absolutePath must be relative to "files", value is "%s"',
2082
-				[
2083
-					$absolutePath
2084
-				]
2085
-			);
2086
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2087
-		}
2088
-		if (isset($parts[2])) {
2089
-			return $parts[2];
2090
-		}
2091
-		return '';
2092
-	}
2093
-
2094
-	/**
2095
-	 * @param string $filename
2096
-	 * @return array
2097
-	 * @throws \OC\User\NoUserException
2098
-	 * @throws NotFoundException
2099
-	 */
2100
-	public function getUidAndFilename($filename) {
2101
-		$info = $this->getFileInfo($filename);
2102
-		if (!$info instanceof \OCP\Files\FileInfo) {
2103
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2104
-		}
2105
-		$uid = $info->getOwner()->getUID();
2106
-		if ($uid != \OCP\User::getUser()) {
2107
-			Filesystem::initMountPoints($uid);
2108
-			$ownerView = new View('/' . $uid . '/files');
2109
-			try {
2110
-				$filename = $ownerView->getPath($info['fileid']);
2111
-			} catch (NotFoundException $e) {
2112
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2113
-			}
2114
-		}
2115
-		return [$uid, $filename];
2116
-	}
2117
-
2118
-	/**
2119
-	 * Creates parent non-existing folders
2120
-	 *
2121
-	 * @param string $filePath
2122
-	 * @return bool
2123
-	 */
2124
-	private function createParentDirectories($filePath) {
2125
-		$directoryParts = explode('/', $filePath);
2126
-		$directoryParts = array_filter($directoryParts);
2127
-		foreach ($directoryParts as $key => $part) {
2128
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2129
-			$currentPath = '/' . implode('/', $currentPathElements);
2130
-			if ($this->is_file($currentPath)) {
2131
-				return false;
2132
-			}
2133
-			if (!$this->file_exists($currentPath)) {
2134
-				$this->mkdir($currentPath);
2135
-			}
2136
-		}
2137
-
2138
-		return true;
2139
-	}
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
+            if (fseek($handle, $from) === 0) {
451
+                $chunkSize = 8192; // 8 kB chunks
452
+                $end = $to + 1;
453
+                while (!feof($handle) && ftell($handle) < $end) {
454
+                    $len = $end - ftell($handle);
455
+                    if ($len > $chunkSize) {
456
+                        $len = $chunkSize;
457
+                    }
458
+                    echo fread($handle, $len);
459
+                    flush();
460
+                }
461
+                $size = ftell($handle) - $from;
462
+                return $size;
463
+            }
464
+
465
+            throw new \OCP\Files\UnseekableException('fseek error');
466
+        }
467
+        return false;
468
+    }
469
+
470
+    /**
471
+     * @param string $path
472
+     * @return mixed
473
+     */
474
+    public function isCreatable($path) {
475
+        return $this->basicOperation('isCreatable', $path);
476
+    }
477
+
478
+    /**
479
+     * @param string $path
480
+     * @return mixed
481
+     */
482
+    public function isReadable($path) {
483
+        return $this->basicOperation('isReadable', $path);
484
+    }
485
+
486
+    /**
487
+     * @param string $path
488
+     * @return mixed
489
+     */
490
+    public function isUpdatable($path) {
491
+        return $this->basicOperation('isUpdatable', $path);
492
+    }
493
+
494
+    /**
495
+     * @param string $path
496
+     * @return bool|mixed
497
+     */
498
+    public function isDeletable($path) {
499
+        $absolutePath = $this->getAbsolutePath($path);
500
+        $mount = Filesystem::getMountManager()->find($absolutePath);
501
+        if ($mount->getInternalPath($absolutePath) === '') {
502
+            return $mount instanceof MoveableMount;
503
+        }
504
+        return $this->basicOperation('isDeletable', $path);
505
+    }
506
+
507
+    /**
508
+     * @param string $path
509
+     * @return mixed
510
+     */
511
+    public function isSharable($path) {
512
+        return $this->basicOperation('isSharable', $path);
513
+    }
514
+
515
+    /**
516
+     * @param string $path
517
+     * @return bool|mixed
518
+     */
519
+    public function file_exists($path) {
520
+        if ($path == '/') {
521
+            return true;
522
+        }
523
+        return $this->basicOperation('file_exists', $path);
524
+    }
525
+
526
+    /**
527
+     * @param string $path
528
+     * @return mixed
529
+     */
530
+    public function filemtime($path) {
531
+        return $this->basicOperation('filemtime', $path);
532
+    }
533
+
534
+    /**
535
+     * @param string $path
536
+     * @param int|string $mtime
537
+     * @return bool
538
+     */
539
+    public function touch($path, $mtime = null) {
540
+        if (!is_null($mtime) and !is_numeric($mtime)) {
541
+            $mtime = strtotime($mtime);
542
+        }
543
+
544
+        $hooks = array('touch');
545
+
546
+        if (!$this->file_exists($path)) {
547
+            $hooks[] = 'create';
548
+            $hooks[] = 'write';
549
+        }
550
+        $result = $this->basicOperation('touch', $path, $hooks, $mtime);
551
+        if (!$result) {
552
+            // If create file fails because of permissions on external storage like SMB folders,
553
+            // check file exists and return false if not.
554
+            if (!$this->file_exists($path)) {
555
+                return false;
556
+            }
557
+            if (is_null($mtime)) {
558
+                $mtime = time();
559
+            }
560
+            //if native touch fails, we emulate it by changing the mtime in the cache
561
+            $this->putFileInfo($path, array('mtime' => floor($mtime)));
562
+        }
563
+        return true;
564
+    }
565
+
566
+    /**
567
+     * @param string $path
568
+     * @return mixed
569
+     */
570
+    public function file_get_contents($path) {
571
+        return $this->basicOperation('file_get_contents', $path, array('read'));
572
+    }
573
+
574
+    /**
575
+     * @param bool $exists
576
+     * @param string $path
577
+     * @param bool $run
578
+     */
579
+    protected function emit_file_hooks_pre($exists, $path, &$run) {
580
+        if (!$exists) {
581
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
582
+                Filesystem::signal_param_path => $this->getHookPath($path),
583
+                Filesystem::signal_param_run => &$run,
584
+            ));
585
+        } else {
586
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
587
+                Filesystem::signal_param_path => $this->getHookPath($path),
588
+                Filesystem::signal_param_run => &$run,
589
+            ));
590
+        }
591
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
592
+            Filesystem::signal_param_path => $this->getHookPath($path),
593
+            Filesystem::signal_param_run => &$run,
594
+        ));
595
+    }
596
+
597
+    /**
598
+     * @param bool $exists
599
+     * @param string $path
600
+     */
601
+    protected function emit_file_hooks_post($exists, $path) {
602
+        if (!$exists) {
603
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
604
+                Filesystem::signal_param_path => $this->getHookPath($path),
605
+            ));
606
+        } else {
607
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
608
+                Filesystem::signal_param_path => $this->getHookPath($path),
609
+            ));
610
+        }
611
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
612
+            Filesystem::signal_param_path => $this->getHookPath($path),
613
+        ));
614
+    }
615
+
616
+    /**
617
+     * @param string $path
618
+     * @param mixed $data
619
+     * @return bool|mixed
620
+     * @throws \Exception
621
+     */
622
+    public function file_put_contents($path, $data) {
623
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
624
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
625
+            if (Filesystem::isValidPath($path)
626
+                and !Filesystem::isFileBlacklisted($path)
627
+            ) {
628
+                $path = $this->getRelativePath($absolutePath);
629
+
630
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
631
+
632
+                $exists = $this->file_exists($path);
633
+                $run = true;
634
+                if ($this->shouldEmitHooks($path)) {
635
+                    $this->emit_file_hooks_pre($exists, $path, $run);
636
+                }
637
+                if (!$run) {
638
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
639
+                    return false;
640
+                }
641
+
642
+                $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
643
+
644
+                /** @var \OC\Files\Storage\Storage $storage */
645
+                list($storage, $internalPath) = $this->resolvePath($path);
646
+                $target = $storage->fopen($internalPath, 'w');
647
+                if ($target) {
648
+                    list (, $result) = \OC_Helper::streamCopy($data, $target);
649
+                    fclose($target);
650
+                    fclose($data);
651
+
652
+                    $this->writeUpdate($storage, $internalPath);
653
+
654
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
655
+
656
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
657
+                        $this->emit_file_hooks_post($exists, $path);
658
+                    }
659
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
660
+                    return $result;
661
+                } else {
662
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
663
+                    return false;
664
+                }
665
+            } else {
666
+                return false;
667
+            }
668
+        } else {
669
+            $hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
670
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
671
+        }
672
+    }
673
+
674
+    /**
675
+     * @param string $path
676
+     * @return bool|mixed
677
+     */
678
+    public function unlink($path) {
679
+        if ($path === '' || $path === '/') {
680
+            // do not allow deleting the root
681
+            return false;
682
+        }
683
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
684
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
685
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
686
+        if ($mount and $mount->getInternalPath($absolutePath) === '') {
687
+            return $this->removeMount($mount, $absolutePath);
688
+        }
689
+        if ($this->is_dir($path)) {
690
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
691
+        } else {
692
+            $result = $this->basicOperation('unlink', $path, ['delete']);
693
+        }
694
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
695
+            $storage = $mount->getStorage();
696
+            $internalPath = $mount->getInternalPath($absolutePath);
697
+            $storage->getUpdater()->remove($internalPath);
698
+            return true;
699
+        } else {
700
+            return $result;
701
+        }
702
+    }
703
+
704
+    /**
705
+     * @param string $directory
706
+     * @return bool|mixed
707
+     */
708
+    public function deleteAll($directory) {
709
+        return $this->rmdir($directory);
710
+    }
711
+
712
+    /**
713
+     * Rename/move a file or folder from the source path to target path.
714
+     *
715
+     * @param string $path1 source path
716
+     * @param string $path2 target path
717
+     *
718
+     * @return bool|mixed
719
+     */
720
+    public function rename($path1, $path2) {
721
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
722
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
723
+        $result = false;
724
+        if (
725
+            Filesystem::isValidPath($path2)
726
+            and Filesystem::isValidPath($path1)
727
+            and !Filesystem::isFileBlacklisted($path2)
728
+        ) {
729
+            $path1 = $this->getRelativePath($absolutePath1);
730
+            $path2 = $this->getRelativePath($absolutePath2);
731
+            $exists = $this->file_exists($path2);
732
+
733
+            if ($path1 == null or $path2 == null) {
734
+                return false;
735
+            }
736
+
737
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
738
+            try {
739
+                $this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
740
+            } catch (LockedException $e) {
741
+                $this->unlockFile($path1, ILockingProvider::LOCK_SHARED);
742
+                throw $e;
743
+            }
744
+
745
+            $run = true;
746
+            if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
747
+                // if it was a rename from a part file to a regular file it was a write and not a rename operation
748
+                $this->emit_file_hooks_pre($exists, $path2, $run);
749
+            } elseif ($this->shouldEmitHooks($path1)) {
750
+                \OC_Hook::emit(
751
+                    Filesystem::CLASSNAME, Filesystem::signal_rename,
752
+                    array(
753
+                        Filesystem::signal_param_oldpath => $this->getHookPath($path1),
754
+                        Filesystem::signal_param_newpath => $this->getHookPath($path2),
755
+                        Filesystem::signal_param_run => &$run
756
+                    )
757
+                );
758
+            }
759
+            if ($run) {
760
+                $this->verifyPath(dirname($path2), basename($path2));
761
+
762
+                $manager = Filesystem::getMountManager();
763
+                $mount1 = $this->getMount($path1);
764
+                $mount2 = $this->getMount($path2);
765
+                $storage1 = $mount1->getStorage();
766
+                $storage2 = $mount2->getStorage();
767
+                $internalPath1 = $mount1->getInternalPath($absolutePath1);
768
+                $internalPath2 = $mount2->getInternalPath($absolutePath2);
769
+
770
+                $this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
771
+                $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
772
+
773
+                if ($internalPath1 === '') {
774
+                    if ($mount1 instanceof MoveableMount) {
775
+                        if ($this->isTargetAllowed($absolutePath2)) {
776
+                            /**
777
+                             * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
778
+                             */
779
+                            $sourceMountPoint = $mount1->getMountPoint();
780
+                            $result = $mount1->moveMount($absolutePath2);
781
+                            $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
782
+                        } else {
783
+                            $result = false;
784
+                        }
785
+                    } else {
786
+                        $result = false;
787
+                    }
788
+                    // moving a file/folder within the same mount point
789
+                } elseif ($storage1 === $storage2) {
790
+                    if ($storage1) {
791
+                        $result = $storage1->rename($internalPath1, $internalPath2);
792
+                    } else {
793
+                        $result = false;
794
+                    }
795
+                    // moving a file/folder between storages (from $storage1 to $storage2)
796
+                } else {
797
+                    $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
798
+                }
799
+
800
+                if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
801
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
802
+
803
+                    $this->writeUpdate($storage2, $internalPath2);
804
+                } else if ($result) {
805
+                    if ($internalPath1 !== '') { // don't do a cache update for moved mounts
806
+                        $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
807
+                    }
808
+                }
809
+
810
+                $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
811
+                $this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
812
+
813
+                if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
814
+                    if ($this->shouldEmitHooks()) {
815
+                        $this->emit_file_hooks_post($exists, $path2);
816
+                    }
817
+                } elseif ($result) {
818
+                    if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
819
+                        \OC_Hook::emit(
820
+                            Filesystem::CLASSNAME,
821
+                            Filesystem::signal_post_rename,
822
+                            array(
823
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
824
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
825
+                            )
826
+                        );
827
+                    }
828
+                }
829
+            }
830
+            $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
831
+            $this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
832
+        }
833
+        return $result;
834
+    }
835
+
836
+    /**
837
+     * Copy a file/folder from the source path to target path
838
+     *
839
+     * @param string $path1 source path
840
+     * @param string $path2 target path
841
+     * @param bool $preserveMtime whether to preserve mtime on the copy
842
+     *
843
+     * @return bool|mixed
844
+     */
845
+    public function copy($path1, $path2, $preserveMtime = false) {
846
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
847
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
848
+        $result = false;
849
+        if (
850
+            Filesystem::isValidPath($path2)
851
+            and Filesystem::isValidPath($path1)
852
+            and !Filesystem::isFileBlacklisted($path2)
853
+        ) {
854
+            $path1 = $this->getRelativePath($absolutePath1);
855
+            $path2 = $this->getRelativePath($absolutePath2);
856
+
857
+            if ($path1 == null or $path2 == null) {
858
+                return false;
859
+            }
860
+            $run = true;
861
+
862
+            $this->lockFile($path2, ILockingProvider::LOCK_SHARED);
863
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED);
864
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
865
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
866
+
867
+            try {
868
+
869
+                $exists = $this->file_exists($path2);
870
+                if ($this->shouldEmitHooks()) {
871
+                    \OC_Hook::emit(
872
+                        Filesystem::CLASSNAME,
873
+                        Filesystem::signal_copy,
874
+                        array(
875
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
876
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
877
+                            Filesystem::signal_param_run => &$run
878
+                        )
879
+                    );
880
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
881
+                }
882
+                if ($run) {
883
+                    $mount1 = $this->getMount($path1);
884
+                    $mount2 = $this->getMount($path2);
885
+                    $storage1 = $mount1->getStorage();
886
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
887
+                    $storage2 = $mount2->getStorage();
888
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
889
+
890
+                    $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
891
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
892
+
893
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
894
+                        if ($storage1) {
895
+                            $result = $storage1->copy($internalPath1, $internalPath2);
896
+                        } else {
897
+                            $result = false;
898
+                        }
899
+                    } else {
900
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
901
+                    }
902
+
903
+                    $this->writeUpdate($storage2, $internalPath2);
904
+
905
+                    $this->changeLock($path2, ILockingProvider::LOCK_SHARED);
906
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
907
+
908
+                    if ($this->shouldEmitHooks() && $result !== false) {
909
+                        \OC_Hook::emit(
910
+                            Filesystem::CLASSNAME,
911
+                            Filesystem::signal_post_copy,
912
+                            array(
913
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
914
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
915
+                            )
916
+                        );
917
+                        $this->emit_file_hooks_post($exists, $path2);
918
+                    }
919
+
920
+                }
921
+            } catch (\Exception $e) {
922
+                $this->unlockFile($path2, $lockTypePath2);
923
+                $this->unlockFile($path1, $lockTypePath1);
924
+                throw $e;
925
+            }
926
+
927
+            $this->unlockFile($path2, $lockTypePath2);
928
+            $this->unlockFile($path1, $lockTypePath1);
929
+
930
+        }
931
+        return $result;
932
+    }
933
+
934
+    /**
935
+     * @param string $path
936
+     * @param string $mode 'r' or 'w'
937
+     * @return resource
938
+     */
939
+    public function fopen($path, $mode) {
940
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
941
+        $hooks = array();
942
+        switch ($mode) {
943
+            case 'r':
944
+                $hooks[] = 'read';
945
+                break;
946
+            case 'r+':
947
+            case 'w+':
948
+            case 'x+':
949
+            case 'a+':
950
+                $hooks[] = 'read';
951
+                $hooks[] = 'write';
952
+                break;
953
+            case 'w':
954
+            case 'x':
955
+            case 'a':
956
+                $hooks[] = 'write';
957
+                break;
958
+            default:
959
+                \OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
960
+        }
961
+
962
+        if ($mode !== 'r' && $mode !== 'w') {
963
+            \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');
964
+        }
965
+
966
+        return $this->basicOperation('fopen', $path, $hooks, $mode);
967
+    }
968
+
969
+    /**
970
+     * @param string $path
971
+     * @return bool|string
972
+     * @throws \OCP\Files\InvalidPathException
973
+     */
974
+    public function toTmpFile($path) {
975
+        $this->assertPathLength($path);
976
+        if (Filesystem::isValidPath($path)) {
977
+            $source = $this->fopen($path, 'r');
978
+            if ($source) {
979
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
980
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
981
+                file_put_contents($tmpFile, $source);
982
+                return $tmpFile;
983
+            } else {
984
+                return false;
985
+            }
986
+        } else {
987
+            return false;
988
+        }
989
+    }
990
+
991
+    /**
992
+     * @param string $tmpFile
993
+     * @param string $path
994
+     * @return bool|mixed
995
+     * @throws \OCP\Files\InvalidPathException
996
+     */
997
+    public function fromTmpFile($tmpFile, $path) {
998
+        $this->assertPathLength($path);
999
+        if (Filesystem::isValidPath($path)) {
1000
+
1001
+            // Get directory that the file is going into
1002
+            $filePath = dirname($path);
1003
+
1004
+            // Create the directories if any
1005
+            if (!$this->file_exists($filePath)) {
1006
+                $result = $this->createParentDirectories($filePath);
1007
+                if ($result === false) {
1008
+                    return false;
1009
+                }
1010
+            }
1011
+
1012
+            $source = fopen($tmpFile, 'r');
1013
+            if ($source) {
1014
+                $result = $this->file_put_contents($path, $source);
1015
+                // $this->file_put_contents() might have already closed
1016
+                // the resource, so we check it, before trying to close it
1017
+                // to avoid messages in the error log.
1018
+                if (is_resource($source)) {
1019
+                    fclose($source);
1020
+                }
1021
+                unlink($tmpFile);
1022
+                return $result;
1023
+            } else {
1024
+                return false;
1025
+            }
1026
+        } else {
1027
+            return false;
1028
+        }
1029
+    }
1030
+
1031
+
1032
+    /**
1033
+     * @param string $path
1034
+     * @return mixed
1035
+     * @throws \OCP\Files\InvalidPathException
1036
+     */
1037
+    public function getMimeType($path) {
1038
+        $this->assertPathLength($path);
1039
+        return $this->basicOperation('getMimeType', $path);
1040
+    }
1041
+
1042
+    /**
1043
+     * @param string $type
1044
+     * @param string $path
1045
+     * @param bool $raw
1046
+     * @return bool|null|string
1047
+     */
1048
+    public function hash($type, $path, $raw = false) {
1049
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1050
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1051
+        if (Filesystem::isValidPath($path)) {
1052
+            $path = $this->getRelativePath($absolutePath);
1053
+            if ($path == null) {
1054
+                return false;
1055
+            }
1056
+            if ($this->shouldEmitHooks($path)) {
1057
+                \OC_Hook::emit(
1058
+                    Filesystem::CLASSNAME,
1059
+                    Filesystem::signal_read,
1060
+                    array(Filesystem::signal_param_path => $this->getHookPath($path))
1061
+                );
1062
+            }
1063
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1064
+            if ($storage) {
1065
+                $result = $storage->hash($type, $internalPath, $raw);
1066
+                return $result;
1067
+            }
1068
+        }
1069
+        return null;
1070
+    }
1071
+
1072
+    /**
1073
+     * @param string $path
1074
+     * @return mixed
1075
+     * @throws \OCP\Files\InvalidPathException
1076
+     */
1077
+    public function free_space($path = '/') {
1078
+        $this->assertPathLength($path);
1079
+        $result = $this->basicOperation('free_space', $path);
1080
+        if ($result === null) {
1081
+            throw new InvalidPathException();
1082
+        }
1083
+        return $result;
1084
+    }
1085
+
1086
+    /**
1087
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1088
+     *
1089
+     * @param string $operation
1090
+     * @param string $path
1091
+     * @param array $hooks (optional)
1092
+     * @param mixed $extraParam (optional)
1093
+     * @return mixed
1094
+     * @throws \Exception
1095
+     *
1096
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1097
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1098
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1099
+     */
1100
+    private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1101
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1102
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1103
+        if (Filesystem::isValidPath($path)
1104
+            and !Filesystem::isFileBlacklisted($path)
1105
+        ) {
1106
+            $path = $this->getRelativePath($absolutePath);
1107
+            if ($path == null) {
1108
+                return false;
1109
+            }
1110
+
1111
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1112
+                // always a shared lock during pre-hooks so the hook can read the file
1113
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1114
+            }
1115
+
1116
+            $run = $this->runHooks($hooks, $path);
1117
+            /** @var \OC\Files\Storage\Storage $storage */
1118
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1119
+            if ($run and $storage) {
1120
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1121
+                    $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1122
+                }
1123
+                try {
1124
+                    if (!is_null($extraParam)) {
1125
+                        $result = $storage->$operation($internalPath, $extraParam);
1126
+                    } else {
1127
+                        $result = $storage->$operation($internalPath);
1128
+                    }
1129
+                } catch (\Exception $e) {
1130
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1131
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1132
+                    } else if (in_array('read', $hooks)) {
1133
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1134
+                    }
1135
+                    throw $e;
1136
+                }
1137
+
1138
+                if ($result && in_array('delete', $hooks) and $result) {
1139
+                    $this->removeUpdate($storage, $internalPath);
1140
+                }
1141
+                if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1142
+                    $this->writeUpdate($storage, $internalPath);
1143
+                }
1144
+                if ($result && in_array('touch', $hooks)) {
1145
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1146
+                }
1147
+
1148
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1149
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1150
+                }
1151
+
1152
+                $unlockLater = false;
1153
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1154
+                    $unlockLater = true;
1155
+                    // make sure our unlocking callback will still be called if connection is aborted
1156
+                    ignore_user_abort(true);
1157
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1158
+                        if (in_array('write', $hooks)) {
1159
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1160
+                        } else if (in_array('read', $hooks)) {
1161
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1162
+                        }
1163
+                    });
1164
+                }
1165
+
1166
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1167
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1168
+                        $this->runHooks($hooks, $path, true);
1169
+                    }
1170
+                }
1171
+
1172
+                if (!$unlockLater
1173
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1174
+                ) {
1175
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1176
+                }
1177
+                return $result;
1178
+            } else {
1179
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1180
+            }
1181
+        }
1182
+        return null;
1183
+    }
1184
+
1185
+    /**
1186
+     * get the path relative to the default root for hook usage
1187
+     *
1188
+     * @param string $path
1189
+     * @return string
1190
+     */
1191
+    private function getHookPath($path) {
1192
+        if (!Filesystem::getView()) {
1193
+            return $path;
1194
+        }
1195
+        return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1196
+    }
1197
+
1198
+    private function shouldEmitHooks($path = '') {
1199
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1200
+            return false;
1201
+        }
1202
+        if (!Filesystem::$loaded) {
1203
+            return false;
1204
+        }
1205
+        $defaultRoot = Filesystem::getRoot();
1206
+        if ($defaultRoot === null) {
1207
+            return false;
1208
+        }
1209
+        if ($this->fakeRoot === $defaultRoot) {
1210
+            return true;
1211
+        }
1212
+        $fullPath = $this->getAbsolutePath($path);
1213
+
1214
+        if ($fullPath === $defaultRoot) {
1215
+            return true;
1216
+        }
1217
+
1218
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1219
+    }
1220
+
1221
+    /**
1222
+     * @param string[] $hooks
1223
+     * @param string $path
1224
+     * @param bool $post
1225
+     * @return bool
1226
+     */
1227
+    private function runHooks($hooks, $path, $post = false) {
1228
+        $relativePath = $path;
1229
+        $path = $this->getHookPath($path);
1230
+        $prefix = ($post) ? 'post_' : '';
1231
+        $run = true;
1232
+        if ($this->shouldEmitHooks($relativePath)) {
1233
+            foreach ($hooks as $hook) {
1234
+                if ($hook != 'read') {
1235
+                    \OC_Hook::emit(
1236
+                        Filesystem::CLASSNAME,
1237
+                        $prefix . $hook,
1238
+                        array(
1239
+                            Filesystem::signal_param_run => &$run,
1240
+                            Filesystem::signal_param_path => $path
1241
+                        )
1242
+                    );
1243
+                } elseif (!$post) {
1244
+                    \OC_Hook::emit(
1245
+                        Filesystem::CLASSNAME,
1246
+                        $prefix . $hook,
1247
+                        array(
1248
+                            Filesystem::signal_param_path => $path
1249
+                        )
1250
+                    );
1251
+                }
1252
+            }
1253
+        }
1254
+        return $run;
1255
+    }
1256
+
1257
+    /**
1258
+     * check if a file or folder has been updated since $time
1259
+     *
1260
+     * @param string $path
1261
+     * @param int $time
1262
+     * @return bool
1263
+     */
1264
+    public function hasUpdated($path, $time) {
1265
+        return $this->basicOperation('hasUpdated', $path, array(), $time);
1266
+    }
1267
+
1268
+    /**
1269
+     * @param string $ownerId
1270
+     * @return \OC\User\User
1271
+     */
1272
+    private function getUserObjectForOwner($ownerId) {
1273
+        $owner = $this->userManager->get($ownerId);
1274
+        if ($owner instanceof IUser) {
1275
+            return $owner;
1276
+        } else {
1277
+            return new User($ownerId, null);
1278
+        }
1279
+    }
1280
+
1281
+    /**
1282
+     * Get file info from cache
1283
+     *
1284
+     * If the file is not in cached it will be scanned
1285
+     * If the file has changed on storage the cache will be updated
1286
+     *
1287
+     * @param \OC\Files\Storage\Storage $storage
1288
+     * @param string $internalPath
1289
+     * @param string $relativePath
1290
+     * @return ICacheEntry|bool
1291
+     */
1292
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1293
+        $cache = $storage->getCache($internalPath);
1294
+        $data = $cache->get($internalPath);
1295
+        $watcher = $storage->getWatcher($internalPath);
1296
+
1297
+        try {
1298
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1299
+            if (!$data || $data['size'] === -1) {
1300
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1301
+                if (!$storage->file_exists($internalPath)) {
1302
+                    $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1303
+                    return false;
1304
+                }
1305
+                $scanner = $storage->getScanner($internalPath);
1306
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1307
+                $data = $cache->get($internalPath);
1308
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1309
+            } else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1310
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1311
+                $watcher->update($internalPath, $data);
1312
+                $storage->getPropagator()->propagateChange($internalPath, time());
1313
+                $data = $cache->get($internalPath);
1314
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1315
+            }
1316
+        } catch (LockedException $e) {
1317
+            // if the file is locked we just use the old cache info
1318
+        }
1319
+
1320
+        return $data;
1321
+    }
1322
+
1323
+    /**
1324
+     * get the filesystem info
1325
+     *
1326
+     * @param string $path
1327
+     * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1328
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1329
+     * defaults to true
1330
+     * @return \OC\Files\FileInfo|false False if file does not exist
1331
+     */
1332
+    public function getFileInfo($path, $includeMountPoints = true) {
1333
+        $this->assertPathLength($path);
1334
+        if (!Filesystem::isValidPath($path)) {
1335
+            return false;
1336
+        }
1337
+        if (Cache\Scanner::isPartialFile($path)) {
1338
+            return $this->getPartFileInfo($path);
1339
+        }
1340
+        $relativePath = $path;
1341
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1342
+
1343
+        $mount = Filesystem::getMountManager()->find($path);
1344
+        $storage = $mount->getStorage();
1345
+        $internalPath = $mount->getInternalPath($path);
1346
+        if ($storage) {
1347
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1348
+
1349
+            if (!$data instanceof ICacheEntry) {
1350
+                return false;
1351
+            }
1352
+
1353
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1354
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1355
+            }
1356
+
1357
+            $owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1358
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1359
+
1360
+            if ($data and isset($data['fileid'])) {
1361
+                if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1362
+                    //add the sizes of other mount points to the folder
1363
+                    $extOnly = ($includeMountPoints === 'ext');
1364
+                    $mounts = Filesystem::getMountManager()->findIn($path);
1365
+                    $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1366
+                        $subStorage = $mount->getStorage();
1367
+                        return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1368
+                    }));
1369
+                }
1370
+            }
1371
+
1372
+            return $info;
1373
+        }
1374
+
1375
+        return false;
1376
+    }
1377
+
1378
+    /**
1379
+     * get the content of a directory
1380
+     *
1381
+     * @param string $directory path under datadirectory
1382
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1383
+     * @return FileInfo[]
1384
+     */
1385
+    public function getDirectoryContent($directory, $mimetype_filter = '') {
1386
+        $this->assertPathLength($directory);
1387
+        if (!Filesystem::isValidPath($directory)) {
1388
+            return [];
1389
+        }
1390
+        $path = $this->getAbsolutePath($directory);
1391
+        $path = Filesystem::normalizePath($path);
1392
+        $mount = $this->getMount($directory);
1393
+        $storage = $mount->getStorage();
1394
+        $internalPath = $mount->getInternalPath($path);
1395
+        if ($storage) {
1396
+            $cache = $storage->getCache($internalPath);
1397
+            $user = \OC_User::getUser();
1398
+
1399
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1400
+
1401
+            if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1402
+                return [];
1403
+            }
1404
+
1405
+            $folderId = $data['fileid'];
1406
+            $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1407
+
1408
+            $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1409
+            /**
1410
+             * @var \OC\Files\FileInfo[] $files
1411
+             */
1412
+            $files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1413
+                if ($sharingDisabled) {
1414
+                    $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1415
+                }
1416
+                $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1417
+                return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1418
+            }, $contents);
1419
+
1420
+            //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1421
+            $mounts = Filesystem::getMountManager()->findIn($path);
1422
+            $dirLength = strlen($path);
1423
+            foreach ($mounts as $mount) {
1424
+                $mountPoint = $mount->getMountPoint();
1425
+                $subStorage = $mount->getStorage();
1426
+                if ($subStorage) {
1427
+                    $subCache = $subStorage->getCache('');
1428
+
1429
+                    $rootEntry = $subCache->get('');
1430
+                    if (!$rootEntry) {
1431
+                        $subScanner = $subStorage->getScanner('');
1432
+                        try {
1433
+                            $subScanner->scanFile('');
1434
+                        } catch (\OCP\Files\StorageNotAvailableException $e) {
1435
+                            continue;
1436
+                        } catch (\OCP\Files\StorageInvalidException $e) {
1437
+                            continue;
1438
+                        } catch (\Exception $e) {
1439
+                            // sometimes when the storage is not available it can be any exception
1440
+                            \OCP\Util::writeLog(
1441
+                                'core',
1442
+                                'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1443
+                                get_class($e) . ': ' . $e->getMessage(),
1444
+                                \OCP\Util::ERROR
1445
+                            );
1446
+                            continue;
1447
+                        }
1448
+                        $rootEntry = $subCache->get('');
1449
+                    }
1450
+
1451
+                    if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1452
+                        $relativePath = trim(substr($mountPoint, $dirLength), '/');
1453
+                        if ($pos = strpos($relativePath, '/')) {
1454
+                            //mountpoint inside subfolder add size to the correct folder
1455
+                            $entryName = substr($relativePath, 0, $pos);
1456
+                            foreach ($files as &$entry) {
1457
+                                if ($entry->getName() === $entryName) {
1458
+                                    $entry->addSubEntry($rootEntry, $mountPoint);
1459
+                                }
1460
+                            }
1461
+                        } else { //mountpoint in this folder, add an entry for it
1462
+                            $rootEntry['name'] = $relativePath;
1463
+                            $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1464
+                            $permissions = $rootEntry['permissions'];
1465
+                            // do not allow renaming/deleting the mount point if they are not shared files/folders
1466
+                            // for shared files/folders we use the permissions given by the owner
1467
+                            if ($mount instanceof MoveableMount) {
1468
+                                $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1469
+                            } else {
1470
+                                $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1471
+                            }
1472
+
1473
+                            //remove any existing entry with the same name
1474
+                            foreach ($files as $i => $file) {
1475
+                                if ($file['name'] === $rootEntry['name']) {
1476
+                                    unset($files[$i]);
1477
+                                    break;
1478
+                                }
1479
+                            }
1480
+                            $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1481
+
1482
+                            // if sharing was disabled for the user we remove the share permissions
1483
+                            if (\OCP\Util::isSharingDisabledForUser()) {
1484
+                                $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1485
+                            }
1486
+
1487
+                            $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1488
+                            $files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1489
+                        }
1490
+                    }
1491
+                }
1492
+            }
1493
+
1494
+            if ($mimetype_filter) {
1495
+                $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1496
+                    if (strpos($mimetype_filter, '/')) {
1497
+                        return $file->getMimetype() === $mimetype_filter;
1498
+                    } else {
1499
+                        return $file->getMimePart() === $mimetype_filter;
1500
+                    }
1501
+                });
1502
+            }
1503
+
1504
+            return $files;
1505
+        } else {
1506
+            return [];
1507
+        }
1508
+    }
1509
+
1510
+    /**
1511
+     * change file metadata
1512
+     *
1513
+     * @param string $path
1514
+     * @param array|\OCP\Files\FileInfo $data
1515
+     * @return int
1516
+     *
1517
+     * returns the fileid of the updated file
1518
+     */
1519
+    public function putFileInfo($path, $data) {
1520
+        $this->assertPathLength($path);
1521
+        if ($data instanceof FileInfo) {
1522
+            $data = $data->getData();
1523
+        }
1524
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1525
+        /**
1526
+         * @var \OC\Files\Storage\Storage $storage
1527
+         * @var string $internalPath
1528
+         */
1529
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
1530
+        if ($storage) {
1531
+            $cache = $storage->getCache($path);
1532
+
1533
+            if (!$cache->inCache($internalPath)) {
1534
+                $scanner = $storage->getScanner($internalPath);
1535
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1536
+            }
1537
+
1538
+            return $cache->put($internalPath, $data);
1539
+        } else {
1540
+            return -1;
1541
+        }
1542
+    }
1543
+
1544
+    /**
1545
+     * search for files with the name matching $query
1546
+     *
1547
+     * @param string $query
1548
+     * @return FileInfo[]
1549
+     */
1550
+    public function search($query) {
1551
+        return $this->searchCommon('search', array('%' . $query . '%'));
1552
+    }
1553
+
1554
+    /**
1555
+     * search for files with the name matching $query
1556
+     *
1557
+     * @param string $query
1558
+     * @return FileInfo[]
1559
+     */
1560
+    public function searchRaw($query) {
1561
+        return $this->searchCommon('search', array($query));
1562
+    }
1563
+
1564
+    /**
1565
+     * search for files by mimetype
1566
+     *
1567
+     * @param string $mimetype
1568
+     * @return FileInfo[]
1569
+     */
1570
+    public function searchByMime($mimetype) {
1571
+        return $this->searchCommon('searchByMime', array($mimetype));
1572
+    }
1573
+
1574
+    /**
1575
+     * search for files by tag
1576
+     *
1577
+     * @param string|int $tag name or tag id
1578
+     * @param string $userId owner of the tags
1579
+     * @return FileInfo[]
1580
+     */
1581
+    public function searchByTag($tag, $userId) {
1582
+        return $this->searchCommon('searchByTag', array($tag, $userId));
1583
+    }
1584
+
1585
+    /**
1586
+     * @param string $method cache method
1587
+     * @param array $args
1588
+     * @return FileInfo[]
1589
+     */
1590
+    private function searchCommon($method, $args) {
1591
+        $files = array();
1592
+        $rootLength = strlen($this->fakeRoot);
1593
+
1594
+        $mount = $this->getMount('');
1595
+        $mountPoint = $mount->getMountPoint();
1596
+        $storage = $mount->getStorage();
1597
+        if ($storage) {
1598
+            $cache = $storage->getCache('');
1599
+
1600
+            $results = call_user_func_array(array($cache, $method), $args);
1601
+            foreach ($results as $result) {
1602
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1603
+                    $internalPath = $result['path'];
1604
+                    $path = $mountPoint . $result['path'];
1605
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1606
+                    $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1607
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1608
+                }
1609
+            }
1610
+
1611
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1612
+            foreach ($mounts as $mount) {
1613
+                $mountPoint = $mount->getMountPoint();
1614
+                $storage = $mount->getStorage();
1615
+                if ($storage) {
1616
+                    $cache = $storage->getCache('');
1617
+
1618
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1619
+                    $results = call_user_func_array(array($cache, $method), $args);
1620
+                    if ($results) {
1621
+                        foreach ($results as $result) {
1622
+                            $internalPath = $result['path'];
1623
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1624
+                            $path = rtrim($mountPoint . $internalPath, '/');
1625
+                            $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1626
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1627
+                        }
1628
+                    }
1629
+                }
1630
+            }
1631
+        }
1632
+        return $files;
1633
+    }
1634
+
1635
+    /**
1636
+     * Get the owner for a file or folder
1637
+     *
1638
+     * @param string $path
1639
+     * @return string the user id of the owner
1640
+     * @throws NotFoundException
1641
+     */
1642
+    public function getOwner($path) {
1643
+        $info = $this->getFileInfo($path);
1644
+        if (!$info) {
1645
+            throw new NotFoundException($path . ' not found while trying to get owner');
1646
+        }
1647
+        return $info->getOwner()->getUID();
1648
+    }
1649
+
1650
+    /**
1651
+     * get the ETag for a file or folder
1652
+     *
1653
+     * @param string $path
1654
+     * @return string
1655
+     */
1656
+    public function getETag($path) {
1657
+        /**
1658
+         * @var Storage\Storage $storage
1659
+         * @var string $internalPath
1660
+         */
1661
+        list($storage, $internalPath) = $this->resolvePath($path);
1662
+        if ($storage) {
1663
+            return $storage->getETag($internalPath);
1664
+        } else {
1665
+            return null;
1666
+        }
1667
+    }
1668
+
1669
+    /**
1670
+     * Get the path of a file by id, relative to the view
1671
+     *
1672
+     * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1673
+     *
1674
+     * @param int $id
1675
+     * @throws NotFoundException
1676
+     * @return string
1677
+     */
1678
+    public function getPath($id) {
1679
+        $id = (int)$id;
1680
+        $manager = Filesystem::getMountManager();
1681
+        $mounts = $manager->findIn($this->fakeRoot);
1682
+        $mounts[] = $manager->find($this->fakeRoot);
1683
+        // reverse the array so we start with the storage this view is in
1684
+        // which is the most likely to contain the file we're looking for
1685
+        $mounts = array_reverse($mounts);
1686
+        foreach ($mounts as $mount) {
1687
+            /**
1688
+             * @var \OC\Files\Mount\MountPoint $mount
1689
+             */
1690
+            if ($mount->getStorage()) {
1691
+                $cache = $mount->getStorage()->getCache();
1692
+                $internalPath = $cache->getPathById($id);
1693
+                if (is_string($internalPath)) {
1694
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1695
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1696
+                        return $path;
1697
+                    }
1698
+                }
1699
+            }
1700
+        }
1701
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1702
+    }
1703
+
1704
+    /**
1705
+     * @param string $path
1706
+     * @throws InvalidPathException
1707
+     */
1708
+    private function assertPathLength($path) {
1709
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1710
+        // Check for the string length - performed using isset() instead of strlen()
1711
+        // because isset() is about 5x-40x faster.
1712
+        if (isset($path[$maxLen])) {
1713
+            $pathLen = strlen($path);
1714
+            throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1715
+        }
1716
+    }
1717
+
1718
+    /**
1719
+     * check if it is allowed to move a mount point to a given target.
1720
+     * It is not allowed to move a mount point into a different mount point or
1721
+     * into an already shared folder
1722
+     *
1723
+     * @param string $target path
1724
+     * @return boolean
1725
+     */
1726
+    private function isTargetAllowed($target) {
1727
+
1728
+        list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1729
+        if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1730
+            \OCP\Util::writeLog('files',
1731
+                'It is not allowed to move one mount point into another one',
1732
+                \OCP\Util::DEBUG);
1733
+            return false;
1734
+        }
1735
+
1736
+        // note: cannot use the view because the target is already locked
1737
+        $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1738
+        if ($fileId === -1) {
1739
+            // target might not exist, need to check parent instead
1740
+            $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1741
+        }
1742
+
1743
+        // check if any of the parents were shared by the current owner (include collections)
1744
+        $shares = \OCP\Share::getItemShared(
1745
+            'folder',
1746
+            $fileId,
1747
+            \OCP\Share::FORMAT_NONE,
1748
+            null,
1749
+            true
1750
+        );
1751
+
1752
+        if (count($shares) > 0) {
1753
+            \OCP\Util::writeLog('files',
1754
+                'It is not allowed to move one mount point into a shared folder',
1755
+                \OCP\Util::DEBUG);
1756
+            return false;
1757
+        }
1758
+
1759
+        return true;
1760
+    }
1761
+
1762
+    /**
1763
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1764
+     *
1765
+     * @param string $path
1766
+     * @return \OCP\Files\FileInfo
1767
+     */
1768
+    private function getPartFileInfo($path) {
1769
+        $mount = $this->getMount($path);
1770
+        $storage = $mount->getStorage();
1771
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1772
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1773
+        return new FileInfo(
1774
+            $this->getAbsolutePath($path),
1775
+            $storage,
1776
+            $internalPath,
1777
+            [
1778
+                'fileid' => null,
1779
+                'mimetype' => $storage->getMimeType($internalPath),
1780
+                'name' => basename($path),
1781
+                'etag' => null,
1782
+                'size' => $storage->filesize($internalPath),
1783
+                'mtime' => $storage->filemtime($internalPath),
1784
+                'encrypted' => false,
1785
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1786
+            ],
1787
+            $mount,
1788
+            $owner
1789
+        );
1790
+    }
1791
+
1792
+    /**
1793
+     * @param string $path
1794
+     * @param string $fileName
1795
+     * @throws InvalidPathException
1796
+     */
1797
+    public function verifyPath($path, $fileName) {
1798
+        try {
1799
+            /** @type \OCP\Files\Storage $storage */
1800
+            list($storage, $internalPath) = $this->resolvePath($path);
1801
+            $storage->verifyPath($internalPath, $fileName);
1802
+        } catch (ReservedWordException $ex) {
1803
+            $l = \OC::$server->getL10N('lib');
1804
+            throw new InvalidPathException($l->t('File name is a reserved word'));
1805
+        } catch (InvalidCharacterInPathException $ex) {
1806
+            $l = \OC::$server->getL10N('lib');
1807
+            throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1808
+        } catch (FileNameTooLongException $ex) {
1809
+            $l = \OC::$server->getL10N('lib');
1810
+            throw new InvalidPathException($l->t('File name is too long'));
1811
+        } catch (InvalidDirectoryException $ex) {
1812
+            $l = \OC::$server->getL10N('lib');
1813
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1814
+        } catch (EmptyFileNameException $ex) {
1815
+            $l = \OC::$server->getL10N('lib');
1816
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1817
+        }
1818
+    }
1819
+
1820
+    /**
1821
+     * get all parent folders of $path
1822
+     *
1823
+     * @param string $path
1824
+     * @return string[]
1825
+     */
1826
+    private function getParents($path) {
1827
+        $path = trim($path, '/');
1828
+        if (!$path) {
1829
+            return [];
1830
+        }
1831
+
1832
+        $parts = explode('/', $path);
1833
+
1834
+        // remove the single file
1835
+        array_pop($parts);
1836
+        $result = array('/');
1837
+        $resultPath = '';
1838
+        foreach ($parts as $part) {
1839
+            if ($part) {
1840
+                $resultPath .= '/' . $part;
1841
+                $result[] = $resultPath;
1842
+            }
1843
+        }
1844
+        return $result;
1845
+    }
1846
+
1847
+    /**
1848
+     * Returns the mount point for which to lock
1849
+     *
1850
+     * @param string $absolutePath absolute path
1851
+     * @param bool $useParentMount true to return parent mount instead of whatever
1852
+     * is mounted directly on the given path, false otherwise
1853
+     * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1854
+     */
1855
+    private function getMountForLock($absolutePath, $useParentMount = false) {
1856
+        $results = [];
1857
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1858
+        if (!$mount) {
1859
+            return $results;
1860
+        }
1861
+
1862
+        if ($useParentMount) {
1863
+            // find out if something is mounted directly on the path
1864
+            $internalPath = $mount->getInternalPath($absolutePath);
1865
+            if ($internalPath === '') {
1866
+                // resolve the parent mount instead
1867
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1868
+            }
1869
+        }
1870
+
1871
+        return $mount;
1872
+    }
1873
+
1874
+    /**
1875
+     * Lock the given path
1876
+     *
1877
+     * @param string $path the path of the file to lock, relative to the view
1878
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1879
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1880
+     *
1881
+     * @return bool False if the path is excluded from locking, true otherwise
1882
+     * @throws \OCP\Lock\LockedException if the path is already locked
1883
+     */
1884
+    private function lockPath($path, $type, $lockMountPoint = false) {
1885
+        $absolutePath = $this->getAbsolutePath($path);
1886
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1887
+        if (!$this->shouldLockFile($absolutePath)) {
1888
+            return false;
1889
+        }
1890
+
1891
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1892
+        if ($mount) {
1893
+            try {
1894
+                $storage = $mount->getStorage();
1895
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1896
+                    $storage->acquireLock(
1897
+                        $mount->getInternalPath($absolutePath),
1898
+                        $type,
1899
+                        $this->lockingProvider
1900
+                    );
1901
+                }
1902
+            } catch (\OCP\Lock\LockedException $e) {
1903
+                // rethrow with the a human-readable path
1904
+                throw new \OCP\Lock\LockedException(
1905
+                    $this->getPathRelativeToFiles($absolutePath),
1906
+                    $e
1907
+                );
1908
+            }
1909
+        }
1910
+
1911
+        return true;
1912
+    }
1913
+
1914
+    /**
1915
+     * Change the lock type
1916
+     *
1917
+     * @param string $path the path of the file to lock, relative to the view
1918
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1919
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1920
+     *
1921
+     * @return bool False if the path is excluded from locking, true otherwise
1922
+     * @throws \OCP\Lock\LockedException if the path is already locked
1923
+     */
1924
+    public function changeLock($path, $type, $lockMountPoint = false) {
1925
+        $path = Filesystem::normalizePath($path);
1926
+        $absolutePath = $this->getAbsolutePath($path);
1927
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1928
+        if (!$this->shouldLockFile($absolutePath)) {
1929
+            return false;
1930
+        }
1931
+
1932
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1933
+        if ($mount) {
1934
+            try {
1935
+                $storage = $mount->getStorage();
1936
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1937
+                    $storage->changeLock(
1938
+                        $mount->getInternalPath($absolutePath),
1939
+                        $type,
1940
+                        $this->lockingProvider
1941
+                    );
1942
+                }
1943
+            } catch (\OCP\Lock\LockedException $e) {
1944
+                try {
1945
+                    // rethrow with the a human-readable path
1946
+                    throw new \OCP\Lock\LockedException(
1947
+                        $this->getPathRelativeToFiles($absolutePath),
1948
+                        $e
1949
+                    );
1950
+                } catch (\InvalidArgumentException $e) {
1951
+                    throw new \OCP\Lock\LockedException(
1952
+                        $absolutePath,
1953
+                        $e
1954
+                    );
1955
+                }
1956
+            }
1957
+        }
1958
+
1959
+        return true;
1960
+    }
1961
+
1962
+    /**
1963
+     * Unlock the given path
1964
+     *
1965
+     * @param string $path the path of the file to unlock, relative to the view
1966
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1967
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1968
+     *
1969
+     * @return bool False if the path is excluded from locking, true otherwise
1970
+     */
1971
+    private function unlockPath($path, $type, $lockMountPoint = false) {
1972
+        $absolutePath = $this->getAbsolutePath($path);
1973
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1974
+        if (!$this->shouldLockFile($absolutePath)) {
1975
+            return false;
1976
+        }
1977
+
1978
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1979
+        if ($mount) {
1980
+            $storage = $mount->getStorage();
1981
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1982
+                $storage->releaseLock(
1983
+                    $mount->getInternalPath($absolutePath),
1984
+                    $type,
1985
+                    $this->lockingProvider
1986
+                );
1987
+            }
1988
+        }
1989
+
1990
+        return true;
1991
+    }
1992
+
1993
+    /**
1994
+     * Lock a path and all its parents up to the root of the view
1995
+     *
1996
+     * @param string $path the path of the file to lock relative to the view
1997
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1998
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1999
+     *
2000
+     * @return bool False if the path is excluded from locking, true otherwise
2001
+     */
2002
+    public function lockFile($path, $type, $lockMountPoint = false) {
2003
+        $absolutePath = $this->getAbsolutePath($path);
2004
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2005
+        if (!$this->shouldLockFile($absolutePath)) {
2006
+            return false;
2007
+        }
2008
+
2009
+        $this->lockPath($path, $type, $lockMountPoint);
2010
+
2011
+        $parents = $this->getParents($path);
2012
+        foreach ($parents as $parent) {
2013
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2014
+        }
2015
+
2016
+        return true;
2017
+    }
2018
+
2019
+    /**
2020
+     * Unlock a path and all its parents up to the root of the view
2021
+     *
2022
+     * @param string $path the path of the file to lock relative to the view
2023
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2024
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2025
+     *
2026
+     * @return bool False if the path is excluded from locking, true otherwise
2027
+     */
2028
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2029
+        $absolutePath = $this->getAbsolutePath($path);
2030
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2031
+        if (!$this->shouldLockFile($absolutePath)) {
2032
+            return false;
2033
+        }
2034
+
2035
+        $this->unlockPath($path, $type, $lockMountPoint);
2036
+
2037
+        $parents = $this->getParents($path);
2038
+        foreach ($parents as $parent) {
2039
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2040
+        }
2041
+
2042
+        return true;
2043
+    }
2044
+
2045
+    /**
2046
+     * Only lock files in data/user/files/
2047
+     *
2048
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2049
+     * @return bool
2050
+     */
2051
+    protected function shouldLockFile($path) {
2052
+        $path = Filesystem::normalizePath($path);
2053
+
2054
+        $pathSegments = explode('/', $path);
2055
+        if (isset($pathSegments[2])) {
2056
+            // E.g.: /username/files/path-to-file
2057
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2058
+        }
2059
+
2060
+        return strpos($path, '/appdata_') !== 0;
2061
+    }
2062
+
2063
+    /**
2064
+     * Shortens the given absolute path to be relative to
2065
+     * "$user/files".
2066
+     *
2067
+     * @param string $absolutePath absolute path which is under "files"
2068
+     *
2069
+     * @return string path relative to "files" with trimmed slashes or null
2070
+     * if the path was NOT relative to files
2071
+     *
2072
+     * @throws \InvalidArgumentException if the given path was not under "files"
2073
+     * @since 8.1.0
2074
+     */
2075
+    public function getPathRelativeToFiles($absolutePath) {
2076
+        $path = Filesystem::normalizePath($absolutePath);
2077
+        $parts = explode('/', trim($path, '/'), 3);
2078
+        // "$user", "files", "path/to/dir"
2079
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2080
+            $this->logger->error(
2081
+                '$absolutePath must be relative to "files", value is "%s"',
2082
+                [
2083
+                    $absolutePath
2084
+                ]
2085
+            );
2086
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2087
+        }
2088
+        if (isset($parts[2])) {
2089
+            return $parts[2];
2090
+        }
2091
+        return '';
2092
+    }
2093
+
2094
+    /**
2095
+     * @param string $filename
2096
+     * @return array
2097
+     * @throws \OC\User\NoUserException
2098
+     * @throws NotFoundException
2099
+     */
2100
+    public function getUidAndFilename($filename) {
2101
+        $info = $this->getFileInfo($filename);
2102
+        if (!$info instanceof \OCP\Files\FileInfo) {
2103
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2104
+        }
2105
+        $uid = $info->getOwner()->getUID();
2106
+        if ($uid != \OCP\User::getUser()) {
2107
+            Filesystem::initMountPoints($uid);
2108
+            $ownerView = new View('/' . $uid . '/files');
2109
+            try {
2110
+                $filename = $ownerView->getPath($info['fileid']);
2111
+            } catch (NotFoundException $e) {
2112
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2113
+            }
2114
+        }
2115
+        return [$uid, $filename];
2116
+    }
2117
+
2118
+    /**
2119
+     * Creates parent non-existing folders
2120
+     *
2121
+     * @param string $filePath
2122
+     * @return bool
2123
+     */
2124
+    private function createParentDirectories($filePath) {
2125
+        $directoryParts = explode('/', $filePath);
2126
+        $directoryParts = array_filter($directoryParts);
2127
+        foreach ($directoryParts as $key => $part) {
2128
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2129
+            $currentPath = '/' . implode('/', $currentPathElements);
2130
+            if ($this->is_file($currentPath)) {
2131
+                return false;
2132
+            }
2133
+            if (!$this->file_exists($currentPath)) {
2134
+                $this->mkdir($currentPath);
2135
+            }
2136
+        }
2137
+
2138
+        return true;
2139
+    }
2140 2140
 }
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.