Completed
Pull Request — master (#9293)
by Blizzz
38:09 queued 17:25
created
lib/private/Tags.php 2 patches
Indentation   +803 added lines, -803 removed lines patch added patch discarded remove patch
@@ -51,807 +51,807 @@
 block discarded – undo
51 51
 
52 52
 class Tags implements \OCP\ITags {
53 53
 
54
-	/**
55
-	 * Tags
56
-	 *
57
-	 * @var array
58
-	 */
59
-	private $tags = array();
60
-
61
-	/**
62
-	 * Used for storing objectid/categoryname pairs while rescanning.
63
-	 *
64
-	 * @var array
65
-	 */
66
-	private static $relations = array();
67
-
68
-	/**
69
-	 * Type
70
-	 *
71
-	 * @var string
72
-	 */
73
-	private $type;
74
-
75
-	/**
76
-	 * User
77
-	 *
78
-	 * @var string
79
-	 */
80
-	private $user;
81
-
82
-	/**
83
-	 * Are we including tags for shared items?
84
-	 *
85
-	 * @var bool
86
-	 */
87
-	private $includeShared = false;
88
-
89
-	/**
90
-	 * The current user, plus any owners of the items shared with the current
91
-	 * user, if $this->includeShared === true.
92
-	 *
93
-	 * @var array
94
-	 */
95
-	private $owners = array();
96
-
97
-	/**
98
-	 * The Mapper we're using to communicate our Tag objects to the database.
99
-	 *
100
-	 * @var TagMapper
101
-	 */
102
-	private $mapper;
103
-
104
-	/**
105
-	 * The sharing backend for objects of $this->type. Required if
106
-	 * $this->includeShared === true to determine ownership of items.
107
-	 *
108
-	 * @var \OCP\Share_Backend
109
-	 */
110
-	private $backend;
111
-
112
-	const TAG_TABLE = '*PREFIX*vcategory';
113
-	const RELATION_TABLE = '*PREFIX*vcategory_to_object';
114
-
115
-	const TAG_FAVORITE = '_$!<Favorite>!$_';
116
-
117
-	/**
118
-	* Constructor.
119
-	*
120
-	* @param TagMapper $mapper Instance of the TagMapper abstraction layer.
121
-	* @param string $user The user whose data the object will operate on.
122
-	* @param string $type The type of items for which tags will be loaded.
123
-	* @param array $defaultTags Tags that should be created at construction.
124
-	* @param boolean $includeShared Whether to include tags for items shared with this user by others.
125
-	*/
126
-	public function __construct(TagMapper $mapper, $user, $type, $defaultTags = array(), $includeShared = false) {
127
-		$this->mapper = $mapper;
128
-		$this->user = $user;
129
-		$this->type = $type;
130
-		$this->includeShared = $includeShared;
131
-		$this->owners = array($this->user);
132
-		if ($this->includeShared) {
133
-			$this->owners = array_merge($this->owners, \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true));
134
-			$this->backend = \OC\Share\Share::getBackend($this->type);
135
-		}
136
-		$this->tags = $this->mapper->loadTags($this->owners, $this->type);
137
-
138
-		if(count($defaultTags) > 0 && count($this->tags) === 0) {
139
-			$this->addMultiple($defaultTags, true);
140
-		}
141
-	}
142
-
143
-	/**
144
-	* Check if any tags are saved for this type and user.
145
-	*
146
-	* @return boolean
147
-	*/
148
-	public function isEmpty() {
149
-		return count($this->tags) === 0;
150
-	}
151
-
152
-	/**
153
-	* Returns an array mapping a given tag's properties to its values:
154
-	* ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
155
-	*
156
-	* @param string $id The ID of the tag that is going to be mapped
157
-	* @return array|false
158
-	*/
159
-	public function getTag($id) {
160
-		$key = $this->getTagById($id);
161
-		if ($key !== false) {
162
-			return $this->tagMap($this->tags[$key]);
163
-		}
164
-		return false;
165
-	}
166
-
167
-	/**
168
-	* Get the tags for a specific user.
169
-	*
170
-	* This returns an array with maps containing each tag's properties:
171
-	* [
172
-	* 	['id' => 0, 'name' = 'First tag', 'owner' = 'User', 'type' => 'tagtype'],
173
-	* 	['id' => 1, 'name' = 'Shared tag', 'owner' = 'Other user', 'type' => 'tagtype'],
174
-	* ]
175
-	*
176
-	* @return array
177
-	*/
178
-	public function getTags() {
179
-		if(!count($this->tags)) {
180
-			return array();
181
-		}
182
-
183
-		usort($this->tags, function($a, $b) {
184
-			return strnatcasecmp($a->getName(), $b->getName());
185
-		});
186
-		$tagMap = array();
187
-
188
-		foreach($this->tags as $tag) {
189
-			if($tag->getName() !== self::TAG_FAVORITE) {
190
-				$tagMap[] = $this->tagMap($tag);
191
-			}
192
-		}
193
-		return $tagMap;
194
-
195
-	}
196
-
197
-	/**
198
-	* Return only the tags owned by the given user, omitting any tags shared
199
-	* by other users.
200
-	*
201
-	* @param string $user The user whose tags are to be checked.
202
-	* @return array An array of Tag objects.
203
-	*/
204
-	public function getTagsForUser($user) {
205
-		return array_filter($this->tags,
206
-			function($tag) use($user) {
207
-				return $tag->getOwner() === $user;
208
-			}
209
-		);
210
-	}
211
-
212
-	/**
213
-	 * Get the list of tags for the given ids.
214
-	 *
215
-	 * @param array $objIds array of object ids
216
-	 * @return array|boolean of tags id as key to array of tag names
217
-	 * or false if an error occurred
218
-	 */
219
-	public function getTagsForObjects(array $objIds) {
220
-		$entries = array();
221
-
222
-		try {
223
-			$conn = \OC::$server->getDatabaseConnection();
224
-			$chunks = array_chunk($objIds, 900, false);
225
-			foreach ($chunks as $chunk) {
226
-				$result = $conn->executeQuery(
227
-					'SELECT `category`, `categoryid`, `objid` ' .
228
-					'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
229
-					'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
230
-					array($this->user, $this->type, $chunk),
231
-					array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
232
-				);
233
-				while ($row = $result->fetch()) {
234
-					$objId = (int)$row['objid'];
235
-					if (!isset($entries[$objId])) {
236
-						$entries[$objId] = array();
237
-					}
238
-					$entries[$objId][] = $row['category'];
239
-				}
240
-				if ($result === null) {
241
-					\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
242
-					return false;
243
-				}
244
-			}
245
-		} catch(\Exception $e) {
246
-			\OC::$server->getLogger()->logException($e, [
247
-				'message' => __METHOD__,
248
-				'level' => ILogger::ERROR,
249
-				'app' => 'core',
250
-			]);
251
-			return false;
252
-		}
253
-
254
-		return $entries;
255
-	}
256
-
257
-	/**
258
-	* Get the a list if items tagged with $tag.
259
-	*
260
-	* Throws an exception if the tag could not be found.
261
-	*
262
-	* @param string $tag Tag id or name.
263
-	* @return array|false An array of object ids or false on error.
264
-	* @throws \Exception
265
-	*/
266
-	public function getIdsForTag($tag) {
267
-		$result = null;
268
-		$tagId = false;
269
-		if(is_numeric($tag)) {
270
-			$tagId = $tag;
271
-		} elseif(is_string($tag)) {
272
-			$tag = trim($tag);
273
-			if($tag === '') {
274
-				\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
275
-				return false;
276
-			}
277
-			$tagId = $this->getTagId($tag);
278
-		}
279
-
280
-		if($tagId === false) {
281
-			$l10n = \OC::$server->getL10N('core');
282
-			throw new \Exception(
283
-				$l10n->t('Could not find category "%s"', [$tag])
284
-			);
285
-		}
286
-
287
-		$ids = array();
288
-		$sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
289
-			. '` WHERE `categoryid` = ?';
290
-
291
-		try {
292
-			$stmt = \OC_DB::prepare($sql);
293
-			$result = $stmt->execute(array($tagId));
294
-			if ($result === null) {
295
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
296
-				return false;
297
-			}
298
-		} catch(\Exception $e) {
299
-			\OC::$server->getLogger()->logException($e, [
300
-				'message' => __METHOD__,
301
-				'level' => ILogger::ERROR,
302
-				'app' => 'core',
303
-			]);
304
-			return false;
305
-		}
306
-
307
-		if(!is_null($result)) {
308
-			while( $row = $result->fetchRow()) {
309
-				$id = (int)$row['objid'];
310
-
311
-				if ($this->includeShared) {
312
-					// We have to check if we are really allowed to access the
313
-					// items that are tagged with $tag. To that end, we ask the
314
-					// corresponding sharing backend if the item identified by $id
315
-					// is owned by any of $this->owners.
316
-					foreach ($this->owners as $owner) {
317
-						if ($this->backend->isValidSource($id, $owner)) {
318
-							$ids[] = $id;
319
-							break;
320
-						}
321
-					}
322
-				} else {
323
-					$ids[] = $id;
324
-				}
325
-			}
326
-		}
327
-
328
-		return $ids;
329
-	}
330
-
331
-	/**
332
-	* Checks whether a tag is saved for the given user,
333
-	* disregarding the ones shared with him or her.
334
-	*
335
-	* @param string $name The tag name to check for.
336
-	* @param string $user The user whose tags are to be checked.
337
-	* @return bool
338
-	*/
339
-	public function userHasTag($name, $user) {
340
-		$key = $this->array_searchi($name, $this->getTagsForUser($user));
341
-		return ($key !== false) ? $this->tags[$key]->getId() : false;
342
-	}
343
-
344
-	/**
345
-	* Checks whether a tag is saved for or shared with the current user.
346
-	*
347
-	* @param string $name The tag name to check for.
348
-	* @return bool
349
-	*/
350
-	public function hasTag($name) {
351
-		return $this->getTagId($name) !== false;
352
-	}
353
-
354
-	/**
355
-	* Add a new tag.
356
-	*
357
-	* @param string $name A string with a name of the tag
358
-	* @return false|int the id of the added tag or false on error.
359
-	*/
360
-	public function add($name) {
361
-		$name = trim($name);
362
-
363
-		if($name === '') {
364
-			\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
365
-			return false;
366
-		}
367
-		if($this->userHasTag($name, $this->user)) {
368
-			\OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', ILogger::DEBUG);
369
-			return false;
370
-		}
371
-		try {
372
-			$tag = new Tag($this->user, $this->type, $name);
373
-			$tag = $this->mapper->insert($tag);
374
-			$this->tags[] = $tag;
375
-		} catch(\Exception $e) {
376
-			\OC::$server->getLogger()->logException($e, [
377
-				'message' => __METHOD__,
378
-				'level' => ILogger::ERROR,
379
-				'app' => 'core',
380
-			]);
381
-			return false;
382
-		}
383
-		\OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), ILogger::DEBUG);
384
-		return $tag->getId();
385
-	}
386
-
387
-	/**
388
-	* Rename tag.
389
-	*
390
-	* @param string|integer $from The name or ID of the existing tag
391
-	* @param string $to The new name of the tag.
392
-	* @return bool
393
-	*/
394
-	public function rename($from, $to) {
395
-		$from = trim($from);
396
-		$to = trim($to);
397
-
398
-		if($to === '' || $from === '') {
399
-			\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
400
-			return false;
401
-		}
402
-
403
-		if (is_numeric($from)) {
404
-			$key = $this->getTagById($from);
405
-		} else {
406
-			$key = $this->getTagByName($from);
407
-		}
408
-		if($key === false) {
409
-			\OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', ILogger::DEBUG);
410
-			return false;
411
-		}
412
-		$tag = $this->tags[$key];
413
-
414
-		if($this->userHasTag($to, $tag->getOwner())) {
415
-			\OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', ILogger::DEBUG);
416
-			return false;
417
-		}
418
-
419
-		try {
420
-			$tag->setName($to);
421
-			$this->tags[$key] = $this->mapper->update($tag);
422
-		} catch(\Exception $e) {
423
-			\OC::$server->getLogger()->logException($e, [
424
-				'message' => __METHOD__,
425
-				'level' => ILogger::ERROR,
426
-				'app' => 'core',
427
-			]);
428
-			return false;
429
-		}
430
-		return true;
431
-	}
432
-
433
-	/**
434
-	* Add a list of new tags.
435
-	*
436
-	* @param string[] $names A string with a name or an array of strings containing
437
-	* the name(s) of the tag(s) to add.
438
-	* @param bool $sync When true, save the tags
439
-	* @param int|null $id int Optional object id to add to this|these tag(s)
440
-	* @return bool Returns false on error.
441
-	*/
442
-	public function addMultiple($names, $sync=false, $id = null) {
443
-		if(!is_array($names)) {
444
-			$names = array($names);
445
-		}
446
-		$names = array_map('trim', $names);
447
-		array_filter($names);
448
-
449
-		$newones = array();
450
-		foreach($names as $name) {
451
-			if(!$this->hasTag($name) && $name !== '') {
452
-				$newones[] = new Tag($this->user, $this->type, $name);
453
-			}
454
-			if(!is_null($id) ) {
455
-				// Insert $objectid, $categoryid  pairs if not exist.
456
-				self::$relations[] = array('objid' => $id, 'tag' => $name);
457
-			}
458
-		}
459
-		$this->tags = array_merge($this->tags, $newones);
460
-		if($sync === true) {
461
-			$this->save();
462
-		}
463
-
464
-		return true;
465
-	}
466
-
467
-	/**
468
-	 * Save the list of tags and their object relations
469
-	 */
470
-	protected function save() {
471
-		if(is_array($this->tags)) {
472
-			foreach($this->tags as $tag) {
473
-				try {
474
-					if (!$this->mapper->tagExists($tag)) {
475
-						$this->mapper->insert($tag);
476
-					}
477
-				} catch(\Exception $e) {
478
-					\OC::$server->getLogger()->logException($e, [
479
-						'message' => __METHOD__,
480
-						'level' => ILogger::ERROR,
481
-						'app' => 'core',
482
-					]);
483
-				}
484
-			}
485
-
486
-			// reload tags to get the proper ids.
487
-			$this->tags = $this->mapper->loadTags($this->owners, $this->type);
488
-			\OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
489
-				ILogger::DEBUG);
490
-			// Loop through temporarily cached objectid/tagname pairs
491
-			// and save relations.
492
-			$tags = $this->tags;
493
-			// For some reason this is needed or array_search(i) will return 0..?
494
-			ksort($tags);
495
-			$dbConnection = \OC::$server->getDatabaseConnection();
496
-			foreach(self::$relations as $relation) {
497
-				$tagId = $this->getTagId($relation['tag']);
498
-				\OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, ILogger::DEBUG);
499
-				if($tagId) {
500
-					try {
501
-						$dbConnection->insertIfNotExist(self::RELATION_TABLE,
502
-							array(
503
-								'objid' => $relation['objid'],
504
-								'categoryid' => $tagId,
505
-								'type' => $this->type,
506
-								));
507
-					} catch(\Exception $e) {
508
-						\OC::$server->getLogger()->logException($e, [
509
-							'message' => __METHOD__,
510
-							'level' => ILogger::ERROR,
511
-							'app' => 'core',
512
-						]);
513
-					}
514
-				}
515
-			}
516
-			self::$relations = array(); // reset
517
-		} else {
518
-			\OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! '
519
-				. print_r($this->tags, true), ILogger::ERROR);
520
-		}
521
-	}
522
-
523
-	/**
524
-	* Delete tags and tag/object relations for a user.
525
-	*
526
-	* For hooking up on post_deleteUser
527
-	*
528
-	* @param array $arguments
529
-	*/
530
-	public static function post_deleteUser($arguments) {
531
-		// Find all objectid/tagId pairs.
532
-		$result = null;
533
-		try {
534
-			$stmt = \OC_DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
535
-				. 'WHERE `uid` = ?');
536
-			$result = $stmt->execute(array($arguments['uid']));
537
-			if ($result === null) {
538
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
539
-			}
540
-		} catch(\Exception $e) {
541
-			\OC::$server->getLogger()->logException($e, [
542
-				'message' => __METHOD__,
543
-				'level' => ILogger::ERROR,
544
-				'app' => 'core',
545
-			]);
546
-		}
547
-
548
-		if(!is_null($result)) {
549
-			try {
550
-				$stmt = \OC_DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
551
-					. 'WHERE `categoryid` = ?');
552
-				while( $row = $result->fetchRow()) {
553
-					try {
554
-						$stmt->execute(array($row['id']));
555
-					} catch(\Exception $e) {
556
-						\OC::$server->getLogger()->logException($e, [
557
-							'message' => __METHOD__,
558
-							'level' => ILogger::ERROR,
559
-							'app' => 'core',
560
-						]);
561
-					}
562
-				}
563
-			} catch(\Exception $e) {
564
-				\OC::$server->getLogger()->logException($e, [
565
-					'message' => __METHOD__,
566
-					'level' => ILogger::ERROR,
567
-					'app' => 'core',
568
-				]);
569
-			}
570
-		}
571
-		try {
572
-			$stmt = \OC_DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
573
-				. 'WHERE `uid` = ?');
574
-			$result = $stmt->execute(array($arguments['uid']));
575
-			if ($result === null) {
576
-				\OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
577
-			}
578
-		} catch(\Exception $e) {
579
-			\OC::$server->getLogger()->logException($e, [
580
-				'message' => __METHOD__,
581
-				'level' => ILogger::ERROR,
582
-				'app' => 'core',
583
-			]);
584
-		}
585
-	}
586
-
587
-	/**
588
-	* Delete tag/object relations from the db
589
-	*
590
-	* @param array $ids The ids of the objects
591
-	* @return boolean Returns false on error.
592
-	*/
593
-	public function purgeObjects(array $ids) {
594
-		if(count($ids) === 0) {
595
-			// job done ;)
596
-			return true;
597
-		}
598
-		$updates = $ids;
599
-		try {
600
-			$query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
601
-			$query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
602
-			$query .= 'AND `type`= ?';
603
-			$updates[] = $this->type;
604
-			$stmt = \OC_DB::prepare($query);
605
-			$result = $stmt->execute($updates);
606
-			if ($result === null) {
607
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
608
-				return false;
609
-			}
610
-		} catch(\Exception $e) {
611
-			\OC::$server->getLogger()->logException($e, [
612
-				'message' => __METHOD__,
613
-				'level' => ILogger::ERROR,
614
-				'app' => 'core',
615
-			]);
616
-			return false;
617
-		}
618
-		return true;
619
-	}
620
-
621
-	/**
622
-	* Get favorites for an object type
623
-	*
624
-	* @return array|false An array of object ids.
625
-	*/
626
-	public function getFavorites() {
627
-		try {
628
-			return $this->getIdsForTag(self::TAG_FAVORITE);
629
-		} catch(\Exception $e) {
630
-			\OC::$server->getLogger()->logException($e, [
631
-				'message' => __METHOD__,
632
-				'level' => ILogger::ERROR,
633
-				'app' => 'core',
634
-			]);
635
-			return array();
636
-		}
637
-	}
638
-
639
-	/**
640
-	* Add an object to favorites
641
-	*
642
-	* @param int $objid The id of the object
643
-	* @return boolean
644
-	*/
645
-	public function addToFavorites($objid) {
646
-		if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
647
-			$this->add(self::TAG_FAVORITE);
648
-		}
649
-		return $this->tagAs($objid, self::TAG_FAVORITE);
650
-	}
651
-
652
-	/**
653
-	* Remove an object from favorites
654
-	*
655
-	* @param int $objid The id of the object
656
-	* @return boolean
657
-	*/
658
-	public function removeFromFavorites($objid) {
659
-		return $this->unTag($objid, self::TAG_FAVORITE);
660
-	}
661
-
662
-	/**
663
-	* Creates a tag/object relation.
664
-	*
665
-	* @param int $objid The id of the object
666
-	* @param string $tag The id or name of the tag
667
-	* @return boolean Returns false on error.
668
-	*/
669
-	public function tagAs($objid, $tag) {
670
-		if(is_string($tag) && !is_numeric($tag)) {
671
-			$tag = trim($tag);
672
-			if($tag === '') {
673
-				\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
674
-				return false;
675
-			}
676
-			if(!$this->hasTag($tag)) {
677
-				$this->add($tag);
678
-			}
679
-			$tagId =  $this->getTagId($tag);
680
-		} else {
681
-			$tagId = $tag;
682
-		}
683
-		try {
684
-			\OC::$server->getDatabaseConnection()->insertIfNotExist(self::RELATION_TABLE,
685
-				array(
686
-					'objid' => $objid,
687
-					'categoryid' => $tagId,
688
-					'type' => $this->type,
689
-				));
690
-		} catch(\Exception $e) {
691
-			\OC::$server->getLogger()->logException($e, [
692
-				'message' => __METHOD__,
693
-				'level' => ILogger::ERROR,
694
-				'app' => 'core',
695
-			]);
696
-			return false;
697
-		}
698
-		return true;
699
-	}
700
-
701
-	/**
702
-	* Delete single tag/object relation from the db
703
-	*
704
-	* @param int $objid The id of the object
705
-	* @param string $tag The id or name of the tag
706
-	* @return boolean
707
-	*/
708
-	public function unTag($objid, $tag) {
709
-		if(is_string($tag) && !is_numeric($tag)) {
710
-			$tag = trim($tag);
711
-			if($tag === '') {
712
-				\OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', ILogger::DEBUG);
713
-				return false;
714
-			}
715
-			$tagId =  $this->getTagId($tag);
716
-		} else {
717
-			$tagId = $tag;
718
-		}
719
-
720
-		try {
721
-			$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
722
-					. 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
723
-			$stmt = \OC_DB::prepare($sql);
724
-			$stmt->execute(array($objid, $tagId, $this->type));
725
-		} catch(\Exception $e) {
726
-			\OC::$server->getLogger()->logException($e, [
727
-				'message' => __METHOD__,
728
-				'level' => ILogger::ERROR,
729
-				'app' => 'core',
730
-			]);
731
-			return false;
732
-		}
733
-		return true;
734
-	}
735
-
736
-	/**
737
-	* Delete tags from the database.
738
-	*
739
-	* @param string[]|integer[] $names An array of tags (names or IDs) to delete
740
-	* @return bool Returns false on error
741
-	*/
742
-	public function delete($names) {
743
-		if(!is_array($names)) {
744
-			$names = array($names);
745
-		}
746
-
747
-		$names = array_map('trim', $names);
748
-		array_filter($names);
749
-
750
-		\OCP\Util::writeLog('core', __METHOD__ . ', before: '
751
-			. print_r($this->tags, true), ILogger::DEBUG);
752
-		foreach($names as $name) {
753
-			$id = null;
754
-
755
-			if (is_numeric($name)) {
756
-				$key = $this->getTagById($name);
757
-			} else {
758
-				$key = $this->getTagByName($name);
759
-			}
760
-			if ($key !== false) {
761
-				$tag = $this->tags[$key];
762
-				$id = $tag->getId();
763
-				unset($this->tags[$key]);
764
-				$this->mapper->delete($tag);
765
-			} else {
766
-				\OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
767
-					. ': not found.', ILogger::ERROR);
768
-			}
769
-			if(!is_null($id) && $id !== false) {
770
-				try {
771
-					$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
772
-							. 'WHERE `categoryid` = ?';
773
-					$stmt = \OC_DB::prepare($sql);
774
-					$result = $stmt->execute(array($id));
775
-					if ($result === null) {
776
-						\OCP\Util::writeLog('core',
777
-							__METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(),
778
-							ILogger::ERROR);
779
-						return false;
780
-					}
781
-				} catch(\Exception $e) {
782
-					\OC::$server->getLogger()->logException($e, [
783
-						'message' => __METHOD__,
784
-						'level' => ILogger::ERROR,
785
-						'app' => 'core',
786
-					]);
787
-					return false;
788
-				}
789
-			}
790
-		}
791
-		return true;
792
-	}
793
-
794
-	// case-insensitive array_search
795
-	protected function array_searchi($needle, $haystack, $mem='getName') {
796
-		if(!is_array($haystack)) {
797
-			return false;
798
-		}
799
-		return array_search(strtolower($needle), array_map(
800
-			function($tag) use($mem) {
801
-				return strtolower(call_user_func(array($tag, $mem)));
802
-			}, $haystack)
803
-		);
804
-	}
805
-
806
-	/**
807
-	* Get a tag's ID.
808
-	*
809
-	* @param string $name The tag name to look for.
810
-	* @return string|bool The tag's id or false if no matching tag is found.
811
-	*/
812
-	private function getTagId($name) {
813
-		$key = $this->array_searchi($name, $this->tags);
814
-		if ($key !== false) {
815
-			return $this->tags[$key]->getId();
816
-		}
817
-		return false;
818
-	}
819
-
820
-	/**
821
-	* Get a tag by its name.
822
-	*
823
-	* @param string $name The tag name.
824
-	* @return integer|bool The tag object's offset within the $this->tags
825
-	*                      array or false if it doesn't exist.
826
-	*/
827
-	private function getTagByName($name) {
828
-		return $this->array_searchi($name, $this->tags, 'getName');
829
-	}
830
-
831
-	/**
832
-	* Get a tag by its ID.
833
-	*
834
-	* @param string $id The tag ID to look for.
835
-	* @return integer|bool The tag object's offset within the $this->tags
836
-	*                      array or false if it doesn't exist.
837
-	*/
838
-	private function getTagById($id) {
839
-		return $this->array_searchi($id, $this->tags, 'getId');
840
-	}
841
-
842
-	/**
843
-	* Returns an array mapping a given tag's properties to its values:
844
-	* ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
845
-	*
846
-	* @param Tag $tag The tag that is going to be mapped
847
-	* @return array
848
-	*/
849
-	private function tagMap(Tag $tag) {
850
-		return array(
851
-			'id'    => $tag->getId(),
852
-			'name'  => $tag->getName(),
853
-			'owner' => $tag->getOwner(),
854
-			'type'  => $tag->getType()
855
-		);
856
-	}
54
+    /**
55
+     * Tags
56
+     *
57
+     * @var array
58
+     */
59
+    private $tags = array();
60
+
61
+    /**
62
+     * Used for storing objectid/categoryname pairs while rescanning.
63
+     *
64
+     * @var array
65
+     */
66
+    private static $relations = array();
67
+
68
+    /**
69
+     * Type
70
+     *
71
+     * @var string
72
+     */
73
+    private $type;
74
+
75
+    /**
76
+     * User
77
+     *
78
+     * @var string
79
+     */
80
+    private $user;
81
+
82
+    /**
83
+     * Are we including tags for shared items?
84
+     *
85
+     * @var bool
86
+     */
87
+    private $includeShared = false;
88
+
89
+    /**
90
+     * The current user, plus any owners of the items shared with the current
91
+     * user, if $this->includeShared === true.
92
+     *
93
+     * @var array
94
+     */
95
+    private $owners = array();
96
+
97
+    /**
98
+     * The Mapper we're using to communicate our Tag objects to the database.
99
+     *
100
+     * @var TagMapper
101
+     */
102
+    private $mapper;
103
+
104
+    /**
105
+     * The sharing backend for objects of $this->type. Required if
106
+     * $this->includeShared === true to determine ownership of items.
107
+     *
108
+     * @var \OCP\Share_Backend
109
+     */
110
+    private $backend;
111
+
112
+    const TAG_TABLE = '*PREFIX*vcategory';
113
+    const RELATION_TABLE = '*PREFIX*vcategory_to_object';
114
+
115
+    const TAG_FAVORITE = '_$!<Favorite>!$_';
116
+
117
+    /**
118
+     * Constructor.
119
+     *
120
+     * @param TagMapper $mapper Instance of the TagMapper abstraction layer.
121
+     * @param string $user The user whose data the object will operate on.
122
+     * @param string $type The type of items for which tags will be loaded.
123
+     * @param array $defaultTags Tags that should be created at construction.
124
+     * @param boolean $includeShared Whether to include tags for items shared with this user by others.
125
+     */
126
+    public function __construct(TagMapper $mapper, $user, $type, $defaultTags = array(), $includeShared = false) {
127
+        $this->mapper = $mapper;
128
+        $this->user = $user;
129
+        $this->type = $type;
130
+        $this->includeShared = $includeShared;
131
+        $this->owners = array($this->user);
132
+        if ($this->includeShared) {
133
+            $this->owners = array_merge($this->owners, \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true));
134
+            $this->backend = \OC\Share\Share::getBackend($this->type);
135
+        }
136
+        $this->tags = $this->mapper->loadTags($this->owners, $this->type);
137
+
138
+        if(count($defaultTags) > 0 && count($this->tags) === 0) {
139
+            $this->addMultiple($defaultTags, true);
140
+        }
141
+    }
142
+
143
+    /**
144
+     * Check if any tags are saved for this type and user.
145
+     *
146
+     * @return boolean
147
+     */
148
+    public function isEmpty() {
149
+        return count($this->tags) === 0;
150
+    }
151
+
152
+    /**
153
+     * Returns an array mapping a given tag's properties to its values:
154
+     * ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
155
+     *
156
+     * @param string $id The ID of the tag that is going to be mapped
157
+     * @return array|false
158
+     */
159
+    public function getTag($id) {
160
+        $key = $this->getTagById($id);
161
+        if ($key !== false) {
162
+            return $this->tagMap($this->tags[$key]);
163
+        }
164
+        return false;
165
+    }
166
+
167
+    /**
168
+     * Get the tags for a specific user.
169
+     *
170
+     * This returns an array with maps containing each tag's properties:
171
+     * [
172
+     * 	['id' => 0, 'name' = 'First tag', 'owner' = 'User', 'type' => 'tagtype'],
173
+     * 	['id' => 1, 'name' = 'Shared tag', 'owner' = 'Other user', 'type' => 'tagtype'],
174
+     * ]
175
+     *
176
+     * @return array
177
+     */
178
+    public function getTags() {
179
+        if(!count($this->tags)) {
180
+            return array();
181
+        }
182
+
183
+        usort($this->tags, function($a, $b) {
184
+            return strnatcasecmp($a->getName(), $b->getName());
185
+        });
186
+        $tagMap = array();
187
+
188
+        foreach($this->tags as $tag) {
189
+            if($tag->getName() !== self::TAG_FAVORITE) {
190
+                $tagMap[] = $this->tagMap($tag);
191
+            }
192
+        }
193
+        return $tagMap;
194
+
195
+    }
196
+
197
+    /**
198
+     * Return only the tags owned by the given user, omitting any tags shared
199
+     * by other users.
200
+     *
201
+     * @param string $user The user whose tags are to be checked.
202
+     * @return array An array of Tag objects.
203
+     */
204
+    public function getTagsForUser($user) {
205
+        return array_filter($this->tags,
206
+            function($tag) use($user) {
207
+                return $tag->getOwner() === $user;
208
+            }
209
+        );
210
+    }
211
+
212
+    /**
213
+     * Get the list of tags for the given ids.
214
+     *
215
+     * @param array $objIds array of object ids
216
+     * @return array|boolean of tags id as key to array of tag names
217
+     * or false if an error occurred
218
+     */
219
+    public function getTagsForObjects(array $objIds) {
220
+        $entries = array();
221
+
222
+        try {
223
+            $conn = \OC::$server->getDatabaseConnection();
224
+            $chunks = array_chunk($objIds, 900, false);
225
+            foreach ($chunks as $chunk) {
226
+                $result = $conn->executeQuery(
227
+                    'SELECT `category`, `categoryid`, `objid` ' .
228
+                    'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
229
+                    'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
230
+                    array($this->user, $this->type, $chunk),
231
+                    array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
232
+                );
233
+                while ($row = $result->fetch()) {
234
+                    $objId = (int)$row['objid'];
235
+                    if (!isset($entries[$objId])) {
236
+                        $entries[$objId] = array();
237
+                    }
238
+                    $entries[$objId][] = $row['category'];
239
+                }
240
+                if ($result === null) {
241
+                    \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
242
+                    return false;
243
+                }
244
+            }
245
+        } catch(\Exception $e) {
246
+            \OC::$server->getLogger()->logException($e, [
247
+                'message' => __METHOD__,
248
+                'level' => ILogger::ERROR,
249
+                'app' => 'core',
250
+            ]);
251
+            return false;
252
+        }
253
+
254
+        return $entries;
255
+    }
256
+
257
+    /**
258
+     * Get the a list if items tagged with $tag.
259
+     *
260
+     * Throws an exception if the tag could not be found.
261
+     *
262
+     * @param string $tag Tag id or name.
263
+     * @return array|false An array of object ids or false on error.
264
+     * @throws \Exception
265
+     */
266
+    public function getIdsForTag($tag) {
267
+        $result = null;
268
+        $tagId = false;
269
+        if(is_numeric($tag)) {
270
+            $tagId = $tag;
271
+        } elseif(is_string($tag)) {
272
+            $tag = trim($tag);
273
+            if($tag === '') {
274
+                \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
275
+                return false;
276
+            }
277
+            $tagId = $this->getTagId($tag);
278
+        }
279
+
280
+        if($tagId === false) {
281
+            $l10n = \OC::$server->getL10N('core');
282
+            throw new \Exception(
283
+                $l10n->t('Could not find category "%s"', [$tag])
284
+            );
285
+        }
286
+
287
+        $ids = array();
288
+        $sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
289
+            . '` WHERE `categoryid` = ?';
290
+
291
+        try {
292
+            $stmt = \OC_DB::prepare($sql);
293
+            $result = $stmt->execute(array($tagId));
294
+            if ($result === null) {
295
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
296
+                return false;
297
+            }
298
+        } catch(\Exception $e) {
299
+            \OC::$server->getLogger()->logException($e, [
300
+                'message' => __METHOD__,
301
+                'level' => ILogger::ERROR,
302
+                'app' => 'core',
303
+            ]);
304
+            return false;
305
+        }
306
+
307
+        if(!is_null($result)) {
308
+            while( $row = $result->fetchRow()) {
309
+                $id = (int)$row['objid'];
310
+
311
+                if ($this->includeShared) {
312
+                    // We have to check if we are really allowed to access the
313
+                    // items that are tagged with $tag. To that end, we ask the
314
+                    // corresponding sharing backend if the item identified by $id
315
+                    // is owned by any of $this->owners.
316
+                    foreach ($this->owners as $owner) {
317
+                        if ($this->backend->isValidSource($id, $owner)) {
318
+                            $ids[] = $id;
319
+                            break;
320
+                        }
321
+                    }
322
+                } else {
323
+                    $ids[] = $id;
324
+                }
325
+            }
326
+        }
327
+
328
+        return $ids;
329
+    }
330
+
331
+    /**
332
+     * Checks whether a tag is saved for the given user,
333
+     * disregarding the ones shared with him or her.
334
+     *
335
+     * @param string $name The tag name to check for.
336
+     * @param string $user The user whose tags are to be checked.
337
+     * @return bool
338
+     */
339
+    public function userHasTag($name, $user) {
340
+        $key = $this->array_searchi($name, $this->getTagsForUser($user));
341
+        return ($key !== false) ? $this->tags[$key]->getId() : false;
342
+    }
343
+
344
+    /**
345
+     * Checks whether a tag is saved for or shared with the current user.
346
+     *
347
+     * @param string $name The tag name to check for.
348
+     * @return bool
349
+     */
350
+    public function hasTag($name) {
351
+        return $this->getTagId($name) !== false;
352
+    }
353
+
354
+    /**
355
+     * Add a new tag.
356
+     *
357
+     * @param string $name A string with a name of the tag
358
+     * @return false|int the id of the added tag or false on error.
359
+     */
360
+    public function add($name) {
361
+        $name = trim($name);
362
+
363
+        if($name === '') {
364
+            \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
365
+            return false;
366
+        }
367
+        if($this->userHasTag($name, $this->user)) {
368
+            \OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', ILogger::DEBUG);
369
+            return false;
370
+        }
371
+        try {
372
+            $tag = new Tag($this->user, $this->type, $name);
373
+            $tag = $this->mapper->insert($tag);
374
+            $this->tags[] = $tag;
375
+        } catch(\Exception $e) {
376
+            \OC::$server->getLogger()->logException($e, [
377
+                'message' => __METHOD__,
378
+                'level' => ILogger::ERROR,
379
+                'app' => 'core',
380
+            ]);
381
+            return false;
382
+        }
383
+        \OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), ILogger::DEBUG);
384
+        return $tag->getId();
385
+    }
386
+
387
+    /**
388
+     * Rename tag.
389
+     *
390
+     * @param string|integer $from The name or ID of the existing tag
391
+     * @param string $to The new name of the tag.
392
+     * @return bool
393
+     */
394
+    public function rename($from, $to) {
395
+        $from = trim($from);
396
+        $to = trim($to);
397
+
398
+        if($to === '' || $from === '') {
399
+            \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
400
+            return false;
401
+        }
402
+
403
+        if (is_numeric($from)) {
404
+            $key = $this->getTagById($from);
405
+        } else {
406
+            $key = $this->getTagByName($from);
407
+        }
408
+        if($key === false) {
409
+            \OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', ILogger::DEBUG);
410
+            return false;
411
+        }
412
+        $tag = $this->tags[$key];
413
+
414
+        if($this->userHasTag($to, $tag->getOwner())) {
415
+            \OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', ILogger::DEBUG);
416
+            return false;
417
+        }
418
+
419
+        try {
420
+            $tag->setName($to);
421
+            $this->tags[$key] = $this->mapper->update($tag);
422
+        } catch(\Exception $e) {
423
+            \OC::$server->getLogger()->logException($e, [
424
+                'message' => __METHOD__,
425
+                'level' => ILogger::ERROR,
426
+                'app' => 'core',
427
+            ]);
428
+            return false;
429
+        }
430
+        return true;
431
+    }
432
+
433
+    /**
434
+     * Add a list of new tags.
435
+     *
436
+     * @param string[] $names A string with a name or an array of strings containing
437
+     * the name(s) of the tag(s) to add.
438
+     * @param bool $sync When true, save the tags
439
+     * @param int|null $id int Optional object id to add to this|these tag(s)
440
+     * @return bool Returns false on error.
441
+     */
442
+    public function addMultiple($names, $sync=false, $id = null) {
443
+        if(!is_array($names)) {
444
+            $names = array($names);
445
+        }
446
+        $names = array_map('trim', $names);
447
+        array_filter($names);
448
+
449
+        $newones = array();
450
+        foreach($names as $name) {
451
+            if(!$this->hasTag($name) && $name !== '') {
452
+                $newones[] = new Tag($this->user, $this->type, $name);
453
+            }
454
+            if(!is_null($id) ) {
455
+                // Insert $objectid, $categoryid  pairs if not exist.
456
+                self::$relations[] = array('objid' => $id, 'tag' => $name);
457
+            }
458
+        }
459
+        $this->tags = array_merge($this->tags, $newones);
460
+        if($sync === true) {
461
+            $this->save();
462
+        }
463
+
464
+        return true;
465
+    }
466
+
467
+    /**
468
+     * Save the list of tags and their object relations
469
+     */
470
+    protected function save() {
471
+        if(is_array($this->tags)) {
472
+            foreach($this->tags as $tag) {
473
+                try {
474
+                    if (!$this->mapper->tagExists($tag)) {
475
+                        $this->mapper->insert($tag);
476
+                    }
477
+                } catch(\Exception $e) {
478
+                    \OC::$server->getLogger()->logException($e, [
479
+                        'message' => __METHOD__,
480
+                        'level' => ILogger::ERROR,
481
+                        'app' => 'core',
482
+                    ]);
483
+                }
484
+            }
485
+
486
+            // reload tags to get the proper ids.
487
+            $this->tags = $this->mapper->loadTags($this->owners, $this->type);
488
+            \OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
489
+                ILogger::DEBUG);
490
+            // Loop through temporarily cached objectid/tagname pairs
491
+            // and save relations.
492
+            $tags = $this->tags;
493
+            // For some reason this is needed or array_search(i) will return 0..?
494
+            ksort($tags);
495
+            $dbConnection = \OC::$server->getDatabaseConnection();
496
+            foreach(self::$relations as $relation) {
497
+                $tagId = $this->getTagId($relation['tag']);
498
+                \OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, ILogger::DEBUG);
499
+                if($tagId) {
500
+                    try {
501
+                        $dbConnection->insertIfNotExist(self::RELATION_TABLE,
502
+                            array(
503
+                                'objid' => $relation['objid'],
504
+                                'categoryid' => $tagId,
505
+                                'type' => $this->type,
506
+                                ));
507
+                    } catch(\Exception $e) {
508
+                        \OC::$server->getLogger()->logException($e, [
509
+                            'message' => __METHOD__,
510
+                            'level' => ILogger::ERROR,
511
+                            'app' => 'core',
512
+                        ]);
513
+                    }
514
+                }
515
+            }
516
+            self::$relations = array(); // reset
517
+        } else {
518
+            \OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! '
519
+                . print_r($this->tags, true), ILogger::ERROR);
520
+        }
521
+    }
522
+
523
+    /**
524
+     * Delete tags and tag/object relations for a user.
525
+     *
526
+     * For hooking up on post_deleteUser
527
+     *
528
+     * @param array $arguments
529
+     */
530
+    public static function post_deleteUser($arguments) {
531
+        // Find all objectid/tagId pairs.
532
+        $result = null;
533
+        try {
534
+            $stmt = \OC_DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
535
+                . 'WHERE `uid` = ?');
536
+            $result = $stmt->execute(array($arguments['uid']));
537
+            if ($result === null) {
538
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
539
+            }
540
+        } catch(\Exception $e) {
541
+            \OC::$server->getLogger()->logException($e, [
542
+                'message' => __METHOD__,
543
+                'level' => ILogger::ERROR,
544
+                'app' => 'core',
545
+            ]);
546
+        }
547
+
548
+        if(!is_null($result)) {
549
+            try {
550
+                $stmt = \OC_DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
551
+                    . 'WHERE `categoryid` = ?');
552
+                while( $row = $result->fetchRow()) {
553
+                    try {
554
+                        $stmt->execute(array($row['id']));
555
+                    } catch(\Exception $e) {
556
+                        \OC::$server->getLogger()->logException($e, [
557
+                            'message' => __METHOD__,
558
+                            'level' => ILogger::ERROR,
559
+                            'app' => 'core',
560
+                        ]);
561
+                    }
562
+                }
563
+            } catch(\Exception $e) {
564
+                \OC::$server->getLogger()->logException($e, [
565
+                    'message' => __METHOD__,
566
+                    'level' => ILogger::ERROR,
567
+                    'app' => 'core',
568
+                ]);
569
+            }
570
+        }
571
+        try {
572
+            $stmt = \OC_DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
573
+                . 'WHERE `uid` = ?');
574
+            $result = $stmt->execute(array($arguments['uid']));
575
+            if ($result === null) {
576
+                \OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
577
+            }
578
+        } catch(\Exception $e) {
579
+            \OC::$server->getLogger()->logException($e, [
580
+                'message' => __METHOD__,
581
+                'level' => ILogger::ERROR,
582
+                'app' => 'core',
583
+            ]);
584
+        }
585
+    }
586
+
587
+    /**
588
+     * Delete tag/object relations from the db
589
+     *
590
+     * @param array $ids The ids of the objects
591
+     * @return boolean Returns false on error.
592
+     */
593
+    public function purgeObjects(array $ids) {
594
+        if(count($ids) === 0) {
595
+            // job done ;)
596
+            return true;
597
+        }
598
+        $updates = $ids;
599
+        try {
600
+            $query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
601
+            $query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
602
+            $query .= 'AND `type`= ?';
603
+            $updates[] = $this->type;
604
+            $stmt = \OC_DB::prepare($query);
605
+            $result = $stmt->execute($updates);
606
+            if ($result === null) {
607
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
608
+                return false;
609
+            }
610
+        } catch(\Exception $e) {
611
+            \OC::$server->getLogger()->logException($e, [
612
+                'message' => __METHOD__,
613
+                'level' => ILogger::ERROR,
614
+                'app' => 'core',
615
+            ]);
616
+            return false;
617
+        }
618
+        return true;
619
+    }
620
+
621
+    /**
622
+     * Get favorites for an object type
623
+     *
624
+     * @return array|false An array of object ids.
625
+     */
626
+    public function getFavorites() {
627
+        try {
628
+            return $this->getIdsForTag(self::TAG_FAVORITE);
629
+        } catch(\Exception $e) {
630
+            \OC::$server->getLogger()->logException($e, [
631
+                'message' => __METHOD__,
632
+                'level' => ILogger::ERROR,
633
+                'app' => 'core',
634
+            ]);
635
+            return array();
636
+        }
637
+    }
638
+
639
+    /**
640
+     * Add an object to favorites
641
+     *
642
+     * @param int $objid The id of the object
643
+     * @return boolean
644
+     */
645
+    public function addToFavorites($objid) {
646
+        if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
647
+            $this->add(self::TAG_FAVORITE);
648
+        }
649
+        return $this->tagAs($objid, self::TAG_FAVORITE);
650
+    }
651
+
652
+    /**
653
+     * Remove an object from favorites
654
+     *
655
+     * @param int $objid The id of the object
656
+     * @return boolean
657
+     */
658
+    public function removeFromFavorites($objid) {
659
+        return $this->unTag($objid, self::TAG_FAVORITE);
660
+    }
661
+
662
+    /**
663
+     * Creates a tag/object relation.
664
+     *
665
+     * @param int $objid The id of the object
666
+     * @param string $tag The id or name of the tag
667
+     * @return boolean Returns false on error.
668
+     */
669
+    public function tagAs($objid, $tag) {
670
+        if(is_string($tag) && !is_numeric($tag)) {
671
+            $tag = trim($tag);
672
+            if($tag === '') {
673
+                \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
674
+                return false;
675
+            }
676
+            if(!$this->hasTag($tag)) {
677
+                $this->add($tag);
678
+            }
679
+            $tagId =  $this->getTagId($tag);
680
+        } else {
681
+            $tagId = $tag;
682
+        }
683
+        try {
684
+            \OC::$server->getDatabaseConnection()->insertIfNotExist(self::RELATION_TABLE,
685
+                array(
686
+                    'objid' => $objid,
687
+                    'categoryid' => $tagId,
688
+                    'type' => $this->type,
689
+                ));
690
+        } catch(\Exception $e) {
691
+            \OC::$server->getLogger()->logException($e, [
692
+                'message' => __METHOD__,
693
+                'level' => ILogger::ERROR,
694
+                'app' => 'core',
695
+            ]);
696
+            return false;
697
+        }
698
+        return true;
699
+    }
700
+
701
+    /**
702
+     * Delete single tag/object relation from the db
703
+     *
704
+     * @param int $objid The id of the object
705
+     * @param string $tag The id or name of the tag
706
+     * @return boolean
707
+     */
708
+    public function unTag($objid, $tag) {
709
+        if(is_string($tag) && !is_numeric($tag)) {
710
+            $tag = trim($tag);
711
+            if($tag === '') {
712
+                \OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', ILogger::DEBUG);
713
+                return false;
714
+            }
715
+            $tagId =  $this->getTagId($tag);
716
+        } else {
717
+            $tagId = $tag;
718
+        }
719
+
720
+        try {
721
+            $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
722
+                    . 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
723
+            $stmt = \OC_DB::prepare($sql);
724
+            $stmt->execute(array($objid, $tagId, $this->type));
725
+        } catch(\Exception $e) {
726
+            \OC::$server->getLogger()->logException($e, [
727
+                'message' => __METHOD__,
728
+                'level' => ILogger::ERROR,
729
+                'app' => 'core',
730
+            ]);
731
+            return false;
732
+        }
733
+        return true;
734
+    }
735
+
736
+    /**
737
+     * Delete tags from the database.
738
+     *
739
+     * @param string[]|integer[] $names An array of tags (names or IDs) to delete
740
+     * @return bool Returns false on error
741
+     */
742
+    public function delete($names) {
743
+        if(!is_array($names)) {
744
+            $names = array($names);
745
+        }
746
+
747
+        $names = array_map('trim', $names);
748
+        array_filter($names);
749
+
750
+        \OCP\Util::writeLog('core', __METHOD__ . ', before: '
751
+            . print_r($this->tags, true), ILogger::DEBUG);
752
+        foreach($names as $name) {
753
+            $id = null;
754
+
755
+            if (is_numeric($name)) {
756
+                $key = $this->getTagById($name);
757
+            } else {
758
+                $key = $this->getTagByName($name);
759
+            }
760
+            if ($key !== false) {
761
+                $tag = $this->tags[$key];
762
+                $id = $tag->getId();
763
+                unset($this->tags[$key]);
764
+                $this->mapper->delete($tag);
765
+            } else {
766
+                \OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
767
+                    . ': not found.', ILogger::ERROR);
768
+            }
769
+            if(!is_null($id) && $id !== false) {
770
+                try {
771
+                    $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
772
+                            . 'WHERE `categoryid` = ?';
773
+                    $stmt = \OC_DB::prepare($sql);
774
+                    $result = $stmt->execute(array($id));
775
+                    if ($result === null) {
776
+                        \OCP\Util::writeLog('core',
777
+                            __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(),
778
+                            ILogger::ERROR);
779
+                        return false;
780
+                    }
781
+                } catch(\Exception $e) {
782
+                    \OC::$server->getLogger()->logException($e, [
783
+                        'message' => __METHOD__,
784
+                        'level' => ILogger::ERROR,
785
+                        'app' => 'core',
786
+                    ]);
787
+                    return false;
788
+                }
789
+            }
790
+        }
791
+        return true;
792
+    }
793
+
794
+    // case-insensitive array_search
795
+    protected function array_searchi($needle, $haystack, $mem='getName') {
796
+        if(!is_array($haystack)) {
797
+            return false;
798
+        }
799
+        return array_search(strtolower($needle), array_map(
800
+            function($tag) use($mem) {
801
+                return strtolower(call_user_func(array($tag, $mem)));
802
+            }, $haystack)
803
+        );
804
+    }
805
+
806
+    /**
807
+     * Get a tag's ID.
808
+     *
809
+     * @param string $name The tag name to look for.
810
+     * @return string|bool The tag's id or false if no matching tag is found.
811
+     */
812
+    private function getTagId($name) {
813
+        $key = $this->array_searchi($name, $this->tags);
814
+        if ($key !== false) {
815
+            return $this->tags[$key]->getId();
816
+        }
817
+        return false;
818
+    }
819
+
820
+    /**
821
+     * Get a tag by its name.
822
+     *
823
+     * @param string $name The tag name.
824
+     * @return integer|bool The tag object's offset within the $this->tags
825
+     *                      array or false if it doesn't exist.
826
+     */
827
+    private function getTagByName($name) {
828
+        return $this->array_searchi($name, $this->tags, 'getName');
829
+    }
830
+
831
+    /**
832
+     * Get a tag by its ID.
833
+     *
834
+     * @param string $id The tag ID to look for.
835
+     * @return integer|bool The tag object's offset within the $this->tags
836
+     *                      array or false if it doesn't exist.
837
+     */
838
+    private function getTagById($id) {
839
+        return $this->array_searchi($id, $this->tags, 'getId');
840
+    }
841
+
842
+    /**
843
+     * Returns an array mapping a given tag's properties to its values:
844
+     * ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
845
+     *
846
+     * @param Tag $tag The tag that is going to be mapped
847
+     * @return array
848
+     */
849
+    private function tagMap(Tag $tag) {
850
+        return array(
851
+            'id'    => $tag->getId(),
852
+            'name'  => $tag->getName(),
853
+            'owner' => $tag->getOwner(),
854
+            'type'  => $tag->getType()
855
+        );
856
+    }
857 857
 }
