Completed
Pull Request — master (#8787)
by Morris
78:58 queued 56:29
created
lib/private/Tags.php 2 patches
Indentation   +802 added lines, -802 removed lines patch added patch discarded remove patch
@@ -50,806 +50,806 @@
 block discarded – undo
50 50
 
51 51
 class Tags implements \OCP\ITags {
52 52
 
53
-	/**
54
-	 * Tags
55
-	 *
56
-	 * @var array
57
-	 */
58
-	private $tags = array();
59
-
60
-	/**
61
-	 * Used for storing objectid/categoryname pairs while rescanning.
62
-	 *
63
-	 * @var array
64
-	 */
65
-	private static $relations = array();
66
-
67
-	/**
68
-	 * Type
69
-	 *
70
-	 * @var string
71
-	 */
72
-	private $type;
73
-
74
-	/**
75
-	 * User
76
-	 *
77
-	 * @var string
78
-	 */
79
-	private $user;
80
-
81
-	/**
82
-	 * Are we including tags for shared items?
83
-	 *
84
-	 * @var bool
85
-	 */
86
-	private $includeShared = false;
87
-
88
-	/**
89
-	 * The current user, plus any owners of the items shared with the current
90
-	 * user, if $this->includeShared === true.
91
-	 *
92
-	 * @var array
93
-	 */
94
-	private $owners = array();
95
-
96
-	/**
97
-	 * The Mapper we're using to communicate our Tag objects to the database.
98
-	 *
99
-	 * @var TagMapper
100
-	 */
101
-	private $mapper;
102
-
103
-	/**
104
-	 * The sharing backend for objects of $this->type. Required if
105
-	 * $this->includeShared === true to determine ownership of items.
106
-	 *
107
-	 * @var \OCP\Share_Backend
108
-	 */
109
-	private $backend;
110
-
111
-	const TAG_TABLE = '*PREFIX*vcategory';
112
-	const RELATION_TABLE = '*PREFIX*vcategory_to_object';
113
-
114
-	const TAG_FAVORITE = '_$!<Favorite>!$_';
115
-
116
-	/**
117
-	* Constructor.
118
-	*
119
-	* @param TagMapper $mapper Instance of the TagMapper abstraction layer.
120
-	* @param string $user The user whose data the object will operate on.
121
-	* @param string $type The type of items for which tags will be loaded.
122
-	* @param array $defaultTags Tags that should be created at construction.
123
-	* @param boolean $includeShared Whether to include tags for items shared with this user by others.
124
-	*/
125
-	public function __construct(TagMapper $mapper, $user, $type, $defaultTags = array(), $includeShared = false) {
126
-		$this->mapper = $mapper;
127
-		$this->user = $user;
128
-		$this->type = $type;
129
-		$this->includeShared = $includeShared;
130
-		$this->owners = array($this->user);
131
-		if ($this->includeShared) {
132
-			$this->owners = array_merge($this->owners, \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true));
133
-			$this->backend = \OC\Share\Share::getBackend($this->type);
134
-		}
135
-		$this->tags = $this->mapper->loadTags($this->owners, $this->type);
136
-
137
-		if(count($defaultTags) > 0 && count($this->tags) === 0) {
138
-			$this->addMultiple($defaultTags, true);
139
-		}
140
-	}
141
-
142
-	/**
143
-	* Check if any tags are saved for this type and user.
144
-	*
145
-	* @return boolean
146
-	*/
147
-	public function isEmpty() {
148
-		return count($this->tags) === 0;
149
-	}
150
-
151
-	/**
152
-	* Returns an array mapping a given tag's properties to its values:
153
-	* ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
154
-	*
155
-	* @param string $id The ID of the tag that is going to be mapped
156
-	* @return array|false
157
-	*/
158
-	public function getTag($id) {
159
-		$key = $this->getTagById($id);
160
-		if ($key !== false) {
161
-			return $this->tagMap($this->tags[$key]);
162
-		}
163
-		return false;
164
-	}
165
-
166
-	/**
167
-	* Get the tags for a specific user.
168
-	*
169
-	* This returns an array with maps containing each tag's properties:
170
-	* [
171
-	* 	['id' => 0, 'name' = 'First tag', 'owner' = 'User', 'type' => 'tagtype'],
172
-	* 	['id' => 1, 'name' = 'Shared tag', 'owner' = 'Other user', 'type' => 'tagtype'],
173
-	* ]
174
-	*
175
-	* @return array
176
-	*/
177
-	public function getTags() {
178
-		if(!count($this->tags)) {
179
-			return array();
180
-		}
181
-
182
-		usort($this->tags, function($a, $b) {
183
-			return strnatcasecmp($a->getName(), $b->getName());
184
-		});
185
-		$tagMap = array();
186
-
187
-		foreach($this->tags as $tag) {
188
-			if($tag->getName() !== self::TAG_FAVORITE) {
189
-				$tagMap[] = $this->tagMap($tag);
190
-			}
191
-		}
192
-		return $tagMap;
193
-
194
-	}
195
-
196
-	/**
197
-	* Return only the tags owned by the given user, omitting any tags shared
198
-	* by other users.
199
-	*
200
-	* @param string $user The user whose tags are to be checked.
201
-	* @return array An array of Tag objects.
202
-	*/
203
-	public function getTagsForUser($user) {
204
-		return array_filter($this->tags,
205
-			function($tag) use($user) {
206
-				return $tag->getOwner() === $user;
207
-			}
208
-		);
209
-	}
210
-
211
-	/**
212
-	 * Get the list of tags for the given ids.
213
-	 *
214
-	 * @param array $objIds array of object ids
215
-	 * @return array|boolean of tags id as key to array of tag names
216
-	 * or false if an error occurred
217
-	 */
218
-	public function getTagsForObjects(array $objIds) {
219
-		$entries = array();
220
-
221
-		try {
222
-			$conn = \OC::$server->getDatabaseConnection();
223
-			$chunks = array_chunk($objIds, 900, false);
224
-			foreach ($chunks as $chunk) {
225
-				$result = $conn->executeQuery(
226
-					'SELECT `category`, `categoryid`, `objid` ' .
227
-					'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
228
-					'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
229
-					array($this->user, $this->type, $chunk),
230
-					array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
231
-				);
232
-				while ($row = $result->fetch()) {
233
-					$objId = (int)$row['objid'];
234
-					if (!isset($entries[$objId])) {
235
-						$entries[$objId] = array();
236
-					}
237
-					$entries[$objId][] = $row['category'];
238
-				}
239
-				if ($result === null) {
240
-					\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
241
-					return false;
242
-				}
243
-			}
244
-		} catch(\Exception $e) {
245
-			\OC::$server->getLogger()->logException($e, [
246
-				'message' => __METHOD__,
247
-				'level' => \OCP\Util::ERROR,
248
-				'app' => 'core',
249
-			]);
250
-			return false;
251
-		}
252
-
253
-		return $entries;
254
-	}
255
-
256
-	/**
257
-	* Get the a list if items tagged with $tag.
258
-	*
259
-	* Throws an exception if the tag could not be found.
260
-	*
261
-	* @param string $tag Tag id or name.
262
-	* @return array|false An array of object ids or false on error.
263
-	* @throws \Exception
264
-	*/
265
-	public function getIdsForTag($tag) {
266
-		$result = null;
267
-		$tagId = false;
268
-		if(is_numeric($tag)) {
269
-			$tagId = $tag;
270
-		} elseif(is_string($tag)) {
271
-			$tag = trim($tag);
272
-			if($tag === '') {
273
-				\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
274
-				return false;
275
-			}
276
-			$tagId = $this->getTagId($tag);
277
-		}
278
-
279
-		if($tagId === false) {
280
-			$l10n = \OC::$server->getL10N('core');
281
-			throw new \Exception(
282
-				$l10n->t('Could not find category "%s"', [$tag])
283
-			);
284
-		}
285
-
286
-		$ids = array();
287
-		$sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
288
-			. '` WHERE `categoryid` = ?';
289
-
290
-		try {
291
-			$stmt = \OCP\DB::prepare($sql);
292
-			$result = $stmt->execute(array($tagId));
293
-			if ($result === null) {
294
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
295
-				return false;
296
-			}
297
-		} catch(\Exception $e) {
298
-			\OC::$server->getLogger()->logException($e, [
299
-				'message' => __METHOD__,
300
-				'level' => \OCP\Util::ERROR,
301
-				'app' => 'core',
302
-			]);
303
-			return false;
304
-		}
305
-
306
-		if(!is_null($result)) {
307
-			while( $row = $result->fetchRow()) {
308
-				$id = (int)$row['objid'];
309
-
310
-				if ($this->includeShared) {
311
-					// We have to check if we are really allowed to access the
312
-					// items that are tagged with $tag. To that end, we ask the
313
-					// corresponding sharing backend if the item identified by $id
314
-					// is owned by any of $this->owners.
315
-					foreach ($this->owners as $owner) {
316
-						if ($this->backend->isValidSource($id, $owner)) {
317
-							$ids[] = $id;
318
-							break;
319
-						}
320
-					}
321
-				} else {
322
-					$ids[] = $id;
323
-				}
324
-			}
325
-		}
326
-
327
-		return $ids;
328
-	}
329
-
330
-	/**
331
-	* Checks whether a tag is saved for the given user,
332
-	* disregarding the ones shared with him or her.
333
-	*
334
-	* @param string $name The tag name to check for.
335
-	* @param string $user The user whose tags are to be checked.
336
-	* @return bool
337
-	*/
338
-	public function userHasTag($name, $user) {
339
-		$key = $this->array_searchi($name, $this->getTagsForUser($user));
340
-		return ($key !== false) ? $this->tags[$key]->getId() : false;
341
-	}
342
-
343
-	/**
344
-	* Checks whether a tag is saved for or shared with the current user.
345
-	*
346
-	* @param string $name The tag name to check for.
347
-	* @return bool
348
-	*/
349
-	public function hasTag($name) {
350
-		return $this->getTagId($name) !== false;
351
-	}
352
-
353
-	/**
354
-	* Add a new tag.
355
-	*
356
-	* @param string $name A string with a name of the tag
357
-	* @return false|int the id of the added tag or false on error.
358
-	*/
359
-	public function add($name) {
360
-		$name = trim($name);
361
-
362
-		if($name === '') {
363
-			\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
364
-			return false;
365
-		}
366
-		if($this->userHasTag($name, $this->user)) {
367
-			\OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', \OCP\Util::DEBUG);
368
-			return false;
369
-		}
370
-		try {
371
-			$tag = new Tag($this->user, $this->type, $name);
372
-			$tag = $this->mapper->insert($tag);
373
-			$this->tags[] = $tag;
374
-		} catch(\Exception $e) {
375
-			\OC::$server->getLogger()->logException($e, [
376
-				'message' => __METHOD__,
377
-				'level' => \OCP\Util::ERROR,
378
-				'app' => 'core',
379
-			]);
380
-			return false;
381
-		}
382
-		\OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), \OCP\Util::DEBUG);
383
-		return $tag->getId();
384
-	}
385
-
386
-	/**
387
-	* Rename tag.
388
-	*
389
-	* @param string|integer $from The name or ID of the existing tag
390
-	* @param string $to The new name of the tag.
391
-	* @return bool
392
-	*/
393
-	public function rename($from, $to) {
394
-		$from = trim($from);
395
-		$to = trim($to);
396
-
397
-		if($to === '' || $from === '') {
398
-			\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
399
-			return false;
400
-		}
401
-
402
-		if (is_numeric($from)) {
403
-			$key = $this->getTagById($from);
404
-		} else {
405
-			$key = $this->getTagByName($from);
406
-		}
407
-		if($key === false) {
408
-			\OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', \OCP\Util::DEBUG);
409
-			return false;
410
-		}
411
-		$tag = $this->tags[$key];
412
-
413
-		if($this->userHasTag($to, $tag->getOwner())) {
414
-			\OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', \OCP\Util::DEBUG);
415
-			return false;
416
-		}
417
-
418
-		try {
419
-			$tag->setName($to);
420
-			$this->tags[$key] = $this->mapper->update($tag);
421
-		} catch(\Exception $e) {
422
-			\OC::$server->getLogger()->logException($e, [
423
-				'message' => __METHOD__,
424
-				'level' => \OCP\Util::ERROR,
425
-				'app' => 'core',
426
-			]);
427
-			return false;
428
-		}
429
-		return true;
430
-	}
431
-
432
-	/**
433
-	* Add a list of new tags.
434
-	*
435
-	* @param string[] $names A string with a name or an array of strings containing
436
-	* the name(s) of the tag(s) to add.
437
-	* @param bool $sync When true, save the tags
438
-	* @param int|null $id int Optional object id to add to this|these tag(s)
439
-	* @return bool Returns false on error.
440
-	*/
441
-	public function addMultiple($names, $sync=false, $id = null) {
442
-		if(!is_array($names)) {
443
-			$names = array($names);
444
-		}
445
-		$names = array_map('trim', $names);
446
-		array_filter($names);
447
-
448
-		$newones = array();
449
-		foreach($names as $name) {
450
-			if(!$this->hasTag($name) && $name !== '') {
451
-				$newones[] = new Tag($this->user, $this->type, $name);
452
-			}
453
-			if(!is_null($id) ) {
454
-				// Insert $objectid, $categoryid  pairs if not exist.
455
-				self::$relations[] = array('objid' => $id, 'tag' => $name);
456
-			}
457
-		}
458
-		$this->tags = array_merge($this->tags, $newones);
459
-		if($sync === true) {
460
-			$this->save();
461
-		}
462
-
463
-		return true;
464
-	}
465
-
466
-	/**
467
-	 * Save the list of tags and their object relations
468
-	 */
469
-	protected function save() {
470
-		if(is_array($this->tags)) {
471
-			foreach($this->tags as $tag) {
472
-				try {
473
-					if (!$this->mapper->tagExists($tag)) {
474
-						$this->mapper->insert($tag);
475
-					}
476
-				} catch(\Exception $e) {
477
-					\OC::$server->getLogger()->logException($e, [
478
-						'message' => __METHOD__,
479
-						'level' => \OCP\Util::ERROR,
480
-						'app' => 'core',
481
-					]);
482
-				}
483
-			}
484
-
485
-			// reload tags to get the proper ids.
486
-			$this->tags = $this->mapper->loadTags($this->owners, $this->type);
487
-			\OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
488
-				\OCP\Util::DEBUG);
489
-			// Loop through temporarily cached objectid/tagname pairs
490
-			// and save relations.
491
-			$tags = $this->tags;
492
-			// For some reason this is needed or array_search(i) will return 0..?
493
-			ksort($tags);
494
-			foreach(self::$relations as $relation) {
495
-				$tagId = $this->getTagId($relation['tag']);
496
-				\OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, \OCP\Util::DEBUG);
497
-				if($tagId) {
498
-					try {
499
-						\OCP\DB::insertIfNotExist(self::RELATION_TABLE,
500
-							array(
501
-								'objid' => $relation['objid'],
502
-								'categoryid' => $tagId,
503
-								'type' => $this->type,
504
-								));
505
-					} catch(\Exception $e) {
506
-						\OC::$server->getLogger()->logException($e, [
507
-							'message' => __METHOD__,
508
-							'level' => \OCP\Util::ERROR,
509
-							'app' => 'core',
510
-						]);
511
-					}
512
-				}
513
-			}
514
-			self::$relations = array(); // reset
515
-		} else {
516
-			\OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! '
517
-				. print_r($this->tags, true), \OCP\Util::ERROR);
518
-		}
519
-	}
520
-
521
-	/**
522
-	* Delete tags and tag/object relations for a user.
523
-	*
524
-	* For hooking up on post_deleteUser
525
-	*
526
-	* @param array $arguments
527
-	*/
528
-	public static function post_deleteUser($arguments) {
529
-		// Find all objectid/tagId pairs.
530
-		$result = null;
531
-		try {
532
-			$stmt = \OCP\DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
533
-				. 'WHERE `uid` = ?');
534
-			$result = $stmt->execute(array($arguments['uid']));
535
-			if ($result === null) {
536
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
537
-			}
538
-		} catch(\Exception $e) {
539
-			\OC::$server->getLogger()->logException($e, [
540
-				'message' => __METHOD__,
541
-				'level' => \OCP\Util::ERROR,
542
-				'app' => 'core',
543
-			]);
544
-		}
545
-
546
-		if(!is_null($result)) {
547
-			try {
548
-				$stmt = \OCP\DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
549
-					. 'WHERE `categoryid` = ?');
550
-				while( $row = $result->fetchRow()) {
551
-					try {
552
-						$stmt->execute(array($row['id']));
553
-					} catch(\Exception $e) {
554
-						\OC::$server->getLogger()->logException($e, [
555
-							'message' => __METHOD__,
556
-							'level' => \OCP\Util::ERROR,
557
-							'app' => 'core',
558
-						]);
559
-					}
560
-				}
561
-			} catch(\Exception $e) {
562
-				\OC::$server->getLogger()->logException($e, [
563
-					'message' => __METHOD__,
564
-					'level' => \OCP\Util::ERROR,
565
-					'app' => 'core',
566
-				]);
567
-			}
568
-		}
569
-		try {
570
-			$stmt = \OCP\DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
571
-				. 'WHERE `uid` = ?');
572
-			$result = $stmt->execute(array($arguments['uid']));
573
-			if ($result === null) {
574
-				\OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
575
-			}
576
-		} catch(\Exception $e) {
577
-			\OC::$server->getLogger()->logException($e, [
578
-				'message' => __METHOD__,
579
-				'level' => \OCP\Util::ERROR,
580
-				'app' => 'core',
581
-			]);
582
-		}
583
-	}
584
-
585
-	/**
586
-	* Delete tag/object relations from the db
587
-	*
588
-	* @param array $ids The ids of the objects
589
-	* @return boolean Returns false on error.
590
-	*/
591
-	public function purgeObjects(array $ids) {
592
-		if(count($ids) === 0) {
593
-			// job done ;)
594
-			return true;
595
-		}
596
-		$updates = $ids;
597
-		try {
598
-			$query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
599
-			$query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
600
-			$query .= 'AND `type`= ?';
601
-			$updates[] = $this->type;
602
-			$stmt = \OCP\DB::prepare($query);
603
-			$result = $stmt->execute($updates);
604
-			if ($result === null) {
605
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
606
-				return false;
607
-			}
608
-		} catch(\Exception $e) {
609
-			\OC::$server->getLogger()->logException($e, [
610
-				'message' => __METHOD__,
611
-				'level' => \OCP\Util::ERROR,
612
-				'app' => 'core',
613
-			]);
614
-			return false;
615
-		}
616
-		return true;
617
-	}
618
-
619
-	/**
620
-	* Get favorites for an object type
621
-	*
622
-	* @return array|false An array of object ids.
623
-	*/
624
-	public function getFavorites() {
625
-		try {
626
-			return $this->getIdsForTag(self::TAG_FAVORITE);
627
-		} catch(\Exception $e) {
628
-			\OC::$server->getLogger()->logException($e, [
629
-				'message' => __METHOD__,
630
-				'level' => \OCP\Util::ERROR,
631
-				'app' => 'core',
632
-			]);
633
-			return array();
634
-		}
635
-	}
636
-
637
-	/**
638
-	* Add an object to favorites
639
-	*
640
-	* @param int $objid The id of the object
641
-	* @return boolean
642
-	*/
643
-	public function addToFavorites($objid) {
644
-		if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
645
-			$this->add(self::TAG_FAVORITE);
646
-		}
647
-		return $this->tagAs($objid, self::TAG_FAVORITE);
648
-	}
649
-
650
-	/**
651
-	* Remove an object from favorites
652
-	*
653
-	* @param int $objid The id of the object
654
-	* @return boolean
655
-	*/
656
-	public function removeFromFavorites($objid) {
657
-		return $this->unTag($objid, self::TAG_FAVORITE);
658
-	}
659
-
660
-	/**
661
-	* Creates a tag/object relation.
662
-	*
663
-	* @param int $objid The id of the object
664
-	* @param string $tag The id or name of the tag
665
-	* @return boolean Returns false on error.
666
-	*/
667
-	public function tagAs($objid, $tag) {
668
-		if(is_string($tag) && !is_numeric($tag)) {
669
-			$tag = trim($tag);
670
-			if($tag === '') {
671
-				\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
672
-				return false;
673
-			}
674
-			if(!$this->hasTag($tag)) {
675
-				$this->add($tag);
676
-			}
677
-			$tagId =  $this->getTagId($tag);
678
-		} else {
679
-			$tagId = $tag;
680
-		}
681
-		try {
682
-			\OCP\DB::insertIfNotExist(self::RELATION_TABLE,
683
-				array(
684
-					'objid' => $objid,
685
-					'categoryid' => $tagId,
686
-					'type' => $this->type,
687
-				));
688
-		} catch(\Exception $e) {
689
-			\OC::$server->getLogger()->logException($e, [
690
-				'message' => __METHOD__,
691
-				'level' => \OCP\Util::ERROR,
692
-				'app' => 'core',
693
-			]);
694
-			return false;
695
-		}
696
-		return true;
697
-	}
698
-
699
-	/**
700
-	* Delete single tag/object relation from the db
701
-	*
702
-	* @param int $objid The id of the object
703
-	* @param string $tag The id or name of the tag
704
-	* @return boolean
705
-	*/
706
-	public function unTag($objid, $tag) {
707
-		if(is_string($tag) && !is_numeric($tag)) {
708
-			$tag = trim($tag);
709
-			if($tag === '') {
710
-				\OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', \OCP\Util::DEBUG);
711
-				return false;
712
-			}
713
-			$tagId =  $this->getTagId($tag);
714
-		} else {
715
-			$tagId = $tag;
716
-		}
717
-
718
-		try {
719
-			$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
720
-					. 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
721
-			$stmt = \OCP\DB::prepare($sql);
722
-			$stmt->execute(array($objid, $tagId, $this->type));
723
-		} catch(\Exception $e) {
724
-			\OC::$server->getLogger()->logException($e, [
725
-				'message' => __METHOD__,
726
-				'level' => \OCP\Util::ERROR,
727
-				'app' => 'core',
728
-			]);
729
-			return false;
730
-		}
731
-		return true;
732
-	}
733
-
734
-	/**
735
-	* Delete tags from the database.
736
-	*
737
-	* @param string[]|integer[] $names An array of tags (names or IDs) to delete
738
-	* @return bool Returns false on error
739
-	*/
740
-	public function delete($names) {
741
-		if(!is_array($names)) {
742
-			$names = array($names);
743
-		}
744
-
745
-		$names = array_map('trim', $names);
746
-		array_filter($names);
747
-
748
-		\OCP\Util::writeLog('core', __METHOD__ . ', before: '
749
-			. print_r($this->tags, true), \OCP\Util::DEBUG);
750
-		foreach($names as $name) {
751
-			$id = null;
752
-
753
-			if (is_numeric($name)) {
754
-				$key = $this->getTagById($name);
755
-			} else {
756
-				$key = $this->getTagByName($name);
757
-			}
758
-			if ($key !== false) {
759
-				$tag = $this->tags[$key];
760
-				$id = $tag->getId();
761
-				unset($this->tags[$key]);
762
-				$this->mapper->delete($tag);
763
-			} else {
764
-				\OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
765
-					. ': not found.', \OCP\Util::ERROR);
766
-			}
767
-			if(!is_null($id) && $id !== false) {
768
-				try {
769
-					$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
770
-							. 'WHERE `categoryid` = ?';
771
-					$stmt = \OCP\DB::prepare($sql);
772
-					$result = $stmt->execute(array($id));
773
-					if ($result === null) {
774
-						\OCP\Util::writeLog('core',
775
-							__METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(),
776
-							\OCP\Util::ERROR);
777
-						return false;
778
-					}
779
-				} catch(\Exception $e) {
780
-					\OC::$server->getLogger()->logException($e, [
781
-						'message' => __METHOD__,
782
-						'level' => \OCP\Util::ERROR,
783
-						'app' => 'core',
784
-					]);
785
-					return false;
786
-				}
787
-			}
788
-		}
789
-		return true;
790
-	}
791
-
792
-	// case-insensitive array_search
793
-	protected function array_searchi($needle, $haystack, $mem='getName') {
794
-		if(!is_array($haystack)) {
795
-			return false;
796
-		}
797
-		return array_search(strtolower($needle), array_map(
798
-			function($tag) use($mem) {
799
-				return strtolower(call_user_func(array($tag, $mem)));
800
-			}, $haystack)
801
-		);
802
-	}
803
-
804
-	/**
805
-	* Get a tag's ID.
806
-	*
807
-	* @param string $name The tag name to look for.
808
-	* @return string|bool The tag's id or false if no matching tag is found.
809
-	*/
810
-	private function getTagId($name) {
811
-		$key = $this->array_searchi($name, $this->tags);
812
-		if ($key !== false) {
813
-			return $this->tags[$key]->getId();
814
-		}
815
-		return false;
816
-	}
817
-
818
-	/**
819
-	* Get a tag by its name.
820
-	*
821
-	* @param string $name The tag name.
822
-	* @return integer|bool The tag object's offset within the $this->tags
823
-	*                      array or false if it doesn't exist.
824
-	*/
825
-	private function getTagByName($name) {
826
-		return $this->array_searchi($name, $this->tags, 'getName');
827
-	}
828
-
829
-	/**
830
-	* Get a tag by its ID.
831
-	*
832
-	* @param string $id The tag ID to look for.
833
-	* @return integer|bool The tag object's offset within the $this->tags
834
-	*                      array or false if it doesn't exist.
835
-	*/
836
-	private function getTagById($id) {
837
-		return $this->array_searchi($id, $this->tags, 'getId');
838
-	}
839
-
840
-	/**
841
-	* Returns an array mapping a given tag's properties to its values:
842
-	* ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
843
-	*
844
-	* @param Tag $tag The tag that is going to be mapped
845
-	* @return array
846
-	*/
847
-	private function tagMap(Tag $tag) {
848
-		return array(
849
-			'id'    => $tag->getId(),
850
-			'name'  => $tag->getName(),
851
-			'owner' => $tag->getOwner(),
852
-			'type'  => $tag->getType()
853
-		);
854
-	}
53
+    /**
54
+     * Tags
55
+     *
56
+     * @var array
57
+     */
58
+    private $tags = array();
59
+
60
+    /**
61
+     * Used for storing objectid/categoryname pairs while rescanning.
62
+     *
63
+     * @var array
64
+     */
65
+    private static $relations = array();
66
+
67
+    /**
68
+     * Type
69
+     *
70
+     * @var string
71
+     */
72
+    private $type;
73
+
74
+    /**
75
+     * User
76
+     *
77
+     * @var string
78
+     */
79
+    private $user;
80
+
81
+    /**
82
+     * Are we including tags for shared items?
83
+     *
84
+     * @var bool
85
+     */
86
+    private $includeShared = false;
87
+
88
+    /**
89
+     * The current user, plus any owners of the items shared with the current
90
+     * user, if $this->includeShared === true.
91
+     *
92
+     * @var array
93
+     */
94
+    private $owners = array();
95
+
96
+    /**
97
+     * The Mapper we're using to communicate our Tag objects to the database.
98
+     *
99
+     * @var TagMapper
100
+     */
101
+    private $mapper;
102
+
103
+    /**
104
+     * The sharing backend for objects of $this->type. Required if
105
+     * $this->includeShared === true to determine ownership of items.
106
+     *
107
+     * @var \OCP\Share_Backend
108
+     */
109
+    private $backend;
110
+
111
+    const TAG_TABLE = '*PREFIX*vcategory';
112
+    const RELATION_TABLE = '*PREFIX*vcategory_to_object';
113
+
114
+    const TAG_FAVORITE = '_$!<Favorite>!$_';
115
+
116
+    /**
117
+     * Constructor.
118
+     *
119
+     * @param TagMapper $mapper Instance of the TagMapper abstraction layer.
120
+     * @param string $user The user whose data the object will operate on.
121
+     * @param string $type The type of items for which tags will be loaded.
122
+     * @param array $defaultTags Tags that should be created at construction.
123
+     * @param boolean $includeShared Whether to include tags for items shared with this user by others.
124
+     */
125
+    public function __construct(TagMapper $mapper, $user, $type, $defaultTags = array(), $includeShared = false) {
126
+        $this->mapper = $mapper;
127
+        $this->user = $user;
128
+        $this->type = $type;
129
+        $this->includeShared = $includeShared;
130
+        $this->owners = array($this->user);
131
+        if ($this->includeShared) {
132
+            $this->owners = array_merge($this->owners, \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true));
133
+            $this->backend = \OC\Share\Share::getBackend($this->type);
134
+        }
135
+        $this->tags = $this->mapper->loadTags($this->owners, $this->type);
136
+
137
+        if(count($defaultTags) > 0 && count($this->tags) === 0) {
138
+            $this->addMultiple($defaultTags, true);
139
+        }
140
+    }
141
+
142
+    /**
143
+     * Check if any tags are saved for this type and user.
144
+     *
145
+     * @return boolean
146
+     */
147
+    public function isEmpty() {
148
+        return count($this->tags) === 0;
149
+    }
150
+
151
+    /**
152
+     * Returns an array mapping a given tag's properties to its values:
153
+     * ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
154
+     *
155
+     * @param string $id The ID of the tag that is going to be mapped
156
+     * @return array|false
157
+     */
158
+    public function getTag($id) {
159
+        $key = $this->getTagById($id);
160
+        if ($key !== false) {
161
+            return $this->tagMap($this->tags[$key]);
162
+        }
163
+        return false;
164
+    }
165
+
166
+    /**
167
+     * Get the tags for a specific user.
168
+     *
169
+     * This returns an array with maps containing each tag's properties:
170
+     * [
171
+     * 	['id' => 0, 'name' = 'First tag', 'owner' = 'User', 'type' => 'tagtype'],
172
+     * 	['id' => 1, 'name' = 'Shared tag', 'owner' = 'Other user', 'type' => 'tagtype'],
173
+     * ]
174
+     *
175
+     * @return array
176
+     */
177
+    public function getTags() {
178
+        if(!count($this->tags)) {
179
+            return array();
180
+        }
181
+
182
+        usort($this->tags, function($a, $b) {
183
+            return strnatcasecmp($a->getName(), $b->getName());
184
+        });
185
+        $tagMap = array();
186
+
187
+        foreach($this->tags as $tag) {
188
+            if($tag->getName() !== self::TAG_FAVORITE) {
189
+                $tagMap[] = $this->tagMap($tag);
190
+            }
191
+        }
192
+        return $tagMap;
193
+
194
+    }
195
+
196
+    /**
197
+     * Return only the tags owned by the given user, omitting any tags shared
198
+     * by other users.
199
+     *
200
+     * @param string $user The user whose tags are to be checked.
201
+     * @return array An array of Tag objects.
202
+     */
203
+    public function getTagsForUser($user) {
204
+        return array_filter($this->tags,
205
+            function($tag) use($user) {
206
+                return $tag->getOwner() === $user;
207
+            }
208
+        );
209
+    }
210
+
211
+    /**
212
+     * Get the list of tags for the given ids.
213
+     *
214
+     * @param array $objIds array of object ids
215
+     * @return array|boolean of tags id as key to array of tag names
216
+     * or false if an error occurred
217
+     */
218
+    public function getTagsForObjects(array $objIds) {
219
+        $entries = array();
220
+
221
+        try {
222
+            $conn = \OC::$server->getDatabaseConnection();
223
+            $chunks = array_chunk($objIds, 900, false);
224
+            foreach ($chunks as $chunk) {
225
+                $result = $conn->executeQuery(
226
+                    'SELECT `category`, `categoryid`, `objid` ' .
227
+                    'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
228
+                    'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
229
+                    array($this->user, $this->type, $chunk),
230
+                    array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
231
+                );
232
+                while ($row = $result->fetch()) {
233
+                    $objId = (int)$row['objid'];
234
+                    if (!isset($entries[$objId])) {
235
+                        $entries[$objId] = array();
236
+                    }
237
+                    $entries[$objId][] = $row['category'];
238
+                }
239
+                if ($result === null) {
240
+                    \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
241
+                    return false;
242
+                }
243
+            }
244
+        } catch(\Exception $e) {
245
+            \OC::$server->getLogger()->logException($e, [
246
+                'message' => __METHOD__,
247
+                'level' => \OCP\Util::ERROR,
248
+                'app' => 'core',
249
+            ]);
250
+            return false;
251
+        }
252
+
253
+        return $entries;
254
+    }
255
+
256
+    /**
257
+     * Get the a list if items tagged with $tag.
258
+     *
259
+     * Throws an exception if the tag could not be found.
260
+     *
261
+     * @param string $tag Tag id or name.
262
+     * @return array|false An array of object ids or false on error.
263
+     * @throws \Exception
264
+     */
265
+    public function getIdsForTag($tag) {
266
+        $result = null;
267
+        $tagId = false;
268
+        if(is_numeric($tag)) {
269
+            $tagId = $tag;
270
+        } elseif(is_string($tag)) {
271
+            $tag = trim($tag);
272
+            if($tag === '') {
273
+                \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
274
+                return false;
275
+            }
276
+            $tagId = $this->getTagId($tag);
277
+        }
278
+
279
+        if($tagId === false) {
280
+            $l10n = \OC::$server->getL10N('core');
281
+            throw new \Exception(
282
+                $l10n->t('Could not find category "%s"', [$tag])
283
+            );
284
+        }
285
+
286
+        $ids = array();
287
+        $sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
288
+            . '` WHERE `categoryid` = ?';
289
+
290
+        try {
291
+            $stmt = \OCP\DB::prepare($sql);
292
+            $result = $stmt->execute(array($tagId));
293
+            if ($result === null) {
294
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
295
+                return false;
296
+            }
297
+        } catch(\Exception $e) {
298
+            \OC::$server->getLogger()->logException($e, [
299
+                'message' => __METHOD__,
300
+                'level' => \OCP\Util::ERROR,
301
+                'app' => 'core',
302
+            ]);
303
+            return false;
304
+        }
305
+
306
+        if(!is_null($result)) {
307
+            while( $row = $result->fetchRow()) {
308
+                $id = (int)$row['objid'];
309
+
310
+                if ($this->includeShared) {
311
+                    // We have to check if we are really allowed to access the
312
+                    // items that are tagged with $tag. To that end, we ask the
313
+                    // corresponding sharing backend if the item identified by $id
314
+                    // is owned by any of $this->owners.
315
+                    foreach ($this->owners as $owner) {
316
+                        if ($this->backend->isValidSource($id, $owner)) {
317
+                            $ids[] = $id;
318
+                            break;
319
+                        }
320
+                    }
321
+                } else {
322
+                    $ids[] = $id;
323
+                }
324
+            }
325
+        }
326
+
327
+        return $ids;
328
+    }
329
+
330
+    /**
331
+     * Checks whether a tag is saved for the given user,
332
+     * disregarding the ones shared with him or her.
333
+     *
334
+     * @param string $name The tag name to check for.
335
+     * @param string $user The user whose tags are to be checked.
336
+     * @return bool
337
+     */
338
+    public function userHasTag($name, $user) {
339
+        $key = $this->array_searchi($name, $this->getTagsForUser($user));
340
+        return ($key !== false) ? $this->tags[$key]->getId() : false;
341
+    }
342
+
343
+    /**
344
+     * Checks whether a tag is saved for or shared with the current user.
345
+     *
346
+     * @param string $name The tag name to check for.
347
+     * @return bool
348
+     */
349
+    public function hasTag($name) {
350
+        return $this->getTagId($name) !== false;
351
+    }
352
+
353
+    /**
354
+     * Add a new tag.
355
+     *
356
+     * @param string $name A string with a name of the tag
357
+     * @return false|int the id of the added tag or false on error.
358
+     */
359
+    public function add($name) {
360
+        $name = trim($name);
361
+
362
+        if($name === '') {
363
+            \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
364
+            return false;
365
+        }
366
+        if($this->userHasTag($name, $this->user)) {
367
+            \OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', \OCP\Util::DEBUG);
368
+            return false;
369
+        }
370
+        try {
371
+            $tag = new Tag($this->user, $this->type, $name);
372
+            $tag = $this->mapper->insert($tag);
373
+            $this->tags[] = $tag;
374
+        } catch(\Exception $e) {
375
+            \OC::$server->getLogger()->logException($e, [
376
+                'message' => __METHOD__,
377
+                'level' => \OCP\Util::ERROR,
378
+                'app' => 'core',
379
+            ]);
380
+            return false;
381
+        }
382
+        \OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), \OCP\Util::DEBUG);
383
+        return $tag->getId();
384
+    }
385
+
386
+    /**
387
+     * Rename tag.
388
+     *
389
+     * @param string|integer $from The name or ID of the existing tag
390
+     * @param string $to The new name of the tag.
391
+     * @return bool
392
+     */
393
+    public function rename($from, $to) {
394
+        $from = trim($from);
395
+        $to = trim($to);
396
+
397
+        if($to === '' || $from === '') {
398
+            \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
399
+            return false;
400
+        }
401
+
402
+        if (is_numeric($from)) {
403
+            $key = $this->getTagById($from);
404
+        } else {
405
+            $key = $this->getTagByName($from);
406
+        }
407
+        if($key === false) {
408
+            \OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', \OCP\Util::DEBUG);
409
+            return false;
410
+        }
411
+        $tag = $this->tags[$key];
412
+
413
+        if($this->userHasTag($to, $tag->getOwner())) {
414
+            \OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', \OCP\Util::DEBUG);
415
+            return false;
416
+        }
417
+
418
+        try {
419
+            $tag->setName($to);
420
+            $this->tags[$key] = $this->mapper->update($tag);
421
+        } catch(\Exception $e) {
422
+            \OC::$server->getLogger()->logException($e, [
423
+                'message' => __METHOD__,
424
+                'level' => \OCP\Util::ERROR,
425
+                'app' => 'core',
426
+            ]);
427
+            return false;
428
+        }
429
+        return true;
430
+    }
431
+
432
+    /**
433
+     * Add a list of new tags.
434
+     *
435
+     * @param string[] $names A string with a name or an array of strings containing
436
+     * the name(s) of the tag(s) to add.
437
+     * @param bool $sync When true, save the tags
438
+     * @param int|null $id int Optional object id to add to this|these tag(s)
439
+     * @return bool Returns false on error.
440
+     */
441
+    public function addMultiple($names, $sync=false, $id = null) {
442
+        if(!is_array($names)) {
443
+            $names = array($names);
444
+        }
445
+        $names = array_map('trim', $names);
446
+        array_filter($names);
447
+
448
+        $newones = array();
449
+        foreach($names as $name) {
450
+            if(!$this->hasTag($name) && $name !== '') {
451
+                $newones[] = new Tag($this->user, $this->type, $name);
452
+            }
453
+            if(!is_null($id) ) {
454
+                // Insert $objectid, $categoryid  pairs if not exist.
455
+                self::$relations[] = array('objid' => $id, 'tag' => $name);
456
+            }
457
+        }
458
+        $this->tags = array_merge($this->tags, $newones);
459
+        if($sync === true) {
460
+            $this->save();
461
+        }
462
+
463
+        return true;
464
+    }
465
+
466
+    /**
467
+     * Save the list of tags and their object relations
468
+     */
469
+    protected function save() {
470
+        if(is_array($this->tags)) {
471
+            foreach($this->tags as $tag) {
472
+                try {
473
+                    if (!$this->mapper->tagExists($tag)) {
474
+                        $this->mapper->insert($tag);
475
+                    }
476
+                } catch(\Exception $e) {
477
+                    \OC::$server->getLogger()->logException($e, [
478
+                        'message' => __METHOD__,
479
+                        'level' => \OCP\Util::ERROR,
480
+                        'app' => 'core',
481
+                    ]);
482
+                }
483
+            }
484
+
485
+            // reload tags to get the proper ids.
486
+            $this->tags = $this->mapper->loadTags($this->owners, $this->type);
487
+            \OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
488
+                \OCP\Util::DEBUG);
489
+            // Loop through temporarily cached objectid/tagname pairs
490
+            // and save relations.
491
+            $tags = $this->tags;
492
+            // For some reason this is needed or array_search(i) will return 0..?
493
+            ksort($tags);
494
+            foreach(self::$relations as $relation) {
495
+                $tagId = $this->getTagId($relation['tag']);
496
+                \OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, \OCP\Util::DEBUG);
497
+                if($tagId) {
498
+                    try {
499
+                        \OCP\DB::insertIfNotExist(self::RELATION_TABLE,
500
+                            array(
501
+                                'objid' => $relation['objid'],
502
+                                'categoryid' => $tagId,
503
+                                'type' => $this->type,
504
+                                ));
505
+                    } catch(\Exception $e) {
506
+                        \OC::$server->getLogger()->logException($e, [
507
+                            'message' => __METHOD__,
508
+                            'level' => \OCP\Util::ERROR,
509
+                            'app' => 'core',
510
+                        ]);
511
+                    }
512
+                }
513
+            }
514
+            self::$relations = array(); // reset
515
+        } else {
516
+            \OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! '
517
+                . print_r($this->tags, true), \OCP\Util::ERROR);
518
+        }
519
+    }
520
+
521
+    /**
522
+     * Delete tags and tag/object relations for a user.
523
+     *
524
+     * For hooking up on post_deleteUser
525
+     *
526
+     * @param array $arguments
527
+     */
528
+    public static function post_deleteUser($arguments) {
529
+        // Find all objectid/tagId pairs.
530
+        $result = null;
531
+        try {
532
+            $stmt = \OCP\DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
533
+                . 'WHERE `uid` = ?');
534
+            $result = $stmt->execute(array($arguments['uid']));
535
+            if ($result === null) {
536
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
537
+            }
538
+        } catch(\Exception $e) {
539
+            \OC::$server->getLogger()->logException($e, [
540
+                'message' => __METHOD__,
541
+                'level' => \OCP\Util::ERROR,
542
+                'app' => 'core',
543
+            ]);
544
+        }
545
+
546
+        if(!is_null($result)) {
547
+            try {
548
+                $stmt = \OCP\DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
549
+                    . 'WHERE `categoryid` = ?');
550
+                while( $row = $result->fetchRow()) {
551
+                    try {
552
+                        $stmt->execute(array($row['id']));
553
+                    } catch(\Exception $e) {
554
+                        \OC::$server->getLogger()->logException($e, [
555
+                            'message' => __METHOD__,
556
+                            'level' => \OCP\Util::ERROR,
557
+                            'app' => 'core',
558
+                        ]);
559
+                    }
560
+                }
561
+            } catch(\Exception $e) {
562
+                \OC::$server->getLogger()->logException($e, [
563
+                    'message' => __METHOD__,
564
+                    'level' => \OCP\Util::ERROR,
565
+                    'app' => 'core',
566
+                ]);
567
+            }
568
+        }
569
+        try {
570
+            $stmt = \OCP\DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
571
+                . 'WHERE `uid` = ?');
572
+            $result = $stmt->execute(array($arguments['uid']));
573
+            if ($result === null) {
574
+                \OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
575
+            }
576
+        } catch(\Exception $e) {
577
+            \OC::$server->getLogger()->logException($e, [
578
+                'message' => __METHOD__,
579
+                'level' => \OCP\Util::ERROR,
580
+                'app' => 'core',
581
+            ]);
582
+        }
583
+    }
584
+
585
+    /**
586
+     * Delete tag/object relations from the db
587
+     *
588
+     * @param array $ids The ids of the objects
589
+     * @return boolean Returns false on error.
590
+     */
591
+    public function purgeObjects(array $ids) {
592
+        if(count($ids) === 0) {
593
+            // job done ;)
594
+            return true;
595
+        }
596
+        $updates = $ids;
597
+        try {
598
+            $query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
599
+            $query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
600
+            $query .= 'AND `type`= ?';
601
+            $updates[] = $this->type;
602
+            $stmt = \OCP\DB::prepare($query);
603
+            $result = $stmt->execute($updates);
604
+            if ($result === null) {
605
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
606
+                return false;
607
+            }
608
+        } catch(\Exception $e) {
609
+            \OC::$server->getLogger()->logException($e, [
610
+                'message' => __METHOD__,
611
+                'level' => \OCP\Util::ERROR,
612
+                'app' => 'core',
613
+            ]);
614
+            return false;
615
+        }
616
+        return true;
617
+    }
618
+
619
+    /**
620
+     * Get favorites for an object type
621
+     *
622
+     * @return array|false An array of object ids.
623
+     */
624
+    public function getFavorites() {
625
+        try {
626
+            return $this->getIdsForTag(self::TAG_FAVORITE);
627
+        } catch(\Exception $e) {
628
+            \OC::$server->getLogger()->logException($e, [
629
+                'message' => __METHOD__,
630
+                'level' => \OCP\Util::ERROR,
631
+                'app' => 'core',
632
+            ]);
633
+            return array();
634
+        }
635
+    }
636
+
637
+    /**
638
+     * Add an object to favorites
639
+     *
640
+     * @param int $objid The id of the object
641
+     * @return boolean
642
+     */
643
+    public function addToFavorites($objid) {
644
+        if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
645
+            $this->add(self::TAG_FAVORITE);
646
+        }
647
+        return $this->tagAs($objid, self::TAG_FAVORITE);
648
+    }
649
+
650
+    /**
651
+     * Remove an object from favorites
652
+     *
653
+     * @param int $objid The id of the object
654
+     * @return boolean
655
+     */
656
+    public function removeFromFavorites($objid) {
657
+        return $this->unTag($objid, self::TAG_FAVORITE);
658
+    }
659
+
660
+    /**
661
+     * Creates a tag/object relation.
662
+     *
663
+     * @param int $objid The id of the object
664
+     * @param string $tag The id or name of the tag
665
+     * @return boolean Returns false on error.
666
+     */
667
+    public function tagAs($objid, $tag) {
668
+        if(is_string($tag) && !is_numeric($tag)) {
669
+            $tag = trim($tag);
670
+            if($tag === '') {
671
+                \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
672
+                return false;
673
+            }
674
+            if(!$this->hasTag($tag)) {
675
+                $this->add($tag);
676
+            }
677
+            $tagId =  $this->getTagId($tag);
678
+        } else {
679
+            $tagId = $tag;
680
+        }
681
+        try {
682
+            \OCP\DB::insertIfNotExist(self::RELATION_TABLE,
683
+                array(
684
+                    'objid' => $objid,
685
+                    'categoryid' => $tagId,
686
+                    'type' => $this->type,
687
+                ));
688
+        } catch(\Exception $e) {
689
+            \OC::$server->getLogger()->logException($e, [
690
+                'message' => __METHOD__,
691
+                'level' => \OCP\Util::ERROR,
692
+                'app' => 'core',
693
+            ]);
694
+            return false;
695
+        }
696
+        return true;
697
+    }
698
+
699
+    /**
700
+     * Delete single tag/object relation from the db
701
+     *
702
+     * @param int $objid The id of the object
703
+     * @param string $tag The id or name of the tag
704
+     * @return boolean
705
+     */
706
+    public function unTag($objid, $tag) {
707
+        if(is_string($tag) && !is_numeric($tag)) {
708
+            $tag = trim($tag);
709
+            if($tag === '') {
710
+                \OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', \OCP\Util::DEBUG);
711
+                return false;
712
+            }
713
+            $tagId =  $this->getTagId($tag);
714
+        } else {
715
+            $tagId = $tag;
716
+        }
717
+
718
+        try {
719
+            $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
720
+                    . 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
721
+            $stmt = \OCP\DB::prepare($sql);
722
+            $stmt->execute(array($objid, $tagId, $this->type));
723
+        } catch(\Exception $e) {
724
+            \OC::$server->getLogger()->logException($e, [
725
+                'message' => __METHOD__,
726
+                'level' => \OCP\Util::ERROR,
727
+                'app' => 'core',
728
+            ]);
729
+            return false;
730
+        }
731
+        return true;
732
+    }
733
+
734
+    /**
735
+     * Delete tags from the database.
736
+     *
737
+     * @param string[]|integer[] $names An array of tags (names or IDs) to delete
738
+     * @return bool Returns false on error
739
+     */
740
+    public function delete($names) {
741
+        if(!is_array($names)) {
742
+            $names = array($names);
743
+        }
744
+
745
+        $names = array_map('trim', $names);
746
+        array_filter($names);
747
+
748
+        \OCP\Util::writeLog('core', __METHOD__ . ', before: '
749
+            . print_r($this->tags, true), \OCP\Util::DEBUG);
750
+        foreach($names as $name) {
751
+            $id = null;
752
+
753
+            if (is_numeric($name)) {
754
+                $key = $this->getTagById($name);
755
+            } else {
756
+                $key = $this->getTagByName($name);
757
+            }
758
+            if ($key !== false) {
759
+                $tag = $this->tags[$key];
760
+                $id = $tag->getId();
761
+                unset($this->tags[$key]);
762
+                $this->mapper->delete($tag);
763
+            } else {
764
+                \OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
765
+                    . ': not found.', \OCP\Util::ERROR);
766
+            }
767
+            if(!is_null($id) && $id !== false) {
768
+                try {
769
+                    $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
770
+                            . 'WHERE `categoryid` = ?';
771
+                    $stmt = \OCP\DB::prepare($sql);
772
+                    $result = $stmt->execute(array($id));
773
+                    if ($result === null) {
774
+                        \OCP\Util::writeLog('core',
775
+                            __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(),
776
+                            \OCP\Util::ERROR);
777
+                        return false;
778
+                    }
779
+                } catch(\Exception $e) {
780
+                    \OC::$server->getLogger()->logException($e, [
781
+                        'message' => __METHOD__,
782
+                        'level' => \OCP\Util::ERROR,
783
+                        'app' => 'core',
784
+                    ]);
785
+                    return false;
786
+                }
787
+            }
788
+        }
789
+        return true;
790
+    }
791
+
792
+    // case-insensitive array_search
793
+    protected function array_searchi($needle, $haystack, $mem='getName') {
794
+        if(!is_array($haystack)) {
795
+            return false;
796
+        }
797
+        return array_search(strtolower($needle), array_map(
798
+            function($tag) use($mem) {
799
+                return strtolower(call_user_func(array($tag, $mem)));
800
+            }, $haystack)
801
+        );
802
+    }
803
+
804
+    /**
805
+     * Get a tag's ID.
806
+     *
807
+     * @param string $name The tag name to look for.
808
+     * @return string|bool The tag's id or false if no matching tag is found.
809
+     */
810
+    private function getTagId($name) {
811
+        $key = $this->array_searchi($name, $this->tags);
812
+        if ($key !== false) {
813
+            return $this->tags[$key]->getId();
814
+        }
815
+        return false;
816
+    }
817
+
818
+    /**
819
+     * Get a tag by its name.
820
+     *
821
+     * @param string $name The tag name.
822
+     * @return integer|bool The tag object's offset within the $this->tags
823
+     *                      array or false if it doesn't exist.
824
+     */
825
+    private function getTagByName($name) {
826
+        return $this->array_searchi($name, $this->tags, 'getName');
827
+    }
828
+
829
+    /**
830
+     * Get a tag by its ID.
831
+     *
832
+     * @param string $id The tag ID to look for.
833
+     * @return integer|bool The tag object's offset within the $this->tags
834
+     *                      array or false if it doesn't exist.
835
+     */
836
+    private function getTagById($id) {
837
+        return $this->array_searchi($id, $this->tags, 'getId');
838
+    }
839
+
840
+    /**
841
+     * Returns an array mapping a given tag's properties to its values:
842
+     * ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
843
+     *
844
+     * @param Tag $tag The tag that is going to be mapped
845
+     * @return array
846
+     */
847
+    private function tagMap(Tag $tag) {
848
+        return array(
849
+            'id'    => $tag->getId(),
850
+            'name'  => $tag->getName(),
851
+            'owner' => $tag->getOwner(),
852
+            'type'  => $tag->getType()
853
+        );
854
+    }
855 855
 }
