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.

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