TagDAO.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. <?php
  2. class FreshRSS_TagDAO extends Minz_ModelPdo {
  3. public function sqlIgnore(): string {
  4. return 'IGNORE';
  5. }
  6. public function createTagTable(): bool {
  7. $ok = false;
  8. $hadTransaction = $this->pdo->inTransaction();
  9. if ($hadTransaction) {
  10. $this->pdo->commit();
  11. }
  12. try {
  13. require(APP_PATH . '/SQL/install.sql.' . $this->pdo->dbType() . '.php');
  14. Minz_Log::warning('SQL ALTER GUID case sensitivity…');
  15. $databaseDAO = FreshRSS_Factory::createDatabaseDAO();
  16. $databaseDAO->ensureCaseInsensitiveGuids();
  17. Minz_Log::warning('SQL CREATE TABLE tag…');
  18. $ok = $this->pdo->exec($GLOBALS['SQL_CREATE_TABLE_TAGS']) !== false;
  19. } catch (Exception $e) {
  20. Minz_Log::error('FreshRSS_EntryDAO::createTagTable error: ' . $e->getMessage());
  21. }
  22. if ($hadTransaction) {
  23. $this->pdo->beginTransaction();
  24. }
  25. return $ok;
  26. }
  27. /** @param array<string> $errorInfo */
  28. protected function autoUpdateDb(array $errorInfo): bool {
  29. if (isset($errorInfo[0])) {
  30. if ($errorInfo[0] === FreshRSS_DatabaseDAO::ER_BAD_TABLE_ERROR || $errorInfo[0] === FreshRSS_DatabaseDAOPGSQL::UNDEFINED_TABLE) {
  31. if (stripos($errorInfo[2], 'tag') !== false) {
  32. return $this->createTagTable(); //v1.12.0
  33. }
  34. }
  35. }
  36. return false;
  37. }
  38. /**
  39. * @param array{'id'?:int,'name':string,'attributes'?:array<string,mixed>} $valuesTmp
  40. * @return int|false
  41. */
  42. public function addTag(array $valuesTmp) {
  43. // TRIM() gives a text type hint to PostgreSQL
  44. // No category of the same name
  45. $sql = <<<'SQL'
  46. INSERT INTO `_tag`(name, attributes)
  47. SELECT * FROM (SELECT TRIM(?) as name, TRIM(?) as attributes) t2
  48. WHERE NOT EXISTS (SELECT 1 FROM `_category` WHERE name = TRIM(?))
  49. SQL;
  50. $stm = $this->pdo->prepare($sql);
  51. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, 63, 'UTF-8');
  52. if (!isset($valuesTmp['attributes'])) {
  53. $valuesTmp['attributes'] = [];
  54. }
  55. $values = array(
  56. $valuesTmp['name'],
  57. is_string($valuesTmp['attributes']) ? $valuesTmp['attributes'] : json_encode($valuesTmp['attributes'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
  58. $valuesTmp['name'],
  59. );
  60. if ($stm !== false && $stm->execute($values) && $stm->rowCount() > 0) {
  61. $tagId = $this->pdo->lastInsertId('`_tag_id_seq`');
  62. return $tagId === false ? false : (int)$tagId;
  63. } else {
  64. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  65. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  66. return false;
  67. }
  68. }
  69. /** @return int|false */
  70. public function addTagObject(FreshRSS_Tag $tag) {
  71. $tag0 = $this->searchByName($tag->name());
  72. if (!$tag0) {
  73. $values = array(
  74. 'name' => $tag->name(),
  75. 'attributes' => $tag->attributes(),
  76. );
  77. return $this->addTag($values);
  78. }
  79. return $tag->id();
  80. }
  81. /** @return int|false */
  82. public function updateTagName(int $id, string $name) {
  83. // No category of the same name
  84. $sql = <<<'SQL'
  85. UPDATE `_tag` SET name=? WHERE id=?
  86. AND NOT EXISTS (SELECT 1 FROM `_category` WHERE name = ?)
  87. SQL;
  88. $name = mb_strcut(trim($name), 0, 63, 'UTF-8');
  89. $stm = $this->pdo->prepare($sql);
  90. if ($stm !== false &&
  91. $stm->bindValue(':id', $id, PDO::PARAM_INT) &&
  92. $stm->bindValue(':name', $name, PDO::PARAM_STR) &&
  93. $stm->execute()) {
  94. return $stm->rowCount();
  95. } else {
  96. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  97. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  98. return false;
  99. }
  100. }
  101. /**
  102. * @param array<string,mixed> $attributes
  103. * @return int|false
  104. */
  105. public function updateTagAttributes(int $id, array $attributes) {
  106. $sql = 'UPDATE `_tag` SET attributes=:attributes WHERE id=:id';
  107. $stm = $this->pdo->prepare($sql);
  108. if ($stm !== false &&
  109. $stm->bindValue(':id', $id, PDO::PARAM_INT) &&
  110. $stm->bindValue(':attributes', json_encode($attributes, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), PDO::PARAM_STR) &&
  111. $stm->execute()) {
  112. return $stm->rowCount();
  113. }
  114. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  115. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  116. return false;
  117. }
  118. /**
  119. * @param mixed $value
  120. * @return int|false
  121. */
  122. public function updateTagAttribute(FreshRSS_Tag $tag, string $key, $value) {
  123. $tag->_attributes($key, $value);
  124. return $this->updateTagAttributes($tag->id(), $tag->attributes());
  125. }
  126. /**
  127. * @return int|false
  128. */
  129. public function deleteTag(int $id) {
  130. if ($id <= 0) {
  131. return false;
  132. }
  133. $sql = 'DELETE FROM `_tag` WHERE id=?';
  134. $stm = $this->pdo->prepare($sql);
  135. $values = array($id);
  136. if ($stm !== false && $stm->execute($values)) {
  137. return $stm->rowCount();
  138. } else {
  139. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  140. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  141. return false;
  142. }
  143. }
  144. /** @return Traversable<array{'id':int,'name':string,'attributes'?:array<string,mixed>}> */
  145. public function selectAll(): Traversable {
  146. $sql = 'SELECT id, name, attributes FROM `_tag`';
  147. $stm = $this->pdo->query($sql);
  148. if ($stm === false) {
  149. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($this->pdo->errorInfo()));
  150. return;
  151. }
  152. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  153. yield $row;
  154. }
  155. }
  156. /** @return Traversable<array{'id_tag':int,'id_entry':string}> */
  157. public function selectEntryTag(): Traversable {
  158. $sql = 'SELECT id_tag, id_entry FROM `_entrytag`';
  159. $stm = $this->pdo->query($sql);
  160. if ($stm === false) {
  161. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($this->pdo->errorInfo()));
  162. return;
  163. }
  164. while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
  165. yield $row;
  166. }
  167. }
  168. /** @return int|false */
  169. public function updateEntryTag(int $oldTagId, int $newTagId) {
  170. $sql = <<<'SQL'
  171. DELETE FROM `_entrytag` WHERE EXISTS (
  172. SELECT 1 FROM `_entrytag` AS e
  173. WHERE e.id_entry = `_entrytag`.id_entry AND e.id_tag = ? AND `_entrytag`.id_tag = ?)
  174. SQL;
  175. $stm = $this->pdo->prepare($sql);
  176. if ($stm === false || !$stm->execute([$newTagId, $oldTagId])) {
  177. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  178. Minz_Log::error('SQL error ' . __METHOD__ . ' A ' . json_encode($info));
  179. return false;
  180. }
  181. $sql = 'UPDATE `_entrytag` SET id_tag = ? WHERE id_tag = ?';
  182. $stm = $this->pdo->prepare($sql);
  183. if ($stm !== false && $stm->execute([$newTagId, $oldTagId])) {
  184. return $stm->rowCount();
  185. }
  186. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  187. Minz_Log::error('SQL error ' . __METHOD__ . ' B ' . json_encode($info));
  188. return false;
  189. }
  190. public function searchById(int $id): ?FreshRSS_Tag {
  191. $res = $this->fetchAssoc('SELECT * FROM `_tag` WHERE id=:id', [':id' => $id]);
  192. /** @var array<array{'id':int,'name':string,'attributes'?:string}>|null $res */
  193. return $res === null ? null : self::daoToTag($res)[0] ?? null;
  194. }
  195. public function searchByName(string $name): ?FreshRSS_Tag {
  196. $res = $this->fetchAssoc('SELECT * FROM `_tag` WHERE name=:name', [':name' => $name]);
  197. /** @var array<array{'id':int,'name':string,'attributes'?:string}>|null $res */
  198. return $res === null ? null : self::daoToTag($res)[0] ?? null;
  199. }
  200. /** @return array<FreshRSS_Tag>|false */
  201. public function listTags(bool $precounts = false) {
  202. if ($precounts) {
  203. $sql = <<<'SQL'
  204. SELECT t.id, t.name, count(e.id) AS unreads
  205. FROM `_tag` t
  206. LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id
  207. LEFT OUTER JOIN `_entry` e ON et.id_entry = e.id AND e.is_read = 0
  208. GROUP BY t.id
  209. ORDER BY t.name
  210. SQL;
  211. } else {
  212. $sql = 'SELECT * FROM `_tag` ORDER BY name';
  213. }
  214. $stm = $this->pdo->query($sql);
  215. if ($stm !== false) {
  216. $res = $stm->fetchAll(PDO::FETCH_ASSOC) ?: [];
  217. return self::daoToTag($res);
  218. } else {
  219. $info = $this->pdo->errorInfo();
  220. if ($this->autoUpdateDb($info)) {
  221. return $this->listTags($precounts);
  222. }
  223. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  224. return false;
  225. }
  226. }
  227. /** @return array<string,string> */
  228. public function listTagsNewestItemUsec(?int $id_tag = null): array {
  229. $sql = <<<'SQL'
  230. SELECT t.id AS id_tag, MAX(e.id) AS newest_item_us
  231. FROM `_tag` t
  232. LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id
  233. LEFT OUTER JOIN `_entry` e ON et.id_entry = e.id
  234. SQL;
  235. if ($id_tag === null) {
  236. $sql .= ' GROUP BY t.id';
  237. } else {
  238. $sql .= ' WHERE t.id=' . intval($id_tag);
  239. }
  240. $res = $this->fetchAssoc($sql);
  241. if ($res == null) {
  242. return [];
  243. }
  244. $newestItemUsec = [];
  245. foreach ($res as $line) {
  246. $newestItemUsec['t_' . $line['id_tag']] = (string)($line['newest_item_us']);
  247. }
  248. return $newestItemUsec;
  249. }
  250. public function count(): int {
  251. $sql = 'SELECT COUNT(*) AS count FROM `_tag`';
  252. $stm = $this->pdo->query($sql);
  253. if ($stm !== false) {
  254. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  255. return (int)$res[0]['count'];
  256. }
  257. $info = $this->pdo->errorInfo();
  258. if ($this->autoUpdateDb($info)) {
  259. return $this->count();
  260. }
  261. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  262. return -1;
  263. }
  264. public function countEntries(int $id): int {
  265. $sql = 'SELECT COUNT(*) AS count FROM `_entrytag` WHERE id_tag=:id_tag';
  266. $res = $this->fetchAssoc($sql, [':id_tag' => $id]);
  267. if ($res == null || !isset($res[0]['count'])) {
  268. return -1;
  269. }
  270. return (int)$res[0]['count'];
  271. }
  272. public function countNotRead(?int $id = null): int {
  273. $sql = <<<'SQL'
  274. SELECT COUNT(*) AS count FROM `_entrytag` et
  275. INNER JOIN `_entry` e ON et.id_entry=e.id
  276. WHERE e.is_read=0
  277. SQL;
  278. $values = [];
  279. if (null !== $id) {
  280. $sql .= ' AND et.id_tag=:id_tag';
  281. $values[':id_tag'] = $id;
  282. }
  283. $res = $this->fetchAssoc($sql, $values);
  284. if ($res == null || !isset($res[0]['count'])) {
  285. return -1;
  286. }
  287. return (int)$res[0]['count'];
  288. }
  289. public function tagEntry(int $id_tag, string $id_entry, bool $checked = true): bool {
  290. if ($checked) {
  291. $sql = 'INSERT ' . $this->sqlIgnore() . ' INTO `_entrytag`(id_tag, id_entry) VALUES(?, ?)';
  292. } else {
  293. $sql = 'DELETE FROM `_entrytag` WHERE id_tag=? AND id_entry=?';
  294. }
  295. $stm = $this->pdo->prepare($sql);
  296. $values = array($id_tag, $id_entry);
  297. if ($stm !== false && $stm->execute($values)) {
  298. return true;
  299. }
  300. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  301. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  302. return false;
  303. }
  304. /**
  305. * @return array<int,array{'id':int,'name':string,'id_entry':string,'checked':bool}>|false
  306. */
  307. public function getTagsForEntry(string $id_entry) {
  308. $sql = <<<'SQL'
  309. SELECT t.id, t.name, et.id_entry IS NOT NULL as checked
  310. FROM `_tag` t
  311. LEFT OUTER JOIN `_entrytag` et ON et.id_tag = t.id AND et.id_entry=?
  312. ORDER BY t.name
  313. SQL;
  314. $stm = $this->pdo->prepare($sql);
  315. $values = array($id_entry);
  316. if ($stm !== false && $stm->execute($values)) {
  317. $lines = $stm->fetchAll(PDO::FETCH_ASSOC);
  318. for ($i = count($lines) - 1; $i >= 0; $i--) {
  319. $lines[$i]['id'] = intval($lines[$i]['id']);
  320. $lines[$i]['checked'] = !empty($lines[$i]['checked']);
  321. }
  322. return $lines;
  323. }
  324. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  325. if ($this->autoUpdateDb($info)) {
  326. return $this->getTagsForEntry($id_entry);
  327. }
  328. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  329. return false;
  330. }
  331. /**
  332. * @param array<FreshRSS_Entry|numeric-string|array<string,string>> $entries
  333. * @return array<array{'id_entry':string,'id_tag':int,'name':string}>|false
  334. */
  335. public function getTagsForEntries(array $entries) {
  336. $sql = <<<'SQL'
  337. SELECT et.id_entry, et.id_tag, t.name
  338. FROM `_tag` t
  339. INNER JOIN `_entrytag` et ON et.id_tag = t.id
  340. SQL;
  341. $values = array();
  342. if (is_array($entries) && count($entries) > 0) {
  343. if (count($entries) > FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER) {
  344. // Split a query with too many variables parameters
  345. $idsChunks = array_chunk($entries, FreshRSS_DatabaseDAO::MAX_VARIABLE_NUMBER);
  346. foreach ($idsChunks as $idsChunk) {
  347. $values += $this->getTagsForEntries($idsChunk);
  348. }
  349. return $values;
  350. }
  351. $sql .= ' AND et.id_entry IN (' . str_repeat('?,', count($entries) - 1). '?)';
  352. if (is_array($entries[0])) {
  353. foreach ($entries as $entry) {
  354. if (!empty($entry['id'])) {
  355. $values[] = $entry['id'];
  356. }
  357. }
  358. } elseif (is_object($entries[0])) {
  359. /** @var array<FreshRSS_Entry> $entries */
  360. foreach ($entries as $entry) {
  361. $values[] = $entry->id();
  362. }
  363. } else {
  364. foreach ($entries as $entry) {
  365. $values[] = $entry;
  366. }
  367. }
  368. }
  369. $stm = $this->pdo->prepare($sql);
  370. if ($stm !== false && $stm->execute($values)) {
  371. return $stm->fetchAll(PDO::FETCH_ASSOC);
  372. }
  373. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  374. if ($this->autoUpdateDb($info)) {
  375. return $this->getTagsForEntries($entries);
  376. }
  377. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  378. return false;
  379. }
  380. /**
  381. * For API
  382. * @param array<FreshRSS_Entry|numeric-string> $entries
  383. * @return array<string,array<string>>
  384. */
  385. public function getEntryIdsTagNames(array $entries): array {
  386. $result = array();
  387. foreach ($this->getTagsForEntries($entries) ?: [] as $line) {
  388. $entryId = 'e_' . $line['id_entry'];
  389. $tagName = $line['name'];
  390. if (empty($result[$entryId])) {
  391. $result[$entryId] = array();
  392. }
  393. $result[$entryId][] = $tagName;
  394. }
  395. return $result;
  396. }
  397. /**
  398. * @param iterable<array{'id':int,'name':string,'attributes'?:string}> $listDAO
  399. * @return array<FreshRSS_Tag>
  400. */
  401. private static function daoToTag(iterable $listDAO): array {
  402. $list = [];
  403. foreach ($listDAO as $dao) {
  404. if (empty($dao['id']) || empty($dao['name'])) {
  405. continue;
  406. }
  407. $tag = new FreshRSS_Tag($dao['name']);
  408. $tag->_id($dao['id']);
  409. if (!empty($dao['attributes'])) {
  410. $tag->_attributes('', $dao['attributes']);
  411. }
  412. if (isset($dao['unreads'])) {
  413. $tag->_nbUnread($dao['unreads']);
  414. }
  415. $list[] = $tag;
  416. }
  417. return $list;
  418. }
  419. }