You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Tags.php 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bernhard Reiter <ockham@raz.or.at>
  6. * @author derkostka <sebastian.kostka@gmail.com>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Julius Härtl <jus@bitgrid.net>
  9. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Robin McCorkell <robin@mccorkell.me.uk>
  13. * @author Roeland Jago Douma <roeland@famdouma.nl>
  14. * @author Thomas Müller <thomas.mueller@tmit.eu>
  15. * @author Thomas Tanghus <thomas@tanghus.net>
  16. * @author Vincent Petry <pvince81@owncloud.com>
  17. *
  18. * @license AGPL-3.0
  19. *
  20. * This code is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License, version 3,
  22. * as published by the Free Software Foundation.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License, version 3,
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>
  31. *
  32. */
  33. /**
  34. * Class for easily tagging objects by their id
  35. *
  36. * A tag can be e.g. 'Family', 'Work', 'Chore', 'Special Occation' or
  37. * anything else that is either parsed from a vobject or that the user chooses
  38. * to add.
  39. * Tag names are not case-sensitive, but will be saved with the case they
  40. * are entered in. If a user already has a tag 'family' for a type, and
  41. * tries to add a tag named 'Family' it will be silently ignored.
  42. */
  43. namespace OC;
  44. use OC\Tagging\Tag;
  45. use OC\Tagging\TagMapper;
  46. use OCP\DB\QueryBuilder\IQueryBuilder;
  47. use OCP\ILogger;
  48. class Tags implements \OCP\ITags {
  49. /**
  50. * Tags
  51. *
  52. * @var array
  53. */
  54. private $tags = array();
  55. /**
  56. * Used for storing objectid/categoryname pairs while rescanning.
  57. *
  58. * @var array
  59. */
  60. private static $relations = array();
  61. /**
  62. * Type
  63. *
  64. * @var string
  65. */
  66. private $type;
  67. /**
  68. * User
  69. *
  70. * @var string
  71. */
  72. private $user;
  73. /**
  74. * Are we including tags for shared items?
  75. *
  76. * @var bool
  77. */
  78. private $includeShared = false;
  79. /**
  80. * The current user, plus any owners of the items shared with the current
  81. * user, if $this->includeShared === true.
  82. *
  83. * @var array
  84. */
  85. private $owners = array();
  86. /**
  87. * The Mapper we're using to communicate our Tag objects to the database.
  88. *
  89. * @var TagMapper
  90. */
  91. private $mapper;
  92. /**
  93. * The sharing backend for objects of $this->type. Required if
  94. * $this->includeShared === true to determine ownership of items.
  95. *
  96. * @var \OCP\Share_Backend
  97. */
  98. private $backend;
  99. const TAG_TABLE = '*PREFIX*vcategory';
  100. const RELATION_TABLE = '*PREFIX*vcategory_to_object';
  101. const TAG_FAVORITE = '_$!<Favorite>!$_';
  102. /**
  103. * Constructor.
  104. *
  105. * @param TagMapper $mapper Instance of the TagMapper abstraction layer.
  106. * @param string $user The user whose data the object will operate on.
  107. * @param string $type The type of items for which tags will be loaded.
  108. * @param array $defaultTags Tags that should be created at construction.
  109. * @param boolean $includeShared Whether to include tags for items shared with this user by others.
  110. */
  111. public function __construct(TagMapper $mapper, $user, $type, $defaultTags = array(), $includeShared = false) {
  112. $this->mapper = $mapper;
  113. $this->user = $user;
  114. $this->type = $type;
  115. $this->includeShared = $includeShared;
  116. $this->owners = array($this->user);
  117. if ($this->includeShared) {
  118. $this->owners = array_merge($this->owners, \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true));
  119. $this->backend = \OC\Share\Share::getBackend($this->type);
  120. }
  121. $this->tags = $this->mapper->loadTags($this->owners, $this->type);
  122. if(count($defaultTags) > 0 && count($this->tags) === 0) {
  123. $this->addMultiple($defaultTags, true);
  124. }
  125. }
  126. /**
  127. * Check if any tags are saved for this type and user.
  128. *
  129. * @return boolean
  130. */
  131. public function isEmpty() {
  132. return count($this->tags) === 0;
  133. }
  134. /**
  135. * Returns an array mapping a given tag's properties to its values:
  136. * ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
  137. *
  138. * @param string $id The ID of the tag that is going to be mapped
  139. * @return array|false
  140. */
  141. public function getTag($id) {
  142. $key = $this->getTagById($id);
  143. if ($key !== false) {
  144. return $this->tagMap($this->tags[$key]);
  145. }
  146. return false;
  147. }
  148. /**
  149. * Get the tags for a specific user.
  150. *
  151. * This returns an array with maps containing each tag's properties:
  152. * [
  153. * ['id' => 0, 'name' = 'First tag', 'owner' = 'User', 'type' => 'tagtype'],
  154. * ['id' => 1, 'name' = 'Shared tag', 'owner' = 'Other user', 'type' => 'tagtype'],
  155. * ]
  156. *
  157. * @return array
  158. */
  159. public function getTags() {
  160. if(!count($this->tags)) {
  161. return array();
  162. }
  163. usort($this->tags, function($a, $b) {
  164. return strnatcasecmp($a->getName(), $b->getName());
  165. });
  166. $tagMap = array();
  167. foreach($this->tags as $tag) {
  168. if($tag->getName() !== self::TAG_FAVORITE) {
  169. $tagMap[] = $this->tagMap($tag);
  170. }
  171. }
  172. return $tagMap;
  173. }
  174. /**
  175. * Return only the tags owned by the given user, omitting any tags shared
  176. * by other users.
  177. *
  178. * @param string $user The user whose tags are to be checked.
  179. * @return array An array of Tag objects.
  180. */
  181. public function getTagsForUser($user) {
  182. return array_filter($this->tags,
  183. function($tag) use($user) {
  184. return $tag->getOwner() === $user;
  185. }
  186. );
  187. }
  188. /**
  189. * Get the list of tags for the given ids.
  190. *
  191. * @param array $objIds array of object ids
  192. * @return array|boolean of tags id as key to array of tag names
  193. * or false if an error occurred
  194. */
  195. public function getTagsForObjects(array $objIds) {
  196. $entries = array();
  197. try {
  198. $conn = \OC::$server->getDatabaseConnection();
  199. $chunks = array_chunk($objIds, 900, false);
  200. foreach ($chunks as $chunk) {
  201. $result = $conn->executeQuery(
  202. 'SELECT `category`, `categoryid`, `objid` ' .
  203. 'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
  204. 'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
  205. array($this->user, $this->type, $chunk),
  206. array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
  207. );
  208. while ($row = $result->fetch()) {
  209. $objId = (int)$row['objid'];
  210. if (!isset($entries[$objId])) {
  211. $entries[$objId] = array();
  212. }
  213. $entries[$objId][] = $row['category'];
  214. }
  215. if ($result === null) {
  216. \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
  217. return false;
  218. }
  219. }
  220. } catch(\Exception $e) {
  221. \OC::$server->getLogger()->logException($e, [
  222. 'message' => __METHOD__,
  223. 'level' => ILogger::ERROR,
  224. 'app' => 'core',
  225. ]);
  226. return false;
  227. }
  228. return $entries;
  229. }
  230. /**
  231. * Get the a list if items tagged with $tag.
  232. *
  233. * Throws an exception if the tag could not be found.
  234. *
  235. * @param string $tag Tag id or name.
  236. * @return array|false An array of object ids or false on error.
  237. * @throws \Exception
  238. */
  239. public function getIdsForTag($tag) {
  240. $result = null;
  241. $tagId = false;
  242. if(is_numeric($tag)) {
  243. $tagId = $tag;
  244. } elseif(is_string($tag)) {
  245. $tag = trim($tag);
  246. if($tag === '') {
  247. \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
  248. return false;
  249. }
  250. $tagId = $this->getTagId($tag);
  251. }
  252. if($tagId === false) {
  253. $l10n = \OC::$server->getL10N('core');
  254. throw new \Exception(
  255. $l10n->t('Could not find category "%s"', [$tag])
  256. );
  257. }
  258. $ids = array();
  259. $sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
  260. . '` WHERE `categoryid` = ?';
  261. try {
  262. $stmt = \OC_DB::prepare($sql);
  263. $result = $stmt->execute(array($tagId));
  264. if ($result === null) {
  265. \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
  266. return false;
  267. }
  268. } catch(\Exception $e) {
  269. \OC::$server->getLogger()->logException($e, [
  270. 'message' => __METHOD__,
  271. 'level' => ILogger::ERROR,
  272. 'app' => 'core',
  273. ]);
  274. return false;
  275. }
  276. if(!is_null($result)) {
  277. while( $row = $result->fetchRow()) {
  278. $id = (int)$row['objid'];
  279. if ($this->includeShared) {
  280. // We have to check if we are really allowed to access the
  281. // items that are tagged with $tag. To that end, we ask the
  282. // corresponding sharing backend if the item identified by $id
  283. // is owned by any of $this->owners.
  284. foreach ($this->owners as $owner) {
  285. if ($this->backend->isValidSource($id, $owner)) {
  286. $ids[] = $id;
  287. break;
  288. }
  289. }
  290. } else {
  291. $ids[] = $id;
  292. }
  293. }
  294. }
  295. return $ids;
  296. }
  297. /**
  298. * Checks whether a tag is saved for the given user,
  299. * disregarding the ones shared with him or her.
  300. *
  301. * @param string $name The tag name to check for.
  302. * @param string $user The user whose tags are to be checked.
  303. * @return bool
  304. */
  305. public function userHasTag($name, $user) {
  306. $key = $this->array_searchi($name, $this->getTagsForUser($user));
  307. return ($key !== false) ? $this->tags[$key]->getId() : false;
  308. }
  309. /**
  310. * Checks whether a tag is saved for or shared with the current user.
  311. *
  312. * @param string $name The tag name to check for.
  313. * @return bool
  314. */
  315. public function hasTag($name) {
  316. return $this->getTagId($name) !== false;
  317. }
  318. /**
  319. * Add a new tag.
  320. *
  321. * @param string $name A string with a name of the tag
  322. * @return false|int the id of the added tag or false on error.
  323. */
  324. public function add($name) {
  325. $name = trim($name);
  326. if($name === '') {
  327. \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
  328. return false;
  329. }
  330. if($this->userHasTag($name, $this->user)) {
  331. \OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', ILogger::DEBUG);
  332. return false;
  333. }
  334. try {
  335. $tag = new Tag($this->user, $this->type, $name);
  336. $tag = $this->mapper->insert($tag);
  337. $this->tags[] = $tag;
  338. } catch(\Exception $e) {
  339. \OC::$server->getLogger()->logException($e, [
  340. 'message' => __METHOD__,
  341. 'level' => ILogger::ERROR,
  342. 'app' => 'core',
  343. ]);
  344. return false;
  345. }
  346. \OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), ILogger::DEBUG);
  347. return $tag->getId();
  348. }
  349. /**
  350. * Rename tag.
  351. *
  352. * @param string|integer $from The name or ID of the existing tag
  353. * @param string $to The new name of the tag.
  354. * @return bool
  355. */
  356. public function rename($from, $to) {
  357. $from = trim($from);
  358. $to = trim($to);
  359. if($to === '' || $from === '') {
  360. \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
  361. return false;
  362. }
  363. if (is_numeric($from)) {
  364. $key = $this->getTagById($from);
  365. } else {
  366. $key = $this->getTagByName($from);
  367. }
  368. if($key === false) {
  369. \OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', ILogger::DEBUG);
  370. return false;
  371. }
  372. $tag = $this->tags[$key];
  373. if($this->userHasTag($to, $tag->getOwner())) {
  374. \OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', ILogger::DEBUG);
  375. return false;
  376. }
  377. try {
  378. $tag->setName($to);
  379. $this->tags[$key] = $this->mapper->update($tag);
  380. } catch(\Exception $e) {
  381. \OC::$server->getLogger()->logException($e, [
  382. 'message' => __METHOD__,
  383. 'level' => ILogger::ERROR,
  384. 'app' => 'core',
  385. ]);
  386. return false;
  387. }
  388. return true;
  389. }
  390. /**
  391. * Add a list of new tags.
  392. *
  393. * @param string[] $names A string with a name or an array of strings containing
  394. * the name(s) of the tag(s) to add.
  395. * @param bool $sync When true, save the tags
  396. * @param int|null $id int Optional object id to add to this|these tag(s)
  397. * @return bool Returns false on error.
  398. */
  399. public function addMultiple($names, $sync=false, $id = null) {
  400. if(!is_array($names)) {
  401. $names = array($names);
  402. }
  403. $names = array_map('trim', $names);
  404. array_filter($names);
  405. $newones = array();
  406. foreach($names as $name) {
  407. if(!$this->hasTag($name) && $name !== '') {
  408. $newones[] = new Tag($this->user, $this->type, $name);
  409. }
  410. if(!is_null($id) ) {
  411. // Insert $objectid, $categoryid pairs if not exist.
  412. self::$relations[] = array('objid' => $id, 'tag' => $name);
  413. }
  414. }
  415. $this->tags = array_merge($this->tags, $newones);
  416. if($sync === true) {
  417. $this->save();
  418. }
  419. return true;
  420. }
  421. /**
  422. * Save the list of tags and their object relations
  423. */
  424. protected function save() {
  425. if(is_array($this->tags)) {
  426. foreach($this->tags as $tag) {
  427. try {
  428. if (!$this->mapper->tagExists($tag)) {
  429. $this->mapper->insert($tag);
  430. }
  431. } catch(\Exception $e) {
  432. \OC::$server->getLogger()->logException($e, [
  433. 'message' => __METHOD__,
  434. 'level' => ILogger::ERROR,
  435. 'app' => 'core',
  436. ]);
  437. }
  438. }
  439. // reload tags to get the proper ids.
  440. $this->tags = $this->mapper->loadTags($this->owners, $this->type);
  441. \OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
  442. ILogger::DEBUG);
  443. // Loop through temporarily cached objectid/tagname pairs
  444. // and save relations.
  445. $tags = $this->tags;
  446. // For some reason this is needed or array_search(i) will return 0..?
  447. ksort($tags);
  448. $dbConnection = \OC::$server->getDatabaseConnection();
  449. foreach(self::$relations as $relation) {
  450. $tagId = $this->getTagId($relation['tag']);
  451. \OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, ILogger::DEBUG);
  452. if($tagId) {
  453. try {
  454. $dbConnection->insertIfNotExist(self::RELATION_TABLE,
  455. array(
  456. 'objid' => $relation['objid'],
  457. 'categoryid' => $tagId,
  458. 'type' => $this->type,
  459. ));
  460. } catch(\Exception $e) {
  461. \OC::$server->getLogger()->logException($e, [
  462. 'message' => __METHOD__,
  463. 'level' => ILogger::ERROR,
  464. 'app' => 'core',
  465. ]);
  466. }
  467. }
  468. }
  469. self::$relations = array(); // reset
  470. } else {
  471. \OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! '
  472. . print_r($this->tags, true), ILogger::ERROR);
  473. }
  474. }
  475. /**
  476. * Delete tags and tag/object relations for a user.
  477. *
  478. * For hooking up on post_deleteUser
  479. *
  480. * @param array $arguments
  481. */
  482. public static function post_deleteUser($arguments) {
  483. // Find all objectid/tagId pairs.
  484. $result = null;
  485. try {
  486. $stmt = \OC_DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
  487. . 'WHERE `uid` = ?');
  488. $result = $stmt->execute(array($arguments['uid']));
  489. if ($result === null) {
  490. \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
  491. }
  492. } catch(\Exception $e) {
  493. \OC::$server->getLogger()->logException($e, [
  494. 'message' => __METHOD__,
  495. 'level' => ILogger::ERROR,
  496. 'app' => 'core',
  497. ]);
  498. }
  499. if(!is_null($result)) {
  500. try {
  501. $stmt = \OC_DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
  502. . 'WHERE `categoryid` = ?');
  503. while( $row = $result->fetchRow()) {
  504. try {
  505. $stmt->execute(array($row['id']));
  506. } catch(\Exception $e) {
  507. \OC::$server->getLogger()->logException($e, [
  508. 'message' => __METHOD__,
  509. 'level' => ILogger::ERROR,
  510. 'app' => 'core',
  511. ]);
  512. }
  513. }
  514. } catch(\Exception $e) {
  515. \OC::$server->getLogger()->logException($e, [
  516. 'message' => __METHOD__,
  517. 'level' => ILogger::ERROR,
  518. 'app' => 'core',
  519. ]);
  520. }
  521. }
  522. try {
  523. $stmt = \OC_DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
  524. . 'WHERE `uid` = ?');
  525. $result = $stmt->execute(array($arguments['uid']));
  526. if ($result === null) {
  527. \OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
  528. }
  529. } catch(\Exception $e) {
  530. \OC::$server->getLogger()->logException($e, [
  531. 'message' => __METHOD__,
  532. 'level' => ILogger::ERROR,
  533. 'app' => 'core',
  534. ]);
  535. }
  536. }
  537. /**
  538. * Delete tag/object relations from the db
  539. *
  540. * @param array $ids The ids of the objects
  541. * @return boolean Returns false on error.
  542. */
  543. public function purgeObjects(array $ids) {
  544. if(count($ids) === 0) {
  545. // job done ;)
  546. return true;
  547. }
  548. $updates = $ids;
  549. try {
  550. $query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
  551. $query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
  552. $query .= 'AND `type`= ?';
  553. $updates[] = $this->type;
  554. $stmt = \OC_DB::prepare($query);
  555. $result = $stmt->execute($updates);
  556. if ($result === null) {
  557. \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
  558. return false;
  559. }
  560. } catch(\Exception $e) {
  561. \OC::$server->getLogger()->logException($e, [
  562. 'message' => __METHOD__,
  563. 'level' => ILogger::ERROR,
  564. 'app' => 'core',
  565. ]);
  566. return false;
  567. }
  568. return true;
  569. }
  570. /**
  571. * Get favorites for an object type
  572. *
  573. * @return array|false An array of object ids.
  574. */
  575. public function getFavorites() {
  576. if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
  577. return [];
  578. }
  579. try {
  580. return $this->getIdsForTag(self::TAG_FAVORITE);
  581. } catch(\Exception $e) {
  582. \OC::$server->getLogger()->logException($e, [
  583. 'message' => __METHOD__,
  584. 'level' => ILogger::ERROR,
  585. 'app' => 'core',
  586. ]);
  587. return array();
  588. }
  589. }
  590. /**
  591. * Add an object to favorites
  592. *
  593. * @param int $objid The id of the object
  594. * @return boolean
  595. */
  596. public function addToFavorites($objid) {
  597. if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
  598. $this->add(self::TAG_FAVORITE);
  599. }
  600. return $this->tagAs($objid, self::TAG_FAVORITE);
  601. }
  602. /**
  603. * Remove an object from favorites
  604. *
  605. * @param int $objid The id of the object
  606. * @return boolean
  607. */
  608. public function removeFromFavorites($objid) {
  609. return $this->unTag($objid, self::TAG_FAVORITE);
  610. }
  611. /**
  612. * Creates a tag/object relation.
  613. *
  614. * @param int $objid The id of the object
  615. * @param string $tag The id or name of the tag
  616. * @return boolean Returns false on error.
  617. */
  618. public function tagAs($objid, $tag) {
  619. if(is_string($tag) && !is_numeric($tag)) {
  620. $tag = trim($tag);
  621. if($tag === '') {
  622. \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
  623. return false;
  624. }
  625. if(!$this->hasTag($tag)) {
  626. $this->add($tag);
  627. }
  628. $tagId = $this->getTagId($tag);
  629. } else {
  630. $tagId = $tag;
  631. }
  632. try {
  633. \OC::$server->getDatabaseConnection()->insertIfNotExist(self::RELATION_TABLE,
  634. array(
  635. 'objid' => $objid,
  636. 'categoryid' => $tagId,
  637. 'type' => $this->type,
  638. ));
  639. } catch(\Exception $e) {
  640. \OC::$server->getLogger()->logException($e, [
  641. 'message' => __METHOD__,
  642. 'level' => ILogger::ERROR,
  643. 'app' => 'core',
  644. ]);
  645. return false;
  646. }
  647. return true;
  648. }
  649. /**
  650. * Delete single tag/object relation from the db
  651. *
  652. * @param int $objid The id of the object
  653. * @param string $tag The id or name of the tag
  654. * @return boolean
  655. */
  656. public function unTag($objid, $tag) {
  657. if(is_string($tag) && !is_numeric($tag)) {
  658. $tag = trim($tag);
  659. if($tag === '') {
  660. \OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', ILogger::DEBUG);
  661. return false;
  662. }
  663. $tagId = $this->getTagId($tag);
  664. } else {
  665. $tagId = $tag;
  666. }
  667. try {
  668. $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
  669. . 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
  670. $stmt = \OC_DB::prepare($sql);
  671. $stmt->execute(array($objid, $tagId, $this->type));
  672. } catch(\Exception $e) {
  673. \OC::$server->getLogger()->logException($e, [
  674. 'message' => __METHOD__,
  675. 'level' => ILogger::ERROR,
  676. 'app' => 'core',
  677. ]);
  678. return false;
  679. }
  680. return true;
  681. }
  682. /**
  683. * Delete tags from the database.
  684. *
  685. * @param string[]|integer[] $names An array of tags (names or IDs) to delete
  686. * @return bool Returns false on error
  687. */
  688. public function delete($names) {
  689. if(!is_array($names)) {
  690. $names = array($names);
  691. }
  692. $names = array_map('trim', $names);
  693. array_filter($names);
  694. \OCP\Util::writeLog('core', __METHOD__ . ', before: '
  695. . print_r($this->tags, true), ILogger::DEBUG);
  696. foreach($names as $name) {
  697. $id = null;
  698. if (is_numeric($name)) {
  699. $key = $this->getTagById($name);
  700. } else {
  701. $key = $this->getTagByName($name);
  702. }
  703. if ($key !== false) {
  704. $tag = $this->tags[$key];
  705. $id = $tag->getId();
  706. unset($this->tags[$key]);
  707. $this->mapper->delete($tag);
  708. } else {
  709. \OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
  710. . ': not found.', ILogger::ERROR);
  711. }
  712. if(!is_null($id) && $id !== false) {
  713. try {
  714. $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
  715. . 'WHERE `categoryid` = ?';
  716. $stmt = \OC_DB::prepare($sql);
  717. $result = $stmt->execute(array($id));
  718. if ($result === null) {
  719. \OCP\Util::writeLog('core',
  720. __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(),
  721. ILogger::ERROR);
  722. return false;
  723. }
  724. } catch(\Exception $e) {
  725. \OC::$server->getLogger()->logException($e, [
  726. 'message' => __METHOD__,
  727. 'level' => ILogger::ERROR,
  728. 'app' => 'core',
  729. ]);
  730. return false;
  731. }
  732. }
  733. }
  734. return true;
  735. }
  736. // case-insensitive array_search
  737. protected function array_searchi($needle, $haystack, $mem='getName') {
  738. if(!is_array($haystack)) {
  739. return false;
  740. }
  741. return array_search(strtolower($needle), array_map(
  742. function($tag) use($mem) {
  743. return strtolower(call_user_func(array($tag, $mem)));
  744. }, $haystack)
  745. );
  746. }
  747. /**
  748. * Get a tag's ID.
  749. *
  750. * @param string $name The tag name to look for.
  751. * @return string|bool The tag's id or false if no matching tag is found.
  752. */
  753. private function getTagId($name) {
  754. $key = $this->array_searchi($name, $this->tags);
  755. if ($key !== false) {
  756. return $this->tags[$key]->getId();
  757. }
  758. return false;
  759. }
  760. /**
  761. * Get a tag by its name.
  762. *
  763. * @param string $name The tag name.
  764. * @return integer|bool The tag object's offset within the $this->tags
  765. * array or false if it doesn't exist.
  766. */
  767. private function getTagByName($name) {
  768. return $this->array_searchi($name, $this->tags, 'getName');
  769. }
  770. /**
  771. * Get a tag by its ID.
  772. *
  773. * @param string $id The tag ID to look for.
  774. * @return integer|bool The tag object's offset within the $this->tags
  775. * array or false if it doesn't exist.
  776. */
  777. private function getTagById($id) {
  778. return $this->array_searchi($id, $this->tags, 'getId');
  779. }
  780. /**
  781. * Returns an array mapping a given tag's properties to its values:
  782. * ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
  783. *
  784. * @param Tag $tag The tag that is going to be mapped
  785. * @return array
  786. */
  787. private function tagMap(Tag $tag) {
  788. return array(
  789. 'id' => $tag->getId(),
  790. 'name' => $tag->getName(),
  791. 'owner' => $tag->getOwner(),
  792. 'type' => $tag->getType()
  793. );
  794. }
  795. }