Please login to merge, or discard this patch.
Spacing   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 		}
135 135
 		$this->tags = $this->mapper->loadTags($this->owners, $this->type);
136 136
 
137
-		if(count($defaultTags) > 0 && count($this->tags) === 0) {
137
+		if (count($defaultTags) > 0 && count($this->tags) === 0) {
138 138
 			$this->addMultiple($defaultTags, true);
139 139
 		}
140 140
 	}
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 	* @return array
176 176
 	*/
177 177
 	public function getTags() {
178
-		if(!count($this->tags)) {
178
+		if (!count($this->tags)) {
179 179
 			return array();
180 180
 		}
181 181
 
@@ -184,8 +184,8 @@  discard block
 block discarded – undo
184 184
 		});
185 185
 		$tagMap = array();
186 186
 
187
-		foreach($this->tags as $tag) {
188
-			if($tag->getName() !== self::TAG_FAVORITE) {
187
+		foreach ($this->tags as $tag) {
188
+			if ($tag->getName() !== self::TAG_FAVORITE) {
189 189
 				$tagMap[] = $this->tagMap($tag);
190 190
 			}
191 191
 		}
@@ -223,25 +223,25 @@  discard block
 block discarded – undo
223 223
 			$chunks = array_chunk($objIds, 900, false);
224 224
 			foreach ($chunks as $chunk) {
225 225
 				$result = $conn->executeQuery(
226
-					'SELECT `category`, `categoryid`, `objid` ' .
227
-					'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
226
+					'SELECT `category`, `categoryid`, `objid` '.
227
+					'FROM `'.self::RELATION_TABLE.'` r, `'.self::TAG_TABLE.'` '.
228 228
 					'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
229 229
 					array($this->user, $this->type, $chunk),
230 230
 					array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
231 231
 				);
232 232
 				while ($row = $result->fetch()) {
233
-					$objId = (int)$row['objid'];
233
+					$objId = (int) $row['objid'];
234 234
 					if (!isset($entries[$objId])) {
235 235
 						$entries[$objId] = array();
236 236
 					}
237 237
 					$entries[$objId][] = $row['category'];
238 238
 				}
239 239
 				if ($result === null) {
240
-					\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
240
+					\OCP\Util::writeLog('core', __METHOD__.'DB error: '.\OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
241 241
 					return false;
242 242
 				}
243 243
 			}
244
-		} catch(\Exception $e) {
244
+		} catch (\Exception $e) {
245 245
 			\OC::$server->getLogger()->logException($e, [
246 246
 				'message' => __METHOD__,
247 247
 				'level' => \OCP\Util::ERROR,
@@ -265,18 +265,18 @@  discard block
 block discarded – undo
265 265
 	public function getIdsForTag($tag) {
266 266
 		$result = null;
267 267
 		$tagId = false;
268
-		if(is_numeric($tag)) {
268
+		if (is_numeric($tag)) {
269 269
 			$tagId = $tag;
270
-		} elseif(is_string($tag)) {
270
+		} elseif (is_string($tag)) {
271 271
 			$tag = trim($tag);
272
-			if($tag === '') {
272
+			if ($tag === '') {
273 273
 				\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
274 274
 				return false;
275 275
 			}
276 276
 			$tagId = $this->getTagId($tag);
277 277
 		}
278 278
 
279
-		if($tagId === false) {
279
+		if ($tagId === false) {
280 280
 			$l10n = \OC::$server->getL10N('core');
281 281
 			throw new \Exception(
282 282
 				$l10n->t('Could not find category "%s"', [$tag])
@@ -284,17 +284,17 @@  discard block
 block discarded – undo
284 284
 		}
285 285
 
286 286
 		$ids = array();
287
-		$sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
287
+		$sql = 'SELECT `objid` FROM `'.self::RELATION_TABLE
288 288
 			. '` WHERE `categoryid` = ?';
289 289
 
290 290
 		try {
291 291
 			$stmt = \OCP\DB::prepare($sql);
292 292
 			$result = $stmt->execute(array($tagId));
293 293
 			if ($result === null) {
294
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
294
+				\OCP\Util::writeLog('core', __METHOD__.'DB error: '.\OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
295 295
 				return false;
296 296
 			}
297
-		} catch(\Exception $e) {
297
+		} catch (\Exception $e) {
298 298
 			\OC::$server->getLogger()->logException($e, [
299 299
 				'message' => __METHOD__,
300 300
 				'level' => \OCP\Util::ERROR,
@@ -303,9 +303,9 @@  discard block
 block discarded – undo
303 303
 			return false;
304 304
 		}
305 305
 
306
-		if(!is_null($result)) {
307
-			while( $row = $result->fetchRow()) {
308
-				$id = (int)$row['objid'];
306
+		if (!is_null($result)) {
307
+			while ($row = $result->fetchRow()) {
308
+				$id = (int) $row['objid'];
309 309
 
310 310
 				if ($this->includeShared) {
311 311
 					// We have to check if we are really allowed to access the
@@ -359,19 +359,19 @@  discard block
 block discarded – undo
359 359
 	public function add($name) {
360 360
 		$name = trim($name);
361 361
 
362
-		if($name === '') {
362
+		if ($name === '') {
363 363
 			\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
364 364
 			return false;
365 365
 		}
366
-		if($this->userHasTag($name, $this->user)) {
367
-			\OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', \OCP\Util::DEBUG);
366
+		if ($this->userHasTag($name, $this->user)) {
367
+			\OCP\Util::writeLog('core', __METHOD__.', name: '.$name.' exists already', \OCP\Util::DEBUG);
368 368
 			return false;
369 369
 		}
370 370
 		try {
371 371
 			$tag = new Tag($this->user, $this->type, $name);
372 372
 			$tag = $this->mapper->insert($tag);
373 373
 			$this->tags[] = $tag;
374
-		} catch(\Exception $e) {
374
+		} catch (\Exception $e) {
375 375
 			\OC::$server->getLogger()->logException($e, [
376 376
 				'message' => __METHOD__,
377 377
 				'level' => \OCP\Util::ERROR,
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
 			]);
380 380
 			return false;
381 381
 		}
382
-		\OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), \OCP\Util::DEBUG);
382
+		\OCP\Util::writeLog('core', __METHOD__.', id: '.$tag->getId(), \OCP\Util::DEBUG);
383 383
 		return $tag->getId();
384 384
 	}
385 385
 
@@ -394,7 +394,7 @@  discard block
 block discarded – undo
394 394
 		$from = trim($from);
395 395
 		$to = trim($to);
396 396
 
397
-		if($to === '' || $from === '') {
397
+		if ($to === '' || $from === '') {
398 398
 			\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
399 399
 			return false;
400 400
 		}
@@ -404,21 +404,21 @@  discard block
 block discarded – undo
404 404
 		} else {
405 405
 			$key = $this->getTagByName($from);
406 406
 		}
407
-		if($key === false) {
408
-			\OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', \OCP\Util::DEBUG);
407
+		if ($key === false) {
408
+			\OCP\Util::writeLog('core', __METHOD__.', tag: '.$from.' does not exist', \OCP\Util::DEBUG);
409 409
 			return false;
410 410
 		}
411 411
 		$tag = $this->tags[$key];
412 412
 
413
-		if($this->userHasTag($to, $tag->getOwner())) {
414
-			\OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', \OCP\Util::DEBUG);
413
+		if ($this->userHasTag($to, $tag->getOwner())) {
414
+			\OCP\Util::writeLog('core', __METHOD__.', A tag named '.$to.' already exists for user '.$tag->getOwner().'.', \OCP\Util::DEBUG);
415 415
 			return false;
416 416
 		}
417 417
 
418 418
 		try {
419 419
 			$tag->setName($to);
420 420
 			$this->tags[$key] = $this->mapper->update($tag);
421
-		} catch(\Exception $e) {
421
+		} catch (\Exception $e) {
422 422
 			\OC::$server->getLogger()->logException($e, [
423 423
 				'message' => __METHOD__,
424 424
 				'level' => \OCP\Util::ERROR,
@@ -438,25 +438,25 @@  discard block
 block discarded – undo
438 438
 	* @param int|null $id int Optional object id to add to this|these tag(s)
439 439
 	* @return bool Returns false on error.
440 440
 	*/
441
-	public function addMultiple($names, $sync=false, $id = null) {
442
-		if(!is_array($names)) {
441
+	public function addMultiple($names, $sync = false, $id = null) {
442
+		if (!is_array($names)) {
443 443
 			$names = array($names);
444 444
 		}
445 445
 		$names = array_map('trim', $names);
446 446
 		array_filter($names);
447 447
 
448 448
 		$newones = array();
449
-		foreach($names as $name) {
450
-			if(!$this->hasTag($name) && $name !== '') {
449
+		foreach ($names as $name) {
450
+			if (!$this->hasTag($name) && $name !== '') {
451 451
 				$newones[] = new Tag($this->user, $this->type, $name);
452 452
 			}
453
-			if(!is_null($id) ) {
453
+			if (!is_null($id)) {
454 454
 				// Insert $objectid, $categoryid  pairs if not exist.
455 455
 				self::$relations[] = array('objid' => $id, 'tag' => $name);
456 456
 			}
457 457
 		}
458 458
 		$this->tags = array_merge($this->tags, $newones);
459
-		if($sync === true) {
459
+		if ($sync === true) {
460 460
 			$this->save();
461 461
 		}
462 462
 
@@ -467,13 +467,13 @@  discard block
 block discarded – undo
467 467
 	 * Save the list of tags and their object relations
468 468
 	 */
469 469
 	protected function save() {
470
-		if(is_array($this->tags)) {
471
-			foreach($this->tags as $tag) {
470
+		if (is_array($this->tags)) {
471
+			foreach ($this->tags as $tag) {
472 472
 				try {
473 473
 					if (!$this->mapper->tagExists($tag)) {
474 474
 						$this->mapper->insert($tag);
475 475
 					}
476
-				} catch(\Exception $e) {
476
+				} catch (\Exception $e) {
477 477
 					\OC::$server->getLogger()->logException($e, [
478 478
 						'message' => __METHOD__,
479 479
 						'level' => \OCP\Util::ERROR,
@@ -484,17 +484,17 @@  discard block
 block discarded – undo
484 484
 
485 485
 			// reload tags to get the proper ids.
486 486
 			$this->tags = $this->mapper->loadTags($this->owners, $this->type);
487
-			\OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
487
+			\OCP\Util::writeLog('core', __METHOD__.', tags: '.print_r($this->tags, true),
488 488
 				\OCP\Util::DEBUG);
489 489
 			// Loop through temporarily cached objectid/tagname pairs
490 490
 			// and save relations.
491 491
 			$tags = $this->tags;
492 492
 			// For some reason this is needed or array_search(i) will return 0..?
493 493
 			ksort($tags);
494
-			foreach(self::$relations as $relation) {
494
+			foreach (self::$relations as $relation) {
495 495
 				$tagId = $this->getTagId($relation['tag']);
496
-				\OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, \OCP\Util::DEBUG);
497
-				if($tagId) {
496
+				\OCP\Util::writeLog('core', __METHOD__.'catid, '.$relation['tag'].' '.$tagId, \OCP\Util::DEBUG);
497
+				if ($tagId) {
498 498
 					try {
499 499
 						\OCP\DB::insertIfNotExist(self::RELATION_TABLE,
500 500
 							array(
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
 								'categoryid' => $tagId,
503 503
 								'type' => $this->type,
504 504
 								));
505
-					} catch(\Exception $e) {
505
+					} catch (\Exception $e) {
506 506
 						\OC::$server->getLogger()->logException($e, [
507 507
 							'message' => __METHOD__,
508 508
 							'level' => \OCP\Util::ERROR,
@@ -529,13 +529,13 @@  discard block
 block discarded – undo
529 529
 		// Find all objectid/tagId pairs.
530 530
 		$result = null;
531 531
 		try {
532
-			$stmt = \OCP\DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
532
+			$stmt = \OCP\DB::prepare('SELECT `id` FROM `'.self::TAG_TABLE.'` '
533 533
 				. 'WHERE `uid` = ?');
534 534
 			$result = $stmt->execute(array($arguments['uid']));
535 535
 			if ($result === null) {
536
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
536
+				\OCP\Util::writeLog('core', __METHOD__.'DB error: '.\OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
537 537
 			}
538
-		} catch(\Exception $e) {
538
+		} catch (\Exception $e) {
539 539
 			\OC::$server->getLogger()->logException($e, [
540 540
 				'message' => __METHOD__,
541 541
 				'level' => \OCP\Util::ERROR,
@@ -543,14 +543,14 @@  discard block
 block discarded – undo
543 543
 			]);
544 544
 		}
545 545
 
546
-		if(!is_null($result)) {
546
+		if (!is_null($result)) {
547 547
 			try {
548
-				$stmt = \OCP\DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
548
+				$stmt = \OCP\DB::prepare('DELETE FROM `'.self::RELATION_TABLE.'` '
549 549
 					. 'WHERE `categoryid` = ?');
550
-				while( $row = $result->fetchRow()) {
550
+				while ($row = $result->fetchRow()) {
551 551
 					try {
552 552
 						$stmt->execute(array($row['id']));
553
-					} catch(\Exception $e) {
553
+					} catch (\Exception $e) {
554 554
 						\OC::$server->getLogger()->logException($e, [
555 555
 							'message' => __METHOD__,
556 556
 							'level' => \OCP\Util::ERROR,
@@ -558,7 +558,7 @@  discard block
 block discarded – undo
558 558
 						]);
559 559
 					}
560 560
 				}
561
-			} catch(\Exception $e) {
561
+			} catch (\Exception $e) {
562 562
 				\OC::$server->getLogger()->logException($e, [
563 563
 					'message' => __METHOD__,
564 564
 					'level' => \OCP\Util::ERROR,
@@ -567,13 +567,13 @@  discard block
 block discarded – undo
567 567
 			}
568 568
 		}
569 569
 		try {
570
-			$stmt = \OCP\DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
570
+			$stmt = \OCP\DB::prepare('DELETE FROM `'.self::TAG_TABLE.'` '
571 571
 				. 'WHERE `uid` = ?');
572 572
 			$result = $stmt->execute(array($arguments['uid']));
573 573
 			if ($result === null) {
574
-				\OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
574
+				\OCP\Util::writeLog('core', __METHOD__.', DB error: '.\OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
575 575
 			}
576
-		} catch(\Exception $e) {
576
+		} catch (\Exception $e) {
577 577
 			\OC::$server->getLogger()->logException($e, [
578 578
 				'message' => __METHOD__,
579 579
 				'level' => \OCP\Util::ERROR,
@@ -589,23 +589,23 @@  discard block
 block discarded – undo
589 589
 	* @return boolean Returns false on error.
590 590
 	*/
591 591
 	public function purgeObjects(array $ids) {
592
-		if(count($ids) === 0) {
592
+		if (count($ids) === 0) {
593 593
 			// job done ;)
594 594
 			return true;
595 595
 		}
596 596
 		$updates = $ids;
597 597
 		try {
598
-			$query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
599
-			$query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
598
+			$query = 'DELETE FROM `'.self::RELATION_TABLE.'` ';
599
+			$query .= 'WHERE `objid` IN ('.str_repeat('?,', count($ids) - 1).'?) ';
600 600
 			$query .= 'AND `type`= ?';
601 601
 			$updates[] = $this->type;
602 602
 			$stmt = \OCP\DB::prepare($query);
603 603
 			$result = $stmt->execute($updates);
604 604
 			if ($result === null) {
605
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
605
+				\OCP\Util::writeLog('core', __METHOD__.'DB error: '.\OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
606 606
 				return false;
607 607
 			}
608
-		} catch(\Exception $e) {
608
+		} catch (\Exception $e) {
609 609
 			\OC::$server->getLogger()->logException($e, [
610 610
 				'message' => __METHOD__,
611 611
 				'level' => \OCP\Util::ERROR,
@@ -624,7 +624,7 @@  discard block
 block discarded – undo
624 624
 	public function getFavorites() {
625 625
 		try {
626 626
 			return $this->getIdsForTag(self::TAG_FAVORITE);
627
-		} catch(\Exception $e) {
627
+		} catch (\Exception $e) {
628 628
 			\OC::$server->getLogger()->logException($e, [
629 629
 				'message' => __METHOD__,
630 630
 				'level' => \OCP\Util::ERROR,
@@ -641,7 +641,7 @@  discard block
 block discarded – undo
641 641
 	* @return boolean
642 642
 	*/
643 643
 	public function addToFavorites($objid) {
644
-		if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
644
+		if (!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
645 645
 			$this->add(self::TAG_FAVORITE);
646 646
 		}
647 647
 		return $this->tagAs($objid, self::TAG_FAVORITE);
@@ -665,16 +665,16 @@  discard block
 block discarded – undo
665 665
 	* @return boolean Returns false on error.
666 666
 	*/
667 667
 	public function tagAs($objid, $tag) {
668
-		if(is_string($tag) && !is_numeric($tag)) {
668
+		if (is_string($tag) && !is_numeric($tag)) {
669 669
 			$tag = trim($tag);
670
-			if($tag === '') {
670
+			if ($tag === '') {
671 671
 				\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
672 672
 				return false;
673 673
 			}
674
-			if(!$this->hasTag($tag)) {
674
+			if (!$this->hasTag($tag)) {
675 675
 				$this->add($tag);
676 676
 			}
677
-			$tagId =  $this->getTagId($tag);
677
+			$tagId = $this->getTagId($tag);
678 678
 		} else {
679 679
 			$tagId = $tag;
680 680
 		}
@@ -685,7 +685,7 @@  discard block
 block discarded – undo
685 685
 					'categoryid' => $tagId,
686 686
 					'type' => $this->type,
687 687
 				));
688
-		} catch(\Exception $e) {
688
+		} catch (\Exception $e) {
689 689
 			\OC::$server->getLogger()->logException($e, [
690 690
 				'message' => __METHOD__,
691 691
 				'level' => \OCP\Util::ERROR,
@@ -704,23 +704,23 @@  discard block
 block discarded – undo
704 704
 	* @return boolean
705 705
 	*/
706 706
 	public function unTag($objid, $tag) {
707
-		if(is_string($tag) && !is_numeric($tag)) {
707
+		if (is_string($tag) && !is_numeric($tag)) {
708 708
 			$tag = trim($tag);
709
-			if($tag === '') {
709
+			if ($tag === '') {
710 710
 				\OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', \OCP\Util::DEBUG);
711 711
 				return false;
712 712
 			}
713
-			$tagId =  $this->getTagId($tag);
713
+			$tagId = $this->getTagId($tag);
714 714
 		} else {
715 715
 			$tagId = $tag;
716 716
 		}
717 717
 
718 718
 		try {
719
-			$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
719
+			$sql = 'DELETE FROM `'.self::RELATION_TABLE.'` '
720 720
 					. 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
721 721
 			$stmt = \OCP\DB::prepare($sql);
722 722
 			$stmt->execute(array($objid, $tagId, $this->type));
723
-		} catch(\Exception $e) {
723
+		} catch (\Exception $e) {
724 724
 			\OC::$server->getLogger()->logException($e, [
725 725
 				'message' => __METHOD__,
726 726
 				'level' => \OCP\Util::ERROR,
@@ -738,16 +738,16 @@  discard block
 block discarded – undo
738 738
 	* @return bool Returns false on error
739 739
 	*/
740 740
 	public function delete($names) {
741
-		if(!is_array($names)) {
741
+		if (!is_array($names)) {
742 742
 			$names = array($names);
743 743
 		}
744 744
 
745 745
 		$names = array_map('trim', $names);
746 746
 		array_filter($names);
747 747
 
748
-		\OCP\Util::writeLog('core', __METHOD__ . ', before: '
748
+		\OCP\Util::writeLog('core', __METHOD__.', before: '
749 749
 			. print_r($this->tags, true), \OCP\Util::DEBUG);
750
-		foreach($names as $name) {
750
+		foreach ($names as $name) {
751 751
 			$id = null;
752 752
 
753 753
 			if (is_numeric($name)) {
@@ -761,22 +761,22 @@  discard block
 block discarded – undo
761 761
 				unset($this->tags[$key]);
762 762
 				$this->mapper->delete($tag);
763 763
 			} else {
764
-				\OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
764
+				\OCP\Util::writeLog('core', __METHOD__.'Cannot delete tag '.$name
765 765
 					. ': not found.', \OCP\Util::ERROR);
766 766
 			}
767
-			if(!is_null($id) && $id !== false) {
767
+			if (!is_null($id) && $id !== false) {
768 768
 				try {
769
-					$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
769
+					$sql = 'DELETE FROM `'.self::RELATION_TABLE.'` '
770 770
 							. 'WHERE `categoryid` = ?';
771 771
 					$stmt = \OCP\DB::prepare($sql);
772 772
 					$result = $stmt->execute(array($id));
773 773
 					if ($result === null) {
774 774
 						\OCP\Util::writeLog('core',
775
-							__METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(),
775
+							__METHOD__.'DB error: '.\OCP\DB::getErrorMessage(),
776 776
 							\OCP\Util::ERROR);
777 777
 						return false;
778 778
 					}
779
-				} catch(\Exception $e) {
779
+				} catch (\Exception $e) {
780 780
 					\OC::$server->getLogger()->logException($e, [
781 781
 						'message' => __METHOD__,
782 782
 						'level' => \OCP\Util::ERROR,
@@ -790,8 +790,8 @@  discard block
 block discarded – undo
790 790
 	}
791 791
 
792 792
 	// case-insensitive array_search
793
-	protected function array_searchi($needle, $haystack, $mem='getName') {
794
-		if(!is_array($haystack)) {
793
+	protected function array_searchi($needle, $haystack, $mem = 'getName') {
794
+		if (!is_array($haystack)) {
795 795
 			return false;
796 796
 		}
797 797
 		return array_search(strtolower($needle), array_map(
Please login to merge, or discard this patch.
lib/public/DB.php 2 patches
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -46,65 +46,65 @@
 block discarded – undo
46 46
  * @since 4.5.0
47 47
  */
48 48
 class DB {
49
-	/**
50
-	 * Prepare a SQL query
51
-	 * @param string $query Query string
52
-	 * @param int $limit Limit of the SQL statement
53
-	 * @param int $offset Offset of the SQL statement
54
-	 * @return \OC_DB_StatementWrapper prepared SQL query
55
-	 *
56
-	 * SQL query via Doctrine prepare(), needs to be execute()'d!
57
-	 * @deprecated 8.1.0 use prepare() of \OCP\IDBConnection - \OC::$server->getDatabaseConnection()
58
-	 * @since 4.5.0
59
-	 */
60
-	static public function prepare( $query, $limit=null, $offset=null ) {
61
-		return \OC_DB::prepare($query, $limit, $offset);
62
-	}
49
+    /**
50
+     * Prepare a SQL query
51
+     * @param string $query Query string
52
+     * @param int $limit Limit of the SQL statement
53
+     * @param int $offset Offset of the SQL statement
54
+     * @return \OC_DB_StatementWrapper prepared SQL query
55
+     *
56
+     * SQL query via Doctrine prepare(), needs to be execute()'d!
57
+     * @deprecated 8.1.0 use prepare() of \OCP\IDBConnection - \OC::$server->getDatabaseConnection()
58
+     * @since 4.5.0
59
+     */
60
+    static public function prepare( $query, $limit=null, $offset=null ) {
61
+        return \OC_DB::prepare($query, $limit, $offset);
62
+    }
63 63
 
64
-	/**
65
-	 * Insert a row if the matching row does not exists.
66
-	 *
67
-	 * @param string $table The table name (will replace *PREFIX* with the actual prefix)
68
-	 * @param array $input data that should be inserted into the table  (column name => value)
69
-	 * @param array|null $compare List of values that should be checked for "if not exists"
70
-	 *				If this is null or an empty array, all keys of $input will be compared
71
-	 * @return int number of inserted rows
72
-	 * @throws \Doctrine\DBAL\DBALException
73
-	 * @deprecated 8.1.0 use insertIfNotExist() of \OCP\IDBConnection - \OC::$server->getDatabaseConnection()
74
-	 * @since 5.0.0 - parameter $compare was added in 8.1.0
75
-	 *
76
-	 */
77
-	public static function insertIfNotExist($table, $input, array $compare = null) {
78
-		return \OC::$server->getDatabaseConnection()->insertIfNotExist($table, $input, $compare);
79
-	}
64
+    /**
65
+     * Insert a row if the matching row does not exists.
66
+     *
67
+     * @param string $table The table name (will replace *PREFIX* with the actual prefix)
68
+     * @param array $input data that should be inserted into the table  (column name => value)
69
+     * @param array|null $compare List of values that should be checked for "if not exists"
70
+     *				If this is null or an empty array, all keys of $input will be compared
71
+     * @return int number of inserted rows
72
+     * @throws \Doctrine\DBAL\DBALException
73
+     * @deprecated 8.1.0 use insertIfNotExist() of \OCP\IDBConnection - \OC::$server->getDatabaseConnection()
74
+     * @since 5.0.0 - parameter $compare was added in 8.1.0
75
+     *
76
+     */
77
+    public static function insertIfNotExist($table, $input, array $compare = null) {
78
+        return \OC::$server->getDatabaseConnection()->insertIfNotExist($table, $input, $compare);
79
+    }
80 80
 
81
-	/**
82
-	 * Start a transaction
83
-	 * @deprecated 8.1.0 use beginTransaction() of \OCP\IDBConnection - \OC::$server->getDatabaseConnection()
84
-	 * @since 4.5.0
85
-	 */
86
-	public static function beginTransaction() {
87
-		\OC::$server->getDatabaseConnection()->beginTransaction();
88
-	}
81
+    /**
82
+     * Start a transaction
83
+     * @deprecated 8.1.0 use beginTransaction() of \OCP\IDBConnection - \OC::$server->getDatabaseConnection()
84
+     * @since 4.5.0
85
+     */
86
+    public static function beginTransaction() {
87
+        \OC::$server->getDatabaseConnection()->beginTransaction();
88
+    }
89 89
 
90
-	/**
91
-	 * Commit the database changes done during a transaction that is in progress
92
-	 * @deprecated 8.1.0 use commit() of \OCP\IDBConnection - \OC::$server->getDatabaseConnection()
93
-	 * @since 4.5.0
94
-	 */
95
-	public static function commit() {
96
-		\OC::$server->getDatabaseConnection()->commit();
97
-	}
90
+    /**
91
+     * Commit the database changes done during a transaction that is in progress
92
+     * @deprecated 8.1.0 use commit() of \OCP\IDBConnection - \OC::$server->getDatabaseConnection()
93
+     * @since 4.5.0
94
+     */
95
+    public static function commit() {
96
+        \OC::$server->getDatabaseConnection()->commit();
97
+    }
98 98
 
99
-	/**
100
-	 * returns the error code and message as a string for logging
101
-	 * works with DoctrineException
102
-	 * @return string
103
-	 * @deprecated 8.1.0 use getError() of \OCP\IDBConnection - \OC::$server->getDatabaseConnection()
104
-	 * @since 6.0.0
105
-	 */
106
-	public static function getErrorMessage() {
107
-		return \OC::$server->getDatabaseConnection()->getError();
108
-	}
99
+    /**
100
+     * returns the error code and message as a string for logging
101
+     * works with DoctrineException
102
+     * @return string
103
+     * @deprecated 8.1.0 use getError() of \OCP\IDBConnection - \OC::$server->getDatabaseConnection()
104
+     * @since 6.0.0
105
+     */
106
+    public static function getErrorMessage() {
107
+        return \OC::$server->getDatabaseConnection()->getError();
108
+    }
109 109
 
110 110
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -57,7 +57,7 @@
 block discarded – undo
57 57
 	 * @deprecated 8.1.0 use prepare() of \OCP\IDBConnection - \OC::$server->getDatabaseConnection()
58 58
 	 * @since 4.5.0
59 59
 	 */
60
-	static public function prepare( $query, $limit=null, $offset=null ) {
60
+	static public function prepare($query, $limit = null, $offset = null) {
61 61
 		return \OC_DB::prepare($query, $limit, $offset);
62 62
 	}
63 63
 
Please login to merge, or discard this patch.
apps/user_ldap/lib/Helper.php 2 patches
Indentation   +261 added lines, -261 removed lines patch added patch discarded remove patch
@@ -37,125 +37,125 @@  discard block
 block discarded – undo
37 37
 
38 38
 class Helper {
39 39
 
40
-	/** @var IConfig */
41
-	private $config;
42
-
43
-	/**
44
-	 * Helper constructor.
45
-	 *
46
-	 * @param IConfig $config
47
-	 */
48
-	public function __construct(IConfig $config) {
49
-		$this->config = $config;
50
-	}
51
-
52
-	/**
53
-	 * returns prefixes for each saved LDAP/AD server configuration.
54
-	 * @param bool $activeConfigurations optional, whether only active configuration shall be
55
-	 * retrieved, defaults to false
56
-	 * @return array with a list of the available prefixes
57
-	 *
58
-	 * Configuration prefixes are used to set up configurations for n LDAP or
59
-	 * AD servers. Since configuration is stored in the database, table
60
-	 * appconfig under appid user_ldap, the common identifiers in column
61
-	 * 'configkey' have a prefix. The prefix for the very first server
62
-	 * configuration is empty.
63
-	 * Configkey Examples:
64
-	 * Server 1: ldap_login_filter
65
-	 * Server 2: s1_ldap_login_filter
66
-	 * Server 3: s2_ldap_login_filter
67
-	 *
68
-	 * The prefix needs to be passed to the constructor of Connection class,
69
-	 * except the default (first) server shall be connected to.
70
-	 *
71
-	 */
72
-	public function getServerConfigurationPrefixes($activeConfigurations = false) {
73
-		$referenceConfigkey = 'ldap_configuration_active';
74
-
75
-		$keys = $this->getServersConfig($referenceConfigkey);
76
-
77
-		$prefixes = [];
78
-		foreach ($keys as $key) {
79
-			if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') {
80
-				continue;
81
-			}
82
-
83
-			$len = strlen($key) - strlen($referenceConfigkey);
84
-			$prefixes[] = substr($key, 0, $len);
85
-		}
86
-
87
-		return $prefixes;
88
-	}
89
-
90
-	/**
91
-	 *
92
-	 * determines the host for every configured connection
93
-	 * @return array an array with configprefix as keys
94
-	 *
95
-	 */
96
-	public function getServerConfigurationHosts() {
97
-		$referenceConfigkey = 'ldap_host';
98
-
99
-		$keys = $this->getServersConfig($referenceConfigkey);
100
-
101
-		$result = array();
102
-		foreach($keys as $key) {
103
-			$len = strlen($key) - strlen($referenceConfigkey);
104
-			$prefix = substr($key, 0, $len);
105
-			$result[$prefix] = $this->config->getAppValue('user_ldap', $key);
106
-		}
107
-
108
-		return $result;
109
-	}
110
-
111
-	/**
112
-	 * return the next available configuration prefix
113
-	 *
114
-	 * @return string
115
-	 */
116
-	public function getNextServerConfigurationPrefix() {
117
-		$serverConnections = $this->getServerConfigurationPrefixes();
118
-
119
-		if(count($serverConnections) === 0) {
120
-			return 's01';
121
-		}
122
-
123
-		sort($serverConnections);
124
-		$lastKey = array_pop($serverConnections);
125
-		$lastNumber = (int)str_replace('s', '', $lastKey);
126
-		return 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
127
-	}
128
-
129
-	private function getServersConfig($value) {
130
-		$regex = '/' . $value . '$/S';
131
-
132
-		$keys = $this->config->getAppKeys('user_ldap');
133
-		$result = [];
134
-		foreach ($keys as $key) {
135
-			if (preg_match($regex, $key) === 1) {
136
-				$result[] = $key;
137
-			}
138
-		}
139
-
140
-		return $result;
141
-	}
142
-
143
-	/**
144
-	 * deletes a given saved LDAP/AD server configuration.
145
-	 * @param string $prefix the configuration prefix of the config to delete
146
-	 * @return bool true on success, false otherwise
147
-	 */
148
-	public function deleteServerConfiguration($prefix) {
149
-		if(!in_array($prefix, self::getServerConfigurationPrefixes())) {
150
-			return false;
151
-		}
152
-
153
-		$saveOtherConfigurations = '';
154
-		if(empty($prefix)) {
155
-			$saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
156
-		}
157
-
158
-		$query = \OCP\DB::prepare('
40
+    /** @var IConfig */
41
+    private $config;
42
+
43
+    /**
44
+     * Helper constructor.
45
+     *
46
+     * @param IConfig $config
47
+     */
48
+    public function __construct(IConfig $config) {
49
+        $this->config = $config;
50
+    }
51
+
52
+    /**
53
+     * returns prefixes for each saved LDAP/AD server configuration.
54
+     * @param bool $activeConfigurations optional, whether only active configuration shall be
55
+     * retrieved, defaults to false
56
+     * @return array with a list of the available prefixes
57
+     *
58
+     * Configuration prefixes are used to set up configurations for n LDAP or
59
+     * AD servers. Since configuration is stored in the database, table
60
+     * appconfig under appid user_ldap, the common identifiers in column
61
+     * 'configkey' have a prefix. The prefix for the very first server
62
+     * configuration is empty.
63
+     * Configkey Examples:
64
+     * Server 1: ldap_login_filter
65
+     * Server 2: s1_ldap_login_filter
66
+     * Server 3: s2_ldap_login_filter
67
+     *
68
+     * The prefix needs to be passed to the constructor of Connection class,
69
+     * except the default (first) server shall be connected to.
70
+     *
71
+     */
72
+    public function getServerConfigurationPrefixes($activeConfigurations = false) {
73
+        $referenceConfigkey = 'ldap_configuration_active';
74
+
75
+        $keys = $this->getServersConfig($referenceConfigkey);
76
+
77
+        $prefixes = [];
78
+        foreach ($keys as $key) {
79
+            if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') {
80
+                continue;
81
+            }
82
+
83
+            $len = strlen($key) - strlen($referenceConfigkey);
84
+            $prefixes[] = substr($key, 0, $len);
85
+        }
86
+
87
+        return $prefixes;
88
+    }
89
+
90
+    /**
91
+     *
92
+     * determines the host for every configured connection
93
+     * @return array an array with configprefix as keys
94
+     *
95
+     */
96
+    public function getServerConfigurationHosts() {
97
+        $referenceConfigkey = 'ldap_host';
98
+
99
+        $keys = $this->getServersConfig($referenceConfigkey);
100
+
101
+        $result = array();
102
+        foreach($keys as $key) {
103
+            $len = strlen($key) - strlen($referenceConfigkey);
104
+            $prefix = substr($key, 0, $len);
105
+            $result[$prefix] = $this->config->getAppValue('user_ldap', $key);
106
+        }
107
+
108
+        return $result;
109
+    }
110
+
111
+    /**
112
+     * return the next available configuration prefix
113
+     *
114
+     * @return string
115
+     */
116
+    public function getNextServerConfigurationPrefix() {
117
+        $serverConnections = $this->getServerConfigurationPrefixes();
118
+
119
+        if(count($serverConnections) === 0) {
120
+            return 's01';
121
+        }
122
+
123
+        sort($serverConnections);
124
+        $lastKey = array_pop($serverConnections);
125
+        $lastNumber = (int)str_replace('s', '', $lastKey);
126
+        return 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
127
+    }
128
+
129
+    private function getServersConfig($value) {
130
+        $regex = '/' . $value . '$/S';
131
+
132
+        $keys = $this->config->getAppKeys('user_ldap');
133
+        $result = [];
134
+        foreach ($keys as $key) {
135
+            if (preg_match($regex, $key) === 1) {
136
+                $result[] = $key;
137
+            }
138
+        }
139
+
140
+        return $result;
141
+    }
142
+
143
+    /**
144
+     * deletes a given saved LDAP/AD server configuration.
145
+     * @param string $prefix the configuration prefix of the config to delete
146
+     * @return bool true on success, false otherwise
147
+     */
148
+    public function deleteServerConfiguration($prefix) {
149
+        if(!in_array($prefix, self::getServerConfigurationPrefixes())) {
150
+            return false;
151
+        }
152
+
153
+        $saveOtherConfigurations = '';
154
+        if(empty($prefix)) {
155
+            $saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
156
+        }
157
+
158
+        $query = \OCP\DB::prepare('
159 159
 			DELETE
160 160
 			FROM `*PREFIX*appconfig`
161 161
 			WHERE `configkey` LIKE ?
@@ -163,149 +163,149 @@  discard block
 block discarded – undo
163 163
 				AND `appid` = \'user_ldap\'
164 164
 				AND `configkey` NOT IN (\'enabled\', \'installed_version\', \'types\', \'bgjUpdateGroupsLastRun\')
165 165
 		');
166
-		$delRows = $query->execute(array($prefix.'%'));
167
-
168
-		if($delRows === null) {
169
-			return false;
170
-		}
171
-
172
-		if($delRows === 0) {
173
-			return false;
174
-		}
175
-
176
-		return true;
177
-	}
178
-
179
-	/**
180
-	 * checks whether there is one or more disabled LDAP configurations
181
-	 * @throws \Exception
182
-	 * @return bool
183
-	 */
184
-	public function haveDisabledConfigurations() {
185
-		$all = $this->getServerConfigurationPrefixes(false);
186
-		$active = $this->getServerConfigurationPrefixes(true);
187
-
188
-		if(!is_array($all) || !is_array($active)) {
189
-			throw new \Exception('Unexpected Return Value');
190
-		}
191
-
192
-		return count($all) !== count($active) || count($all) === 0;
193
-	}
194
-
195
-	/**
196
-	 * extracts the domain from a given URL
197
-	 * @param string $url the URL
198
-	 * @return string|false domain as string on success, false otherwise
199
-	 */
200
-	public function getDomainFromURL($url) {
201
-		$uinfo = parse_url($url);
202
-		if(!is_array($uinfo)) {
203
-			return false;
204
-		}
205
-
206
-		$domain = false;
207
-		if(isset($uinfo['host'])) {
208
-			$domain = $uinfo['host'];
209
-		} else if(isset($uinfo['path'])) {
210
-			$domain = $uinfo['path'];
211
-		}
212
-
213
-		return $domain;
214
-	}
166
+        $delRows = $query->execute(array($prefix.'%'));
167
+
168
+        if($delRows === null) {
169
+            return false;
170
+        }
171
+
172
+        if($delRows === 0) {
173
+            return false;
174
+        }
175
+
176
+        return true;
177
+    }
178
+
179
+    /**
180
+     * checks whether there is one or more disabled LDAP configurations
181
+     * @throws \Exception
182
+     * @return bool
183
+     */
184
+    public function haveDisabledConfigurations() {
185
+        $all = $this->getServerConfigurationPrefixes(false);
186
+        $active = $this->getServerConfigurationPrefixes(true);
187
+
188
+        if(!is_array($all) || !is_array($active)) {
189
+            throw new \Exception('Unexpected Return Value');
190
+        }
191
+
192
+        return count($all) !== count($active) || count($all) === 0;
193
+    }
194
+
195
+    /**
196
+     * extracts the domain from a given URL
197
+     * @param string $url the URL
198
+     * @return string|false domain as string on success, false otherwise
199
+     */
200
+    public function getDomainFromURL($url) {
201
+        $uinfo = parse_url($url);
202
+        if(!is_array($uinfo)) {
203
+            return false;
204
+        }
205
+
206
+        $domain = false;
207
+        if(isset($uinfo['host'])) {
208
+            $domain = $uinfo['host'];
209
+        } else if(isset($uinfo['path'])) {
210
+            $domain = $uinfo['path'];
211
+        }
212
+
213
+        return $domain;
214
+    }
215 215
 	
216
-	/**
217
-	 *
218
-	 * Set the LDAPProvider in the config
219
-	 *
220
-	 */
221
-	public function setLDAPProvider() {
222
-		$current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
223
-		if(is_null($current)) {
224
-			\OC::$server->getConfig()->setSystemValue('ldapProviderFactory', LDAPProviderFactory::class);
225
-		}
226
-	}
216
+    /**
217
+     *
218
+     * Set the LDAPProvider in the config
219
+     *
220
+     */
221
+    public function setLDAPProvider() {
222
+        $current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
223
+        if(is_null($current)) {
224
+            \OC::$server->getConfig()->setSystemValue('ldapProviderFactory', LDAPProviderFactory::class);
225
+        }
226
+    }
227 227
 	
228
-	/**
229
-	 * sanitizes a DN received from the LDAP server
230
-	 * @param array $dn the DN in question
231
-	 * @return array|string the sanitized DN
232
-	 */
233
-	public function sanitizeDN($dn) {
234
-		//treating multiple base DNs
235
-		if(is_array($dn)) {
236
-			$result = array();
237
-			foreach($dn as $singleDN) {
238
-				$result[] = $this->sanitizeDN($singleDN);
239
-			}
240
-			return $result;
241
-		}
242
-
243
-		//OID sometimes gives back DNs with whitespace after the comma
244
-		// a la "uid=foo, cn=bar, dn=..." We need to tackle this!
245
-		$dn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
246
-
247
-		//make comparisons and everything work
248
-		$dn = mb_strtolower($dn, 'UTF-8');
249
-
250
-		//escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
251
-		//to use the DN in search filters, \ needs to be escaped to \5c additionally
252
-		//to use them in bases, we convert them back to simple backslashes in readAttribute()
253
-		$replacements = array(
254
-			'\,' => '\5c2C',
255
-			'\=' => '\5c3D',
256
-			'\+' => '\5c2B',
257
-			'\<' => '\5c3C',
258
-			'\>' => '\5c3E',
259
-			'\;' => '\5c3B',
260
-			'\"' => '\5c22',
261
-			'\#' => '\5c23',
262
-			'('  => '\28',
263
-			')'  => '\29',
264
-			'*'  => '\2A',
265
-		);
266
-		$dn = str_replace(array_keys($replacements), array_values($replacements), $dn);
267
-
268
-		return $dn;
269
-	}
228
+    /**
229
+     * sanitizes a DN received from the LDAP server
230
+     * @param array $dn the DN in question
231
+     * @return array|string the sanitized DN
232
+     */
233
+    public function sanitizeDN($dn) {
234
+        //treating multiple base DNs
235
+        if(is_array($dn)) {
236
+            $result = array();
237
+            foreach($dn as $singleDN) {
238
+                $result[] = $this->sanitizeDN($singleDN);
239
+            }
240
+            return $result;
241
+        }
242
+
243
+        //OID sometimes gives back DNs with whitespace after the comma
244
+        // a la "uid=foo, cn=bar, dn=..." We need to tackle this!
245
+        $dn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
246
+
247
+        //make comparisons and everything work
248
+        $dn = mb_strtolower($dn, 'UTF-8');
249
+
250
+        //escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
251
+        //to use the DN in search filters, \ needs to be escaped to \5c additionally
252
+        //to use them in bases, we convert them back to simple backslashes in readAttribute()
253
+        $replacements = array(
254
+            '\,' => '\5c2C',
255
+            '\=' => '\5c3D',
256
+            '\+' => '\5c2B',
257
+            '\<' => '\5c3C',
258
+            '\>' => '\5c3E',
259
+            '\;' => '\5c3B',
260
+            '\"' => '\5c22',
261
+            '\#' => '\5c23',
262
+            '('  => '\28',
263
+            ')'  => '\29',
264
+            '*'  => '\2A',
265
+        );
266
+        $dn = str_replace(array_keys($replacements), array_values($replacements), $dn);
267
+
268
+        return $dn;
269
+    }
270 270
 	
271
-	/**
272
-	 * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters
273
-	 * @param string $dn the DN
274
-	 * @return string
275
-	 */
276
-	public function DNasBaseParameter($dn) {
277
-		return str_ireplace('\\5c', '\\', $dn);
278
-	}
279
-
280
-	/**
281
-	 * listens to a hook thrown by server2server sharing and replaces the given
282
-	 * login name by a username, if it matches an LDAP user.
283
-	 *
284
-	 * @param array $param
285
-	 * @throws \Exception
286
-	 */
287
-	public static function loginName2UserName($param) {
288
-		if(!isset($param['uid'])) {
289
-			throw new \Exception('key uid is expected to be set in $param');
290
-		}
291
-
292
-		//ain't it ironic?
293
-		$helper = new Helper(\OC::$server->getConfig());
294
-
295
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
296
-		$ldapWrapper = new LDAP();
297
-		$ocConfig = \OC::$server->getConfig();
298
-		$notificationManager = \OC::$server->getNotificationManager();
299
-
300
-		$userSession = \OC::$server->getUserSession();
301
-		$userPluginManager = \OC::$server->query('LDAPUserPluginManager');
302
-
303
-		$userBackend  = new User_Proxy(
304
-			$configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager
305
-		);
306
-		$uid = $userBackend->loginName2UserName($param['uid'] );
307
-		if($uid !== false) {
308
-			$param['uid'] = $uid;
309
-		}
310
-	}
271
+    /**
272
+     * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters
273
+     * @param string $dn the DN
274
+     * @return string
275
+     */
276
+    public function DNasBaseParameter($dn) {
277
+        return str_ireplace('\\5c', '\\', $dn);
278
+    }
279
+
280
+    /**
281
+     * listens to a hook thrown by server2server sharing and replaces the given
282
+     * login name by a username, if it matches an LDAP user.
283
+     *
284
+     * @param array $param
285
+     * @throws \Exception
286
+     */
287
+    public static function loginName2UserName($param) {
288
+        if(!isset($param['uid'])) {
289
+            throw new \Exception('key uid is expected to be set in $param');
290
+        }
291
+
292
+        //ain't it ironic?
293
+        $helper = new Helper(\OC::$server->getConfig());
294
+
295
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
296
+        $ldapWrapper = new LDAP();
297
+        $ocConfig = \OC::$server->getConfig();
298
+        $notificationManager = \OC::$server->getNotificationManager();
299
+
300
+        $userSession = \OC::$server->getUserSession();
301
+        $userPluginManager = \OC::$server->query('LDAPUserPluginManager');
302
+
303
+        $userBackend  = new User_Proxy(
304
+            $configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager
305
+        );
306
+        $uid = $userBackend->loginName2UserName($param['uid'] );
307
+        if($uid !== false) {
308
+            $param['uid'] = $uid;
309
+        }
310
+    }
311 311
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
 		$keys = $this->getServersConfig($referenceConfigkey);
100 100
 
101 101
 		$result = array();
102
-		foreach($keys as $key) {
102
+		foreach ($keys as $key) {
103 103
 			$len = strlen($key) - strlen($referenceConfigkey);
104 104
 			$prefix = substr($key, 0, $len);
105 105
 			$result[$prefix] = $this->config->getAppValue('user_ldap', $key);
@@ -116,18 +116,18 @@  discard block
 block discarded – undo
116 116
 	public function getNextServerConfigurationPrefix() {
117 117
 		$serverConnections = $this->getServerConfigurationPrefixes();
118 118
 
119
-		if(count($serverConnections) === 0) {
119
+		if (count($serverConnections) === 0) {
120 120
 			return 's01';
121 121
 		}
122 122
 
123 123
 		sort($serverConnections);
124 124
 		$lastKey = array_pop($serverConnections);
125
-		$lastNumber = (int)str_replace('s', '', $lastKey);
126
-		return 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
125
+		$lastNumber = (int) str_replace('s', '', $lastKey);
126
+		return 's'.str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
127 127
 	}
128 128
 
129 129
 	private function getServersConfig($value) {
130
-		$regex = '/' . $value . '$/S';
130
+		$regex = '/'.$value.'$/S';
131 131
 
132 132
 		$keys = $this->config->getAppKeys('user_ldap');
133 133
 		$result = [];
@@ -146,12 +146,12 @@  discard block
 block discarded – undo
146 146
 	 * @return bool true on success, false otherwise
147 147
 	 */
148 148
 	public function deleteServerConfiguration($prefix) {
149
-		if(!in_array($prefix, self::getServerConfigurationPrefixes())) {
149
+		if (!in_array($prefix, self::getServerConfigurationPrefixes())) {
150 150
 			return false;
151 151
 		}
152 152
 
153 153
 		$saveOtherConfigurations = '';
154
-		if(empty($prefix)) {
154
+		if (empty($prefix)) {
155 155
 			$saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
156 156
 		}
157 157
 
@@ -165,11 +165,11 @@  discard block
 block discarded – undo
165 165
 		');
166 166
 		$delRows = $query->execute(array($prefix.'%'));
167 167
 
168
-		if($delRows === null) {
168
+		if ($delRows === null) {
169 169
 			return false;
170 170
 		}
171 171
 
172
-		if($delRows === 0) {
172
+		if ($delRows === 0) {
173 173
 			return false;
174 174
 		}
175 175
 
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
 		$all = $this->getServerConfigurationPrefixes(false);
186 186
 		$active = $this->getServerConfigurationPrefixes(true);
187 187
 
188
-		if(!is_array($all) || !is_array($active)) {
188
+		if (!is_array($all) || !is_array($active)) {
189 189
 			throw new \Exception('Unexpected Return Value');
190 190
 		}
191 191
 
@@ -199,14 +199,14 @@  discard block
 block discarded – undo
199 199
 	 */
200 200
 	public function getDomainFromURL($url) {
201 201
 		$uinfo = parse_url($url);
202
-		if(!is_array($uinfo)) {
202
+		if (!is_array($uinfo)) {
203 203
 			return false;
204 204
 		}
205 205
 
206 206
 		$domain = false;
207
-		if(isset($uinfo['host'])) {
207
+		if (isset($uinfo['host'])) {
208 208
 			$domain = $uinfo['host'];
209
-		} else if(isset($uinfo['path'])) {
209
+		} else if (isset($uinfo['path'])) {
210 210
 			$domain = $uinfo['path'];
211 211
 		}
212 212
 
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
 	 */
221 221
 	public function setLDAPProvider() {
222 222
 		$current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
223
-		if(is_null($current)) {
223
+		if (is_null($current)) {
224 224
 			\OC::$server->getConfig()->setSystemValue('ldapProviderFactory', LDAPProviderFactory::class);
225 225
 		}
226 226
 	}
@@ -232,9 +232,9 @@  discard block
 block discarded – undo
232 232
 	 */
233 233
 	public function sanitizeDN($dn) {
234 234
 		//treating multiple base DNs
235
-		if(is_array($dn)) {
235
+		if (is_array($dn)) {
236 236
 			$result = array();
237
-			foreach($dn as $singleDN) {
237
+			foreach ($dn as $singleDN) {
238 238
 				$result[] = $this->sanitizeDN($singleDN);
239 239
 			}
240 240
 			return $result;
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
 	 * @throws \Exception
286 286
 	 */
287 287
 	public static function loginName2UserName($param) {
288
-		if(!isset($param['uid'])) {
288
+		if (!isset($param['uid'])) {
289 289
 			throw new \Exception('key uid is expected to be set in $param');
290 290
 		}
291 291
 
@@ -300,11 +300,11 @@  discard block
 block discarded – undo
300 300
 		$userSession = \OC::$server->getUserSession();
301 301
 		$userPluginManager = \OC::$server->query('LDAPUserPluginManager');
302 302
 
303
-		$userBackend  = new User_Proxy(
303
+		$userBackend = new User_Proxy(
304 304
 			$configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager
305 305
 		);
306
-		$uid = $userBackend->loginName2UserName($param['uid'] );
307
-		if($uid !== false) {
306
+		$uid = $userBackend->loginName2UserName($param['uid']);
307
+		if ($uid !== false) {
308 308
 			$param['uid'] = $uid;
309 309
 		}
310 310
 	}
Please login to merge, or discard this patch.