Welcome to mirror list, hosted at ThFree Co, Russian Federation.

tags.php « private « lib - github.com/nextcloud/server.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0b62caf2dd89102d280228878b9d9e3fc4bb7481 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
<?php
/**
* ownCloud
*
* @author Thomas Tanghus
* @copyright 2012-2013 Thomas Tanghus <thomas@tanghus.net>
* @copyright 2012 Bart Visscher bartv@thisnet.nl
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/

/**
 * Class for easily tagging objects by their id
 *
 * A tag can be e.g. 'Family', 'Work', 'Chore', 'Special Occation' or
 * anything else that is either parsed from a vobject or that the user chooses
 * to add.
 * Tag names are not case-sensitive, but will be saved with the case they
 * are entered in. If a user already has a tag 'family' for a type, and
 * tries to add a tag named 'Family' it will be silently ignored.
 */

namespace OC;

class Tags implements \OCP\ITags {

	/**
	 * Tags
	 *
	 * @var array
	 */
	private $tags = array();

	/**
	 * Used for storing objectid/categoryname pairs while rescanning.
	 *
	 * @var array
	 */
	private static $relations = array();

	/**
	 * Type
	 *
	 * @var string
	 */
	private $type = null;

	/**
	 * User
	 *
	 * @var string
	 */
	private $user = null;

	const TAG_TABLE = '*PREFIX*vcategory';
	const RELATION_TABLE = '*PREFIX*vcategory_to_object';

	const TAG_FAVORITE = '_$!<Favorite>!$_';

	/**
	* Constructor.
	*
	* @param string $user The user whos data the object will operate on.
	* @param string $type
	*/
	public function __construct($user, $type, $defaultTags = array()) {
		$this->user = $user;
		$this->type = $type;
		$this->loadTags($defaultTags);
	}

