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

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