Please login to merge, or discard this patch.
Spacing   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
 		}
136 136
 		$this->tags = $this->mapper->loadTags($this->owners, $this->type);
137 137
 
138
-		if(count($defaultTags) > 0 && count($this->tags) === 0) {
138
+		if (count($defaultTags) > 0 && count($this->tags) === 0) {
139 139
 			$this->addMultiple($defaultTags, true);
140 140
 		}
141 141
 	}
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 	* @return array
177 177
 	*/
178 178
 	public function getTags() {
179
-		if(!count($this->tags)) {
179
+		if (!count($this->tags)) {
180 180
 			return array();
181 181
 		}
182 182
 
@@ -185,8 +185,8 @@  discard block
 block discarded – undo
185 185
 		});
186 186
 		$tagMap = array();
187 187
 
188
-		foreach($this->tags as $tag) {
189
-			if($tag->getName() !== self::TAG_FAVORITE) {
188
+		foreach ($this->tags as $tag) {
189
+			if ($tag->getName() !== self::TAG_FAVORITE) {
190 190
 				$tagMap[] = $this->tagMap($tag);
191 191
 			}
192 192
 		}
@@ -224,25 +224,25 @@  discard block
 block discarded – undo
224 224
 			$chunks = array_chunk($objIds, 900, false);
225 225
 			foreach ($chunks as $chunk) {
226 226
 				$result = $conn->executeQuery(
227
-					'SELECT `category`, `categoryid`, `objid` ' .
228
-					'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
227
+					'SELECT `category`, `categoryid`, `objid` '.
228
+					'FROM `'.self::RELATION_TABLE.'` r, `'.self::TAG_TABLE.'` '.
229 229
 					'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
230 230
 					array($this->user, $this->type, $chunk),
231 231
 					array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
232 232
 				);
233 233
 				while ($row = $result->fetch()) {
234
-					$objId = (int)$row['objid'];
234
+					$objId = (int) $row['objid'];
235 235
 					if (!isset($entries[$objId])) {
236 236
 						$entries[$objId] = array();
237 237
 					}
238 238
 					$entries[$objId][] = $row['category'];
239 239
 				}
240 240
 				if ($result === null) {
241
-					\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
241
+					\OCP\Util::writeLog('core', __METHOD__.'DB error: '.\OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
242 242
 					return false;
243 243
 				}
244 244
 			}
245
-		} catch(\Exception $e) {
245
+		} catch (\Exception $e) {
246 246
 			\OC::$server->getLogger()->logException($e, [
247 247
 				'message' => __METHOD__,
248 248
 				'level' => ILogger::ERROR,
@@ -266,18 +266,18 @@  discard block
 block discarded – undo
266 266
 	public function getIdsForTag($tag) {
267 267
 		$result = null;
268 268
 		$tagId = false;
269
-		if(is_numeric($tag)) {
269
+		if (is_numeric($tag)) {
270 270
 			$tagId = $tag;
271
-		} elseif(is_string($tag)) {
271
+		} elseif (is_string($tag)) {
272 272
 			$tag = trim($tag);
273
-			if($tag === '') {
273
+			if ($tag === '') {
274 274
 				\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
275 275
 				return false;
276 276
 			}
277 277
 			$tagId = $this->getTagId($tag);
278 278
 		}
279 279
 
280
-		if($tagId === false) {
280
+		if ($tagId === false) {
281 281
 			$l10n = \OC::$server->getL10N('core');
282 282
 			throw new \Exception(
283 283
 				$l10n->t('Could not find category "%s"', [$tag])
@@ -285,17 +285,17 @@  discard block
 block discarded – undo
285 285
 		}
286 286
 
287 287
 		$ids = array();
288
-		$sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
288
+		$sql = 'SELECT `objid` FROM `'.self::RELATION_TABLE
289 289
 			. '` WHERE `categoryid` = ?';
290 290
 
291 291
 		try {
292 292
 			$stmt = \OC_DB::prepare($sql);
293 293
 			$result = $stmt->execute(array($tagId));
294 294
 			if ($result === null) {
295
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
295
+				\OCP\Util::writeLog('core', __METHOD__.'DB error: '.\OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
296 296
 				return false;
297 297
 			}
298
-		} catch(\Exception $e) {
298
+		} catch (\Exception $e) {
299 299
 			\OC::$server->getLogger()->logException($e, [
300 300
 				'message' => __METHOD__,
301 301
 				'level' => ILogger::ERROR,
@@ -304,9 +304,9 @@  discard block
 block discarded – undo
304 304
 			return false;
305 305
 		}
306 306
 
307
-		if(!is_null($result)) {
308
-			while( $row = $result->fetchRow()) {
309
-				$id = (int)$row['objid'];
307
+		if (!is_null($result)) {
308
+			while ($row = $result->fetchRow()) {
309
+				$id = (int) $row['objid'];
310 310
 
311 311
 				if ($this->includeShared) {
312 312
 					// We have to check if we are really allowed to access the
@@ -360,19 +360,19 @@  discard block
 block discarded – undo
360 360
 	public function add($name) {
361 361
 		$name = trim($name);
362 362
 
363
-		if($name === '') {
363
+		if ($name === '') {
364 364
 			\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
365 365
 			return false;
366 366
 		}
367
-		if($this->userHasTag($name, $this->user)) {
368
-			\OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', ILogger::DEBUG);
367
+		if ($this->userHasTag($name, $this->user)) {
368
+			\OCP\Util::writeLog('core', __METHOD__.', name: '.$name.' exists already', ILogger::DEBUG);
369 369
 			return false;
370 370
 		}
371 371
 		try {
372 372
 			$tag = new Tag($this->user, $this->type, $name);
373 373
 			$tag = $this->mapper->insert($tag);
374 374
 			$this->tags[] = $tag;
375
-		} catch(\Exception $e) {
375
+		} catch (\Exception $e) {
376 376
 			\OC::$server->getLogger()->logException($e, [
377 377
 				'message' => __METHOD__,
378 378
 				'level' => ILogger::ERROR,
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 			]);
381 381
 			return false;
382 382
 		}
383
-		\OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), ILogger::DEBUG);
383
+		\OCP\Util::writeLog('core', __METHOD__.', id: '.$tag->getId(), ILogger::DEBUG);
384 384
 		return $tag->getId();
385 385
 	}
386 386
 
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
 		$from = trim($from);
396 396
 		$to = trim($to);
397 397
 
398
-		if($to === '' || $from === '') {
398
+		if ($to === '' || $from === '') {
399 399
 			\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
400 400
 			return false;
401 401
 		}
@@ -405,21 +405,21 @@  discard block
 block discarded – undo
405 405
 		} else {
406 406
 			$key = $this->getTagByName($from);
407 407
 		}
408
-		if($key === false) {
409
-			\OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', ILogger::DEBUG);
408
+		if ($key === false) {
409
+			\OCP\Util::writeLog('core', __METHOD__.', tag: '.$from.' does not exist', ILogger::DEBUG);
410 410
 			return false;
411 411
 		}
412 412
 		$tag = $this->tags[$key];
413 413
 
414
-		if($this->userHasTag($to, $tag->getOwner())) {
415
-			\OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', ILogger::DEBUG);
414
+		if ($this->userHasTag($to, $tag->getOwner())) {
415
+			\OCP\Util::writeLog('core', __METHOD__.', A tag named '.$to.' already exists for user '.$tag->getOwner().'.', ILogger::DEBUG);
416 416
 			return false;
417 417
 		}
418 418
 
419 419
 		try {
420 420
 			$tag->setName($to);
421 421
 			$this->tags[$key] = $this->mapper->update($tag);
422
-		} catch(\Exception $e) {
422
+		} catch (\Exception $e) {
423 423
 			\OC::$server->getLogger()->logException($e, [
424 424
 				'message' => __METHOD__,
425 425
 				'level' => ILogger::ERROR,
@@ -439,25 +439,25 @@  discard block
 block discarded – undo
439 439
 	* @param int|null $id int Optional object id to add to this|these tag(s)
440 440
 	* @return bool Returns false on error.
441 441
 	*/
442
-	public function addMultiple($names, $sync=false, $id = null) {
443
-		if(!is_array($names)) {
442
+	public function addMultiple($names, $sync = false, $id = null) {
443
+		if (!is_array($names)) {
444 444
 			$names = array($names);
445 445
 		}
446 446
 		$names = array_map('trim', $names);
447 447
 		array_filter($names);
448 448
 
449 449
 		$newones = array();
450
-		foreach($names as $name) {
451
-			if(!$this->hasTag($name) && $name !== '') {
450
+		foreach ($names as $name) {
451
+			if (!$this->hasTag($name) && $name !== '') {
452 452
 				$newones[] = new Tag($this->user, $this->type, $name);
453 453
 			}
454
-			if(!is_null($id) ) {
454
+			if (!is_null($id)) {
455 455
 				// Insert $objectid, $categoryid  pairs if not exist.
456 456
 				self::$relations[] = array('objid' => $id, 'tag' => $name);
457 457
 			}
458 458
 		}
459 459
 		$this->tags = array_merge($this->tags, $newones);
460
-		if($sync === true) {
460
+		if ($sync === true) {
461 461
 			$this->save();
462 462
 		}
463 463
 
@@ -468,13 +468,13 @@  discard block
 block discarded – undo
468 468
 	 * Save the list of tags and their object relations
469 469
 	 */
470 470
 	protected function save() {
471
-		if(is_array($this->tags)) {
472
-			foreach($this->tags as $tag) {
471
+		if (is_array($this->tags)) {
472
+			foreach ($this->tags as $tag) {
473 473
 				try {
474 474
 					if (!$this->mapper->tagExists($tag)) {
475 475
 						$this->mapper->insert($tag);
476 476
 					}
477
-				} catch(\Exception $e) {
477
+				} catch (\Exception $e) {
478 478
 					\OC::$server->getLogger()->logException($e, [
479 479
 						'message' => __METHOD__,
480 480
 						'level' => ILogger::ERROR,
@@ -485,7 +485,7 @@  discard block
 block discarded – undo
485 485
 
486 486
 			// reload tags to get the proper ids.
487 487
 			$this->tags = $this->mapper->loadTags($this->owners, $this->type);
488
-			\OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
488
+			\OCP\Util::writeLog('core', __METHOD__.', tags: '.print_r($this->tags, true),
489 489
 				ILogger::DEBUG);
490 490
 			// Loop through temporarily cached objectid/tagname pairs
491 491
 			// and save relations.
@@ -493,10 +493,10 @@  discard block
 block discarded – undo
493 493
 			// For some reason this is needed or array_search(i) will return 0..?
494 494
 			ksort($tags);
495 495
 			$dbConnection = \OC::$server->getDatabaseConnection();
496
-			foreach(self::$relations as $relation) {
496
+			foreach (self::$relations as $relation) {
497 497
 				$tagId = $this->getTagId($relation['tag']);
498
-				\OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, ILogger::DEBUG);
499
-				if($tagId) {
498
+				\OCP\Util::writeLog('core', __METHOD__.'catid, '.$relation['tag'].' '.$tagId, ILogger::DEBUG);
499
+				if ($tagId) {
500 500
 					try {
501 501
 						$dbConnection->insertIfNotExist(self::RELATION_TABLE,
502 502
 							array(
@@ -504,7 +504,7 @@  discard block
 block discarded – undo
504 504
 								'categoryid' => $tagId,
505 505
 								'type' => $this->type,
506 506
 								));
507
-					} catch(\Exception $e) {
507
+					} catch (\Exception $e) {
508 508
 						\OC::$server->getLogger()->logException($e, [
509 509
 							'message' => __METHOD__,
510 510
 							'level' => ILogger::ERROR,
@@ -531,13 +531,13 @@  discard block
 block discarded – undo
531 531
 		// Find all objectid/tagId pairs.
532 532
 		$result = null;
533 533
 		try {
534
-			$stmt = \OC_DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
534
+			$stmt = \OC_DB::prepare('SELECT `id` FROM `'.self::TAG_TABLE.'` '
535 535
 				. 'WHERE `uid` = ?');
536 536
 			$result = $stmt->execute(array($arguments['uid']));
537 537
 			if ($result === null) {
538
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
538
+				\OCP\Util::writeLog('core', __METHOD__.'DB error: '.\OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
539 539
 			}
540
-		} catch(\Exception $e) {
540
+		} catch (\Exception $e) {
541 541
 			\OC::$server->getLogger()->logException($e, [
542 542
 				'message' => __METHOD__,
543 543
 				'level' => ILogger::ERROR,
@@ -545,14 +545,14 @@  discard block
 block discarded – undo
545 545
 			]);
546 546
 		}
547 547
 
548
-		if(!is_null($result)) {
548
+		if (!is_null($result)) {
549 549
 			try {
550
-				$stmt = \OC_DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
550
+				$stmt = \OC_DB::prepare('DELETE FROM `'.self::RELATION_TABLE.'` '
551 551
 					. 'WHERE `categoryid` = ?');
552
-				while( $row = $result->fetchRow()) {
552
+				while ($row = $result->fetchRow()) {
553 553
 					try {
554 554
 						$stmt->execute(array($row['id']));
555
-					} catch(\Exception $e) {
555
+					} catch (\Exception $e) {
556 556
 						\OC::$server->getLogger()->logException($e, [
557 557
 							'message' => __METHOD__,
558 558
 							'level' => ILogger::ERROR,
@@ -560,7 +560,7 @@  discard block
 block discarded – undo
560 560
 						]);
561 561
 					}
562 562
 				}
563
-			} catch(\Exception $e) {
563
+			} catch (\Exception $e) {
564 564
 				\OC::$server->getLogger()->logException($e, [
565 565
 					'message' => __METHOD__,
566 566
 					'level' => ILogger::ERROR,
@@ -569,13 +569,13 @@  discard block
 block discarded – undo
569 569
 			}
570 570
 		}
571 571
 		try {
572
-			$stmt = \OC_DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
572
+			$stmt = \OC_DB::prepare('DELETE FROM `'.self::TAG_TABLE.'` '
573 573
 				. 'WHERE `uid` = ?');
574 574
 			$result = $stmt->execute(array($arguments['uid']));
575 575
 			if ($result === null) {
576
-				\OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
576
+				\OCP\Util::writeLog('core', __METHOD__.', DB error: '.\OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
577 577
 			}
578
-		} catch(\Exception $e) {
578
+		} catch (\Exception $e) {
579 579
 			\OC::$server->getLogger()->logException($e, [
580 580
 				'message' => __METHOD__,
581 581
 				'level' => ILogger::ERROR,
@@ -591,23 +591,23 @@  discard block
 block discarded – undo
591 591
 	* @return boolean Returns false on error.
592 592
 	*/
593 593
 	public function purgeObjects(array $ids) {
594
-		if(count($ids) === 0) {
594
+		if (count($ids) === 0) {
595 595
 			// job done ;)
596 596
 			return true;
597 597
 		}
598 598
 		$updates = $ids;
599 599
 		try {
600
-			$query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
601
-			$query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
600
+			$query = 'DELETE FROM `'.self::RELATION_TABLE.'` ';
601
+			$query .= 'WHERE `objid` IN ('.str_repeat('?,', count($ids) - 1).'?) ';
602 602
 			$query .= 'AND `type`= ?';
603 603
 			$updates[] = $this->type;
604 604
 			$stmt = \OC_DB::prepare($query);
605 605
 			$result = $stmt->execute($updates);
606 606
 			if ($result === null) {
607
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
607
+				\OCP\Util::writeLog('core', __METHOD__.'DB error: '.\OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
608 608
 				return false;
609 609
 			}
610
-		} catch(\Exception $e) {
610
+		} catch (\Exception $e) {
611 611
 			\OC::$server->getLogger()->logException($e, [
612 612
 				'message' => __METHOD__,
613 613
 				'level' => ILogger::ERROR,
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
 	public function getFavorites() {
627 627
 		try {
628 628
 			return $this->getIdsForTag(self::TAG_FAVORITE);
629
-		} catch(\Exception $e) {
629
+		} catch (\Exception $e) {
630 630
 			\OC::$server->getLogger()->logException($e, [
631 631
 				'message' => __METHOD__,
632 632
 				'level' => ILogger::ERROR,
@@ -643,7 +643,7 @@  discard block
 block discarded – undo
643 643
 	* @return boolean
644 644
 	*/
645 645
 	public function addToFavorites($objid) {
646
-		if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
646
+		if (!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
647 647
 			$this->add(self::TAG_FAVORITE);
648 648
 		}
649 649
 		return $this->tagAs($objid, self::TAG_FAVORITE);
@@ -667,16 +667,16 @@  discard block
 block discarded – undo
667 667
 	* @return boolean Returns false on error.
668 668
 	*/
669 669
 	public function tagAs($objid, $tag) {
670
-		if(is_string($tag) && !is_numeric($tag)) {
670
+		if (is_string($tag) && !is_numeric($tag)) {
671 671
 			$tag = trim($tag);
672
-			if($tag === '') {
672
+			if ($tag === '') {
673 673
 				\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
674 674
 				return false;
675 675
 			}
676
-			if(!$this->hasTag($tag)) {
676
+			if (!$this->hasTag($tag)) {
677 677
 				$this->add($tag);
678 678
 			}
679
-			$tagId =  $this->getTagId($tag);
679
+			$tagId = $this->getTagId($tag);
680 680
 		} else {
681 681
 			$tagId = $tag;
682 682
 		}
@@ -687,7 +687,7 @@  discard block
 block discarded – undo
687 687
 					'categoryid' => $tagId,
688 688
 					'type' => $this->type,
689 689
 				));
690
-		} catch(\Exception $e) {
690
+		} catch (\Exception $e) {
691 691
 			\OC::$server->getLogger()->logException($e, [
692 692
 				'message' => __METHOD__,
693 693
 				'level' => ILogger::ERROR,
@@ -706,23 +706,23 @@  discard block
 block discarded – undo
706 706
 	* @return boolean
707 707
 	*/
708 708
 	public function unTag($objid, $tag) {
709
-		if(is_string($tag) && !is_numeric($tag)) {
709
+		if (is_string($tag) && !is_numeric($tag)) {
710 710
 			$tag = trim($tag);
711
-			if($tag === '') {
711
+			if ($tag === '') {
712 712
 				\OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', ILogger::DEBUG);
713 713
 				return false;
714 714
 			}
715
-			$tagId =  $this->getTagId($tag);
715
+			$tagId = $this->getTagId($tag);
716 716
 		} else {
717 717
 			$tagId = $tag;
718 718
 		}
719 719
 
720 720
 		try {
721
-			$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
721
+			$sql = 'DELETE FROM `'.self::RELATION_TABLE.'` '
722 722
 					. 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
723 723
 			$stmt = \OC_DB::prepare($sql);
724 724
 			$stmt->execute(array($objid, $tagId, $this->type));
725
-		} catch(\Exception $e) {
725
+		} catch (\Exception $e) {
726 726
 			\OC::$server->getLogger()->logException($e, [
727 727
 				'message' => __METHOD__,
728 728
 				'level' => ILogger::ERROR,
@@ -740,16 +740,16 @@  discard block
 block discarded – undo
740 740
 	* @return bool Returns false on error
741 741
 	*/
742 742
 	public function delete($names) {
743
-		if(!is_array($names)) {
743
+		if (!is_array($names)) {
744 744
 			$names = array($names);
745 745
 		}
746 746
 
747 747
 		$names = array_map('trim', $names);
748 748
 		array_filter($names);
749 749
 
750
-		\OCP\Util::writeLog('core', __METHOD__ . ', before: '
750
+		\OCP\Util::writeLog('core', __METHOD__.', before: '
751 751
 			. print_r($this->tags, true), ILogger::DEBUG);
752
-		foreach($names as $name) {
752
+		foreach ($names as $name) {
753 753
 			$id = null;
754 754
 
755 755
 			if (is_numeric($name)) {
@@ -763,22 +763,22 @@  discard block
 block discarded – undo
763 763
 				unset($this->tags[$key]);
764 764
 				$this->mapper->delete($tag);
765 765
 			} else {
766
-				\OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
766
+				\OCP\Util::writeLog('core', __METHOD__.'Cannot delete tag '.$name
767 767
 					. ': not found.', ILogger::ERROR);
768 768
 			}
769
-			if(!is_null($id) && $id !== false) {
769
+			if (!is_null($id) && $id !== false) {
770 770
 				try {
771
-					$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
771
+					$sql = 'DELETE FROM `'.self::RELATION_TABLE.'` '
772 772
 							. 'WHERE `categoryid` = ?';
773 773
 					$stmt = \OC_DB::prepare($sql);
774 774
 					$result = $stmt->execute(array($id));
775 775
 					if ($result === null) {
776 776
 						\OCP\Util::writeLog('core',
777
-							__METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(),
777
+							__METHOD__.'DB error: '.\OC::$server->getDatabaseConnection()->getError(),
778 778
 							ILogger::ERROR);
779 779
 						return false;
780 780
 					}
781
-				} catch(\Exception $e) {
781
+				} catch (\Exception $e) {
782 782
 					\OC::$server->getLogger()->logException($e, [
783 783
 						'message' => __METHOD__,
784 784
 						'level' => ILogger::ERROR,
@@ -792,8 +792,8 @@  discard block
 block discarded – undo
792 792
 	}
793 793
 
794 794
 	// case-insensitive array_search
795
-	protected function array_searchi($needle, $haystack, $mem='getName') {
796
-		if(!is_array($haystack)) {
795
+	protected function array_searchi($needle, $haystack, $mem = 'getName') {
796
+		if (!is_array($haystack)) {
797 797
 			return false;
798 798
 		}
799 799
 		return array_search(strtolower($needle), array_map(
Please login to merge, or discard this patch.
lib/private/Setup/MySQL.php 3 patches
Indentation   +139 added lines, -139 removed lines patch added patch discarded remove patch
@@ -34,143 +34,143 @@
 block discarded – undo
34 34
 use OCP\ILogger;
35 35
 
36 36
 class MySQL extends AbstractDatabase {
37
-	public $dbprettyname = 'MySQL/MariaDB';
38
-
39
-	public function setupDatabase($username) {
40
-		//check if the database user has admin right
41
-		$connection = $this->connect(['dbname' => null]);
42
-
43
-		// detect mb4
44
-		$tools = new MySqlTools();
45
-		if ($tools->supports4ByteCharset($connection)) {
46
-			$this->config->setValue('mysql.utf8mb4', true);
47
-			$connection = $this->connect(['dbname' => null]);
48
-		}
49
-
50
-		$this->createSpecificUser($username, $connection);
51
-
52
-		//create the database
53
-		$this->createDatabase($connection);
54
-
55
-		//fill the database if needed
56
-		$query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
57
-		$connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
58
-	}
59
-
60
-	/**
61
-	 * @param \OC\DB\Connection $connection
62
-	 */
63
-	private function createDatabase($connection) {
64
-		try{
65
-			$name = $this->dbName;
66
-			$user = $this->dbUser;
67
-			//we can't use OC_DB functions here because we need to connect as the administrative user.
68
-			$characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
69
-			$query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
70
-			$connection->executeUpdate($query);
71
-		} catch (\Exception $ex) {
72
-			$this->logger->logException($ex, [
73
-				'message' => 'Database creation failed.',
74
-				'level' => ILogger::ERROR,
75
-				'app' => 'mysql.setup',
76
-			]);
77
-			return;
78
-		}
79
-
80
-		try {
81
-			//this query will fail if there aren't the right permissions, ignore the error
82
-			$query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
83
-			$connection->executeUpdate($query);
84
-		} catch (\Exception $ex) {
85
-			$this->logger->logException($ex, [
86
-				'message' => 'Could not automatically grant privileges, this can be ignored if database user already had privileges.',
87
-				'level' => ILogger::DEBUG,
88
-				'app' => 'mysql.setup',
89
-			]);
90
-		}
91
-	}
92
-
93
-	/**
94
-	 * @param IDBConnection $connection
95
-	 * @throws \OC\DatabaseSetupException
96
-	 */
97
-	private function createDBUser($connection) {
98
-		try{
99
-			$name = $this->dbUser;
100
-			$password = $this->dbPassword;
101
-			// we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
102
-			// the anonymous user would take precedence when there is one.
103
-			$query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
104
-			$connection->executeUpdate($query);
105
-			$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
106
-			$connection->executeUpdate($query);
107
-		}
108
-		catch (\Exception $ex){
109
-			$this->logger->logException($ex, [
110
-				'message' => 'Database user creation failed.',
111
-				'level' => ILogger::ERROR,
112
-				'app' => 'mysql.setup',
113
-			]);
114
-		}
115
-	}
116
-
117
-	/**
118
-	 * @param $username
119
-	 * @param IDBConnection $connection
120
-	 * @return array
121
-	 */
122
-	private function createSpecificUser($username, $connection) {
123
-		try {
124
-			//user already specified in config
125
-			$oldUser = $this->config->getValue('dbuser', false);
126
-
127
-			//we don't have a dbuser specified in config
128
-			if ($this->dbUser !== $oldUser) {
129
-				//add prefix to the admin username to prevent collisions
130
-				$adminUser = substr('oc_' . $username, 0, 16);
131
-
132
-				$i = 1;
133
-				while (true) {
134
-					//this should be enough to check for admin rights in mysql
135
-					$query = 'SELECT user FROM mysql.user WHERE user=?';
136
-					$result = $connection->executeQuery($query, [$adminUser]);
137
-
138
-					//current dbuser has admin rights
139
-					if ($result) {
140
-						$data = $result->fetchAll();
141
-						//new dbuser does not exist
142
-						if (count($data) === 0) {
143
-							//use the admin login data for the new database user
144
-							$this->dbUser = $adminUser;
145
-
146
-							//create a random password so we don't need to store the admin password in the config file
147
-							$this->dbPassword =  $this->random->generate(30);
148
-
149
-							$this->createDBUser($connection);
150
-
151
-							break;
152
-						} else {
153
-							//repeat with different username
154
-							$length = strlen((string)$i);
155
-							$adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
156
-							$i++;
157
-						}
158
-					} else {
159
-						break;
160
-					}
161
-				}
162
-			}
163
-		} catch (\Exception $ex) {
164
-			$this->logger->logException($ex, [
165
-				'message' => 'Can not create a new MySQL user, will continue with the provided user.',
166
-				'level' => ILogger::INFO,
167
-				'app' => 'mysql.setup',
168
-			]);
169
-		}
170
-
171
-		$this->config->setValues([
172
-			'dbuser' => $this->dbUser,
173
-			'dbpassword' => $this->dbPassword,
174
-		]);
175
-	}
37
+    public $dbprettyname = 'MySQL/MariaDB';
38
+
39
+    public function setupDatabase($username) {
40
+        //check if the database user has admin right
41
+        $connection = $this->connect(['dbname' => null]);
42
+
43
+        // detect mb4
44
+        $tools = new MySqlTools();
45
+        if ($tools->supports4ByteCharset($connection)) {
46
+            $this->config->setValue('mysql.utf8mb4', true);
47
+            $connection = $this->connect(['dbname' => null]);
48
+        }
49
+
50
+        $this->createSpecificUser($username, $connection);
51
+
52
+        //create the database
53
+        $this->createDatabase($connection);
54
+
55
+        //fill the database if needed
56
+        $query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
57
+        $connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
58
+    }
59
+
60
+    /**
61
+     * @param \OC\DB\Connection $connection
62
+     */
63
+    private function createDatabase($connection) {
64
+        try{
65
+            $name = $this->dbName;
66
+            $user = $this->dbUser;
67
+            //we can't use OC_DB functions here because we need to connect as the administrative user.
68
+            $characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
69
+            $query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE ${characterSet}_bin;";
70
+            $connection->executeUpdate($query);
71
+        } catch (\Exception $ex) {
72
+            $this->logger->logException($ex, [
73
+                'message' => 'Database creation failed.',
74
+                'level' => ILogger::ERROR,
75
+                'app' => 'mysql.setup',
76
+            ]);
77
+            return;
78
+        }
79
+
80
+        try {
81
+            //this query will fail if there aren't the right permissions, ignore the error
82
+            $query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
83
+            $connection->executeUpdate($query);
84
+        } catch (\Exception $ex) {
85
+            $this->logger->logException($ex, [
86
+                'message' => 'Could not automatically grant privileges, this can be ignored if database user already had privileges.',
87
+                'level' => ILogger::DEBUG,
88
+                'app' => 'mysql.setup',
89
+            ]);
90
+        }
91
+    }
92
+
93
+    /**
94
+     * @param IDBConnection $connection
95
+     * @throws \OC\DatabaseSetupException
96
+     */
97
+    private function createDBUser($connection) {
98
+        try{
99
+            $name = $this->dbUser;
100
+            $password = $this->dbPassword;
101
+            // we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
102
+            // the anonymous user would take precedence when there is one.
103
+            $query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
104
+            $connection->executeUpdate($query);
105
+            $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
106
+            $connection->executeUpdate($query);
107
+        }
108
+        catch (\Exception $ex){
109
+            $this->logger->logException($ex, [
110
+                'message' => 'Database user creation failed.',
111
+                'level' => ILogger::ERROR,
112
+                'app' => 'mysql.setup',
113
+            ]);
114
+        }
115
+    }
116
+
117
+    /**
118
+     * @param $username
119
+     * @param IDBConnection $connection
120
+     * @return array
121
+     */
122
+    private function createSpecificUser($username, $connection) {
123
+        try {
124
+            //user already specified in config
125
+            $oldUser = $this->config->getValue('dbuser', false);
126
+
127
+            //we don't have a dbuser specified in config
128
+            if ($this->dbUser !== $oldUser) {
129
+                //add prefix to the admin username to prevent collisions
130
+                $adminUser = substr('oc_' . $username, 0, 16);
131
+
132
+                $i = 1;
133
+                while (true) {
134
+                    //this should be enough to check for admin rights in mysql
135
+                    $query = 'SELECT user FROM mysql.user WHERE user=?';
136
+                    $result = $connection->executeQuery($query, [$adminUser]);
137
+
138
+                    //current dbuser has admin rights
139
+                    if ($result) {
140
+                        $data = $result->fetchAll();
141
+                        //new dbuser does not exist
142
+                        if (count($data) === 0) {
143
+                            //use the admin login data for the new database user
144
+                            $this->dbUser = $adminUser;
145
+
146
+                            //create a random password so we don't need to store the admin password in the config file
147
+                            $this->dbPassword =  $this->random->generate(30);
148
+
149
+                            $this->createDBUser($connection);
150
+
151
+                            break;
152
+                        } else {
153
+                            //repeat with different username
154
+                            $length = strlen((string)$i);
155
+                            $adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
156
+                            $i++;
157
+                        }
158
+                    } else {
159
+                        break;
160
+                    }
161
+                }
162
+            }
163
+        } catch (\Exception $ex) {
164
+            $this->logger->logException($ex, [
165
+                'message' => 'Can not create a new MySQL user, will continue with the provided user.',
166
+                'level' => ILogger::INFO,
167
+                'app' => 'mysql.setup',
168
+            ]);
169
+        }
170
+
171
+        $this->config->setValues([
172
+            'dbuser' => $this->dbUser,
173
+            'dbpassword' => $this->dbPassword,
174
+        ]);
175
+    }
176 176
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@  discard block
 block discarded – undo
53 53
 		$this->createDatabase($connection);
54 54
 
55 55
 		//fill the database if needed
56
-		$query='select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
56
+		$query = 'select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
57 57
 		$connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
58 58
 	}
59 59
 
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
 	 * @param \OC\DB\Connection $connection
62 62
 	 */
63 63
 	private function createDatabase($connection) {
64
-		try{
64
+		try {
65 65
 			$name = $this->dbName;
66 66
 			$user = $this->dbUser;
67 67
 			//we can't use OC_DB functions here because we need to connect as the administrative user.
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 
80 80
 		try {
81 81
 			//this query will fail if there aren't the right permissions, ignore the error
82
-			$query="GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
82
+			$query = "GRANT ALL PRIVILEGES ON `$name` . * TO '$user'";
83 83
 			$connection->executeUpdate($query);
84 84
 		} catch (\Exception $ex) {
85 85
 			$this->logger->logException($ex, [
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 	 * @throws \OC\DatabaseSetupException
96 96
 	 */
97 97
 	private function createDBUser($connection) {
98
-		try{
98
+		try {
99 99
 			$name = $this->dbUser;
100 100
 			$password = $this->dbPassword;
101 101
 			// we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 			$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
106 106
 			$connection->executeUpdate($query);
107 107
 		}
108
-		catch (\Exception $ex){
108
+		catch (\Exception $ex) {
109 109
 			$this->logger->logException($ex, [
110 110
 				'message' => 'Database user creation failed.',
111 111
 				'level' => ILogger::ERROR,
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
 			//we don't have a dbuser specified in config
128 128
 			if ($this->dbUser !== $oldUser) {
129 129
 				//add prefix to the admin username to prevent collisions
130
-				$adminUser = substr('oc_' . $username, 0, 16);
130
+				$adminUser = substr('oc_'.$username, 0, 16);
131 131
 
132 132
 				$i = 1;
133 133
 				while (true) {
@@ -144,15 +144,15 @@  discard block
 block discarded – undo
144 144
 							$this->dbUser = $adminUser;
145 145
 
146 146
 							//create a random password so we don't need to store the admin password in the config file
147
-							$this->dbPassword =  $this->random->generate(30);
147
+							$this->dbPassword = $this->random->generate(30);
148 148
 
149 149
 							$this->createDBUser($connection);
150 150
 
151 151
 							break;
152 152
 						} else {
153 153
 							//repeat with different username
154
-							$length = strlen((string)$i);
155
-							$adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
154
+							$length = strlen((string) $i);
155
+							$adminUser = substr('oc_'.$username, 0, 16 - $length).$i;
156 156
 							$i++;
157 157
 						}
158 158
 					} else {
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -104,8 +104,7 @@
 block discarded – undo
104 104
 			$connection->executeUpdate($query);
105 105
 			$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
106 106
 			$connection->executeUpdate($query);
107
-		}
108
-		catch (\Exception $ex){
107
+		} catch (\Exception $ex){
109 108
 			$this->logger->logException($ex, [
110 109
 				'message' => 'Database user creation failed.',
111 110
 				'level' => ILogger::ERROR,
Please login to merge, or discard this patch.
lib/private/Preview/Bitmap.php 1 patch
Indentation   +81 added lines, -81 removed lines patch added patch discarded remove patch
@@ -35,86 +35,86 @@
 block discarded – undo
35 35
  */
36 36
 abstract class Bitmap extends Provider {
37 37
 
38
-	/**
39
-	 * {@inheritDoc}
40
-	 */
41
-	public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
42
-
43
-		$tmpPath = $fileview->toTmpFile($path);
44
-		if (!$tmpPath) {
45
-			return false;
46
-		}
47
-
48
-		// Creates \Imagick object from bitmap or vector file
49
-		try {
50
-			$bp = $this->getResizedPreview($tmpPath, $maxX, $maxY);
51
-		} catch (\Exception $e) {
52
-			\OC::$server->getLogger()->logException($e, [
53
-				'message' => 'Imagick says:',
54
-				'level' => ILogger::ERROR,
55
-				'app' => 'core',
56
-			]);
57
-			return false;
58
-		}
59
-
60
-		unlink($tmpPath);
61
-
62
-		//new bitmap image object
63
-		$image = new \OC_Image();
64
-		$image->loadFromData($bp);
65
-		//check if image object is valid
66
-		return $image->valid() ? $image : false;
67
-	}
68
-
69
-	/**
70
-	 * Returns a preview of maxX times maxY dimensions in PNG format
71
-	 *
72
-	 *    * The default resolution is already 72dpi, no need to change it for a bitmap output
73
-	 *    * It's possible to have proper colour conversion using profileimage().
74
-	 *    ICC profiles are here: http://www.color.org/srgbprofiles.xalter
75
-	 *    * It's possible to Gamma-correct an image via gammaImage()
76
-	 *
77
-	 * @param string $tmpPath the location of the file to convert
78
-	 * @param int $maxX
79
-	 * @param int $maxY
80
-	 *
81
-	 * @return \Imagick
82
-	 */
83
-	private function getResizedPreview($tmpPath, $maxX, $maxY) {
84
-		$bp = new Imagick();
85
-
86
-		// Layer 0 contains either the bitmap or a flat representation of all vector layers
87
-		$bp->readImage($tmpPath . '[0]');
88
-
89
-		$bp = $this->resize($bp, $maxX, $maxY);
90
-
91
-		$bp->setImageFormat('png');
92
-
93
-		return $bp;
94
-	}
95
-
96
-	/**
97
-	 * Returns a resized \Imagick object
98
-	 *
99
-	 * If you want to know more on the various methods available to resize an
100
-	 * image, check out this link : @link https://stackoverflow.com/questions/8517304/what-the-difference-of-sample-resample-scale-resize-adaptive-resize-thumbnail-im
101
-	 *
102
-	 * @param \Imagick $bp
103
-	 * @param int $maxX
104
-	 * @param int $maxY
105
-	 *
106
-	 * @return \Imagick
107
-	 */
108
-	private function resize($bp, $maxX, $maxY) {
109
-		list($previewWidth, $previewHeight) = array_values($bp->getImageGeometry());
110
-
111
-		// We only need to resize a preview which doesn't fit in the maximum dimensions
112
-		if ($previewWidth > $maxX || $previewHeight > $maxY) {
113
-			// TODO: LANCZOS is the default filter, CATROM could bring similar results faster
114
-			$bp->resizeImage($maxX, $maxY, imagick::FILTER_LANCZOS, 1, true);
115
-		}
116
-
117
-		return $bp;
118
-	}
38
+    /**
39
+     * {@inheritDoc}
40
+     */
41
+    public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
42
+
43
+        $tmpPath = $fileview->toTmpFile($path);
44
+        if (!$tmpPath) {
45
+            return false;
46
+        }
47
+
48
+        // Creates \Imagick object from bitmap or vector file
49
+        try {
50
+            $bp = $this->getResizedPreview($tmpPath, $maxX, $maxY);
51
+        } catch (\Exception $e) {
52
+            \OC::$server->getLogger()->logException($e, [
53
+                'message' => 'Imagick says:',
54
+                'level' => ILogger::ERROR,
55
+                'app' => 'core',
56
+            ]);
57
+            return false;
58
+        }
59
+
60
+        unlink($tmpPath);
61
+
62
+        //new bitmap image object
63
+        $image = new \OC_Image();
64
+        $image->loadFromData($bp);
65
+        //check if image object is valid
66
+        return $image->valid() ? $image : false;
67
+    }
68
+
69
+    /**
70
+     * Returns a preview of maxX times maxY dimensions in PNG format
71
+     *
72
+     *    * The default resolution is already 72dpi, no need to change it for a bitmap output
73
+     *    * It's possible to have proper colour conversion using profileimage().
74
+     *    ICC profiles are here: http://www.color.org/srgbprofiles.xalter
75
+     *    * It's possible to Gamma-correct an image via gammaImage()
76
+     *
77
+     * @param string $tmpPath the location of the file to convert
78
+     * @param int $maxX
79
+     * @param int $maxY
80
+     *
81
+     * @return \Imagick
82
+     */
83
+    private function getResizedPreview($tmpPath, $maxX, $maxY) {
84
+        $bp = new Imagick();
85
+
86
+        // Layer 0 contains either the bitmap or a flat representation of all vector layers
87
+        $bp->readImage($tmpPath . '[0]');
88
+
89
+        $bp = $this->resize($bp, $maxX, $maxY);
90
+
91
+        $bp->setImageFormat('png');
92
+
93
+        return $bp;
94
+    }
95
+
96
+    /**
97
+     * Returns a resized \Imagick object
98
+     *
99
+     * If you want to know more on the various methods available to resize an
100
+     * image, check out this link : @link https://stackoverflow.com/questions/8517304/what-the-difference-of-sample-resample-scale-resize-adaptive-resize-thumbnail-im
101
+     *
102
+     * @param \Imagick $bp
103
+     * @param int $maxX
104
+     * @param int $maxY
105
+     *
106
+     * @return \Imagick
107
+     */
108
+    private function resize($bp, $maxX, $maxY) {
109
+        list($previewWidth, $previewHeight) = array_values($bp->getImageGeometry());
110
+
111
+        // We only need to resize a preview which doesn't fit in the maximum dimensions
112
+        if ($previewWidth > $maxX || $previewHeight > $maxY) {
113
+            // TODO: LANCZOS is the default filter, CATROM could bring similar results faster
114
+            $bp->resizeImage($maxX, $maxY, imagick::FILTER_LANCZOS, 1, true);
115
+        }
116
+
117
+        return $bp;
118
+    }
119 119
 
120 120
 }
Please login to merge, or discard this patch.
lib/private/Preview/SVG.php 1 patch
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -27,50 +27,50 @@
 block discarded – undo
27 27
 use OCP\ILogger;
28 28
 
29 29
 class SVG extends Provider {
30
-	/**
31
-	 * {@inheritDoc}
32
-	 */
33
-	public function getMimeType() {
34
-		return '/image\/svg\+xml/';
35
-	}
30
+    /**
31
+     * {@inheritDoc}
32
+     */
33
+    public function getMimeType() {
34
+        return '/image\/svg\+xml/';
35
+    }
36 36
 
37
-	/**
38
-	 * {@inheritDoc}
39
-	 */
40
-	public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
41
-		try {
42
-			$svg = new \Imagick();
43
-			$svg->setBackgroundColor(new \ImagickPixel('transparent'));
37
+    /**
38
+     * {@inheritDoc}
39
+     */
40
+    public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
41
+        try {
42
+            $svg = new \Imagick();
43
+            $svg->setBackgroundColor(new \ImagickPixel('transparent'));
44 44
 
45
-			$content = stream_get_contents($fileview->fopen($path, 'r'));
46
-			if (substr($content, 0, 5) !== '<?xml') {
47
-				$content = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $content;
48
-			}
45
+            $content = stream_get_contents($fileview->fopen($path, 'r'));
46
+            if (substr($content, 0, 5) !== '<?xml') {
47
+                $content = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $content;
48
+            }
49 49
 
50
-			// Do not parse SVG files with references
51
-			if (stripos($content, 'xlink:href') !== false) {
52
-				return false;
53
-			}
50
+            // Do not parse SVG files with references
51
+            if (stripos($content, 'xlink:href') !== false) {
52
+                return false;
53
+            }
54 54
 
55
-			$svg->readImageBlob($content);
56
-			$svg->setImageFormat('png32');
57
-		} catch (\Exception $e) {
58
-			\OC::$server->getLogger()->logException($e, [
59
-				'level' => ILogger::ERROR,
60
-				'app' => 'core',
61
-			]);
62
-			return false;
63
-		}
55
+            $svg->readImageBlob($content);
56
+            $svg->setImageFormat('png32');
57
+        } catch (\Exception $e) {
58
+            \OC::$server->getLogger()->logException($e, [
59
+                'level' => ILogger::ERROR,
60
+                'app' => 'core',
61
+            ]);
62
+            return false;
63
+        }
64 64
 
65
-		//new image object
66
-		$image = new \OC_Image();
67
-		$image->loadFromData($svg);
68
-		//check if image object is valid
69
-		if ($image->valid()) {
70
-			$image->scaleDownToFit($maxX, $maxY);
65
+        //new image object
66
+        $image = new \OC_Image();
67
+        $image->loadFromData($svg);
68
+        //check if image object is valid
69
+        if ($image->valid()) {
70
+            $image->scaleDownToFit($maxX, $maxY);
71 71
 
72
-			return $image;
73
-		}
74
-		return false;
75
-	}
72
+            return $image;
73
+        }
74
+        return false;
75
+    }
76 76
 }
Please login to merge, or discard this patch.
lib/private/Preview/Office.php 1 patch
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -28,83 +28,83 @@
 block discarded – undo
28 28
 use OCP\ILogger;
29 29
 
30 30
 abstract class Office extends Provider {
31
-	private $cmd;
31
+    private $cmd;
32 32
 
33
-	/**
34
-	 * {@inheritDoc}
35
-	 */
36
-	public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
37
-		$this->initCmd();
38
-		if (is_null($this->cmd)) {
39
-			return false;
40
-		}
33
+    /**
34
+     * {@inheritDoc}
35
+     */
36
+    public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) {
37
+        $this->initCmd();
38
+        if (is_null($this->cmd)) {
39
+            return false;
40
+        }
41 41
 
42
-		$absPath = $fileview->toTmpFile($path);
42
+        $absPath = $fileview->toTmpFile($path);
43 43
 
44
-		$tmpDir = \OC::$server->getTempManager()->getTempBaseDir();
44
+        $tmpDir = \OC::$server->getTempManager()->getTempBaseDir();
45 45
 
46
-		$defaultParameters = ' -env:UserInstallation=file://' . escapeshellarg($tmpDir . '/owncloud-' . \OC_Util::getInstanceId() . '/') . ' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to pdf --outdir ';
47
-		$clParameters = \OC::$server->getConfig()->getSystemValue('preview_office_cl_parameters', $defaultParameters);
46
+        $defaultParameters = ' -env:UserInstallation=file://' . escapeshellarg($tmpDir . '/owncloud-' . \OC_Util::getInstanceId() . '/') . ' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to pdf --outdir ';
47
+        $clParameters = \OC::$server->getConfig()->getSystemValue('preview_office_cl_parameters', $defaultParameters);
48 48
 
49
-		$exec = $this->cmd . $clParameters . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath);
49
+        $exec = $this->cmd . $clParameters . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath);
50 50
 
51
-		shell_exec($exec);
51
+        shell_exec($exec);
52 52
 
53
-		//create imagick object from pdf
54
-		$pdfPreview = null;
55
-		try {
56
-			list($dirname, , , $filename) = array_values(pathinfo($absPath));
57
-			$pdfPreview = $dirname . '/' . $filename . '.pdf';
53
+        //create imagick object from pdf
54
+        $pdfPreview = null;
55
+        try {
56
+            list($dirname, , , $filename) = array_values(pathinfo($absPath));
57
+            $pdfPreview = $dirname . '/' . $filename . '.pdf';
58 58
 
59
-			$pdf = new \imagick($pdfPreview . '[0]');
60
-			$pdf->setImageFormat('jpg');
61
-		} catch (\Exception $e) {
62
-			unlink($absPath);
63
-			unlink($pdfPreview);
64
-			\OC::$server->getLogger()->logException($e, [
65
-				'level' => ILogger::ERROR,
66
-				'app' => 'core',
67
-			]);
68
-			return false;
69
-		}
59
+            $pdf = new \imagick($pdfPreview . '[0]');
60
+            $pdf->setImageFormat('jpg');
61
+        } catch (\Exception $e) {
62
+            unlink($absPath);
63
+            unlink($pdfPreview);
64
+            \OC::$server->getLogger()->logException($e, [
65
+                'level' => ILogger::ERROR,
66
+                'app' => 'core',
67
+            ]);
68
+            return false;
69
+        }
70 70
 
71
-		$image = new \OC_Image();
72
-		$image->loadFromData($pdf);
71
+        $image = new \OC_Image();
72
+        $image->loadFromData($pdf);
73 73
 
74
-		unlink($absPath);
75
-		unlink($pdfPreview);
74
+        unlink($absPath);
75
+        unlink($pdfPreview);
76 76
 
77
-		if ($image->valid()) {
78
-			$image->scaleDownToFit($maxX, $maxY);
77
+        if ($image->valid()) {
78
+            $image->scaleDownToFit($maxX, $maxY);
79 79
 
80
-			return $image;
81
-		}
82
-		return false;
80
+            return $image;
81
+        }
82
+        return false;
83 83
 
84
-	}
84
+    }
85 85
 
86
-	private function initCmd() {
87
-		$cmd = '';
86
+    private function initCmd() {
87
+        $cmd = '';
88 88
 
89
-		$libreOfficePath = \OC::$server->getConfig()->getSystemValue('preview_libreoffice_path', null);
90
-		if (is_string($libreOfficePath)) {
91
-			$cmd = $libreOfficePath;
92
-		}
89
+        $libreOfficePath = \OC::$server->getConfig()->getSystemValue('preview_libreoffice_path', null);
90
+        if (is_string($libreOfficePath)) {
91
+            $cmd = $libreOfficePath;
92
+        }
93 93
 
94
-		$whichLibreOffice = shell_exec('command -v libreoffice');
95
-		if ($cmd === '' && !empty($whichLibreOffice)) {
96
-			$cmd = 'libreoffice';
97
-		}
94
+        $whichLibreOffice = shell_exec('command -v libreoffice');
95
+        if ($cmd === '' && !empty($whichLibreOffice)) {
96
+            $cmd = 'libreoffice';
97
+        }
98 98
 
99
-		$whichOpenOffice = shell_exec('command -v openoffice');
100
-		if ($cmd === '' && !empty($whichOpenOffice)) {
101
-			$cmd = 'openoffice';
102
-		}
99
+        $whichOpenOffice = shell_exec('command -v openoffice');
100
+        if ($cmd === '' && !empty($whichOpenOffice)) {
101
+            $cmd = 'openoffice';
102
+        }
103 103
 
104
-		if ($cmd === '') {
105
-			$cmd = null;
106
-		}
104
+        if ($cmd === '') {
105
+            $cmd = null;
106
+        }
107 107
 
108
-		$this->cmd = $cmd;
109
-	}
108
+        $this->cmd = $cmd;
109
+    }
110 110
 }
Please login to merge, or discard this patch.
lib/private/legacy/app.php 2 patches
Indentation   +1034 added lines, -1034 removed lines patch added patch discarded remove patch
@@ -64,1038 +64,1038 @@
 block discarded – undo
64 64
  * upgrading and removing apps.
65 65
  */
66 66
 class OC_App {
67
-	static private $adminForms = [];
68
-	static private $personalForms = [];
69
-	static private $appTypes = [];
70
-	static private $loadedApps = [];
71
-	static private $altLogin = [];
72
-	static private $alreadyRegistered = [];
73
-	const officialApp = 200;
74
-
75
-	/**
76
-	 * clean the appId
77
-	 *
78
-	 * @param string $app AppId that needs to be cleaned
79
-	 * @return string
80
-	 */
81
-	public static function cleanAppId(string $app): string {
82
-		return str_replace(array('\0', '/', '\\', '..'), '', $app);
83
-	}
84
-
85
-	/**
86
-	 * Check if an app is loaded
87
-	 *
88
-	 * @param string $app
89
-	 * @return bool
90
-	 */
91
-	public static function isAppLoaded(string $app): bool {
92
-		return in_array($app, self::$loadedApps, true);
93
-	}
94
-
95
-	/**
96
-	 * loads all apps
97
-	 *
98
-	 * @param string[] $types
99
-	 * @return bool
100
-	 *
101
-	 * This function walks through the ownCloud directory and loads all apps
102
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
103
-	 * exists.
104
-	 *
105
-	 * if $types is set to non-empty array, only apps of those types will be loaded
106
-	 */
107
-	public static function loadApps(array $types = []): bool {
108
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
109
-			return false;
110
-		}
111
-		// Load the enabled apps here
112
-		$apps = self::getEnabledApps();
113
-
114
-		// Add each apps' folder as allowed class path
115
-		foreach($apps as $app) {
116
-			$path = self::getAppPath($app);
117
-			if($path !== false) {
118
-				self::registerAutoloading($app, $path);
119
-			}
120
-		}
121
-
122
-		// prevent app.php from printing output
123
-		ob_start();
124
-		foreach ($apps as $app) {
125
-			if (($types === [] or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
126
-				self::loadApp($app);
127
-			}
128
-		}
129
-		ob_end_clean();
130
-
131
-		return true;
132
-	}
133
-
134
-	/**
135
-	 * load a single app
136
-	 *
137
-	 * @param string $app
138
-	 * @throws Exception
139
-	 */
140
-	public static function loadApp(string $app) {
141
-		self::$loadedApps[] = $app;
142
-		$appPath = self::getAppPath($app);
143
-		if($appPath === false) {
144
-			return;
145
-		}
146
-
147
-		// in case someone calls loadApp() directly
148
-		self::registerAutoloading($app, $appPath);
149
-
150
-		if (is_file($appPath . '/appinfo/app.php')) {
151
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
152
-			try {
153
-				self::requireAppFile($app);
154
-			} catch (Error $ex) {
155
-				\OC::$server->getLogger()->logException($ex);
156
-				if (!\OC::$server->getAppManager()->isShipped($app)) {
157
-					// Only disable apps which are not shipped
158
-					\OC::$server->getAppManager()->disableApp($app);
159
-				}
160
-			}
161
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
162
-		}
163
-
164
-		$info = self::getAppInfo($app);
165
-		if (!empty($info['activity']['filters'])) {
166
-			foreach ($info['activity']['filters'] as $filter) {
167
-				\OC::$server->getActivityManager()->registerFilter($filter);
168
-			}
169
-		}
170
-		if (!empty($info['activity']['settings'])) {
171
-			foreach ($info['activity']['settings'] as $setting) {
172
-				\OC::$server->getActivityManager()->registerSetting($setting);
173
-			}
174
-		}
175
-		if (!empty($info['activity']['providers'])) {
176
-			foreach ($info['activity']['providers'] as $provider) {
177
-				\OC::$server->getActivityManager()->registerProvider($provider);
178
-			}
179
-		}
180
-
181
-		if (!empty($info['settings']['admin'])) {
182
-			foreach ($info['settings']['admin'] as $setting) {
183
-				\OC::$server->getSettingsManager()->registerSetting('admin', $setting);
184
-			}
185
-		}
186
-		if (!empty($info['settings']['admin-section'])) {
187
-			foreach ($info['settings']['admin-section'] as $section) {
188
-				\OC::$server->getSettingsManager()->registerSection('admin', $section);
189
-			}
190
-		}
191
-		if (!empty($info['settings']['personal'])) {
192
-			foreach ($info['settings']['personal'] as $setting) {
193
-				\OC::$server->getSettingsManager()->registerSetting('personal', $setting);
194
-			}
195
-		}
196
-		if (!empty($info['settings']['personal-section'])) {
197
-			foreach ($info['settings']['personal-section'] as $section) {
198
-				\OC::$server->getSettingsManager()->registerSection('personal', $section);
199
-			}
200
-		}
201
-
202
-		if (!empty($info['collaboration']['plugins'])) {
203
-			// deal with one or many plugin entries
204
-			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
205
-				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
206
-			foreach ($plugins as $plugin) {
207
-				if($plugin['@attributes']['type'] === 'collaborator-search') {
208
-					$pluginInfo = [
209
-						'shareType' => $plugin['@attributes']['share-type'],
210
-						'class' => $plugin['@value'],
211
-					];
212
-					\OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
213
-				} else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
214
-					\OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
215
-				}
216
-			}
217
-		}
218
-	}
219
-
220
-	/**
221
-	 * @internal
222
-	 * @param string $app
223
-	 * @param string $path
224
-	 */
225
-	public static function registerAutoloading(string $app, string $path) {
226
-		$key = $app . '-' . $path;
227
-		if(isset(self::$alreadyRegistered[$key])) {
228
-			return;
229
-		}
230
-
231
-		self::$alreadyRegistered[$key] = true;
232
-
233
-		// Register on PSR-4 composer autoloader
234
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
235
-		\OC::$server->registerNamespace($app, $appNamespace);
236
-
237
-		if (file_exists($path . '/composer/autoload.php')) {
238
-			require_once $path . '/composer/autoload.php';
239
-		} else {
240
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
241
-			// Register on legacy autoloader
242
-			\OC::$loader->addValidRoot($path);
243
-		}
244
-
245
-		// Register Test namespace only when testing
246
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
247
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
248
-		}
249
-	}
250
-
251
-	/**
252
-	 * Load app.php from the given app
253
-	 *
254
-	 * @param string $app app name
255
-	 * @throws Error
256
-	 */
257
-	private static function requireAppFile(string $app) {
258
-		// encapsulated here to avoid variable scope conflicts
259
-		require_once $app . '/appinfo/app.php';
260
-	}
261
-
262
-	/**
263
-	 * check if an app is of a specific type
264
-	 *
265
-	 * @param string $app
266
-	 * @param array $types
267
-	 * @return bool
268
-	 */
269
-	public static function isType(string $app, array $types): bool {
270
-		$appTypes = self::getAppTypes($app);
271
-		foreach ($types as $type) {
272
-			if (array_search($type, $appTypes) !== false) {
273
-				return true;
274
-			}
275
-		}
276
-		return false;
277
-	}
278
-
279
-	/**
280
-	 * get the types of an app
281
-	 *
282
-	 * @param string $app
283
-	 * @return array
284
-	 */
285
-	private static function getAppTypes(string $app): array {
286
-		//load the cache
287
-		if (count(self::$appTypes) == 0) {
288
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
289
-		}
290
-
291
-		if (isset(self::$appTypes[$app])) {
292
-			return explode(',', self::$appTypes[$app]);
293
-		}
294
-
295
-		return [];
296
-	}
297
-
298
-	/**
299
-	 * read app types from info.xml and cache them in the database
300
-	 */
301
-	public static function setAppTypes(string $app) {
302
-		$appManager = \OC::$server->getAppManager();
303
-		$appData = $appManager->getAppInfo($app);
304
-		if(!is_array($appData)) {
305
-			return;
306
-		}
307
-
308
-		if (isset($appData['types'])) {
309
-			$appTypes = implode(',', $appData['types']);
310
-		} else {
311
-			$appTypes = '';
312
-			$appData['types'] = [];
313
-		}
314
-
315
-		$config = \OC::$server->getConfig();
316
-		$config->setAppValue($app, 'types', $appTypes);
317
-
318
-		if ($appManager->hasProtectedAppType($appData['types'])) {
319
-			$enabled = $config->getAppValue($app, 'enabled', 'yes');
320
-			if ($enabled !== 'yes' && $enabled !== 'no') {
321
-				$config->setAppValue($app, 'enabled', 'yes');
322
-			}
323
-		}
324
-	}
325
-
326
-	/**
327
-	 * Returns apps enabled for the current user.
328
-	 *
329
-	 * @param bool $forceRefresh whether to refresh the cache
330
-	 * @param bool $all whether to return apps for all users, not only the
331
-	 * currently logged in one
332
-	 * @return string[]
333
-	 */
334
-	public static function getEnabledApps(bool $forceRefresh = false, bool $all = false): array {
335
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
336
-			return [];
337
-		}
338
-		// in incognito mode or when logged out, $user will be false,
339
-		// which is also the case during an upgrade
340
-		$appManager = \OC::$server->getAppManager();
341
-		if ($all) {
342
-			$user = null;
343
-		} else {
344
-			$user = \OC::$server->getUserSession()->getUser();
345
-		}
346
-
347
-		if (is_null($user)) {
348
-			$apps = $appManager->getInstalledApps();
349
-		} else {
350
-			$apps = $appManager->getEnabledAppsForUser($user);
351
-		}
352
-		$apps = array_filter($apps, function ($app) {
353
-			return $app !== 'files';//we add this manually
354
-		});
355
-		sort($apps);
356
-		array_unshift($apps, 'files');
357
-		return $apps;
358
-	}
359
-
360
-	/**
361
-	 * checks whether or not an app is enabled
362
-	 *
363
-	 * @param string $app app
364
-	 * @return bool
365
-	 * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
366
-	 *
367
-	 * This function checks whether or not an app is enabled.
368
-	 */
369
-	public static function isEnabled(string $app): bool {
370
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
371
-	}
372
-
373
-	/**
374
-	 * enables an app
375
-	 *
376
-	 * @param string $appId
377
-	 * @param array $groups (optional) when set, only these groups will have access to the app
378
-	 * @throws \Exception
379
-	 * @return void
380
-	 *
381
-	 * This function set an app as enabled in appconfig.
382
-	 */
383
-	public function enable(string $appId,
384
-						   array $groups = []) {
385
-
386
-		// Check if app is already downloaded
387
-		/** @var Installer $installer */
388
-		$installer = \OC::$server->query(Installer::class);
389
-		$isDownloaded = $installer->isDownloaded($appId);
390
-
391
-		if(!$isDownloaded) {
392
-			$installer->downloadApp($appId);
393
-		}
394
-
395
-		$installer->installApp($appId);
396
-
397
-		$appManager = \OC::$server->getAppManager();
398
-		if ($groups !== []) {
399
-			$groupManager = \OC::$server->getGroupManager();
400
-			$groupsList = [];
401
-			foreach ($groups as $group) {
402
-				$groupItem = $groupManager->get($group);
403
-				if ($groupItem instanceof \OCP\IGroup) {
404
-					$groupsList[] = $groupManager->get($group);
405
-				}
406
-			}
407
-			$appManager->enableAppForGroups($appId, $groupsList);
408
-		} else {
409
-			$appManager->enableApp($appId);
410
-		}
411
-	}
412
-
413
-	/**
414
-	 * Get the path where to install apps
415
-	 *
416
-	 * @return string|false
417
-	 */
418
-	public static function getInstallPath() {
419
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
420
-			return false;
421
-		}
422
-
423
-		foreach (OC::$APPSROOTS as $dir) {
424
-			if (isset($dir['writable']) && $dir['writable'] === true) {
425
-				return $dir['path'];
426
-			}
427
-		}
428
-
429
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', ILogger::ERROR);
430
-		return null;
431
-	}
432
-
433
-
434
-	/**
435
-	 * search for an app in all app-directories
436
-	 *
437
-	 * @param string $appId
438
-	 * @return false|string
439
-	 */
440
-	public static function findAppInDirectories(string $appId) {
441
-		$sanitizedAppId = self::cleanAppId($appId);
442
-		if($sanitizedAppId !== $appId) {
443
-			return false;
444
-		}
445
-		static $app_dir = [];
446
-
447
-		if (isset($app_dir[$appId])) {
448
-			return $app_dir[$appId];
449
-		}
450
-
451
-		$possibleApps = [];
452
-		foreach (OC::$APPSROOTS as $dir) {
453
-			if (file_exists($dir['path'] . '/' . $appId)) {
454
-				$possibleApps[] = $dir;
455
-			}
456
-		}
457
-
458
-		if (empty($possibleApps)) {
459
-			return false;
460
-		} elseif (count($possibleApps) === 1) {
461
-			$dir = array_shift($possibleApps);
462
-			$app_dir[$appId] = $dir;
463
-			return $dir;
464
-		} else {
465
-			$versionToLoad = [];
466
-			foreach ($possibleApps as $possibleApp) {
467
-				$version = self::getAppVersionByPath($possibleApp['path']);
468
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
469
-					$versionToLoad = array(
470
-						'dir' => $possibleApp,
471
-						'version' => $version,
472
-					);
473
-				}
474
-			}
475
-			$app_dir[$appId] = $versionToLoad['dir'];
476
-			return $versionToLoad['dir'];
477
-			//TODO - write test
478
-		}
479
-	}
480
-
481
-	/**
482
-	 * Get the directory for the given app.
483
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
484
-	 *
485
-	 * @param string $appId
486
-	 * @return string|false
487
-	 */
488
-	public static function getAppPath(string $appId) {
489
-		if ($appId === null || trim($appId) === '') {
490
-			return false;
491
-		}
492
-
493
-		if (($dir = self::findAppInDirectories($appId)) != false) {
494
-			return $dir['path'] . '/' . $appId;
495
-		}
496
-		return false;
497
-	}
498
-
499
-	/**
500
-	 * Get the path for the given app on the access
501
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
502
-	 *
503
-	 * @param string $appId
504
-	 * @return string|false
505
-	 */
506
-	public static function getAppWebPath(string $appId) {
507
-		if (($dir = self::findAppInDirectories($appId)) != false) {
508
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
509
-		}
510
-		return false;
511
-	}
512
-
513
-	/**
514
-	 * get the last version of the app from appinfo/info.xml
515
-	 *
516
-	 * @param string $appId
517
-	 * @param bool $useCache
518
-	 * @return string
519
-	 * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion()
520
-	 */
521
-	public static function getAppVersion(string $appId, bool $useCache = true): string {
522
-		return \OC::$server->getAppManager()->getAppVersion($appId, $useCache);
523
-	}
524
-
525
-	/**
526
-	 * get app's version based on it's path
527
-	 *
528
-	 * @param string $path
529
-	 * @return string
530
-	 */
531
-	public static function getAppVersionByPath(string $path): string {
532
-		$infoFile = $path . '/appinfo/info.xml';
533
-		$appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
534
-		return isset($appData['version']) ? $appData['version'] : '';
535
-	}
536
-
537
-
538
-	/**
539
-	 * Read all app metadata from the info.xml file
540
-	 *
541
-	 * @param string $appId id of the app or the path of the info.xml file
542
-	 * @param bool $path
543
-	 * @param string $lang
544
-	 * @return array|null
545
-	 * @note all data is read from info.xml, not just pre-defined fields
546
-	 * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppInfo()
547
-	 */
548
-	public static function getAppInfo(string $appId, bool $path = false, string $lang = null) {
549
-		return \OC::$server->getAppManager()->getAppInfo($appId, $path, $lang);
550
-	}
551
-
552
-	/**
553
-	 * Returns the navigation
554
-	 *
555
-	 * @return array
556
-	 * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll()
557
-	 *
558
-	 * This function returns an array containing all entries added. The
559
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
560
-	 * given for each app the following keys exist:
561
-	 *   - active: boolean, signals if the user is on this navigation entry
562
-	 */
563
-	public static function getNavigation(): array {
564
-		return OC::$server->getNavigationManager()->getAll();
565
-	}
566
-
567
-	/**
568
-	 * Returns the Settings Navigation
569
-	 *
570
-	 * @return string[]
571
-	 * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll('settings')
572
-	 *
573
-	 * This function returns an array containing all settings pages added. The
574
-	 * entries are sorted by the key 'order' ascending.
575
-	 */
576
-	public static function getSettingsNavigation(): array {
577
-		return OC::$server->getNavigationManager()->getAll('settings');
578
-	}
579
-
580
-	/**
581
-	 * get the id of loaded app
582
-	 *
583
-	 * @return string
584
-	 */
585
-	public static function getCurrentApp(): string {
586
-		$request = \OC::$server->getRequest();
587
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
588
-		$topFolder = substr($script, 0, strpos($script, '/') ?: 0);
589
-		if (empty($topFolder)) {
590
-			$path_info = $request->getPathInfo();
591
-			if ($path_info) {
592
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
593
-			}
594
-		}
595
-		if ($topFolder == 'apps') {
596
-			$length = strlen($topFolder);
597
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1) ?: '';
598
-		} else {
599
-			return $topFolder;
600
-		}
601
-	}
602
-
603
-	/**
604
-	 * @param string $type
605
-	 * @return array
606
-	 */
607
-	public static function getForms(string $type): array {
608
-		$forms = [];
609
-		switch ($type) {
610
-			case 'admin':
611
-				$source = self::$adminForms;
612
-				break;
613
-			case 'personal':
614
-				$source = self::$personalForms;
615
-				break;
616
-			default:
617
-				return [];
618
-		}
619
-		foreach ($source as $form) {
620
-			$forms[] = include $form;
621
-		}
622
-		return $forms;
623
-	}
624
-
625
-	/**
626
-	 * register an admin form to be shown
627
-	 *
628
-	 * @param string $app
629
-	 * @param string $page
630
-	 */
631
-	public static function registerAdmin(string $app, string $page) {
632
-		self::$adminForms[] = $app . '/' . $page . '.php';
633
-	}
634
-
635
-	/**
636
-	 * register a personal form to be shown
637
-	 * @param string $app
638
-	 * @param string $page
639
-	 */
640
-	public static function registerPersonal(string $app, string $page) {
641
-		self::$personalForms[] = $app . '/' . $page . '.php';
642
-	}
643
-
644
-	/**
645
-	 * @param array $entry
646
-	 */
647
-	public static function registerLogIn(array $entry) {
648
-		self::$altLogin[] = $entry;
649
-	}
650
-
651
-	/**
652
-	 * @return array
653
-	 */
654
-	public static function getAlternativeLogIns(): array {
655
-		return self::$altLogin;
656
-	}
657
-
658
-	/**
659
-	 * get a list of all apps in the apps folder
660
-	 *
661
-	 * @return array an array of app names (string IDs)
662
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
663
-	 */
664
-	public static function getAllApps(): array {
665
-
666
-		$apps = [];
667
-
668
-		foreach (OC::$APPSROOTS as $apps_dir) {
669
-			if (!is_readable($apps_dir['path'])) {
670
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], ILogger::WARN);
671
-				continue;
672
-			}
673
-			$dh = opendir($apps_dir['path']);
674
-
675
-			if (is_resource($dh)) {
676
-				while (($file = readdir($dh)) !== false) {
677
-
678
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
679
-
680
-						$apps[] = $file;
681
-					}
682
-				}
683
-			}
684
-		}
685
-
686
-		$apps = array_unique($apps);
687
-
688
-		return $apps;
689
-	}
690
-
691
-	/**
692
-	 * List all apps, this is used in apps.php
693
-	 *
694
-	 * @return array
695
-	 */
696
-	public function listAllApps(): array {
697
-		$installedApps = OC_App::getAllApps();
698
-
699
-		$appManager = \OC::$server->getAppManager();
700
-		//we don't want to show configuration for these
701
-		$blacklist = $appManager->getAlwaysEnabledApps();
702
-		$appList = [];
703
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
704
-		$urlGenerator = \OC::$server->getURLGenerator();
705
-
706
-		foreach ($installedApps as $app) {
707
-			if (array_search($app, $blacklist) === false) {
708
-
709
-				$info = OC_App::getAppInfo($app, false, $langCode);
710
-				if (!is_array($info)) {
711
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR);
712
-					continue;
713
-				}
714
-
715
-				if (!isset($info['name'])) {
716
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', ILogger::ERROR);
717
-					continue;
718
-				}
719
-
720
-				$enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
721
-				$info['groups'] = null;
722
-				if ($enabled === 'yes') {
723
-					$active = true;
724
-				} else if ($enabled === 'no') {
725
-					$active = false;
726
-				} else {
727
-					$active = true;
728
-					$info['groups'] = $enabled;
729
-				}
730
-
731
-				$info['active'] = $active;
732
-
733
-				if ($appManager->isShipped($app)) {
734
-					$info['internal'] = true;
735
-					$info['level'] = self::officialApp;
736
-					$info['removable'] = false;
737
-				} else {
738
-					$info['internal'] = false;
739
-					$info['removable'] = true;
740
-				}
741
-
742
-				$appPath = self::getAppPath($app);
743
-				if($appPath !== false) {
744
-					$appIcon = $appPath . '/img/' . $app . '.svg';
745
-					if (file_exists($appIcon)) {
746
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
747
-						$info['previewAsIcon'] = true;
748
-					} else {
749
-						$appIcon = $appPath . '/img/app.svg';
750
-						if (file_exists($appIcon)) {
751
-							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
752
-							$info['previewAsIcon'] = true;
753
-						}
754
-					}
755
-				}
756
-				// fix documentation
757
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
758
-					foreach ($info['documentation'] as $key => $url) {
759
-						// If it is not an absolute URL we assume it is a key
760
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
761
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
762
-							$url = $urlGenerator->linkToDocs($url);
763
-						}
764
-
765
-						$info['documentation'][$key] = $url;
766
-					}
767
-				}
768
-
769
-				$info['version'] = OC_App::getAppVersion($app);
770
-				$appList[] = $info;
771
-			}
772
-		}
773
-
774
-		return $appList;
775
-	}
776
-
777
-	public static function shouldUpgrade(string $app): bool {
778
-		$versions = self::getAppVersions();
779
-		$currentVersion = OC_App::getAppVersion($app);
780
-		if ($currentVersion && isset($versions[$app])) {
781
-			$installedVersion = $versions[$app];
782
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
783
-				return true;
784
-			}
785
-		}
786
-		return false;
787
-	}
788
-
789
-	/**
790
-	 * Adjust the number of version parts of $version1 to match
791
-	 * the number of version parts of $version2.
792
-	 *
793
-	 * @param string $version1 version to adjust
794
-	 * @param string $version2 version to take the number of parts from
795
-	 * @return string shortened $version1
796
-	 */
797
-	private static function adjustVersionParts(string $version1, string $version2): string {
798
-		$version1 = explode('.', $version1);
799
-		$version2 = explode('.', $version2);
800
-		// reduce $version1 to match the number of parts in $version2
801
-		while (count($version1) > count($version2)) {
802
-			array_pop($version1);
803
-		}
804
-		// if $version1 does not have enough parts, add some
805
-		while (count($version1) < count($version2)) {
806
-			$version1[] = '0';
807
-		}
808
-		return implode('.', $version1);
809
-	}
810
-
811
-	/**
812
-	 * Check whether the current ownCloud version matches the given
813
-	 * application's version requirements.
814
-	 *
815
-	 * The comparison is made based on the number of parts that the
816
-	 * app info version has. For example for ownCloud 6.0.3 if the
817
-	 * app info version is expecting version 6.0, the comparison is
818
-	 * made on the first two parts of the ownCloud version.
819
-	 * This means that it's possible to specify "requiremin" => 6
820
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
821
-	 *
822
-	 * @param string $ocVersion ownCloud version to check against
823
-	 * @param array $appInfo app info (from xml)
824
-	 *
825
-	 * @return boolean true if compatible, otherwise false
826
-	 */
827
-	public static function isAppCompatible(string $ocVersion, array $appInfo): bool {
828
-		$requireMin = '';
829
-		$requireMax = '';
830
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
831
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
832
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
833
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
834
-		} else if (isset($appInfo['requiremin'])) {
835
-			$requireMin = $appInfo['requiremin'];
836
-		} else if (isset($appInfo['require'])) {
837
-			$requireMin = $appInfo['require'];
838
-		}
839
-
840
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
841
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
842
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
843
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
844
-		} else if (isset($appInfo['requiremax'])) {
845
-			$requireMax = $appInfo['requiremax'];
846
-		}
847
-
848
-		if (!empty($requireMin)
849
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
850
-		) {
851
-
852
-			return false;
853
-		}
854
-
855
-		if (!empty($requireMax)
856
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
857
-		) {
858
-			return false;
859
-		}
860
-
861
-		return true;
862
-	}
863
-
864
-	/**
865
-	 * get the installed version of all apps
866
-	 */
867
-	public static function getAppVersions() {
868
-		static $versions;
869
-
870
-		if(!$versions) {
871
-			$appConfig = \OC::$server->getAppConfig();
872
-			$versions = $appConfig->getValues(false, 'installed_version');
873
-		}
874
-		return $versions;
875
-	}
876
-
877
-	/**
878
-	 * update the database for the app and call the update script
879
-	 *
880
-	 * @param string $appId
881
-	 * @return bool
882
-	 */
883
-	public static function updateApp(string $appId): bool {
884
-		$appPath = self::getAppPath($appId);
885
-		if($appPath === false) {
886
-			return false;
887
-		}
888
-		self::registerAutoloading($appId, $appPath);
889
-
890
-		$appData = self::getAppInfo($appId);
891
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
892
-
893
-		if (file_exists($appPath . '/appinfo/database.xml')) {
894
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
895
-		} else {
896
-			$ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
897
-			$ms->migrate();
898
-		}
899
-
900
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
901
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
902
-		// update appversion in app manager
903
-		\OC::$server->getAppManager()->getAppVersion($appId, false);
904
-
905
-		// run upgrade code
906
-		if (file_exists($appPath . '/appinfo/update.php')) {
907
-			self::loadApp($appId);
908
-			include $appPath . '/appinfo/update.php';
909
-		}
910
-		self::setupBackgroundJobs($appData['background-jobs']);
911
-
912
-		//set remote/public handlers
913
-		if (array_key_exists('ocsid', $appData)) {
914
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
915
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
916
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
917
-		}
918
-		foreach ($appData['remote'] as $name => $path) {
919
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
920
-		}
921
-		foreach ($appData['public'] as $name => $path) {
922
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
923
-		}
924
-
925
-		self::setAppTypes($appId);
926
-
927
-		$version = \OC_App::getAppVersion($appId);
928
-		\OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
929
-
930
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
931
-			ManagerEvent::EVENT_APP_UPDATE, $appId
932
-		));
933
-
934
-		return true;
935
-	}
936
-
937
-	/**
938
-	 * @param string $appId
939
-	 * @param string[] $steps
940
-	 * @throws \OC\NeedsUpdateException
941
-	 */
942
-	public static function executeRepairSteps(string $appId, array $steps) {
943
-		if (empty($steps)) {
944
-			return;
945
-		}
946
-		// load the app
947
-		self::loadApp($appId);
948
-
949
-		$dispatcher = OC::$server->getEventDispatcher();
950
-
951
-		// load the steps
952
-		$r = new Repair([], $dispatcher);
953
-		foreach ($steps as $step) {
954
-			try {
955
-				$r->addStep($step);
956
-			} catch (Exception $ex) {
957
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
958
-				\OC::$server->getLogger()->logException($ex);
959
-			}
960
-		}
961
-		// run the steps
962
-		$r->run();
963
-	}
964
-
965
-	public static function setupBackgroundJobs(array $jobs) {
966
-		$queue = \OC::$server->getJobList();
967
-		foreach ($jobs as $job) {
968
-			$queue->add($job);
969
-		}
970
-	}
971
-
972
-	/**
973
-	 * @param string $appId
974
-	 * @param string[] $steps
975
-	 */
976
-	private static function setupLiveMigrations(string $appId, array $steps) {
977
-		$queue = \OC::$server->getJobList();
978
-		foreach ($steps as $step) {
979
-			$queue->add('OC\Migration\BackgroundRepair', [
980
-				'app' => $appId,
981
-				'step' => $step]);
982
-		}
983
-	}
984
-
985
-	/**
986
-	 * @param string $appId
987
-	 * @return \OC\Files\View|false
988
-	 */
989
-	public static function getStorage(string $appId) {
990
-		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
991
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
992
-				$view = new \OC\Files\View('/' . OC_User::getUser());
993
-				if (!$view->file_exists($appId)) {
994
-					$view->mkdir($appId);
995
-				}
996
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
997
-			} else {
998
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', ILogger::ERROR);
999
-				return false;
1000
-			}
1001
-		} else {
1002
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', ILogger::ERROR);
1003
-			return false;
1004
-		}
1005
-	}
1006
-
1007
-	protected static function findBestL10NOption(array $options, string $lang): string {
1008
-		// only a single option
1009
-		if (isset($options['@value'])) {
1010
-			return $options['@value'];
1011
-		}
1012
-
1013
-		$fallback = $similarLangFallback = $englishFallback = false;
1014
-
1015
-		$lang = strtolower($lang);
1016
-		$similarLang = $lang;
1017
-		if (strpos($similarLang, '_')) {
1018
-			// For "de_DE" we want to find "de" and the other way around
1019
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1020
-		}
1021
-
1022
-		foreach ($options as $option) {
1023
-			if (is_array($option)) {
1024
-				if ($fallback === false) {
1025
-					$fallback = $option['@value'];
1026
-				}
1027
-
1028
-				if (!isset($option['@attributes']['lang'])) {
1029
-					continue;
1030
-				}
1031
-
1032
-				$attributeLang = strtolower($option['@attributes']['lang']);
1033
-				if ($attributeLang === $lang) {
1034
-					return $option['@value'];
1035
-				}
1036
-
1037
-				if ($attributeLang === $similarLang) {
1038
-					$similarLangFallback = $option['@value'];
1039
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1040
-					if ($similarLangFallback === false) {
1041
-						$similarLangFallback =  $option['@value'];
1042
-					}
1043
-				}
1044
-			} else {
1045
-				$englishFallback = $option;
1046
-			}
1047
-		}
1048
-
1049
-		if ($similarLangFallback !== false) {
1050
-			return $similarLangFallback;
1051
-		} else if ($englishFallback !== false) {
1052
-			return $englishFallback;
1053
-		}
1054
-		return (string) $fallback;
1055
-	}
1056
-
1057
-	/**
1058
-	 * parses the app data array and enhanced the 'description' value
1059
-	 *
1060
-	 * @param array $data the app data
1061
-	 * @param string $lang
1062
-	 * @return array improved app data
1063
-	 */
1064
-	public static function parseAppInfo(array $data, $lang = null): array {
1065
-
1066
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1067
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1068
-		}
1069
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1070
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1071
-		}
1072
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1073
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1074
-		} else if (isset($data['description']) && is_string($data['description'])) {
1075
-			$data['description'] = trim($data['description']);
1076
-		} else  {
1077
-			$data['description'] = '';
1078
-		}
1079
-
1080
-		return $data;
1081
-	}
1082
-
1083
-	/**
1084
-	 * @param \OCP\IConfig $config
1085
-	 * @param \OCP\IL10N $l
1086
-	 * @param array $info
1087
-	 * @throws \Exception
1088
-	 */
1089
-	public static function checkAppDependencies(\OCP\IConfig $config, \OCP\IL10N $l, array $info) {
1090
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1091
-		$missing = $dependencyAnalyzer->analyze($info);
1092
-		if (!empty($missing)) {
1093
-			$missingMsg = implode(PHP_EOL, $missing);
1094
-			throw new \Exception(
1095
-				$l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1096
-					[$info['name'], $missingMsg]
1097
-				)
1098
-			);
1099
-		}
1100
-	}
67
+    static private $adminForms = [];
68
+    static private $personalForms = [];
69
+    static private $appTypes = [];
70
+    static private $loadedApps = [];
71
+    static private $altLogin = [];
72
+    static private $alreadyRegistered = [];
73
+    const officialApp = 200;
74
+
75
+    /**
76
+     * clean the appId
77
+     *
78
+     * @param string $app AppId that needs to be cleaned
79
+     * @return string
80
+     */
81
+    public static function cleanAppId(string $app): string {
82
+        return str_replace(array('\0', '/', '\\', '..'), '', $app);
83
+    }
84
+
85
+    /**
86
+     * Check if an app is loaded
87
+     *
88
+     * @param string $app
89
+     * @return bool
90
+     */
91
+    public static function isAppLoaded(string $app): bool {
92
+        return in_array($app, self::$loadedApps, true);
93
+    }
94
+
95
+    /**
96
+     * loads all apps
97
+     *
98
+     * @param string[] $types
99
+     * @return bool
100
+     *
101
+     * This function walks through the ownCloud directory and loads all apps
102
+     * it can find. A directory contains an app if the file /appinfo/info.xml
103
+     * exists.
104
+     *
105
+     * if $types is set to non-empty array, only apps of those types will be loaded
106
+     */
107
+    public static function loadApps(array $types = []): bool {
108
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
109
+            return false;
110
+        }
111
+        // Load the enabled apps here
112
+        $apps = self::getEnabledApps();
113
+
114
+        // Add each apps' folder as allowed class path
115
+        foreach($apps as $app) {
116
+            $path = self::getAppPath($app);
117
+            if($path !== false) {
118
+                self::registerAutoloading($app, $path);
119
+            }
120
+        }
121
+
122
+        // prevent app.php from printing output
123
+        ob_start();
124
+        foreach ($apps as $app) {
125
+            if (($types === [] or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
126
+                self::loadApp($app);
127
+            }
128
+        }
129
+        ob_end_clean();
130
+
131
+        return true;
132
+    }
133
+
134
+    /**
135
+     * load a single app
136
+     *
137
+     * @param string $app
138
+     * @throws Exception
139
+     */
140
+    public static function loadApp(string $app) {
141
+        self::$loadedApps[] = $app;
142
+        $appPath = self::getAppPath($app);
143
+        if($appPath === false) {
144
+            return;
145
+        }
146
+
147
+        // in case someone calls loadApp() directly
148
+        self::registerAutoloading($app, $appPath);
149
+
150
+        if (is_file($appPath . '/appinfo/app.php')) {
151
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
152
+            try {
153
+                self::requireAppFile($app);
154
+            } catch (Error $ex) {
155
+                \OC::$server->getLogger()->logException($ex);
156
+                if (!\OC::$server->getAppManager()->isShipped($app)) {
157
+                    // Only disable apps which are not shipped
158
+                    \OC::$server->getAppManager()->disableApp($app);
159
+                }
160
+            }
161
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
162
+        }
163
+
164
+        $info = self::getAppInfo($app);
165
+        if (!empty($info['activity']['filters'])) {
166
+            foreach ($info['activity']['filters'] as $filter) {
167
+                \OC::$server->getActivityManager()->registerFilter($filter);
168
+            }
169
+        }
170
+        if (!empty($info['activity']['settings'])) {
171
+            foreach ($info['activity']['settings'] as $setting) {
172
+                \OC::$server->getActivityManager()->registerSetting($setting);
173
+            }
174
+        }
175
+        if (!empty($info['activity']['providers'])) {
176
+            foreach ($info['activity']['providers'] as $provider) {
177
+                \OC::$server->getActivityManager()->registerProvider($provider);
178
+            }
179
+        }
180
+
181
+        if (!empty($info['settings']['admin'])) {
182
+            foreach ($info['settings']['admin'] as $setting) {
183
+                \OC::$server->getSettingsManager()->registerSetting('admin', $setting);
184
+            }
185
+        }
186
+        if (!empty($info['settings']['admin-section'])) {
187
+            foreach ($info['settings']['admin-section'] as $section) {
188
+                \OC::$server->getSettingsManager()->registerSection('admin', $section);
189
+            }
190
+        }
191
+        if (!empty($info['settings']['personal'])) {
192
+            foreach ($info['settings']['personal'] as $setting) {
193
+                \OC::$server->getSettingsManager()->registerSetting('personal', $setting);
194
+            }
195
+        }
196
+        if (!empty($info['settings']['personal-section'])) {
197
+            foreach ($info['settings']['personal-section'] as $section) {
198
+                \OC::$server->getSettingsManager()->registerSection('personal', $section);
199
+            }
200
+        }
201
+
202
+        if (!empty($info['collaboration']['plugins'])) {
203
+            // deal with one or many plugin entries
204
+            $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
205
+                [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
206
+            foreach ($plugins as $plugin) {
207
+                if($plugin['@attributes']['type'] === 'collaborator-search') {
208
+                    $pluginInfo = [
209
+                        'shareType' => $plugin['@attributes']['share-type'],
210
+                        'class' => $plugin['@value'],
211
+                    ];
212
+                    \OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
213
+                } else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
214
+                    \OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
215
+                }
216
+            }
217
+        }
218
+    }
219
+
220
+    /**
221
+     * @internal
222
+     * @param string $app
223
+     * @param string $path
224
+     */
225
+    public static function registerAutoloading(string $app, string $path) {
226
+        $key = $app . '-' . $path;
227
+        if(isset(self::$alreadyRegistered[$key])) {
228
+            return;
229
+        }
230
+
231
+        self::$alreadyRegistered[$key] = true;
232
+
233
+        // Register on PSR-4 composer autoloader
234
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
235
+        \OC::$server->registerNamespace($app, $appNamespace);
236
+
237
+        if (file_exists($path . '/composer/autoload.php')) {
238
+            require_once $path . '/composer/autoload.php';
239
+        } else {
240
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
241
+            // Register on legacy autoloader
242
+            \OC::$loader->addValidRoot($path);
243
+        }
244
+
245
+        // Register Test namespace only when testing
246
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
247
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
248
+        }
249
+    }
250
+
251
+    /**
252
+     * Load app.php from the given app
253
+     *
254
+     * @param string $app app name
255
+     * @throws Error
256
+     */
257
+    private static function requireAppFile(string $app) {
258
+        // encapsulated here to avoid variable scope conflicts
259
+        require_once $app . '/appinfo/app.php';
260
+    }
261
+
262
+    /**
263
+     * check if an app is of a specific type
264
+     *
265
+     * @param string $app
266
+     * @param array $types
267
+     * @return bool
268
+     */
269
+    public static function isType(string $app, array $types): bool {
270
+        $appTypes = self::getAppTypes($app);
271
+        foreach ($types as $type) {
272
+            if (array_search($type, $appTypes) !== false) {
273
+                return true;
274
+            }
275
+        }
276
+        return false;
277
+    }
278
+
279
+    /**
280
+     * get the types of an app
281
+     *
282
+     * @param string $app
283
+     * @return array
284
+     */
285
+    private static function getAppTypes(string $app): array {
286
+        //load the cache
287
+        if (count(self::$appTypes) == 0) {
288
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
289
+        }
290
+
291
+        if (isset(self::$appTypes[$app])) {
292
+            return explode(',', self::$appTypes[$app]);
293
+        }
294
+
295
+        return [];
296
+    }
297
+
298
+    /**
299
+     * read app types from info.xml and cache them in the database
300
+     */
301
+    public static function setAppTypes(string $app) {
302
+        $appManager = \OC::$server->getAppManager();
303
+        $appData = $appManager->getAppInfo($app);
304
+        if(!is_array($appData)) {
305
+            return;
306
+        }
307
+
308
+        if (isset($appData['types'])) {
309
+            $appTypes = implode(',', $appData['types']);
310
+        } else {
311
+            $appTypes = '';
312
+            $appData['types'] = [];
313
+        }
314
+
315
+        $config = \OC::$server->getConfig();
316
+        $config->setAppValue($app, 'types', $appTypes);
317
+
318
+        if ($appManager->hasProtectedAppType($appData['types'])) {
319
+            $enabled = $config->getAppValue($app, 'enabled', 'yes');
320
+            if ($enabled !== 'yes' && $enabled !== 'no') {
321
+                $config->setAppValue($app, 'enabled', 'yes');
322
+            }
323
+        }
324
+    }
325
+
326
+    /**
327
+     * Returns apps enabled for the current user.
328
+     *
329
+     * @param bool $forceRefresh whether to refresh the cache
330
+     * @param bool $all whether to return apps for all users, not only the
331
+     * currently logged in one
332
+     * @return string[]
333
+     */
334
+    public static function getEnabledApps(bool $forceRefresh = false, bool $all = false): array {
335
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
336
+            return [];
337
+        }
338
+        // in incognito mode or when logged out, $user will be false,
339
+        // which is also the case during an upgrade
340
+        $appManager = \OC::$server->getAppManager();
341
+        if ($all) {
342
+            $user = null;
343
+        } else {
344
+            $user = \OC::$server->getUserSession()->getUser();
345
+        }
346
+
347
+        if (is_null($user)) {
348
+            $apps = $appManager->getInstalledApps();
349
+        } else {
350
+            $apps = $appManager->getEnabledAppsForUser($user);
351
+        }
352
+        $apps = array_filter($apps, function ($app) {
353
+            return $app !== 'files';//we add this manually
354
+        });
355
+        sort($apps);
356
+        array_unshift($apps, 'files');
357
+        return $apps;
358
+    }
359
+
360
+    /**
361
+     * checks whether or not an app is enabled
362
+     *
363
+     * @param string $app app
364
+     * @return bool
365
+     * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
366
+     *
367
+     * This function checks whether or not an app is enabled.
368
+     */
369
+    public static function isEnabled(string $app): bool {
370
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
371
+    }
372
+
373
+    /**
374
+     * enables an app
375
+     *
376
+     * @param string $appId
377
+     * @param array $groups (optional) when set, only these groups will have access to the app
378
+     * @throws \Exception
379
+     * @return void
380
+     *
381
+     * This function set an app as enabled in appconfig.
382
+     */
383
+    public function enable(string $appId,
384
+                            array $groups = []) {
385
+
386
+        // Check if app is already downloaded
387
+        /** @var Installer $installer */
388
+        $installer = \OC::$server->query(Installer::class);
389
+        $isDownloaded = $installer->isDownloaded($appId);
390
+
391
+        if(!$isDownloaded) {
392
+            $installer->downloadApp($appId);
393
+        }
394
+
395
+        $installer->installApp($appId);
396
+
397
+        $appManager = \OC::$server->getAppManager();
398
+        if ($groups !== []) {
399
+            $groupManager = \OC::$server->getGroupManager();
400
+            $groupsList = [];
401
+            foreach ($groups as $group) {
402
+                $groupItem = $groupManager->get($group);
403
+                if ($groupItem instanceof \OCP\IGroup) {
404
+                    $groupsList[] = $groupManager->get($group);
405
+                }
406
+            }
407
+            $appManager->enableAppForGroups($appId, $groupsList);
408
+        } else {
409
+            $appManager->enableApp($appId);
410
+        }
411
+    }
412
+
413
+    /**
414
+     * Get the path where to install apps
415
+     *
416
+     * @return string|false
417
+     */
418
+    public static function getInstallPath() {
419
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
420
+            return false;
421
+        }
422
+
423
+        foreach (OC::$APPSROOTS as $dir) {
424
+            if (isset($dir['writable']) && $dir['writable'] === true) {
425
+                return $dir['path'];
426
+            }
427
+        }
428
+
429
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', ILogger::ERROR);
430
+        return null;
431
+    }
432
+
433
+
434
+    /**
435
+     * search for an app in all app-directories
436
+     *
437
+     * @param string $appId
438
+     * @return false|string
439
+     */
440
+    public static function findAppInDirectories(string $appId) {
441
+        $sanitizedAppId = self::cleanAppId($appId);
442
+        if($sanitizedAppId !== $appId) {
443
+            return false;
444
+        }
445
+        static $app_dir = [];
446
+
447
+        if (isset($app_dir[$appId])) {
448
+            return $app_dir[$appId];
449
+        }
450
+
451
+        $possibleApps = [];
452
+        foreach (OC::$APPSROOTS as $dir) {
453
+            if (file_exists($dir['path'] . '/' . $appId)) {
454
+                $possibleApps[] = $dir;
455
+            }
456
+        }
457
+
458
+        if (empty($possibleApps)) {
459
+            return false;
460
+        } elseif (count($possibleApps) === 1) {
461
+            $dir = array_shift($possibleApps);
462
+            $app_dir[$appId] = $dir;
463
+            return $dir;
464
+        } else {
465
+            $versionToLoad = [];
466
+            foreach ($possibleApps as $possibleApp) {
467
+                $version = self::getAppVersionByPath($possibleApp['path']);
468
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
469
+                    $versionToLoad = array(
470
+                        'dir' => $possibleApp,
471
+                        'version' => $version,
472
+                    );
473
+                }
474
+            }
475
+            $app_dir[$appId] = $versionToLoad['dir'];
476
+            return $versionToLoad['dir'];
477
+            //TODO - write test
478
+        }
479
+    }
480
+
481
+    /**
482
+     * Get the directory for the given app.
483
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
484
+     *
485
+     * @param string $appId
486
+     * @return string|false
487
+     */
488
+    public static function getAppPath(string $appId) {
489
+        if ($appId === null || trim($appId) === '') {
490
+            return false;
491
+        }
492
+
493
+        if (($dir = self::findAppInDirectories($appId)) != false) {
494
+            return $dir['path'] . '/' . $appId;
495
+        }
496
+        return false;
497
+    }
498
+
499
+    /**
500
+     * Get the path for the given app on the access
501
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
502
+     *
503
+     * @param string $appId
504
+     * @return string|false
505
+     */
506
+    public static function getAppWebPath(string $appId) {
507
+        if (($dir = self::findAppInDirectories($appId)) != false) {
508
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
509
+        }
510
+        return false;
511
+    }
512
+
513
+    /**
514
+     * get the last version of the app from appinfo/info.xml
515
+     *
516
+     * @param string $appId
517
+     * @param bool $useCache
518
+     * @return string
519
+     * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppVersion()
520
+     */
521
+    public static function getAppVersion(string $appId, bool $useCache = true): string {
522
+        return \OC::$server->getAppManager()->getAppVersion($appId, $useCache);
523
+    }
524
+
525
+    /**
526
+     * get app's version based on it's path
527
+     *
528
+     * @param string $path
529
+     * @return string
530
+     */
531
+    public static function getAppVersionByPath(string $path): string {
532
+        $infoFile = $path . '/appinfo/info.xml';
533
+        $appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
534
+        return isset($appData['version']) ? $appData['version'] : '';
535
+    }
536
+
537
+
538
+    /**
539
+     * Read all app metadata from the info.xml file
540
+     *
541
+     * @param string $appId id of the app or the path of the info.xml file
542
+     * @param bool $path
543
+     * @param string $lang
544
+     * @return array|null
545
+     * @note all data is read from info.xml, not just pre-defined fields
546
+     * @deprecated 14.0.0 use \OC::$server->getAppManager()->getAppInfo()
547
+     */
548
+    public static function getAppInfo(string $appId, bool $path = false, string $lang = null) {
549
+        return \OC::$server->getAppManager()->getAppInfo($appId, $path, $lang);
550
+    }
551
+
552
+    /**
553
+     * Returns the navigation
554
+     *
555
+     * @return array
556
+     * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll()
557
+     *
558
+     * This function returns an array containing all entries added. The
559
+     * entries are sorted by the key 'order' ascending. Additional to the keys
560
+     * given for each app the following keys exist:
561
+     *   - active: boolean, signals if the user is on this navigation entry
562
+     */
563
+    public static function getNavigation(): array {
564
+        return OC::$server->getNavigationManager()->getAll();
565
+    }
566
+
567
+    /**
568
+     * Returns the Settings Navigation
569
+     *
570
+     * @return string[]
571
+     * @deprecated 14.0.0 use \OC::$server->getNavigationManager()->getAll('settings')
572
+     *
573
+     * This function returns an array containing all settings pages added. The
574
+     * entries are sorted by the key 'order' ascending.
575
+     */
576
+    public static function getSettingsNavigation(): array {
577
+        return OC::$server->getNavigationManager()->getAll('settings');
578
+    }
579
+
580
+    /**
581
+     * get the id of loaded app
582
+     *
583
+     * @return string
584
+     */
585
+    public static function getCurrentApp(): string {
586
+        $request = \OC::$server->getRequest();
587
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
588
+        $topFolder = substr($script, 0, strpos($script, '/') ?: 0);
589
+        if (empty($topFolder)) {
590
+            $path_info = $request->getPathInfo();
591
+            if ($path_info) {
592
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
593
+            }
594
+        }
595
+        if ($topFolder == 'apps') {
596
+            $length = strlen($topFolder);
597
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1) ?: '';
598
+        } else {
599
+            return $topFolder;
600
+        }
601
+    }
602
+
603
+    /**
604
+     * @param string $type
605
+     * @return array
606
+     */
607
+    public static function getForms(string $type): array {
608
+        $forms = [];
609
+        switch ($type) {
610
+            case 'admin':
611
+                $source = self::$adminForms;
612
+                break;
613
+            case 'personal':
614
+                $source = self::$personalForms;
615
+                break;
616
+            default:
617
+                return [];
618
+        }
619
+        foreach ($source as $form) {
620
+            $forms[] = include $form;
621
+        }
622
+        return $forms;
623
+    }
624
+
625
+    /**
626
+     * register an admin form to be shown
627
+     *
628
+     * @param string $app
629
+     * @param string $page
630
+     */
631
+    public static function registerAdmin(string $app, string $page) {
632
+        self::$adminForms[] = $app . '/' . $page . '.php';
633
+    }
634
+
635
+    /**
636
+     * register a personal form to be shown
637
+     * @param string $app
638
+     * @param string $page
639
+     */
640
+    public static function registerPersonal(string $app, string $page) {
641
+        self::$personalForms[] = $app . '/' . $page . '.php';
642
+    }
643
+
644
+    /**
645
+     * @param array $entry
646
+     */
647
+    public static function registerLogIn(array $entry) {
648
+        self::$altLogin[] = $entry;
649
+    }
650
+
651
+    /**
652
+     * @return array
653
+     */
654
+    public static function getAlternativeLogIns(): array {
655
+        return self::$altLogin;
656
+    }
657
+
658
+    /**
659
+     * get a list of all apps in the apps folder
660
+     *
661
+     * @return array an array of app names (string IDs)
662
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
663
+     */
664
+    public static function getAllApps(): array {
665
+
666
+        $apps = [];
667
+
668
+        foreach (OC::$APPSROOTS as $apps_dir) {
669
+            if (!is_readable($apps_dir['path'])) {
670
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], ILogger::WARN);
671
+                continue;
672
+            }
673
+            $dh = opendir($apps_dir['path']);
674
+
675
+            if (is_resource($dh)) {
676
+                while (($file = readdir($dh)) !== false) {
677
+
678
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
679
+
680
+                        $apps[] = $file;
681
+                    }
682
+                }
683
+            }
684
+        }
685
+
686
+        $apps = array_unique($apps);
687
+
688
+        return $apps;
689
+    }
690
+
691
+    /**
692
+     * List all apps, this is used in apps.php
693
+     *
694
+     * @return array
695
+     */
696
+    public function listAllApps(): array {
697
+        $installedApps = OC_App::getAllApps();
698
+
699
+        $appManager = \OC::$server->getAppManager();
700
+        //we don't want to show configuration for these
701
+        $blacklist = $appManager->getAlwaysEnabledApps();
702
+        $appList = [];
703
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
704
+        $urlGenerator = \OC::$server->getURLGenerator();
705
+
706
+        foreach ($installedApps as $app) {
707
+            if (array_search($app, $blacklist) === false) {
708
+
709
+                $info = OC_App::getAppInfo($app, false, $langCode);
710
+                if (!is_array($info)) {
711
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR);
712
+                    continue;
713
+                }
714
+
715
+                if (!isset($info['name'])) {
716
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', ILogger::ERROR);
717
+                    continue;
718
+                }
719
+
720
+                $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
721
+                $info['groups'] = null;
722
+                if ($enabled === 'yes') {
723
+                    $active = true;
724
+                } else if ($enabled === 'no') {
725
+                    $active = false;
726
+                } else {
727
+                    $active = true;
728
+                    $info['groups'] = $enabled;
729
+                }
730
+
731
+                $info['active'] = $active;
732
+
733
+                if ($appManager->isShipped($app)) {
734
+                    $info['internal'] = true;
735
+                    $info['level'] = self::officialApp;
736
+                    $info['removable'] = false;
737
+                } else {
738
+                    $info['internal'] = false;
739
+                    $info['removable'] = true;
740
+                }
741
+
742
+                $appPath = self::getAppPath($app);
743
+                if($appPath !== false) {
744
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
745
+                    if (file_exists($appIcon)) {
746
+                        $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
747
+                        $info['previewAsIcon'] = true;
748
+                    } else {
749
+                        $appIcon = $appPath . '/img/app.svg';
750
+                        if (file_exists($appIcon)) {
751
+                            $info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
752
+                            $info['previewAsIcon'] = true;
753
+                        }
754
+                    }
755
+                }
756
+                // fix documentation
757
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
758
+                    foreach ($info['documentation'] as $key => $url) {
759
+                        // If it is not an absolute URL we assume it is a key
760
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
761
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
762
+                            $url = $urlGenerator->linkToDocs($url);
763
+                        }
764
+
765
+                        $info['documentation'][$key] = $url;
766
+                    }
767
+                }
768
+
769
+                $info['version'] = OC_App::getAppVersion($app);
770
+                $appList[] = $info;
771
+            }
772
+        }
773
+
774
+        return $appList;
775
+    }
776
+
777
+    public static function shouldUpgrade(string $app): bool {
778
+        $versions = self::getAppVersions();
779
+        $currentVersion = OC_App::getAppVersion($app);
780
+        if ($currentVersion && isset($versions[$app])) {
781
+            $installedVersion = $versions[$app];
782
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
783
+                return true;
784
+            }
785
+        }
786
+        return false;
787
+    }
788
+
789
+    /**
790
+     * Adjust the number of version parts of $version1 to match
791
+     * the number of version parts of $version2.
792
+     *
793
+     * @param string $version1 version to adjust
794
+     * @param string $version2 version to take the number of parts from
795
+     * @return string shortened $version1
796
+     */
797
+    private static function adjustVersionParts(string $version1, string $version2): string {
798
+        $version1 = explode('.', $version1);
799
+        $version2 = explode('.', $version2);
800
+        // reduce $version1 to match the number of parts in $version2
801
+        while (count($version1) > count($version2)) {
802
+            array_pop($version1);
803
+        }
804
+        // if $version1 does not have enough parts, add some
805
+        while (count($version1) < count($version2)) {
806
+            $version1[] = '0';
807
+        }
808
+        return implode('.', $version1);
809
+    }
810
+
811
+    /**
812
+     * Check whether the current ownCloud version matches the given
813
+     * application's version requirements.
814
+     *
815
+     * The comparison is made based on the number of parts that the
816
+     * app info version has. For example for ownCloud 6.0.3 if the
817
+     * app info version is expecting version 6.0, the comparison is
818
+     * made on the first two parts of the ownCloud version.
819
+     * This means that it's possible to specify "requiremin" => 6
820
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
821
+     *
822
+     * @param string $ocVersion ownCloud version to check against
823
+     * @param array $appInfo app info (from xml)
824
+     *
825
+     * @return boolean true if compatible, otherwise false
826
+     */
827
+    public static function isAppCompatible(string $ocVersion, array $appInfo): bool {
828
+        $requireMin = '';
829
+        $requireMax = '';
830
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
831
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
832
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
833
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
834
+        } else if (isset($appInfo['requiremin'])) {
835
+            $requireMin = $appInfo['requiremin'];
836
+        } else if (isset($appInfo['require'])) {
837
+            $requireMin = $appInfo['require'];
838
+        }
839
+
840
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
841
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
842
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
843
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
844
+        } else if (isset($appInfo['requiremax'])) {
845
+            $requireMax = $appInfo['requiremax'];
846
+        }
847
+
848
+        if (!empty($requireMin)
849
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
850
+        ) {
851
+
852
+            return false;
853
+        }
854
+
855
+        if (!empty($requireMax)
856
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
857
+        ) {
858
+            return false;
859
+        }
860
+
861
+        return true;
862
+    }
863
+
864
+    /**
865
+     * get the installed version of all apps
866
+     */
867
+    public static function getAppVersions() {
868
+        static $versions;
869
+
870
+        if(!$versions) {
871
+            $appConfig = \OC::$server->getAppConfig();
872
+            $versions = $appConfig->getValues(false, 'installed_version');
873
+        }
874
+        return $versions;
875
+    }
876
+
877
+    /**
878
+     * update the database for the app and call the update script
879
+     *
880
+     * @param string $appId
881
+     * @return bool
882
+     */
883
+    public static function updateApp(string $appId): bool {
884
+        $appPath = self::getAppPath($appId);
885
+        if($appPath === false) {
886
+            return false;
887
+        }
888
+        self::registerAutoloading($appId, $appPath);
889
+
890
+        $appData = self::getAppInfo($appId);
891
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
892
+
893
+        if (file_exists($appPath . '/appinfo/database.xml')) {
894
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
895
+        } else {
896
+            $ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
897
+            $ms->migrate();
898
+        }
899
+
900
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
901
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
902
+        // update appversion in app manager
903
+        \OC::$server->getAppManager()->getAppVersion($appId, false);
904
+
905
+        // run upgrade code
906
+        if (file_exists($appPath . '/appinfo/update.php')) {
907
+            self::loadApp($appId);
908
+            include $appPath . '/appinfo/update.php';
909
+        }
910
+        self::setupBackgroundJobs($appData['background-jobs']);
911
+
912
+        //set remote/public handlers
913
+        if (array_key_exists('ocsid', $appData)) {
914
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
915
+        } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
916
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
917
+        }
918
+        foreach ($appData['remote'] as $name => $path) {
919
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
920
+        }
921
+        foreach ($appData['public'] as $name => $path) {
922
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
923
+        }
924
+
925
+        self::setAppTypes($appId);
926
+
927
+        $version = \OC_App::getAppVersion($appId);
928
+        \OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
929
+
930
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
931
+            ManagerEvent::EVENT_APP_UPDATE, $appId
932
+        ));
933
+
934
+        return true;
935
+    }
936
+
937
+    /**
938
+     * @param string $appId
939
+     * @param string[] $steps
940
+     * @throws \OC\NeedsUpdateException
941
+     */
942
+    public static function executeRepairSteps(string $appId, array $steps) {
943
+        if (empty($steps)) {
944
+            return;
945
+        }
946
+        // load the app
947
+        self::loadApp($appId);
948
+
949
+        $dispatcher = OC::$server->getEventDispatcher();
950
+
951
+        // load the steps
952
+        $r = new Repair([], $dispatcher);
953
+        foreach ($steps as $step) {
954
+            try {
955
+                $r->addStep($step);
956
+            } catch (Exception $ex) {
957
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
958
+                \OC::$server->getLogger()->logException($ex);
959
+            }
960
+        }
961
+        // run the steps
962
+        $r->run();
963
+    }
964
+
965
+    public static function setupBackgroundJobs(array $jobs) {
966
+        $queue = \OC::$server->getJobList();
967
+        foreach ($jobs as $job) {
968
+            $queue->add($job);
969
+        }
970
+    }
971
+
972
+    /**
973
+     * @param string $appId
974
+     * @param string[] $steps
975
+     */
976
+    private static function setupLiveMigrations(string $appId, array $steps) {
977
+        $queue = \OC::$server->getJobList();
978
+        foreach ($steps as $step) {
979
+            $queue->add('OC\Migration\BackgroundRepair', [
980
+                'app' => $appId,
981
+                'step' => $step]);
982
+        }
983
+    }
984
+
985
+    /**
986
+     * @param string $appId
987
+     * @return \OC\Files\View|false
988
+     */
989
+    public static function getStorage(string $appId) {
990
+        if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
991
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
992
+                $view = new \OC\Files\View('/' . OC_User::getUser());
993
+                if (!$view->file_exists($appId)) {
994
+                    $view->mkdir($appId);
995
+                }
996
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
997
+            } else {
998
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', ILogger::ERROR);
999
+                return false;
1000
+            }
1001
+        } else {
1002
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', ILogger::ERROR);
1003
+            return false;
1004
+        }
1005
+    }
1006
+
1007
+    protected static function findBestL10NOption(array $options, string $lang): string {
1008
+        // only a single option
1009
+        if (isset($options['@value'])) {
1010
+            return $options['@value'];
1011
+        }
1012
+
1013
+        $fallback = $similarLangFallback = $englishFallback = false;
1014
+
1015
+        $lang = strtolower($lang);
1016
+        $similarLang = $lang;
1017
+        if (strpos($similarLang, '_')) {
1018
+            // For "de_DE" we want to find "de" and the other way around
1019
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1020
+        }
1021
+
1022
+        foreach ($options as $option) {
1023
+            if (is_array($option)) {
1024
+                if ($fallback === false) {
1025
+                    $fallback = $option['@value'];
1026
+                }
1027
+
1028
+                if (!isset($option['@attributes']['lang'])) {
1029
+                    continue;
1030
+                }
1031
+
1032
+                $attributeLang = strtolower($option['@attributes']['lang']);
1033
+                if ($attributeLang === $lang) {
1034
+                    return $option['@value'];
1035
+                }
1036
+
1037
+                if ($attributeLang === $similarLang) {
1038
+                    $similarLangFallback = $option['@value'];
1039
+                } else if (strpos($attributeLang, $similarLang . '_') === 0) {
1040
+                    if ($similarLangFallback === false) {
1041
+                        $similarLangFallback =  $option['@value'];
1042
+                    }
1043
+                }
1044
+            } else {
1045
+                $englishFallback = $option;
1046
+            }
1047
+        }
1048
+
1049
+        if ($similarLangFallback !== false) {
1050
+            return $similarLangFallback;
1051
+        } else if ($englishFallback !== false) {
1052
+            return $englishFallback;
1053
+        }
1054
+        return (string) $fallback;
1055
+    }
1056
+
1057
+    /**
1058
+     * parses the app data array and enhanced the 'description' value
1059
+     *
1060
+     * @param array $data the app data
1061
+     * @param string $lang
1062
+     * @return array improved app data
1063
+     */
1064
+    public static function parseAppInfo(array $data, $lang = null): array {
1065
+
1066
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1067
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1068
+        }
1069
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1070
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1071
+        }
1072
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1073
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1074
+        } else if (isset($data['description']) && is_string($data['description'])) {
1075
+            $data['description'] = trim($data['description']);
1076
+        } else  {
1077
+            $data['description'] = '';
1078
+        }
1079
+
1080
+        return $data;
1081
+    }
1082
+
1083
+    /**
1084
+     * @param \OCP\IConfig $config
1085
+     * @param \OCP\IL10N $l
1086
+     * @param array $info
1087
+     * @throws \Exception
1088
+     */
1089
+    public static function checkAppDependencies(\OCP\IConfig $config, \OCP\IL10N $l, array $info) {
1090
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1091
+        $missing = $dependencyAnalyzer->analyze($info);
1092
+        if (!empty($missing)) {
1093
+            $missingMsg = implode(PHP_EOL, $missing);
1094
+            throw new \Exception(
1095
+                $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1096
+                    [$info['name'], $missingMsg]
1097
+                )
1098
+            );
1099
+        }
1100
+    }
1101 1101
 }
Please login to merge, or discard this patch.
Spacing   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -112,9 +112,9 @@  discard block
 block discarded – undo
112 112
 		$apps = self::getEnabledApps();
113 113
 
114 114
 		// Add each apps' folder as allowed class path
115
-		foreach($apps as $app) {
115
+		foreach ($apps as $app) {
116 116
 			$path = self::getAppPath($app);
117
-			if($path !== false) {
117
+			if ($path !== false) {
118 118
 				self::registerAutoloading($app, $path);
119 119
 			}
120 120
 		}
@@ -140,15 +140,15 @@  discard block
 block discarded – undo
140 140
 	public static function loadApp(string $app) {
141 141
 		self::$loadedApps[] = $app;
142 142
 		$appPath = self::getAppPath($app);
143
-		if($appPath === false) {
143
+		if ($appPath === false) {
144 144
 			return;
145 145
 		}
146 146
 
147 147
 		// in case someone calls loadApp() directly
148 148
 		self::registerAutoloading($app, $appPath);
149 149
 
150
-		if (is_file($appPath . '/appinfo/app.php')) {
151
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
+		if (is_file($appPath.'/appinfo/app.php')) {
151
+			\OC::$server->getEventLogger()->start('load_app_'.$app, 'Load app: '.$app);
152 152
 			try {
153 153
 				self::requireAppFile($app);
154 154
 			} catch (Error $ex) {
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 					\OC::$server->getAppManager()->disableApp($app);
159 159
 				}
160 160
 			}
161
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
161
+			\OC::$server->getEventLogger()->end('load_app_'.$app);
162 162
 		}
163 163
 
164 164
 		$info = self::getAppInfo($app);
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
 			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
205 205
 				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
206 206
 			foreach ($plugins as $plugin) {
207
-				if($plugin['@attributes']['type'] === 'collaborator-search') {
207
+				if ($plugin['@attributes']['type'] === 'collaborator-search') {
208 208
 					$pluginInfo = [
209 209
 						'shareType' => $plugin['@attributes']['share-type'],
210 210
 						'class' => $plugin['@value'],
@@ -223,8 +223,8 @@  discard block
 block discarded – undo
223 223
 	 * @param string $path
224 224
 	 */
225 225
 	public static function registerAutoloading(string $app, string $path) {
226
-		$key = $app . '-' . $path;
227
-		if(isset(self::$alreadyRegistered[$key])) {
226
+		$key = $app.'-'.$path;
227
+		if (isset(self::$alreadyRegistered[$key])) {
228 228
 			return;
229 229
 		}
230 230
 
@@ -234,17 +234,17 @@  discard block
 block discarded – undo
234 234
 		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
235 235
 		\OC::$server->registerNamespace($app, $appNamespace);
236 236
 
237
-		if (file_exists($path . '/composer/autoload.php')) {
238
-			require_once $path . '/composer/autoload.php';
237
+		if (file_exists($path.'/composer/autoload.php')) {
238
+			require_once $path.'/composer/autoload.php';
239 239
 		} else {
240
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
240
+			\OC::$composerAutoloader->addPsr4($appNamespace.'\\', $path.'/lib/', true);
241 241
 			// Register on legacy autoloader
242 242
 			\OC::$loader->addValidRoot($path);
243 243
 		}
244 244
 
245 245
 		// Register Test namespace only when testing
246 246
 		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
247
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
247
+			\OC::$composerAutoloader->addPsr4($appNamespace.'\\Tests\\', $path.'/tests/', true);
248 248
 		}
249 249
 	}
250 250
 
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 	 */
257 257
 	private static function requireAppFile(string $app) {
258 258
 		// encapsulated here to avoid variable scope conflicts
259
-		require_once $app . '/appinfo/app.php';
259
+		require_once $app.'/appinfo/app.php';
260 260
 	}
261 261
 
262 262
 	/**
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 	public static function setAppTypes(string $app) {
302 302
 		$appManager = \OC::$server->getAppManager();
303 303
 		$appData = $appManager->getAppInfo($app);
304
-		if(!is_array($appData)) {
304
+		if (!is_array($appData)) {
305 305
 			return;
306 306
 		}
307 307
 
@@ -349,8 +349,8 @@  discard block
 block discarded – undo
349 349
 		} else {
350 350
 			$apps = $appManager->getEnabledAppsForUser($user);
351 351
 		}
352
-		$apps = array_filter($apps, function ($app) {
353
-			return $app !== 'files';//we add this manually
352
+		$apps = array_filter($apps, function($app) {
353
+			return $app !== 'files'; //we add this manually
354 354
 		});
355 355
 		sort($apps);
356 356
 		array_unshift($apps, 'files');
@@ -388,7 +388,7 @@  discard block
 block discarded – undo
388 388
 		$installer = \OC::$server->query(Installer::class);
389 389
 		$isDownloaded = $installer->isDownloaded($appId);
390 390
 
391
-		if(!$isDownloaded) {
391
+		if (!$isDownloaded) {
392 392
 			$installer->downloadApp($appId);
393 393
 		}
394 394
 
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
 	 */
440 440
 	public static function findAppInDirectories(string $appId) {
441 441
 		$sanitizedAppId = self::cleanAppId($appId);
442
-		if($sanitizedAppId !== $appId) {
442
+		if ($sanitizedAppId !== $appId) {
443 443
 			return false;
444 444
 		}
445 445
 		static $app_dir = [];
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
 
451 451
 		$possibleApps = [];
452 452
 		foreach (OC::$APPSROOTS as $dir) {
453
-			if (file_exists($dir['path'] . '/' . $appId)) {
453
+			if (file_exists($dir['path'].'/'.$appId)) {
454 454
 				$possibleApps[] = $dir;
455 455
 			}
456 456
 		}
@@ -491,7 +491,7 @@  discard block
 block discarded – undo
491 491
 		}
492 492
 
493 493
 		if (($dir = self::findAppInDirectories($appId)) != false) {
494
-			return $dir['path'] . '/' . $appId;
494
+			return $dir['path'].'/'.$appId;
495 495
 		}
496 496
 		return false;
497 497
 	}
@@ -505,7 +505,7 @@  discard block
 block discarded – undo
505 505
 	 */
506 506
 	public static function getAppWebPath(string $appId) {
507 507
 		if (($dir = self::findAppInDirectories($appId)) != false) {
508
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
508
+			return OC::$WEBROOT.$dir['url'].'/'.$appId;
509 509
 		}
510 510
 		return false;
511 511
 	}
@@ -529,7 +529,7 @@  discard block
 block discarded – undo
529 529
 	 * @return string
530 530
 	 */
531 531
 	public static function getAppVersionByPath(string $path): string {
532
-		$infoFile = $path . '/appinfo/info.xml';
532
+		$infoFile = $path.'/appinfo/info.xml';
533 533
 		$appData = \OC::$server->getAppManager()->getAppInfo($infoFile, true);
534 534
 		return isset($appData['version']) ? $appData['version'] : '';
535 535
 	}
@@ -629,7 +629,7 @@  discard block
 block discarded – undo
629 629
 	 * @param string $page
630 630
 	 */
631 631
 	public static function registerAdmin(string $app, string $page) {
632
-		self::$adminForms[] = $app . '/' . $page . '.php';
632
+		self::$adminForms[] = $app.'/'.$page.'.php';
633 633
 	}
634 634
 
635 635
 	/**
@@ -638,7 +638,7 @@  discard block
 block discarded – undo
638 638
 	 * @param string $page
639 639
 	 */
640 640
 	public static function registerPersonal(string $app, string $page) {
641
-		self::$personalForms[] = $app . '/' . $page . '.php';
641
+		self::$personalForms[] = $app.'/'.$page.'.php';
642 642
 	}
643 643
 
644 644
 	/**
@@ -667,7 +667,7 @@  discard block
 block discarded – undo
667 667
 
668 668
 		foreach (OC::$APPSROOTS as $apps_dir) {
669 669
 			if (!is_readable($apps_dir['path'])) {
670
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], ILogger::WARN);
670
+				\OCP\Util::writeLog('core', 'unable to read app folder : '.$apps_dir['path'], ILogger::WARN);
671 671
 				continue;
672 672
 			}
673 673
 			$dh = opendir($apps_dir['path']);
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
 			if (is_resource($dh)) {
676 676
 				while (($file = readdir($dh)) !== false) {
677 677
 
678
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
678
+					if ($file[0] != '.' and is_dir($apps_dir['path'].'/'.$file) and is_file($apps_dir['path'].'/'.$file.'/appinfo/info.xml')) {
679 679
 
680 680
 						$apps[] = $file;
681 681
 					}
@@ -708,12 +708,12 @@  discard block
 block discarded – undo
708 708
 
709 709
 				$info = OC_App::getAppInfo($app, false, $langCode);
710 710
 				if (!is_array($info)) {
711
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', ILogger::ERROR);
711
+					\OCP\Util::writeLog('core', 'Could not read app info file for app "'.$app.'"', ILogger::ERROR);
712 712
 					continue;
713 713
 				}
714 714
 
715 715
 				if (!isset($info['name'])) {
716
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', ILogger::ERROR);
716
+					\OCP\Util::writeLog('core', 'App id "'.$app.'" has no name in appinfo', ILogger::ERROR);
717 717
 					continue;
718 718
 				}
719 719
 
@@ -740,13 +740,13 @@  discard block
 block discarded – undo
740 740
 				}
741 741
 
742 742
 				$appPath = self::getAppPath($app);
743
-				if($appPath !== false) {
744
-					$appIcon = $appPath . '/img/' . $app . '.svg';
743
+				if ($appPath !== false) {
744
+					$appIcon = $appPath.'/img/'.$app.'.svg';
745 745
 					if (file_exists($appIcon)) {
746
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
746
+						$info['preview'] = $urlGenerator->imagePath($app, $app.'.svg');
747 747
 						$info['previewAsIcon'] = true;
748 748
 					} else {
749
-						$appIcon = $appPath . '/img/app.svg';
749
+						$appIcon = $appPath.'/img/app.svg';
750 750
 						if (file_exists($appIcon)) {
751 751
 							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
752 752
 							$info['previewAsIcon'] = true;
@@ -867,7 +867,7 @@  discard block
 block discarded – undo
867 867
 	public static function getAppVersions() {
868 868
 		static $versions;
869 869
 
870
-		if(!$versions) {
870
+		if (!$versions) {
871 871
 			$appConfig = \OC::$server->getAppConfig();
872 872
 			$versions = $appConfig->getValues(false, 'installed_version');
873 873
 		}
@@ -882,7 +882,7 @@  discard block
 block discarded – undo
882 882
 	 */
883 883
 	public static function updateApp(string $appId): bool {
884 884
 		$appPath = self::getAppPath($appId);
885
-		if($appPath === false) {
885
+		if ($appPath === false) {
886 886
 			return false;
887 887
 		}
888 888
 		self::registerAutoloading($appId, $appPath);
@@ -890,8 +890,8 @@  discard block
 block discarded – undo
890 890
 		$appData = self::getAppInfo($appId);
891 891
 		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
892 892
 
893
-		if (file_exists($appPath . '/appinfo/database.xml')) {
894
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
893
+		if (file_exists($appPath.'/appinfo/database.xml')) {
894
+			OC_DB::updateDbFromStructure($appPath.'/appinfo/database.xml');
895 895
 		} else {
896 896
 			$ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
897 897
 			$ms->migrate();
@@ -903,23 +903,23 @@  discard block
 block discarded – undo
903 903
 		\OC::$server->getAppManager()->getAppVersion($appId, false);
904 904
 
905 905
 		// run upgrade code
906
-		if (file_exists($appPath . '/appinfo/update.php')) {
906
+		if (file_exists($appPath.'/appinfo/update.php')) {
907 907
 			self::loadApp($appId);
908
-			include $appPath . '/appinfo/update.php';
908
+			include $appPath.'/appinfo/update.php';
909 909
 		}
910 910
 		self::setupBackgroundJobs($appData['background-jobs']);
911 911
 
912 912
 		//set remote/public handlers
913 913
 		if (array_key_exists('ocsid', $appData)) {
914 914
 			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
915
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
915
+		} elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
916 916
 			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
917 917
 		}
918 918
 		foreach ($appData['remote'] as $name => $path) {
919
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
919
+			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $appId.'/'.$path);
920 920
 		}
921 921
 		foreach ($appData['public'] as $name => $path) {
922
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
922
+			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $appId.'/'.$path);
923 923
 		}
924 924
 
925 925
 		self::setAppTypes($appId);
@@ -989,17 +989,17 @@  discard block
 block discarded – undo
989 989
 	public static function getStorage(string $appId) {
990 990
 		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
991 991
 			if (\OC::$server->getUserSession()->isLoggedIn()) {
992
-				$view = new \OC\Files\View('/' . OC_User::getUser());
992
+				$view = new \OC\Files\View('/'.OC_User::getUser());
993 993
 				if (!$view->file_exists($appId)) {
994 994
 					$view->mkdir($appId);
995 995
 				}
996
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
996
+				return new \OC\Files\View('/'.OC_User::getUser().'/'.$appId);
997 997
 			} else {
998
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', ILogger::ERROR);
998
+				\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.', user not logged in', ILogger::ERROR);
999 999
 				return false;
1000 1000
 			}
1001 1001
 		} else {
1002
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', ILogger::ERROR);
1002
+			\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.' not enabled', ILogger::ERROR);
1003 1003
 			return false;
1004 1004
 		}
1005 1005
 	}
@@ -1036,9 +1036,9 @@  discard block
 block discarded – undo
1036 1036
 
1037 1037
 				if ($attributeLang === $similarLang) {
1038 1038
 					$similarLangFallback = $option['@value'];
1039
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1039
+				} else if (strpos($attributeLang, $similarLang.'_') === 0) {
1040 1040
 					if ($similarLangFallback === false) {
1041
-						$similarLangFallback =  $option['@value'];
1041
+						$similarLangFallback = $option['@value'];
1042 1042
 					}
1043 1043
 				}
1044 1044
 			} else {
@@ -1073,7 +1073,7 @@  discard block
 block discarded – undo
1073 1073
 			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1074 1074
 		} else if (isset($data['description']) && is_string($data['description'])) {
1075 1075
 			$data['description'] = trim($data['description']);
1076
-		} else  {
1076
+		} else {
1077 1077
 			$data['description'] = '';
1078 1078
 		}
1079 1079
 
Please login to merge, or discard this patch.
lib/private/legacy/user.php 2 patches
Indentation   +346 added lines, -346 removed lines patch added patch discarded remove patch
@@ -60,350 +60,350 @@
 block discarded – undo
60 60
  */
61 61
 class OC_User {
62 62
 
63
-	private static $_usedBackends = array();
64
-
65
-	private static $_setupedBackends = array();
66
-
67
-	// bool, stores if a user want to access a resource anonymously, e.g if they open a public link
68
-	private static $incognitoMode = false;
69
-
70
-	/**
71
-	 * Adds the backend to the list of used backends
72
-	 *
73
-	 * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
74
-	 * @return bool
75
-	 *
76
-	 * Set the User Authentication Module
77
-	 * @suppress PhanDeprecatedFunction
78
-	 */
79
-	public static function useBackend($backend = 'database') {
80
-		if ($backend instanceof \OCP\UserInterface) {
81
-			self::$_usedBackends[get_class($backend)] = $backend;
82
-			\OC::$server->getUserManager()->registerBackend($backend);
83
-		} else {
84
-			// You'll never know what happens
85
-			if (null === $backend OR !is_string($backend)) {
86
-				$backend = 'database';
87
-			}
88
-
89
-			// Load backend
90
-			switch ($backend) {
91
-				case 'database':
92
-				case 'mysql':
93
-				case 'sqlite':
94
-					\OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', ILogger::DEBUG);
95
-					self::$_usedBackends[$backend] = new \OC\User\Database();
96
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
97
-					break;
98
-				case 'dummy':
99
-					self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
100
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
101
-					break;
102
-				default:
103
-					\OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', ILogger::DEBUG);
104
-					$className = 'OC_USER_' . strtoupper($backend);
105
-					self::$_usedBackends[$backend] = new $className();
106
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
107
-					break;
108
-			}
109
-		}
110
-		return true;
111
-	}
112
-
113
-	/**
114
-	 * remove all used backends
115
-	 */
116
-	public static function clearBackends() {
117
-		self::$_usedBackends = array();
118
-		\OC::$server->getUserManager()->clearBackends();
119
-	}
120
-
121
-	/**
122
-	 * setup the configured backends in config.php
123
-	 * @suppress PhanDeprecatedFunction
124
-	 */
125
-	public static function setupBackends() {
126
-		OC_App::loadApps(['prelogin']);
127
-		$backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
128
-		if (isset($backends['default']) && !$backends['default']) {
129
-			// clear default backends
130
-			self::clearBackends();
131
-		}
132
-		foreach ($backends as $i => $config) {
133
-			if (!is_array($config)) {
134
-				continue;
135
-			}
136
-			$class = $config['class'];
137
-			$arguments = $config['arguments'];
138
-			if (class_exists($class)) {
139
-				if (array_search($i, self::$_setupedBackends) === false) {
140
-					// make a reflection object
141
-					$reflectionObj = new ReflectionClass($class);
142
-
143
-					// use Reflection to create a new instance, using the $args
144
-					$backend = $reflectionObj->newInstanceArgs($arguments);
145
-					self::useBackend($backend);
146
-					self::$_setupedBackends[] = $i;
147
-				} else {
148
-					\OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', ILogger::DEBUG);
149
-				}
150
-			} else {
151
-				\OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', ILogger::ERROR);
152
-			}
153
-		}
154
-	}
155
-
156
-	/**
157
-	 * Try to login a user, assuming authentication
158
-	 * has already happened (e.g. via Single Sign On).
159
-	 *
160
-	 * Log in a user and regenerate a new session.
161
-	 *
162
-	 * @param \OCP\Authentication\IApacheBackend $backend
163
-	 * @return bool
164
-	 */
165
-	public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
166
-
167
-		$uid = $backend->getCurrentUserId();
168
-		$run = true;
169
-		OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
170
-
171
-		if ($uid) {
172
-			if (self::getUser() !== $uid) {
173
-				self::setUserId($uid);
174
-				$userSession = \OC::$server->getUserSession();
175
-				$userSession->setLoginName($uid);
176
-				$request = OC::$server->getRequest();
177
-				$userSession->createSessionToken($request, $uid, $uid);
178
-				// setup the filesystem
179
-				OC_Util::setupFS($uid);
180
-				// first call the post_login hooks, the login-process needs to be
181
-				// completed before we can safely create the users folder.
182
-				// For example encryption needs to initialize the users keys first
183
-				// before we can create the user folder with the skeleton files
184
-				OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
185
-				//trigger creation of user home and /files folder
186
-				\OC::$server->getUserFolder($uid);
187
-			}
188
-			return true;
189
-		}
190
-		return false;
191
-	}
192
-
193
-	/**
194
-	 * Verify with Apache whether user is authenticated.
195
-	 *
196
-	 * @return boolean|null
197
-	 *          true: authenticated
198
-	 *          false: not authenticated
199
-	 *          null: not handled / no backend available
200
-	 */
201
-	public static function handleApacheAuth() {
202
-		$backend = self::findFirstActiveUsedBackend();
203
-		if ($backend) {
204
-			OC_App::loadApps();
205
-
206
-			//setup extra user backends
207
-			self::setupBackends();
208
-			\OC::$server->getUserSession()->unsetMagicInCookie();
209
-
210
-			return self::loginWithApache($backend);
211
-		}
212
-
213
-		return null;
214
-	}
215
-
216
-
217
-	/**
218
-	 * Sets user id for session and triggers emit
219
-	 *
220
-	 * @param string $uid
221
-	 */
222
-	public static function setUserId($uid) {
223
-		$userSession = \OC::$server->getUserSession();
224
-		$userManager = \OC::$server->getUserManager();
225
-		if ($user = $userManager->get($uid)) {
226
-			$userSession->setUser($user);
227
-		} else {
228
-			\OC::$server->getSession()->set('user_id', $uid);
229
-		}
230
-	}
231
-
232
-	/**
233
-	 * Check if the user is logged in, considers also the HTTP basic credentials
234
-	 *
235
-	 * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
236
-	 * @return bool
237
-	 */
238
-	public static function isLoggedIn() {
239
-		return \OC::$server->getUserSession()->isLoggedIn();
240
-	}
241
-
242
-	/**
243
-	 * set incognito mode, e.g. if a user wants to open a public link
244
-	 *
245
-	 * @param bool $status
246
-	 */
247
-	public static function setIncognitoMode($status) {
248
-		self::$incognitoMode = $status;
249
-	}
250
-
251
-	/**
252
-	 * get incognito mode status
253
-	 *
254
-	 * @return bool
255
-	 */
256
-	public static function isIncognitoMode() {
257
-		return self::$incognitoMode;
258
-	}
259
-
260
-	/**
261
-	 * Returns the current logout URL valid for the currently logged-in user
262
-	 *
263
-	 * @param \OCP\IURLGenerator $urlGenerator
264
-	 * @return string
265
-	 */
266
-	public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) {
267
-		$backend = self::findFirstActiveUsedBackend();
268
-		if ($backend) {
269
-			return $backend->getLogoutUrl();
270
-		}
271
-
272
-		$logoutUrl = $urlGenerator->linkToRouteAbsolute(
273
-			'core.login.logout',
274
-			[
275
-				'requesttoken' => \OCP\Util::callRegister(),
276
-			]
277
-		);
278
-
279
-		return $logoutUrl;
280
-	}
281
-
282
-	/**
283
-	 * Check if the user is an admin user
284
-	 *
285
-	 * @param string $uid uid of the admin
286
-	 * @return bool
287
-	 */
288
-	public static function isAdminUser($uid) {
289
-		$group = \OC::$server->getGroupManager()->get('admin');
290
-		$user = \OC::$server->getUserManager()->get($uid);
291
-		if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
292
-			return true;
293
-		}
294
-		return false;
295
-	}
296
-
297
-
298
-	/**
299
-	 * get the user id of the user currently logged in.
300
-	 *
301
-	 * @return string|bool uid or false
302
-	 */
303
-	public static function getUser() {
304
-		$uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
305
-		if (!is_null($uid) && self::$incognitoMode === false) {
306
-			return $uid;
307
-		} else {
308
-			return false;
309
-		}
310
-	}
311
-
312
-	/**
313
-	 * get the display name of the user currently logged in.
314
-	 *
315
-	 * @param string $uid
316
-	 * @return string|bool uid or false
317
-	 * @deprecated 8.1.0 fetch \OCP\IUser (has getDisplayName()) by using method
318
-	 *                   get() of \OCP\IUserManager - \OC::$server->getUserManager()
319
-	 */
320
-	public static function getDisplayName($uid = null) {
321
-		if ($uid) {
322
-			$user = \OC::$server->getUserManager()->get($uid);
323
-			if ($user) {
324
-				return $user->getDisplayName();
325
-			} else {
326
-				return $uid;
327
-			}
328
-		} else {
329
-			$user = \OC::$server->getUserSession()->getUser();
330
-			if ($user) {
331
-				return $user->getDisplayName();
332
-			} else {
333
-				return false;
334
-			}
335
-		}
336
-	}
337
-
338
-	/**
339
-	 * Set password
340
-	 *
341
-	 * @param string $uid The username
342
-	 * @param string $password The new password
343
-	 * @param string $recoveryPassword for the encryption app to reset encryption keys
344
-	 * @return bool
345
-	 *
346
-	 * Change the password of a user
347
-	 */
348
-	public static function setPassword($uid, $password, $recoveryPassword = null) {
349
-		$user = \OC::$server->getUserManager()->get($uid);
350
-		if ($user) {
351
-			return $user->setPassword($password, $recoveryPassword);
352
-		} else {
353
-			return false;
354
-		}
355
-	}
356
-
357
-	/**
358
-	 * @param string $uid The username
359
-	 * @return string
360
-	 *
361
-	 * returns the path to the users home directory
362
-	 * @deprecated Use \OC::$server->getUserManager->getHome()
363
-	 */
364
-	public static function getHome($uid) {
365
-		$user = \OC::$server->getUserManager()->get($uid);
366
-		if ($user) {
367
-			return $user->getHome();
368
-		} else {
369
-			return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
370
-		}
371
-	}
372
-
373
-	/**
374
-	 * Get a list of all users display name
375
-	 *
376
-	 * @param string $search
377
-	 * @param int $limit
378
-	 * @param int $offset
379
-	 * @return array associative array with all display names (value) and corresponding uids (key)
380
-	 *
381
-	 * Get a list of all display names and user ids.
382
-	 * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
383
-	 */
384
-	public static function getDisplayNames($search = '', $limit = null, $offset = null) {
385
-		$displayNames = array();
386
-		$users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
387
-		foreach ($users as $user) {
388
-			$displayNames[$user->getUID()] = $user->getDisplayName();
389
-		}
390
-		return $displayNames;
391
-	}
392
-
393
-	/**
394
-	 * Returns the first active backend from self::$_usedBackends.
395
-	 *
396
-	 * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
397
-	 */
398
-	private static function findFirstActiveUsedBackend() {
399
-		foreach (self::$_usedBackends as $backend) {
400
-			if ($backend instanceof OCP\Authentication\IApacheBackend) {
401
-				if ($backend->isSessionActive()) {
402
-					return $backend;
403
-				}
404
-			}
405
-		}
406
-
407
-		return null;
408
-	}
63
+    private static $_usedBackends = array();
64
+
65
+    private static $_setupedBackends = array();
66
+
67
+    // bool, stores if a user want to access a resource anonymously, e.g if they open a public link
68
+    private static $incognitoMode = false;
69
+
70
+    /**
71
+     * Adds the backend to the list of used backends
72
+     *
73
+     * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
74
+     * @return bool
75
+     *
76
+     * Set the User Authentication Module
77
+     * @suppress PhanDeprecatedFunction
78
+     */
79
+    public static function useBackend($backend = 'database') {
80
+        if ($backend instanceof \OCP\UserInterface) {
81
+            self::$_usedBackends[get_class($backend)] = $backend;
82
+            \OC::$server->getUserManager()->registerBackend($backend);
83
+        } else {
84
+            // You'll never know what happens
85
+            if (null === $backend OR !is_string($backend)) {
86
+                $backend = 'database';
87
+            }
88
+
89
+            // Load backend
90
+            switch ($backend) {
91
+                case 'database':
92
+                case 'mysql':
93
+                case 'sqlite':
94
+                    \OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', ILogger::DEBUG);
95
+                    self::$_usedBackends[$backend] = new \OC\User\Database();
96
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
97
+                    break;
98
+                case 'dummy':
99
+                    self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
100
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
101
+                    break;
102
+                default:
103
+                    \OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', ILogger::DEBUG);
104
+                    $className = 'OC_USER_' . strtoupper($backend);
105
+                    self::$_usedBackends[$backend] = new $className();
106
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
107
+                    break;
108
+            }
109
+        }
110
+        return true;
111
+    }
112
+
113
+    /**
114
+     * remove all used backends
115
+     */
116
+    public static function clearBackends() {
117
+        self::$_usedBackends = array();
118
+        \OC::$server->getUserManager()->clearBackends();
119
+    }
120
+
121
+    /**
122
+     * setup the configured backends in config.php
123
+     * @suppress PhanDeprecatedFunction
124
+     */
125
+    public static function setupBackends() {
126
+        OC_App::loadApps(['prelogin']);
127
+        $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
128
+        if (isset($backends['default']) && !$backends['default']) {
129
+            // clear default backends
130
+            self::clearBackends();
131
+        }
132
+        foreach ($backends as $i => $config) {
133
+            if (!is_array($config)) {
134
+                continue;
135
+            }
136
+            $class = $config['class'];
137
+            $arguments = $config['arguments'];
138
+            if (class_exists($class)) {
139
+                if (array_search($i, self::$_setupedBackends) === false) {
140
+                    // make a reflection object
141
+                    $reflectionObj = new ReflectionClass($class);
142
+
143
+                    // use Reflection to create a new instance, using the $args
144
+                    $backend = $reflectionObj->newInstanceArgs($arguments);
145
+                    self::useBackend($backend);
146
+                    self::$_setupedBackends[] = $i;
147
+                } else {
148
+                    \OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', ILogger::DEBUG);
149
+                }
150
+            } else {
151
+                \OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', ILogger::ERROR);
152
+            }
153
+        }
154
+    }
155
+
156
+    /**
157
+     * Try to login a user, assuming authentication
158
+     * has already happened (e.g. via Single Sign On).
159
+     *
160
+     * Log in a user and regenerate a new session.
161
+     *
162
+     * @param \OCP\Authentication\IApacheBackend $backend
163
+     * @return bool
164
+     */
165
+    public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
166
+
167
+        $uid = $backend->getCurrentUserId();
168
+        $run = true;
169
+        OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
170
+
171
+        if ($uid) {
172
+            if (self::getUser() !== $uid) {
173
+                self::setUserId($uid);
174
+                $userSession = \OC::$server->getUserSession();
175
+                $userSession->setLoginName($uid);
176
+                $request = OC::$server->getRequest();
177
+                $userSession->createSessionToken($request, $uid, $uid);
178
+                // setup the filesystem
179
+                OC_Util::setupFS($uid);
180
+                // first call the post_login hooks, the login-process needs to be
181
+                // completed before we can safely create the users folder.
182
+                // For example encryption needs to initialize the users keys first
183
+                // before we can create the user folder with the skeleton files
184
+                OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
185
+                //trigger creation of user home and /files folder
186
+                \OC::$server->getUserFolder($uid);
187
+            }
188
+            return true;
189
+        }
190
+        return false;
191
+    }
192
+
193
+    /**
194
+     * Verify with Apache whether user is authenticated.
195
+     *
196
+     * @return boolean|null
197
+     *          true: authenticated
198
+     *          false: not authenticated
199
+     *          null: not handled / no backend available
200
+     */
201
+    public static function handleApacheAuth() {
202
+        $backend = self::findFirstActiveUsedBackend();
203
+        if ($backend) {
204
+            OC_App::loadApps();
205
+
206
+            //setup extra user backends
207
+            self::setupBackends();
208
+            \OC::$server->getUserSession()->unsetMagicInCookie();
209
+
210
+            return self::loginWithApache($backend);
211
+        }
212
+
213
+        return null;
214
+    }
215
+
216
+
217
+    /**
218
+     * Sets user id for session and triggers emit
219
+     *
220
+     * @param string $uid
221
+     */
222
+    public static function setUserId($uid) {
223
+        $userSession = \OC::$server->getUserSession();
224
+        $userManager = \OC::$server->getUserManager();
225
+        if ($user = $userManager->get($uid)) {
226
+            $userSession->setUser($user);
227
+        } else {
228
+            \OC::$server->getSession()->set('user_id', $uid);
229
+        }
230
+    }
231
+
232
+    /**
233
+     * Check if the user is logged in, considers also the HTTP basic credentials
234
+     *
235
+     * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
236
+     * @return bool
237
+     */
238
+    public static function isLoggedIn() {
239
+        return \OC::$server->getUserSession()->isLoggedIn();
240
+    }
241
+
242
+    /**
243
+     * set incognito mode, e.g. if a user wants to open a public link
244
+     *
245
+     * @param bool $status
246
+     */
247
+    public static function setIncognitoMode($status) {
248
+        self::$incognitoMode = $status;
249
+    }
250
+
251
+    /**
252
+     * get incognito mode status
253
+     *
254
+     * @return bool
255
+     */
256
+    public static function isIncognitoMode() {
257
+        return self::$incognitoMode;
258
+    }
259
+
260
+    /**
261
+     * Returns the current logout URL valid for the currently logged-in user
262
+     *
263
+     * @param \OCP\IURLGenerator $urlGenerator
264
+     * @return string
265
+     */
266
+    public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) {
267
+        $backend = self::findFirstActiveUsedBackend();
268
+        if ($backend) {
269
+            return $backend->getLogoutUrl();
270
+        }
271
+
272
+        $logoutUrl = $urlGenerator->linkToRouteAbsolute(
273
+            'core.login.logout',
274
+            [
275
+                'requesttoken' => \OCP\Util::callRegister(),
276
+            ]
277
+        );
278
+
279
+        return $logoutUrl;
280
+    }
281
+
282
+    /**
283
+     * Check if the user is an admin user
284
+     *
285
+     * @param string $uid uid of the admin
286
+     * @return bool
287
+     */
288
+    public static function isAdminUser($uid) {
289
+        $group = \OC::$server->getGroupManager()->get('admin');
290
+        $user = \OC::$server->getUserManager()->get($uid);
291
+        if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
292
+            return true;
293
+        }
294
+        return false;
295
+    }
296
+
297
+
298
+    /**
299
+     * get the user id of the user currently logged in.
300
+     *
301
+     * @return string|bool uid or false
302
+     */
303
+    public static function getUser() {
304
+        $uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
305
+        if (!is_null($uid) && self::$incognitoMode === false) {
306
+            return $uid;
307
+        } else {
308
+            return false;
309
+        }
310
+    }
311
+
312
+    /**
313
+     * get the display name of the user currently logged in.
314
+     *
315
+     * @param string $uid
316
+     * @return string|bool uid or false
317
+     * @deprecated 8.1.0 fetch \OCP\IUser (has getDisplayName()) by using method
318
+     *                   get() of \OCP\IUserManager - \OC::$server->getUserManager()
319
+     */
320
+    public static function getDisplayName($uid = null) {
321
+        if ($uid) {
322
+            $user = \OC::$server->getUserManager()->get($uid);
323
+            if ($user) {
324
+                return $user->getDisplayName();
325
+            } else {
326
+                return $uid;
327
+            }
328
+        } else {
329
+            $user = \OC::$server->getUserSession()->getUser();
330
+            if ($user) {
331
+                return $user->getDisplayName();
332
+            } else {
333
+                return false;
334
+            }
335
+        }
336
+    }
337
+
338
+    /**
339
+     * Set password
340
+     *
341
+     * @param string $uid The username
342
+     * @param string $password The new password
343
+     * @param string $recoveryPassword for the encryption app to reset encryption keys
344
+     * @return bool
345
+     *
346
+     * Change the password of a user
347
+     */
348
+    public static function setPassword($uid, $password, $recoveryPassword = null) {
349
+        $user = \OC::$server->getUserManager()->get($uid);
350
+        if ($user) {
351
+            return $user->setPassword($password, $recoveryPassword);
352
+        } else {
353
+            return false;
354
+        }
355
+    }
356
+
357
+    /**
358
+     * @param string $uid The username
359
+     * @return string
360
+     *
361
+     * returns the path to the users home directory
362
+     * @deprecated Use \OC::$server->getUserManager->getHome()
363
+     */
364
+    public static function getHome($uid) {
365
+        $user = \OC::$server->getUserManager()->get($uid);
366
+        if ($user) {
367
+            return $user->getHome();
368
+        } else {
369
+            return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
370
+        }
371
+    }
372
+
373
+    /**
374
+     * Get a list of all users display name
375
+     *
376
+     * @param string $search
377
+     * @param int $limit
378
+     * @param int $offset
379
+     * @return array associative array with all display names (value) and corresponding uids (key)
380
+     *
381
+     * Get a list of all display names and user ids.
382
+     * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
383
+     */
384
+    public static function getDisplayNames($search = '', $limit = null, $offset = null) {
385
+        $displayNames = array();
386
+        $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
387
+        foreach ($users as $user) {
388
+            $displayNames[$user->getUID()] = $user->getDisplayName();
389
+        }
390
+        return $displayNames;
391
+    }
392
+
393
+    /**
394
+     * Returns the first active backend from self::$_usedBackends.
395
+     *
396
+     * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
397
+     */
398
+    private static function findFirstActiveUsedBackend() {
399
+        foreach (self::$_usedBackends as $backend) {
400
+            if ($backend instanceof OCP\Authentication\IApacheBackend) {
401
+                if ($backend->isSessionActive()) {
402
+                    return $backend;
403
+                }
404
+            }
405
+        }
406
+
407
+        return null;
408
+    }
409 409
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 				case 'database':
92 92
 				case 'mysql':
93 93
 				case 'sqlite':
94
-					\OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', ILogger::DEBUG);
94
+					\OCP\Util::writeLog('core', 'Adding user backend '.$backend.'.', ILogger::DEBUG);
95 95
 					self::$_usedBackends[$backend] = new \OC\User\Database();
96 96
 					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
97 97
 					break;
@@ -100,8 +100,8 @@  discard block
 block discarded – undo
100 100
 					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
101 101
 					break;
102 102
 				default:
103
-					\OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', ILogger::DEBUG);
104
-					$className = 'OC_USER_' . strtoupper($backend);
103
+					\OCP\Util::writeLog('core', 'Adding default user backend '.$backend.'.', ILogger::DEBUG);
104
+					$className = 'OC_USER_'.strtoupper($backend);
105 105
 					self::$_usedBackends[$backend] = new $className();
106 106
 					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
107 107
 					break;
@@ -145,10 +145,10 @@  discard block
 block discarded – undo
145 145
 					self::useBackend($backend);
146 146
 					self::$_setupedBackends[] = $i;
147 147
 				} else {
148
-					\OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', ILogger::DEBUG);
148
+					\OCP\Util::writeLog('core', 'User backend '.$class.' already initialized.', ILogger::DEBUG);
149 149
 				}
150 150
 			} else {
151
-				\OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', ILogger::ERROR);
151
+				\OCP\Util::writeLog('core', 'User backend '.$class.' not found.', ILogger::ERROR);
152 152
 			}
153 153
 		}
154 154
 	}
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
 		if ($user) {
367 367
 			return $user->getHome();
368 368
 		} else {
369
-			return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
369
+			return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT.'/data').'/'.$uid;
370 370
 		}
371 371
 	}
372 372
 
Please login to merge, or discard this patch.
lib/private/legacy/db.php 1 patch
Indentation   +193 added lines, -193 removed lines patch added patch discarded remove patch
@@ -36,209 +36,209 @@
 block discarded – undo
36 36
  */
37 37
 class OC_DB {
38 38
 
39
-	/**
40
-	 * get MDB2 schema manager
41
-	 *
42
-	 * @return \OC\DB\MDB2SchemaManager
43
-	 */
44
-	private static function getMDB2SchemaManager() {
45
-		return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
46
-	}
39
+    /**
40
+     * get MDB2 schema manager
41
+     *
42
+     * @return \OC\DB\MDB2SchemaManager
43
+     */
44
+    private static function getMDB2SchemaManager() {
45
+        return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
46
+    }
47 47
 
48
-	/**
49
-	 * Prepare a SQL query
50
-	 * @param string $query Query string
51
-	 * @param int|null $limit
52
-	 * @param int|null $offset
53
-	 * @param bool|null $isManipulation
54
-	 * @throws \OC\DatabaseException
55
-	 * @return OC_DB_StatementWrapper prepared SQL query
56
-	 *
57
-	 * SQL query via Doctrine prepare(), needs to be execute()'d!
58
-	 */
59
-	static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
60
-		$connection = \OC::$server->getDatabaseConnection();
48
+    /**
49
+     * Prepare a SQL query
50
+     * @param string $query Query string
51
+     * @param int|null $limit
52
+     * @param int|null $offset
53
+     * @param bool|null $isManipulation
54
+     * @throws \OC\DatabaseException
55
+     * @return OC_DB_StatementWrapper prepared SQL query
56
+     *
57
+     * SQL query via Doctrine prepare(), needs to be execute()'d!
58
+     */
59
+    static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
60
+        $connection = \OC::$server->getDatabaseConnection();
61 61
 
62
-		if ($isManipulation === null) {
63
-			//try to guess, so we return the number of rows on manipulations
64
-			$isManipulation = self::isManipulation($query);
65
-		}
62
+        if ($isManipulation === null) {
63
+            //try to guess, so we return the number of rows on manipulations
64
+            $isManipulation = self::isManipulation($query);
65
+        }
66 66
 
67
-		// return the result
68
-		try {
69
-			$result =$connection->prepare($query, $limit, $offset);
70
-		} catch (\Doctrine\DBAL\DBALException $e) {
71
-			throw new \OC\DatabaseException($e->getMessage());
72
-		}
73
-		// differentiate between query and manipulation
74
-		$result = new OC_DB_StatementWrapper($result, $isManipulation);
75
-		return $result;
76
-	}
67
+        // return the result
68
+        try {
69
+            $result =$connection->prepare($query, $limit, $offset);
70
+        } catch (\Doctrine\DBAL\DBALException $e) {
71
+            throw new \OC\DatabaseException($e->getMessage());
72
+        }
73
+        // differentiate between query and manipulation
74
+        $result = new OC_DB_StatementWrapper($result, $isManipulation);
75
+        return $result;
76
+    }
77 77
 
78
-	/**
79
-	 * tries to guess the type of statement based on the first 10 characters
80
-	 * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
81
-	 *
82
-	 * @param string $sql
83
-	 * @return bool
84
-	 */
85
-	static public function isManipulation( $sql ) {
86
-		$selectOccurrence = stripos($sql, 'SELECT');
87
-		if ($selectOccurrence !== false && $selectOccurrence < 10) {
88
-			return false;
89
-		}
90
-		$insertOccurrence = stripos($sql, 'INSERT');
91
-		if ($insertOccurrence !== false && $insertOccurrence < 10) {
92
-			return true;
93
-		}
94
-		$updateOccurrence = stripos($sql, 'UPDATE');
95
-		if ($updateOccurrence !== false && $updateOccurrence < 10) {
96
-			return true;
97
-		}
98
-		$deleteOccurrence = stripos($sql, 'DELETE');
99
-		if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
100
-			return true;
101
-		}
102
-		return false;
103
-	}
78
+    /**
79
+     * tries to guess the type of statement based on the first 10 characters
80
+     * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
81
+     *
82
+     * @param string $sql
83
+     * @return bool
84
+     */
85
+    static public function isManipulation( $sql ) {
86
+        $selectOccurrence = stripos($sql, 'SELECT');
87
+        if ($selectOccurrence !== false && $selectOccurrence < 10) {
88
+            return false;
89
+        }
90
+        $insertOccurrence = stripos($sql, 'INSERT');
91
+        if ($insertOccurrence !== false && $insertOccurrence < 10) {
92
+            return true;
93
+        }
94
+        $updateOccurrence = stripos($sql, 'UPDATE');
95
+        if ($updateOccurrence !== false && $updateOccurrence < 10) {
96
+            return true;
97
+        }
98
+        $deleteOccurrence = stripos($sql, 'DELETE');
99
+        if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
100
+            return true;
101
+        }
102
+        return false;
103
+    }
104 104
 
105
-	/**
106
-	 * execute a prepared statement, on error write log and throw exception
107
-	 * @param mixed $stmt OC_DB_StatementWrapper,
108
-	 *					  an array with 'sql' and optionally 'limit' and 'offset' keys
109
-	 *					.. or a simple sql query string
110
-	 * @param array $parameters
111
-	 * @return OC_DB_StatementWrapper
112
-	 * @throws \OC\DatabaseException
113
-	 */
114
-	static public function executeAudited( $stmt, array $parameters = []) {
115
-		if (is_string($stmt)) {
116
-			// convert to an array with 'sql'
117
-			if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
118
-				// TODO try to convert LIMIT OFFSET notation to parameters
119
-				$message = 'LIMIT and OFFSET are forbidden for portability reasons,'
120
-						 . ' pass an array with \'limit\' and \'offset\' instead';
121
-				throw new \OC\DatabaseException($message);
122
-			}
123
-			$stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
124
-		}
125
-		if (is_array($stmt)) {
126
-			// convert to prepared statement
127
-			if ( ! array_key_exists('sql', $stmt) ) {
128
-				$message = 'statement array must at least contain key \'sql\'';
129
-				throw new \OC\DatabaseException($message);
130
-			}
131
-			if ( ! array_key_exists('limit', $stmt) ) {
132
-				$stmt['limit'] = null;
133
-			}
134
-			if ( ! array_key_exists('limit', $stmt) ) {
135
-				$stmt['offset'] = null;
136
-			}
137
-			$stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
138
-		}
139
-		self::raiseExceptionOnError($stmt, 'Could not prepare statement');
140
-		if ($stmt instanceof OC_DB_StatementWrapper) {
141
-			$result = $stmt->execute($parameters);
142
-			self::raiseExceptionOnError($result, 'Could not execute statement');
143
-		} else {
144
-			if (is_object($stmt)) {
145
-				$message = 'Expected a prepared statement or array got ' . get_class($stmt);
146
-			} else {
147
-				$message = 'Expected a prepared statement or array got ' . gettype($stmt);
148
-			}
149
-			throw new \OC\DatabaseException($message);
150
-		}
151
-		return $result;
152
-	}
105
+    /**
106
+     * execute a prepared statement, on error write log and throw exception
107
+     * @param mixed $stmt OC_DB_StatementWrapper,
108
+     *					  an array with 'sql' and optionally 'limit' and 'offset' keys
109
+     *					.. or a simple sql query string
110
+     * @param array $parameters
111
+     * @return OC_DB_StatementWrapper
112
+     * @throws \OC\DatabaseException
113
+     */
114
+    static public function executeAudited( $stmt, array $parameters = []) {
115
+        if (is_string($stmt)) {
116
+            // convert to an array with 'sql'
117
+            if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
118
+                // TODO try to convert LIMIT OFFSET notation to parameters
119
+                $message = 'LIMIT and OFFSET are forbidden for portability reasons,'
120
+                            . ' pass an array with \'limit\' and \'offset\' instead';
121
+                throw new \OC\DatabaseException($message);
122
+            }
123
+            $stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
124
+        }
125
+        if (is_array($stmt)) {
126
+            // convert to prepared statement
127
+            if ( ! array_key_exists('sql', $stmt) ) {
128
+                $message = 'statement array must at least contain key \'sql\'';
129
+                throw new \OC\DatabaseException($message);
130
+            }
131
+            if ( ! array_key_exists('limit', $stmt) ) {
132
+                $stmt['limit'] = null;
133
+            }
134
+            if ( ! array_key_exists('limit', $stmt) ) {
135
+                $stmt['offset'] = null;
136
+            }
137
+            $stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
138
+        }
139
+        self::raiseExceptionOnError($stmt, 'Could not prepare statement');
140
+        if ($stmt instanceof OC_DB_StatementWrapper) {
141
+            $result = $stmt->execute($parameters);
142
+            self::raiseExceptionOnError($result, 'Could not execute statement');
143
+        } else {
144
+            if (is_object($stmt)) {
145
+                $message = 'Expected a prepared statement or array got ' . get_class($stmt);
146
+            } else {
147
+                $message = 'Expected a prepared statement or array got ' . gettype($stmt);
148
+            }
149
+            throw new \OC\DatabaseException($message);
150
+        }
151
+        return $result;
152
+    }
153 153
 
154
-	/**
155
-	 * saves database schema to xml file
156
-	 * @param string $file name of file
157
-	 * @return bool
158
-	 *
159
-	 * TODO: write more documentation
160
-	 */
161
-	public static function getDbStructure($file) {
162
-		$schemaManager = self::getMDB2SchemaManager();
163
-		return $schemaManager->getDbStructure($file);
164
-	}
154
+    /**
155
+     * saves database schema to xml file
156
+     * @param string $file name of file
157
+     * @return bool
158
+     *
159
+     * TODO: write more documentation
160
+     */
161
+    public static function getDbStructure($file) {
162
+        $schemaManager = self::getMDB2SchemaManager();
163
+        return $schemaManager->getDbStructure($file);
164
+    }
165 165
 
166
-	/**
167
-	 * Creates tables from XML file
168
-	 * @param string $file file to read structure from
169
-	 * @return bool
170
-	 *
171
-	 * TODO: write more documentation
172
-	 */
173
-	public static function createDbFromStructure( $file ) {
174
-		$schemaManager = self::getMDB2SchemaManager();
175
-		return $schemaManager->createDbFromStructure($file);
176
-	}
166
+    /**
167
+     * Creates tables from XML file
168
+     * @param string $file file to read structure from
169
+     * @return bool
170
+     *
171
+     * TODO: write more documentation
172
+     */
173
+    public static function createDbFromStructure( $file ) {
174
+        $schemaManager = self::getMDB2SchemaManager();
175
+        return $schemaManager->createDbFromStructure($file);
176
+    }
177 177
 
178
-	/**
179
-	 * update the database schema
180
-	 * @param string $file file to read structure from
181
-	 * @throws Exception
182
-	 * @return string|boolean
183
-	 * @suppress PhanDeprecatedFunction
184
-	 */
185
-	public static function updateDbFromStructure($file) {
186
-		$schemaManager = self::getMDB2SchemaManager();
187
-		try {
188
-			$result = $schemaManager->updateDbFromStructure($file);
189
-		} catch (Exception $e) {
190
-			\OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', ILogger::FATAL);
191
-			throw $e;
192
-		}
193
-		return $result;
194
-	}
178
+    /**
179
+     * update the database schema
180
+     * @param string $file file to read structure from
181
+     * @throws Exception
182
+     * @return string|boolean
183
+     * @suppress PhanDeprecatedFunction
184
+     */
185
+    public static function updateDbFromStructure($file) {
186
+        $schemaManager = self::getMDB2SchemaManager();
187
+        try {
188
+            $result = $schemaManager->updateDbFromStructure($file);
189
+        } catch (Exception $e) {
190
+            \OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', ILogger::FATAL);
191
+            throw $e;
192
+        }
193
+        return $result;
194
+    }
195 195
 
196
-	/**
197
-	 * remove all tables defined in a database structure xml file
198
-	 * @param string $file the xml file describing the tables
199
-	 */
200
-	public static function removeDBStructure($file) {
201
-		$schemaManager = self::getMDB2SchemaManager();
202
-		$schemaManager->removeDBStructure($file);
203
-	}
196
+    /**
197
+     * remove all tables defined in a database structure xml file
198
+     * @param string $file the xml file describing the tables
199
+     */
200
+    public static function removeDBStructure($file) {
201
+        $schemaManager = self::getMDB2SchemaManager();
202
+        $schemaManager->removeDBStructure($file);
203
+    }
204 204
 
205
-	/**
206
-	 * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
207
-	 * @param mixed $result
208
-	 * @param string $message
209
-	 * @return void
210
-	 * @throws \OC\DatabaseException
211
-	 */
212
-	public static function raiseExceptionOnError($result, $message = null) {
213
-		if($result === false) {
214
-			if ($message === null) {
215
-				$message = self::getErrorMessage();
216
-			} else {
217
-				$message .= ', Root cause:' . self::getErrorMessage();
218
-			}
219
-			throw new \OC\DatabaseException($message);
220
-		}
221
-	}
205
+    /**
206
+     * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
207
+     * @param mixed $result
208
+     * @param string $message
209
+     * @return void
210
+     * @throws \OC\DatabaseException
211
+     */
212
+    public static function raiseExceptionOnError($result, $message = null) {
213
+        if($result === false) {
214
+            if ($message === null) {
215
+                $message = self::getErrorMessage();
216
+            } else {
217
+                $message .= ', Root cause:' . self::getErrorMessage();
218
+            }
219
+            throw new \OC\DatabaseException($message);
220
+        }
221
+    }
222 222
 
223
-	/**
224
-	 * returns the error code and message as a string for logging
225
-	 * works with DoctrineException
226
-	 * @return string
227
-	 */
228
-	public static function getErrorMessage() {
229
-		$connection = \OC::$server->getDatabaseConnection();
230
-		return $connection->getError();
231
-	}
223
+    /**
224
+     * returns the error code and message as a string for logging
225
+     * works with DoctrineException
226
+     * @return string
227
+     */
228
+    public static function getErrorMessage() {
229
+        $connection = \OC::$server->getDatabaseConnection();
230
+        return $connection->getError();
231
+    }
232 232
 
233
-	/**
234
-	 * Checks if a table exists in the database - the database prefix will be prepended
235
-	 *
236
-	 * @param string $table
237
-	 * @return bool
238
-	 * @throws \OC\DatabaseException
239
-	 */
240
-	public static function tableExists($table) {
241
-		$connection = \OC::$server->getDatabaseConnection();
242
-		return $connection->tableExists($table);
243
-	}
233
+    /**
234
+     * Checks if a table exists in the database - the database prefix will be prepended
235
+     *
236
+     * @param string $table
237
+     * @return bool
238
+     * @throws \OC\DatabaseException
239
+     */
240
+    public static function tableExists($table) {
241
+        $connection = \OC::$server->getDatabaseConnection();
242
+        return $connection->tableExists($table);
243
+    }
244 244
 }
Please login to merge, or discard this patch.
lib/private/legacy/files.php 2 patches
Indentation   +430 added lines, -430 removed lines patch added patch discarded remove patch
@@ -49,438 +49,438 @@
 block discarded – undo
49 49
  *
50 50
  */
51 51
 class OC_Files {
52
-	const FILE = 1;
53
-	const ZIP_FILES = 2;
54
-	const ZIP_DIR = 3;
55
-
56
-	const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
57
-
58
-
59
-	private static $multipartBoundary = '';
60
-
61
-	/**
62
-	 * @return string
63
-	 */
64
-	private static function getBoundary() {
65
-		if (empty(self::$multipartBoundary)) {
66
-			self::$multipartBoundary = md5(mt_rand());
67
-		}
68
-		return self::$multipartBoundary;
69
-	}
70
-
71
-	/**
72
-	 * @param string $filename
73
-	 * @param string $name
74
-	 * @param array $rangeArray ('from'=>int,'to'=>int), ...
75
-	 */
76
-	private static function sendHeaders($filename, $name, array $rangeArray) {
77
-		OC_Response::setContentDispositionHeader($name, 'attachment');
78
-		header('Content-Transfer-Encoding: binary', true);
79
-		header('Pragma: public');// enable caching in IE
80
-		header('Expires: 0');
81
-		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
82
-		$fileSize = \OC\Files\Filesystem::filesize($filename);
83
-		$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
84
-		if ($fileSize > -1) {
85
-			if (!empty($rangeArray)) {
86
-			    header('HTTP/1.1 206 Partial Content', true);
87
-			    header('Accept-Ranges: bytes', true);
88
-			    if (count($rangeArray) > 1) {
89
-				$type = 'multipart/byteranges; boundary='.self::getBoundary();
90
-				// no Content-Length header here
91
-			    }
92
-			    else {
93
-				header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
94
-				OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
95
-			    }
96
-			}
97
-			else {
98
-			    OC_Response::setContentLengthHeader($fileSize);
99
-			}
100
-		}
101
-		header('Content-Type: '.$type, true);
102
-	}
103
-
104
-	/**
105
-	 * return the content of a file or return a zip file containing multiple files
106
-	 *
107
-	 * @param string $dir
108
-	 * @param string $files ; separated list of files to download
109
-	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
110
-	 */
111
-	public static function get($dir, $files, $params = null) {
112
-
113
-		$view = \OC\Files\Filesystem::getView();
114
-		$getType = self::FILE;
115
-		$filename = $dir;
116
-		try {
117
-
118
-			if (is_array($files) && count($files) === 1) {
119
-				$files = $files[0];
120
-			}
121
-
122
-			if (!is_array($files)) {
123
-				$filename = $dir . '/' . $files;
124
-				if (!$view->is_dir($filename)) {
125
-					self::getSingleFile($view, $dir, $files, is_null($params) ? array() : $params);
126
-					return;
127
-				}
128
-			}
129
-
130
-			$name = 'download';
131
-			if (is_array($files)) {
132
-				$getType = self::ZIP_FILES;
133
-				$basename = basename($dir);
134
-				if ($basename) {
135
-					$name = $basename;
136
-				}
137
-
138
-				$filename = $dir . '/' . $name;
139
-			} else {
140
-				$filename = $dir . '/' . $files;
141
-				$getType = self::ZIP_DIR;
142
-				// downloading root ?
143
-				if ($files !== '') {
144
-					$name = $files;
145
-				}
146
-			}
147
-
148
-			self::lockFiles($view, $dir, $files);
149
-
150
-			/* Calculate filesize and number of files */
151
-			if ($getType === self::ZIP_FILES) {
152
-				$fileInfos = array();
153
-				$fileSize = 0;
154
-				foreach ($files as $file) {
155
-					$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
156
-					$fileSize += $fileInfo->getSize();
157
-					$fileInfos[] = $fileInfo;
158
-				}
159
-				$numberOfFiles = self::getNumberOfFiles($fileInfos);
160
-			} elseif ($getType === self::ZIP_DIR) {
161
-				$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
162
-				$fileSize = $fileInfo->getSize();
163
-				$numberOfFiles = self::getNumberOfFiles(array($fileInfo));
164
-			}
165
-
166
-			$streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
167
-			OC_Util::obEnd();
168
-
169
-			$streamer->sendHeaders($name);
170
-			$executionTime = (int)OC::$server->getIniWrapper()->getNumeric('max_execution_time');
171
-			if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
172
-				@set_time_limit(0);
173
-			}
174
-			ignore_user_abort(true);
175
-
176
-			if ($getType === self::ZIP_FILES) {
177
-				foreach ($files as $file) {
178
-					$file = $dir . '/' . $file;
179
-					if (\OC\Files\Filesystem::is_file($file)) {
180
-						$fileSize = \OC\Files\Filesystem::filesize($file);
181
-						$fileTime = \OC\Files\Filesystem::filemtime($file);
182
-						$fh = \OC\Files\Filesystem::fopen($file, 'r');
183
-						$streamer->addFileFromStream($fh, basename($file), $fileSize, $fileTime);
184
-						fclose($fh);
185
-					} elseif (\OC\Files\Filesystem::is_dir($file)) {
186
-						$streamer->addDirRecursive($file);
187
-					}
188
-				}
189
-			} elseif ($getType === self::ZIP_DIR) {
190
-				$file = $dir . '/' . $files;
191
-				$streamer->addDirRecursive($file);
192
-			}
193
-			$streamer->finalize();
194
-			set_time_limit($executionTime);
195
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
196
-		} catch (\OCP\Lock\LockedException $ex) {
197
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
198
-			OC::$server->getLogger()->logException($ex);
199
-			$l = \OC::$server->getL10N('core');
200
-			$hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
201
-			\OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint);
202
-		} catch (\OCP\Files\ForbiddenException $ex) {
203
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
204
-			OC::$server->getLogger()->logException($ex);
205
-			$l = \OC::$server->getL10N('core');
206
-			\OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage());
207
-		} catch (\Exception $ex) {
208
-			self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
209
-			OC::$server->getLogger()->logException($ex);
210
-			$l = \OC::$server->getL10N('core');
211
-			$hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
212
-			\OC_Template::printErrorPage($l->t('Can\'t read file'), $hint);
213
-		}
214
-	}
215
-
216
-	/**
217
-	 * @param string $rangeHeaderPos
218
-	 * @param int $fileSize
219
-	 * @return array $rangeArray ('from'=>int,'to'=>int), ...
220
-	 */
221
-	private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
222
-		$rArray=explode(',', $rangeHeaderPos);
223
-		$minOffset = 0;
224
-		$ind = 0;
225
-
226
-		$rangeArray = array();
227
-
228
-		foreach ($rArray as $value) {
229
-			$ranges = explode('-', $value);
230
-			if (is_numeric($ranges[0])) {
231
-				if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
232
-					$ranges[0] = $minOffset;
233
-				}
234
-				if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
235
-					$ind--;
236
-					$ranges[0] = $rangeArray[$ind]['from'];
237
-				}
238
-			}
239
-
240
-			if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
241
-				// case: x-x
242
-				if ($ranges[1] >= $fileSize) {
243
-					$ranges[1] = $fileSize-1;
244
-				}
245
-				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize );
246
-				$minOffset = $ranges[1] + 1;
247
-				if ($minOffset >= $fileSize) {
248
-					break;
249
-				}
250
-			}
251
-			elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
252
-				// case: x-
253
-				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
254
-				break;
255
-			}
256
-			elseif (is_numeric($ranges[1])) {
257
-				// case: -x
258
-				if ($ranges[1] > $fileSize) {
259
-					$ranges[1] = $fileSize;
260
-				}
261
-				$rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize );
262
-				break;
263
-			}
264
-		}
265
-		return $rangeArray;
266
-	}
267
-
268
-	/**
269
-	 * @param View $view
270
-	 * @param string $name
271
-	 * @param string $dir
272
-	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
273
-	 */
274
-	private static function getSingleFile($view, $dir, $name, $params) {
275
-		$filename = $dir . '/' . $name;
276
-		OC_Util::obEnd();
277
-		$view->lockFile($filename, ILockingProvider::LOCK_SHARED);
52
+    const FILE = 1;
53
+    const ZIP_FILES = 2;
54
+    const ZIP_DIR = 3;
55
+
56
+    const UPLOAD_MIN_LIMIT_BYTES = 1048576; // 1 MiB
57
+
58
+
59
+    private static $multipartBoundary = '';
60
+
61
+    /**
62
+     * @return string
63
+     */
64
+    private static function getBoundary() {
65
+        if (empty(self::$multipartBoundary)) {
66
+            self::$multipartBoundary = md5(mt_rand());
67
+        }
68
+        return self::$multipartBoundary;
69
+    }
70
+
71
+    /**
72
+     * @param string $filename
73
+     * @param string $name
74
+     * @param array $rangeArray ('from'=>int,'to'=>int), ...
75
+     */
76
+    private static function sendHeaders($filename, $name, array $rangeArray) {
77
+        OC_Response::setContentDispositionHeader($name, 'attachment');
78
+        header('Content-Transfer-Encoding: binary', true);
79
+        header('Pragma: public');// enable caching in IE
80
+        header('Expires: 0');
81
+        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
82
+        $fileSize = \OC\Files\Filesystem::filesize($filename);
83
+        $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
84
+        if ($fileSize > -1) {
85
+            if (!empty($rangeArray)) {
86
+                header('HTTP/1.1 206 Partial Content', true);
87
+                header('Accept-Ranges: bytes', true);
88
+                if (count($rangeArray) > 1) {
89
+                $type = 'multipart/byteranges; boundary='.self::getBoundary();
90
+                // no Content-Length header here
91
+                }
92
+                else {
93
+                header(sprintf('Content-Range: bytes %d-%d/%d', $rangeArray[0]['from'], $rangeArray[0]['to'], $fileSize), true);
94
+                OC_Response::setContentLengthHeader($rangeArray[0]['to'] - $rangeArray[0]['from'] + 1);
95
+                }
96
+            }
97
+            else {
98
+                OC_Response::setContentLengthHeader($fileSize);
99
+            }
100
+        }
101
+        header('Content-Type: '.$type, true);
102
+    }
103
+
104
+    /**
105
+     * return the content of a file or return a zip file containing multiple files
106
+     *
107
+     * @param string $dir
108
+     * @param string $files ; separated list of files to download
109
+     * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
110
+     */
111
+    public static function get($dir, $files, $params = null) {
112
+
113
+        $view = \OC\Files\Filesystem::getView();
114
+        $getType = self::FILE;
115
+        $filename = $dir;
116
+        try {
117
+
118
+            if (is_array($files) && count($files) === 1) {
119
+                $files = $files[0];
120
+            }
121
+
122
+            if (!is_array($files)) {
123
+                $filename = $dir . '/' . $files;
124
+                if (!$view->is_dir($filename)) {
125
+                    self::getSingleFile($view, $dir, $files, is_null($params) ? array() : $params);
126
+                    return;
127
+                }
128
+            }
129
+
130
+            $name = 'download';
131
+            if (is_array($files)) {
132
+                $getType = self::ZIP_FILES;
133
+                $basename = basename($dir);
134
+                if ($basename) {
135
+                    $name = $basename;
136
+                }
137
+
138
+                $filename = $dir . '/' . $name;
139
+            } else {
140
+                $filename = $dir . '/' . $files;
141
+                $getType = self::ZIP_DIR;
142
+                // downloading root ?
143
+                if ($files !== '') {
144
+                    $name = $files;
145
+                }
146
+            }
147
+
148
+            self::lockFiles($view, $dir, $files);
149
+
150
+            /* Calculate filesize and number of files */
151
+            if ($getType === self::ZIP_FILES) {
152
+                $fileInfos = array();
153
+                $fileSize = 0;
154
+                foreach ($files as $file) {
155
+                    $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
156
+                    $fileSize += $fileInfo->getSize();
157
+                    $fileInfos[] = $fileInfo;
158
+                }
159
+                $numberOfFiles = self::getNumberOfFiles($fileInfos);
160
+            } elseif ($getType === self::ZIP_DIR) {
161
+                $fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
162
+                $fileSize = $fileInfo->getSize();
163
+                $numberOfFiles = self::getNumberOfFiles(array($fileInfo));
164
+            }
165
+
166
+            $streamer = new Streamer(\OC::$server->getRequest(), $fileSize, $numberOfFiles);
167
+            OC_Util::obEnd();
168
+
169
+            $streamer->sendHeaders($name);
170
+            $executionTime = (int)OC::$server->getIniWrapper()->getNumeric('max_execution_time');
171
+            if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
172
+                @set_time_limit(0);
173
+            }
174
+            ignore_user_abort(true);
175
+
176
+            if ($getType === self::ZIP_FILES) {
177
+                foreach ($files as $file) {
178
+                    $file = $dir . '/' . $file;
179
+                    if (\OC\Files\Filesystem::is_file($file)) {
180
+                        $fileSize = \OC\Files\Filesystem::filesize($file);
181
+                        $fileTime = \OC\Files\Filesystem::filemtime($file);
182
+                        $fh = \OC\Files\Filesystem::fopen($file, 'r');
183
+                        $streamer->addFileFromStream($fh, basename($file), $fileSize, $fileTime);
184
+                        fclose($fh);
185
+                    } elseif (\OC\Files\Filesystem::is_dir($file)) {
186
+                        $streamer->addDirRecursive($file);
187
+                    }
188
+                }
189
+            } elseif ($getType === self::ZIP_DIR) {
190
+                $file = $dir . '/' . $files;
191
+                $streamer->addDirRecursive($file);
192
+            }
193
+            $streamer->finalize();
194
+            set_time_limit($executionTime);
195
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
196
+        } catch (\OCP\Lock\LockedException $ex) {
197
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
198
+            OC::$server->getLogger()->logException($ex);
199
+            $l = \OC::$server->getL10N('core');
200
+            $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
201
+            \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint);
202
+        } catch (\OCP\Files\ForbiddenException $ex) {
203
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
204
+            OC::$server->getLogger()->logException($ex);
205
+            $l = \OC::$server->getL10N('core');
206
+            \OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage());
207
+        } catch (\Exception $ex) {
208
+            self::unlockAllTheFiles($dir, $files, $getType, $view, $filename);
209
+            OC::$server->getLogger()->logException($ex);
210
+            $l = \OC::$server->getL10N('core');
211
+            $hint = method_exists($ex, 'getHint') ? $ex->getHint() : '';
212
+            \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint);
213
+        }
214
+    }
215
+
216
+    /**
217
+     * @param string $rangeHeaderPos
218
+     * @param int $fileSize
219
+     * @return array $rangeArray ('from'=>int,'to'=>int), ...
220
+     */
221
+    private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
222
+        $rArray=explode(',', $rangeHeaderPos);
223
+        $minOffset = 0;
224
+        $ind = 0;
225
+
226
+        $rangeArray = array();
227
+
228
+        foreach ($rArray as $value) {
229
+            $ranges = explode('-', $value);
230
+            if (is_numeric($ranges[0])) {
231
+                if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
232
+                    $ranges[0] = $minOffset;
233
+                }
234
+                if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
235
+                    $ind--;
236
+                    $ranges[0] = $rangeArray[$ind]['from'];
237
+                }
238
+            }
239
+
240
+            if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
241
+                // case: x-x
242
+                if ($ranges[1] >= $fileSize) {
243
+                    $ranges[1] = $fileSize-1;
244
+                }
245
+                $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize );
246
+                $minOffset = $ranges[1] + 1;
247
+                if ($minOffset >= $fileSize) {
248
+                    break;
249
+                }
250
+            }
251
+            elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
252
+                // case: x-
253
+                $rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
254
+                break;
255
+            }
256
+            elseif (is_numeric($ranges[1])) {
257
+                // case: -x
258
+                if ($ranges[1] > $fileSize) {
259
+                    $ranges[1] = $fileSize;
260
+                }
261
+                $rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize );
262
+                break;
263
+            }
264
+        }
265
+        return $rangeArray;
266
+    }
267
+
268
+    /**
269
+     * @param View $view
270
+     * @param string $name
271
+     * @param string $dir
272
+     * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
273
+     */
274
+    private static function getSingleFile($view, $dir, $name, $params) {
275
+        $filename = $dir . '/' . $name;
276
+        OC_Util::obEnd();
277
+        $view->lockFile($filename, ILockingProvider::LOCK_SHARED);
278 278
 		
279
-		$rangeArray = array();
279
+        $rangeArray = array();
280 280
 
281
-		if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
282
-			$rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), 
283
-								 \OC\Files\Filesystem::filesize($filename));
284
-		}
281
+        if (isset($params['range']) && substr($params['range'], 0, 6) === 'bytes=') {
282
+            $rangeArray = self::parseHttpRangeHeader(substr($params['range'], 6), 
283
+                                    \OC\Files\Filesystem::filesize($filename));
284
+        }
285 285
 		
286
-		if (\OC\Files\Filesystem::isReadable($filename)) {
287
-			self::sendHeaders($filename, $name, $rangeArray);
288
-		} elseif (!\OC\Files\Filesystem::file_exists($filename)) {
289
-			header("HTTP/1.1 404 Not Found");
290
-			$tmpl = new OC_Template('', '404', 'guest');
291
-			$tmpl->printPage();
292
-			exit();
293
-		} else {
294
-			header("HTTP/1.1 403 Forbidden");
295
-			die('403 Forbidden');
296
-		}
297
-		if (isset($params['head']) && $params['head']) {
298
-			return;
299
-		}
300
-		if (!empty($rangeArray)) {
301
-			try {
302
-			    if (count($rangeArray) == 1) {
303
-				$view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
304
-			    }
305
-			    else {
306
-				// check if file is seekable (if not throw UnseekableException)
307
-				// we have to check it before body contents
308
-				$view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
309
-
310
-				$type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
311
-
312
-				foreach ($rangeArray as $range) {
313
-				    echo "\r\n--".self::getBoundary()."\r\n".
314
-				         "Content-type: ".$type."\r\n".
315
-				         "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
316
-				    $view->readfilePart($filename, $range['from'], $range['to']);
317
-				}
318
-				echo "\r\n--".self::getBoundary()."--\r\n";
319
-			    }
320
-			} catch (\OCP\Files\UnseekableException $ex) {
321
-			    // file is unseekable
322
-			    header_remove('Accept-Ranges');
323
-			    header_remove('Content-Range');
324
-			    header("HTTP/1.1 200 OK");
325
-			    self::sendHeaders($filename, $name, array());
326
-			    $view->readfile($filename);
327
-			}
328
-		}
329
-		else {
330
-		    $view->readfile($filename);
331
-		}
332
-	}
333
-
334
-	/**
335
-	 * Returns the total (recursive) number of files and folders in the given
336
-	 * FileInfos.
337
-	 *
338
-	 * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
339
-	 * @return int the total number of files and folders
340
-	 */
341
-	private static function getNumberOfFiles($fileInfos) {
342
-		$numberOfFiles = 0;
343
-
344
-		$view = new View();
345
-
346
-		while ($fileInfo = array_pop($fileInfos)) {
347
-			$numberOfFiles++;
348
-
349
-			if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
350
-				$fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
351
-			}
352
-		}
353
-
354
-		return $numberOfFiles;
355
-	}
356
-
357
-	/**
358
-	 * @param View $view
359
-	 * @param string $dir
360
-	 * @param string[]|string $files
361
-	 */
362
-	public static function lockFiles($view, $dir, $files) {
363
-		if (!is_array($files)) {
364
-			$file = $dir . '/' . $files;
365
-			$files = [$file];
366
-		}
367
-		foreach ($files as $file) {
368
-			$file = $dir . '/' . $file;
369
-			$view->lockFile($file, ILockingProvider::LOCK_SHARED);
370
-			if ($view->is_dir($file)) {
371
-				$contents = $view->getDirectoryContent($file);
372
-				$contents = array_map(function($fileInfo) use ($file) {
373
-					/** @var \OCP\Files\FileInfo $fileInfo */
374
-					return $file . '/' . $fileInfo->getName();
375
-				}, $contents);
376
-				self::lockFiles($view, $dir, $contents);
377
-			}
378
-		}
379
-	}
380
-
381
-	/**
382
-	 * set the maximum upload size limit for apache hosts using .htaccess
383
-	 *
384
-	 * @param int $size file size in bytes
385
-	 * @param array $files override '.htaccess' and '.user.ini' locations
386
-	 * @return bool|int false on failure, size on success
387
-	 */
388
-	public static function setUploadLimit($size, $files = []) {
389
-		//don't allow user to break his config
390
-		$size = (int)$size;
391
-		if ($size < self::UPLOAD_MIN_LIMIT_BYTES) {
392
-			return false;
393
-		}
394
-		$size = OC_Helper::phpFileSize($size);
395
-
396
-		$phpValueKeys = array(
397
-			'upload_max_filesize',
398
-			'post_max_size'
399
-		);
400
-
401
-		// default locations if not overridden by $files
402
-		$files = array_merge([
403
-			'.htaccess' => OC::$SERVERROOT . '/.htaccess',
404
-			'.user.ini' => OC::$SERVERROOT . '/.user.ini'
405
-		], $files);
406
-
407
-		$updateFiles = [
408
-			$files['.htaccess'] => [
409
-				'pattern' => '/php_value %1$s (\S)*/',
410
-				'setting' => 'php_value %1$s %2$s'
411
-			],
412
-			$files['.user.ini'] => [
413
-				'pattern' => '/%1$s=(\S)*/',
414
-				'setting' => '%1$s=%2$s'
415
-			]
416
-		];
417
-
418
-		$success = true;
419
-
420
-		foreach ($updateFiles as $filename => $patternMap) {
421
-			// suppress warnings from fopen()
422
-			$handle = @fopen($filename, 'r+');
423
-			if (!$handle) {
424
-				\OCP\Util::writeLog('files',
425
-					'Can\'t write upload limit to ' . $filename . '. Please check the file permissions',
426
-					ILogger::WARN);
427
-				$success = false;
428
-				continue; // try to update as many files as possible
429
-			}
430
-
431
-			$content = '';
432
-			while (!feof($handle)) {
433
-				$content .= fread($handle, 1000);
434
-			}
435
-
436
-			foreach ($phpValueKeys as $key) {
437
-				$pattern = vsprintf($patternMap['pattern'], [$key]);
438
-				$setting = vsprintf($patternMap['setting'], [$key, $size]);
439
-				$hasReplaced = 0;
440
-				$newContent = preg_replace($pattern, $setting, $content, 2, $hasReplaced);
441
-				if ($newContent !== null) {
442
-					$content = $newContent;
443
-				}
444
-				if ($hasReplaced === 0) {
445
-					$content .= "\n" . $setting;
446
-				}
447
-			}
448
-
449
-			// write file back
450
-			ftruncate($handle, 0);
451
-			rewind($handle);
452
-			fwrite($handle, $content);
453
-
454
-			fclose($handle);
455
-		}
456
-
457
-		if ($success) {
458
-			return OC_Helper::computerFileSize($size);
459
-		}
460
-		return false;
461
-	}
462
-
463
-	/**
464
-	 * @param string $dir
465
-	 * @param $files
466
-	 * @param integer $getType
467
-	 * @param View $view
468
-	 * @param string $filename
469
-	 */
470
-	private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
471
-		if ($getType === self::FILE) {
472
-			$view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
473
-		}
474
-		if ($getType === self::ZIP_FILES) {
475
-			foreach ($files as $file) {
476
-				$file = $dir . '/' . $file;
477
-				$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
478
-			}
479
-		}
480
-		if ($getType === self::ZIP_DIR) {
481
-			$file = $dir . '/' . $files;
482
-			$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
483
-		}
484
-	}
286
+        if (\OC\Files\Filesystem::isReadable($filename)) {
287
+            self::sendHeaders($filename, $name, $rangeArray);
288
+        } elseif (!\OC\Files\Filesystem::file_exists($filename)) {
289
+            header("HTTP/1.1 404 Not Found");
290
+            $tmpl = new OC_Template('', '404', 'guest');
291
+            $tmpl->printPage();
292
+            exit();
293
+        } else {
294
+            header("HTTP/1.1 403 Forbidden");
295
+            die('403 Forbidden');
296
+        }
297
+        if (isset($params['head']) && $params['head']) {
298
+            return;
299
+        }
300
+        if (!empty($rangeArray)) {
301
+            try {
302
+                if (count($rangeArray) == 1) {
303
+                $view->readfilePart($filename, $rangeArray[0]['from'], $rangeArray[0]['to']);
304
+                }
305
+                else {
306
+                // check if file is seekable (if not throw UnseekableException)
307
+                // we have to check it before body contents
308
+                $view->readfilePart($filename, $rangeArray[0]['size'], $rangeArray[0]['size']);
309
+
310
+                $type = \OC::$server->getMimeTypeDetector()->getSecureMimeType(\OC\Files\Filesystem::getMimeType($filename));
311
+
312
+                foreach ($rangeArray as $range) {
313
+                    echo "\r\n--".self::getBoundary()."\r\n".
314
+                            "Content-type: ".$type."\r\n".
315
+                            "Content-range: bytes ".$range['from']."-".$range['to']."/".$range['size']."\r\n\r\n";
316
+                    $view->readfilePart($filename, $range['from'], $range['to']);
317
+                }
318
+                echo "\r\n--".self::getBoundary()."--\r\n";
319
+                }
320
+            } catch (\OCP\Files\UnseekableException $ex) {
321
+                // file is unseekable
322
+                header_remove('Accept-Ranges');
323
+                header_remove('Content-Range');
324
+                header("HTTP/1.1 200 OK");
325
+                self::sendHeaders($filename, $name, array());
326
+                $view->readfile($filename);
327
+            }
328
+        }
329
+        else {
330
+            $view->readfile($filename);
331
+        }
332
+    }
333
+
334
+    /**
335
+     * Returns the total (recursive) number of files and folders in the given
336
+     * FileInfos.
337
+     *
338
+     * @param \OCP\Files\FileInfo[] $fileInfos the FileInfos to count
339
+     * @return int the total number of files and folders
340
+     */
341
+    private static function getNumberOfFiles($fileInfos) {
342
+        $numberOfFiles = 0;
343
+
344
+        $view = new View();
345
+
346
+        while ($fileInfo = array_pop($fileInfos)) {
347
+            $numberOfFiles++;
348
+
349
+            if ($fileInfo->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
350
+                $fileInfos = array_merge($fileInfos, $view->getDirectoryContent($fileInfo->getPath()));
351
+            }
352
+        }
353
+
354
+        return $numberOfFiles;
355
+    }
356
+
357
+    /**
358
+     * @param View $view
359
+     * @param string $dir
360
+     * @param string[]|string $files
361
+     */
362
+    public static function lockFiles($view, $dir, $files) {
363
+        if (!is_array($files)) {
364
+            $file = $dir . '/' . $files;
365
+            $files = [$file];
366
+        }
367
+        foreach ($files as $file) {
368
+            $file = $dir . '/' . $file;
369
+            $view->lockFile($file, ILockingProvider::LOCK_SHARED);
370
+            if ($view->is_dir($file)) {
371
+                $contents = $view->getDirectoryContent($file);
372
+                $contents = array_map(function($fileInfo) use ($file) {
373
+                    /** @var \OCP\Files\FileInfo $fileInfo */
374
+                    return $file . '/' . $fileInfo->getName();
375
+                }, $contents);
376
+                self::lockFiles($view, $dir, $contents);
377
+            }
378
+        }
379
+    }
380
+
381
+    /**
382
+     * set the maximum upload size limit for apache hosts using .htaccess
383
+     *
384
+     * @param int $size file size in bytes
385
+     * @param array $files override '.htaccess' and '.user.ini' locations
386
+     * @return bool|int false on failure, size on success
387
+     */
388
+    public static function setUploadLimit($size, $files = []) {
389
+        //don't allow user to break his config
390
+        $size = (int)$size;
391
+        if ($size < self::UPLOAD_MIN_LIMIT_BYTES) {
392
+            return false;
393
+        }
394
+        $size = OC_Helper::phpFileSize($size);
395
+
396
+        $phpValueKeys = array(
397
+            'upload_max_filesize',
398
+            'post_max_size'
399
+        );
400
+
401
+        // default locations if not overridden by $files
402
+        $files = array_merge([
403
+            '.htaccess' => OC::$SERVERROOT . '/.htaccess',
404
+            '.user.ini' => OC::$SERVERROOT . '/.user.ini'
405
+        ], $files);
406
+
407
+        $updateFiles = [
408
+            $files['.htaccess'] => [
409
+                'pattern' => '/php_value %1$s (\S)*/',
410
+                'setting' => 'php_value %1$s %2$s'
411
+            ],
412
+            $files['.user.ini'] => [
413
+                'pattern' => '/%1$s=(\S)*/',
414
+                'setting' => '%1$s=%2$s'
415
+            ]
416
+        ];
417
+
418
+        $success = true;
419
+
420
+        foreach ($updateFiles as $filename => $patternMap) {
421
+            // suppress warnings from fopen()
422
+            $handle = @fopen($filename, 'r+');
423
+            if (!$handle) {
424
+                \OCP\Util::writeLog('files',
425
+                    'Can\'t write upload limit to ' . $filename . '. Please check the file permissions',
426
+                    ILogger::WARN);
427
+                $success = false;
428
+                continue; // try to update as many files as possible
429
+            }
430
+
431
+            $content = '';
432
+            while (!feof($handle)) {
433
+                $content .= fread($handle, 1000);
434
+            }
435
+
436
+            foreach ($phpValueKeys as $key) {
437
+                $pattern = vsprintf($patternMap['pattern'], [$key]);
438
+                $setting = vsprintf($patternMap['setting'], [$key, $size]);
439
+                $hasReplaced = 0;
440
+                $newContent = preg_replace($pattern, $setting, $content, 2, $hasReplaced);
441
+                if ($newContent !== null) {
442
+                    $content = $newContent;
443
+                }
444
+                if ($hasReplaced === 0) {
445
+                    $content .= "\n" . $setting;
446
+                }
447
+            }
448
+
449
+            // write file back
450
+            ftruncate($handle, 0);
451
+            rewind($handle);
452
+            fwrite($handle, $content);
453
+
454
+            fclose($handle);
455
+        }
456
+
457
+        if ($success) {
458
+            return OC_Helper::computerFileSize($size);
459
+        }
460
+        return false;
461
+    }
462
+
463
+    /**
464
+     * @param string $dir
465
+     * @param $files
466
+     * @param integer $getType
467
+     * @param View $view
468
+     * @param string $filename
469
+     */
470
+    private static function unlockAllTheFiles($dir, $files, $getType, $view, $filename) {
471
+        if ($getType === self::FILE) {
472
+            $view->unlockFile($filename, ILockingProvider::LOCK_SHARED);
473
+        }
474
+        if ($getType === self::ZIP_FILES) {
475
+            foreach ($files as $file) {
476
+                $file = $dir . '/' . $file;
477
+                $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
478
+            }
479
+        }
480
+        if ($getType === self::ZIP_DIR) {
481
+            $file = $dir . '/' . $files;
482
+            $view->unlockFile($file, ILockingProvider::LOCK_SHARED);
483
+        }
484
+    }
485 485
 
486 486
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	private static function sendHeaders($filename, $name, array $rangeArray) {
77 77
 		OC_Response::setContentDispositionHeader($name, 'attachment');
78 78
 		header('Content-Transfer-Encoding: binary', true);
79
-		header('Pragma: public');// enable caching in IE
79
+		header('Pragma: public'); // enable caching in IE
80 80
 		header('Expires: 0');
81 81
 		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
82 82
 		$fileSize = \OC\Files\Filesystem::filesize($filename);
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
 			}
121 121
 
122 122
 			if (!is_array($files)) {
123
-				$filename = $dir . '/' . $files;
123
+				$filename = $dir.'/'.$files;
124 124
 				if (!$view->is_dir($filename)) {
125 125
 					self::getSingleFile($view, $dir, $files, is_null($params) ? array() : $params);
126 126
 					return;
@@ -135,9 +135,9 @@  discard block
 block discarded – undo
135 135
 					$name = $basename;
136 136
 				}
137 137
 
138
-				$filename = $dir . '/' . $name;
138
+				$filename = $dir.'/'.$name;
139 139
 			} else {
140
-				$filename = $dir . '/' . $files;
140
+				$filename = $dir.'/'.$files;
141 141
 				$getType = self::ZIP_DIR;
142 142
 				// downloading root ?
143 143
 				if ($files !== '') {
@@ -152,13 +152,13 @@  discard block
 block discarded – undo
152 152
 				$fileInfos = array();
153 153
 				$fileSize = 0;
154 154
 				foreach ($files as $file) {
155
-					$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $file);
155
+					$fileInfo = \OC\Files\Filesystem::getFileInfo($dir.'/'.$file);
156 156
 					$fileSize += $fileInfo->getSize();
157 157
 					$fileInfos[] = $fileInfo;
158 158
 				}
159 159
 				$numberOfFiles = self::getNumberOfFiles($fileInfos);
160 160
 			} elseif ($getType === self::ZIP_DIR) {
161
-				$fileInfo = \OC\Files\Filesystem::getFileInfo($dir . '/' . $files);
161
+				$fileInfo = \OC\Files\Filesystem::getFileInfo($dir.'/'.$files);
162 162
 				$fileSize = $fileInfo->getSize();
163 163
 				$numberOfFiles = self::getNumberOfFiles(array($fileInfo));
164 164
 			}
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 			OC_Util::obEnd();
168 168
 
169 169
 			$streamer->sendHeaders($name);
170
-			$executionTime = (int)OC::$server->getIniWrapper()->getNumeric('max_execution_time');
170
+			$executionTime = (int) OC::$server->getIniWrapper()->getNumeric('max_execution_time');
171 171
 			if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
172 172
 				@set_time_limit(0);
173 173
 			}
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 
176 176
 			if ($getType === self::ZIP_FILES) {
177 177
 				foreach ($files as $file) {
178
-					$file = $dir . '/' . $file;
178
+					$file = $dir.'/'.$file;
179 179
 					if (\OC\Files\Filesystem::is_file($file)) {
180 180
 						$fileSize = \OC\Files\Filesystem::filesize($file);
181 181
 						$fileTime = \OC\Files\Filesystem::filemtime($file);
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 					}
188 188
 				}
189 189
 			} elseif ($getType === self::ZIP_DIR) {
190
-				$file = $dir . '/' . $files;
190
+				$file = $dir.'/'.$files;
191 191
 				$streamer->addDirRecursive($file);
192 192
 			}
193 193
 			$streamer->finalize();
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 	 * @return array $rangeArray ('from'=>int,'to'=>int), ...
220 220
 	 */
221 221
 	private static function parseHttpRangeHeader($rangeHeaderPos, $fileSize) {
222
-		$rArray=explode(',', $rangeHeaderPos);
222
+		$rArray = explode(',', $rangeHeaderPos);
223 223
 		$minOffset = 0;
224 224
 		$ind = 0;
225 225
 
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
 				if ($ranges[0] < $minOffset) { // case: bytes=500-700,601-999
232 232
 					$ranges[0] = $minOffset;
233 233
 				}
234
-				if ($ind > 0 && $rangeArray[$ind-1]['to']+1 == $ranges[0]) { // case: bytes=500-600,601-999
234
+				if ($ind > 0 && $rangeArray[$ind - 1]['to'] + 1 == $ranges[0]) { // case: bytes=500-600,601-999
235 235
 					$ind--;
236 236
 					$ranges[0] = $rangeArray[$ind]['from'];
237 237
 				}
@@ -240,9 +240,9 @@  discard block
 block discarded – undo
240 240
 			if (is_numeric($ranges[0]) && is_numeric($ranges[1]) && $ranges[0] < $fileSize && $ranges[0] <= $ranges[1]) {
241 241
 				// case: x-x
242 242
 				if ($ranges[1] >= $fileSize) {
243
-					$ranges[1] = $fileSize-1;
243
+					$ranges[1] = $fileSize - 1;
244 244
 				}
245
-				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize );
245
+				$rangeArray[$ind++] = array('from' => $ranges[0], 'to' => $ranges[1], 'size' => $fileSize);
246 246
 				$minOffset = $ranges[1] + 1;
247 247
 				if ($minOffset >= $fileSize) {
248 248
 					break;
@@ -250,7 +250,7 @@  discard block
 block discarded – undo
250 250
 			}
251 251
 			elseif (is_numeric($ranges[0]) && $ranges[0] < $fileSize) {
252 252
 				// case: x-
253
-				$rangeArray[$ind++] = array( 'from' => $ranges[0], 'to' => $fileSize-1, 'size' => $fileSize );
253
+				$rangeArray[$ind++] = array('from' => $ranges[0], 'to' => $fileSize - 1, 'size' => $fileSize);
254 254
 				break;
255 255
 			}
256 256
 			elseif (is_numeric($ranges[1])) {
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
 				if ($ranges[1] > $fileSize) {
259 259
 					$ranges[1] = $fileSize;
260 260
 				}
261
-				$rangeArray[$ind++] = array( 'from' => $fileSize-$ranges[1], 'to' => $fileSize-1, 'size' => $fileSize );
261
+				$rangeArray[$ind++] = array('from' => $fileSize - $ranges[1], 'to' => $fileSize - 1, 'size' => $fileSize);
262 262
 				break;
263 263
 			}
264 264
 		}
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
 	 * @param array $params ; 'head' boolean to only send header of the request ; 'range' http range header
273 273
 	 */
274 274
 	private static function getSingleFile($view, $dir, $name, $params) {
275
-		$filename = $dir . '/' . $name;
275
+		$filename = $dir.'/'.$name;
276 276
 		OC_Util::obEnd();
277 277
 		$view->lockFile($filename, ILockingProvider::LOCK_SHARED);
278 278
 		
@@ -361,17 +361,17 @@  discard block
 block discarded – undo
361 361
 	 */
362 362
 	public static function lockFiles($view, $dir, $files) {
363 363
 		if (!is_array($files)) {
364
-			$file = $dir . '/' . $files;
364
+			$file = $dir.'/'.$files;
365 365
 			$files = [$file];
366 366
 		}
367 367
 		foreach ($files as $file) {
368
-			$file = $dir . '/' . $file;
368
+			$file = $dir.'/'.$file;
369 369
 			$view->lockFile($file, ILockingProvider::LOCK_SHARED);
370 370
 			if ($view->is_dir($file)) {
371 371
 				$contents = $view->getDirectoryContent($file);
372 372
 				$contents = array_map(function($fileInfo) use ($file) {
373 373
 					/** @var \OCP\Files\FileInfo $fileInfo */
374
-					return $file . '/' . $fileInfo->getName();
374
+					return $file.'/'.$fileInfo->getName();
375 375
 				}, $contents);
376 376
 				self::lockFiles($view, $dir, $contents);
377 377
 			}
@@ -387,7 +387,7 @@  discard block
 block discarded – undo
387 387
 	 */
388 388
 	public static function setUploadLimit($size, $files = []) {
389 389
 		//don't allow user to break his config
390
-		$size = (int)$size;
390
+		$size = (int) $size;
391 391
 		if ($size < self::UPLOAD_MIN_LIMIT_BYTES) {
392 392
 			return false;
393 393
 		}
@@ -400,8 +400,8 @@  discard block
 block discarded – undo
400 400
 
401 401
 		// default locations if not overridden by $files
402 402
 		$files = array_merge([
403
-			'.htaccess' => OC::$SERVERROOT . '/.htaccess',
404
-			'.user.ini' => OC::$SERVERROOT . '/.user.ini'
403
+			'.htaccess' => OC::$SERVERROOT.'/.htaccess',
404
+			'.user.ini' => OC::$SERVERROOT.'/.user.ini'
405 405
 		], $files);
406 406
 
407 407
 		$updateFiles = [
@@ -422,7 +422,7 @@  discard block
 block discarded – undo
422 422
 			$handle = @fopen($filename, 'r+');
423 423
 			if (!$handle) {
424 424
 				\OCP\Util::writeLog('files',
425
-					'Can\'t write upload limit to ' . $filename . '. Please check the file permissions',
425
+					'Can\'t write upload limit to '.$filename.'. Please check the file permissions',
426 426
 					ILogger::WARN);
427 427
 				$success = false;
428 428
 				continue; // try to update as many files as possible
@@ -442,7 +442,7 @@  discard block
 block discarded – undo
442 442
 					$content = $newContent;
443 443
 				}
444 444
 				if ($hasReplaced === 0) {
445
-					$content .= "\n" . $setting;
445
+					$content .= "\n".$setting;
446 446
 				}
447 447
 			}
448 448
 
@@ -473,12 +473,12 @@  discard block
 block discarded – undo
473 473
 		}
474 474
 		if ($getType === self::ZIP_FILES) {
475 475
 			foreach ($files as $file) {
476
-				$file = $dir . '/' . $file;
476
+				$file = $dir.'/'.$file;
477 477
 				$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
478 478
 			}
479 479
 		}
480 480
 		if ($getType === self::ZIP_DIR) {
481
-			$file = $dir . '/' . $files;
481
+			$file = $dir.'/'.$files;
482 482
 			$view->unlockFile($file, ILockingProvider::LOCK_SHARED);
483 483
 		}
484 484
 	}
Please login to merge, or discard this patch.