	/**
	* Load tags from db.
	*
	*/
	protected function loadTags($defaultTags=array()) {
		$this->tags = array();
		$result = null;
		$sql = 'SELECT `id`, `category` FROM `' . self::TAG_TABLE . '` '
			. 'WHERE `uid` = ? AND `type` = ? ORDER BY `category`';
		try {
			$stmt = \OCP\DB::prepare($sql);
			$result = $stmt->execute(array($this->user, $this->type));
			if (\OCP\DB::isError($result)) {
				\OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR);
			}
		} catch(\Exception $e) {
			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
				\OCP\Util::ERROR);
		}

		if(!is_null($result)) {
			while( $row = $result->fetchRow()) {
				$this->tags[$row['id']] = $row['category'];
			}
		}

		if(count($defaultTags) > 0 && count($this->tags) === 0) {
			$this->addMultiple($defaultTags, true);
		}
		\OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
			\OCP\Util::DEBUG);

	}

	/**
	* Check if any tags are saved for this type and user.
	*
	* @return boolean.
	*/
	public function isEmpty() {
		return count($this->tags) === 0;
	}

	/**
	* Get the tags for a specific user.
	*
	* This returns an array with id/name maps:
	* [
	* 	['id' => 0, 'name' = 'First tag'],
	* 	['id' => 1, 'name' = 'Second tag'],
	* ]
	*
	* @return array
	*/
	public function getTags() {
		if(!count($this->tags)) {
			return array();
		}

		$tags = array_values($this->tags);
		uasort($tags, 'strnatcasecmp');
		$tagMap = array();

		foreach($tags as $tag) {
			if($tag !== self::TAG_FAVORITE) {
				$tagMap[] = array(
					'id' => $this->array_searchi($tag, $this->tags),
					'name' => $tag
					);
			}
		}
		return $tagMap;

	}

	/**
	* Get the a list if items tagged with $tag.
	*
	* Throws an exception if the tag could not be found.
	*
	* @param string $tag Tag id or name.
	* @return array An array of object ids or false on error.
	*/
	public function getIdsForTag($tag) {
		$result = null;
		if(is_numeric($tag)) {
			$tagId = $tag;
		} elseif(is_string($tag)) {
			$tag = trim($tag);
			if($tag === '') {
				\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
				return false;
			}
			$tagId = $this->array_searchi($tag, $this->tags);
		}

		if($tagId === false) {
			$l10n = \OC_L10N::get('core');
			throw new \Exception(
				$l10n->t('Could not find category "%s"', $tag)
			);
		}

		$ids = array();
		$sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
			. '` WHERE `categoryid` = ?';

		try {
			$stmt = \OCP\DB::prepare($sql);
			$result = $stmt->execute(array($tagId));
			if (\OCP\DB::isError($result)) {
				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR);
				return false;
			}
		} catch(\Exception $e) {
			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
				\OCP\Util::ERROR);
			return false;
		}

		if(!is_null($result)) {
			while( $row = $result->fetchRow()) {
				$ids[] = (int)$row['objid'];
			}
		}

		return $ids;
	}

	/**
	* Checks whether a tag is already saved.
	*
	* @param string $name The name to check for.
	* @return bool
	*/
	public function hasTag($name) {
		return $this->in_arrayi($name, $this->tags);
	}

	/**
	* Add a new tag.
	*
	* @param string $name A string with a name of the tag
	* @return false|string the id of the added tag or false on error.
	*/
	public function add($name) {
		$name = trim($name);

		if($name === '') {
			\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
			return false;
		}
		if($this->hasTag($name)) {
			\OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', \OCP\Util::DEBUG);
			return false;
		}
		try {
			$result = \OCP\DB::insertIfNotExist(
				self::TAG_TABLE,
				array(
					'uid' => $this->user,
					'type' => $this->type,
					'category' => $name,
				)
			);
			if (\OCP\DB::isError($result)) {
				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR);
				return false;
			} elseif((int)$result === 0) {
				\OCP\Util::writeLog('core', __METHOD__.', Tag already exists: ' . $name, \OCP\Util::DEBUG);
				return false;
			}
		} catch(\Exception $e) {
			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
				\OCP\Util::ERROR);
			return false;
		}
		$id = \OCP\DB::insertid(self::TAG_TABLE);
		\OCP\Util::writeLog('core', __METHOD__.', id: ' . $id, \OCP\Util::DEBUG);
		$this->tags[$id] = $name;
		return $id;
	}

	/**
	* Rename tag.
	*
	* @param string $from The name of the existing tag
	* @param string $to The new name of the tag.
	* @return bool
	*/
	public function rename($from, $to) {
		$from = trim($from);
		$to = trim($to);

		if($to === '' || $from === '') {
			\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
			return false;
		}

		$id = $this->array_searchi($from, $this->tags);
		if($id === false) {
			\OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', \OCP\Util::DEBUG);
			return false;
		}

		$sql = 'UPDATE `' . self::TAG_TABLE . '` SET `category` = ? '
			. 'WHERE `uid` = ? AND `type` = ? AND `id` = ?';
		try {
			$stmt = \OCP\DB::prepare($sql);
			$result = $stmt->execute(array($to, $this->user, $this->type, $id));
			if (\OCP\DB::isError($result)) {
				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR);
				return false;
			}
		} catch(\Exception $e) {
			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
				\OCP\Util::ERROR);
			return false;
		}
		$this->tags[$id] = $to;
		return true;
	}

	/**
	* Add a list of new tags.
	*
	* @param string[] $names A string with a name or an array of strings containing
	* the name(s) of the to add.
	* @param bool $sync When true, save the tags
	* @param int|null $id int Optional object id to add to this|these tag(s)
	* @return bool Returns false on error.
	*/
	public function addMultiple($names, $sync=false, $id = null) {
		if(!is_array($names)) {
			$names = array($names);
		}
		$names = array_map('trim', $names);
		array_filter($names);

		$newones = array();
		foreach($names as $name) {
			if(($this->in_arrayi(
				$name, $this->tags) == false) && $name !== '') {
				$newones[] = $name;
			}
			if(!is_null($id) ) {
				// Insert $objectid, $categoryid  pairs if not exist.
				self::$relations[] = array('objid' => $id, 'tag' => $name);
			}
		}
		$this->tags = array_merge($this->tags, $newones);
		if($sync === true) {
			$this->save();
		}

		return true;
	}

	/**
	 * Save the list of tags and their object relations
	 */
	protected function save() {
		if(is_array($this->tags)) {
			foreach($this->tags as $tag) {
				try {
					\OCP\DB::insertIfNotExist(self::TAG_TABLE,
						array(
							'uid' => $this->user,
							'type' => $this->type,
							'category' => $tag,
						));
				} catch(\Exception $e) {
					\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
						\OCP\Util::ERROR);
				}
			}
			// reload tags to get the proper ids.
			$this->loadTags();
			// Loop through temporarily cached objectid/tagname pairs
			// and save relations.
			$tags = $this->tags;
			// For some reason this is needed or array_search(i) will return 0..?
			ksort($tags);
			foreach(self::$relations as $relation) {
				$tagId = $this->array_searchi($relation['tag'], $tags);
				\OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, \OCP\Util::DEBUG);
				if($tagId) {
					try {
						\OCP\DB::insertIfNotExist(self::RELATION_TABLE,
							array(
								'objid' => $relation['objid'],
								'categoryid' => $tagId,
								'type' => $this->type,
								));
					} catch(\Exception $e) {
						\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
							\OCP\Util::ERROR);
					}
				}
			}
			self::$relations = array(); // reset
		} else {
			\OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! '
				. print_r($this->tags, true), \OCP\Util::ERROR);
		}
	}

	/**
	* Delete tags and tag/object relations for a user.
	*
	* For hooking up on post_deleteUser
	*
	* @param array $arguments
	*/
	public static function post_deleteUser($arguments) {
		// Find all objectid/tagId pairs.
		$result = null;
		try {
			$stmt = \OCP\DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
				. 'WHERE `uid` = ?');
			$result = $stmt->execute(array($arguments['uid']));
			if (\OCP\DB::isError($result)) {
				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR);
			}
		} catch(\Exception $e) {
			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
				\OCP\Util::ERROR);
		}

		if(!is_null($result)) {
			try {
				$stmt = \OCP\DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
					. 'WHERE `categoryid` = ?');
				while( $row = $result->fetchRow()) {
					try {
						$stmt->execute(array($row['id']));
					} catch(\Exception $e) {
						\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
							\OCP\Util::ERROR);
					}
				}
			} catch(\Exception $e) {
				\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
					\OCP\Util::ERROR);
			}
		}
		try {
			$stmt = \OCP\DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
				. 'WHERE `uid` = ?');
			$result = $stmt->execute(array($arguments['uid']));
			if (\OCP\DB::isError($result)) {
				\OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR);
			}
		} catch(\Exception $e) {
			\OCP\Util::writeLog('core', __METHOD__ . ', exception: '
				. $e->getMessage(), \OCP\Util::ERROR);
		}
	}

	/**
	* Delete tag/object relations from the db
	*
	* @param array $ids The ids of the objects
	* @return boolean Returns false on error.
	*/
	public function purgeObjects(array $ids) {
		if(count($ids) === 0) {
			// job done ;)
			return true;
		}
		$updates = $ids;
		try {
			$query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
			$query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
			$query .= 'AND `type`= ?';
			$updates[] = $this->type;
			$stmt = \OCP\DB::prepare($query);
			$result = $stmt->execute($updates);
			if (\OCP\DB::isError($result)) {
				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR);
				return false;
			}
		} catch(\Exception $e) {
			\OCP\Util::writeLog('core', __METHOD__.', exception: ' . $e->getMessage(),
				\OCP\Util::ERROR);
			return false;
		}
		return true;
	}

	/**
	* Get favorites for an object type
	*
	* @return array An array of object ids.
	*/
	public function getFavorites() {
		try {
			return $this->getIdsForTag(self::TAG_FAVORITE);
		} catch(\Exception $e) {
			\OCP\Util::writeLog('core', __METHOD__.', exception: ' . $e->getMessage(),
				\OCP\Util::DEBUG);
			return array();
		}
	}

	/**
	* Add an object to favorites
	*
	* @param int $objid The id of the object
	* @return boolean
	*/
	public function addToFavorites($objid) {
		if(!$this->hasTag(self::TAG_FAVORITE)) {
			$this->add(self::TAG_FAVORITE);
		}
		return $this->tagAs($objid, self::TAG_FAVORITE);
	}

	/**
	* Remove an object from favorites
	*
	* @param int $objid The id of the object
	* @return boolean
	*/
	public function removeFromFavorites($objid) {
		return $this->unTag($objid, self::TAG_FAVORITE);
	}

	/**
	* Creates a tag/object relation.
	*
	* @param int $objid The id of the object
	* @param string $tag The id or name of the tag
	* @return boolean Returns false on error.
	*/
	public function tagAs($objid, $tag) {
		if(is_string($tag) && !is_numeric($tag)) {
			$tag = trim($tag);
			if($tag === '') {
				\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
				return false;
			}
			if(!$this->hasTag($tag)) {
				$this->add($tag);
			}
			$tagId =  $this->array_searchi($tag, $this->tags);
		} else {
			$tagId = $tag;
		}
		try {
			\OCP\DB::insertIfNotExist(self::RELATION_TABLE,
				array(
					'objid' => $objid,
					'categoryid' => $tagId,
					'type' => $this->type,
				));
		} catch(\Exception $e) {
			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
				\OCP\Util::ERROR);
			return false;
		}
		return true;
	}

	/**
	* Delete single tag/object relation from the db
	*
	* @param int $objid The id of the object
	* @param string $tag The id or name of the tag
	* @return boolean
	*/
	public function unTag($objid, $tag) {
		if(is_string($tag) && !is_numeric($tag)) {
			$tag = trim($tag);
			if($tag === '') {
				\OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', \OCP\Util::DEBUG);
				return false;
			}
			$tagId =  $this->array_searchi($tag, $this->tags);
		} else {
			$tagId = $tag;
		}

		try {
			$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
					. 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
			$stmt = \OCP\DB::prepare($sql);
			$stmt->execute(array($objid, $tagId, $this->type));
		} catch(\Exception $e) {
			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
				\OCP\Util::ERROR);
			return false;
		}
		return true;
	}

	/**
	* Delete tags from the
	*
	* @param string[] $names An array of tags to delete
	* @return bool Returns false on error
	*/
	public function delete($names) {
		if(!is_array($names)) {
			$names = array($names);
		}

		$names = array_map('trim', $names);
		array_filter($names);

		\OCP\Util::writeLog('core', __METHOD__ . ', before: '
			. print_r($this->tags, true), \OCP\Util::DEBUG);
		foreach($names as $name) {
			$id = null;

			if($this->hasTag($name)) {
				$id = $this->array_searchi($name, $this->tags);
				unset($this->tags[$id]);
			}
			try {
				$stmt = \OCP\DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` WHERE '
					. '`uid` = ? AND `type` = ? AND `category` = ?');
				$result = $stmt->execute(array($this->user, $this->type, $name));
				if (\OCP\DB::isError($result)) {
					\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR);
				}
			} catch(\Exception $e) {
				\OCP\Util::writeLog('core', __METHOD__ . ', exception: '
					. $e->getMessage(), \OCP\Util::ERROR);
				return false;
			}
			if(!is_null($id) && $id !== false) {
				try {
					$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
							. 'WHERE `categoryid` = ?';
					$stmt = \OCP\DB::prepare($sql);
					$result = $stmt->execute(array($id));
					if (\OCP\DB::isError($result)) {
						\OCP\Util::writeLog('core',
							__METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage($result),
							\OCP\Util::ERROR);
						return false;
					}
				} catch(\Exception $e) {
					\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
						\OCP\Util::ERROR);
					return false;
				}
			}
		}
		return true;
	}

	// case-insensitive in_array
	private function in_arrayi($needle, $haystack) {
		if(!is_array($haystack)) {
			return false;
		}
		return in_array(strtolower($needle), array_map('strtolower', $haystack));
	}

	// case-insensitive array_search
	private function array_searchi($needle, $haystack) {
		if(!is_array($haystack)) {
			return false;
		}
		return array_search(strtolower($needle), array_map('strtolower', $haystack));
	}
}