TagDAO.php 13 KB

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