EntryDAO.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. <?php
  2. class FreshRSS_EntryDAO extends Minz_ModelPdo implements FreshRSS_Searchable {
  3. public function isCompressed() {
  4. return parent::$sharedDbType === 'mysql';
  5. }
  6. public function hasNativeHex() {
  7. return parent::$sharedDbType !== 'sqlite';
  8. }
  9. public function sqlHexDecode($x) {
  10. return 'unhex(' . $x . ')';
  11. }
  12. public function sqlHexEncode($x) {
  13. return 'hex(' . $x . ')';
  14. }
  15. protected function addColumn($name) {
  16. Minz_Log::warning('FreshRSS_EntryDAO::addColumn: ' . $name);
  17. $hasTransaction = false;
  18. try {
  19. $stm = null;
  20. if ($name === 'lastSeen') { //v1.1.1
  21. if (!$this->bd->inTransaction()) {
  22. $this->bd->beginTransaction();
  23. $hasTransaction = true;
  24. }
  25. $stm = $this->bd->prepare('ALTER TABLE `' . $this->prefix . 'entry` ADD COLUMN `lastSeen` INT(11) DEFAULT 0');
  26. if ($stm && $stm->execute()) {
  27. $stm = $this->bd->prepare('CREATE INDEX entry_lastSeen_index ON `' . $this->prefix . 'entry`(`lastSeen`);'); //"IF NOT EXISTS" does not exist in MySQL 5.7
  28. if ($stm && $stm->execute()) {
  29. if ($hasTransaction) {
  30. $this->bd->commit();
  31. }
  32. return true;
  33. }
  34. }
  35. if ($hasTransaction) {
  36. $this->bd->rollBack();
  37. }
  38. } elseif ($name === 'hash') { //v1.1.1
  39. $stm = $this->bd->prepare('ALTER TABLE `' . $this->prefix . 'entry` ADD COLUMN hash BINARY(16)');
  40. return $stm && $stm->execute();
  41. }
  42. } catch (Exception $e) {
  43. Minz_Log::error('FreshRSS_EntryDAO::addColumn error: ' . $e->getMessage());
  44. if ($hasTransaction) {
  45. $this->bd->rollBack();
  46. }
  47. }
  48. return false;
  49. }
  50. private $triedUpdateToUtf8mb4 = false;
  51. protected function updateToUtf8mb4() {
  52. if ($this->triedUpdateToUtf8mb4) {
  53. return false;
  54. }
  55. $this->triedUpdateToUtf8mb4 = true;
  56. $db = FreshRSS_Context::$system_conf->db;
  57. if ($db['type'] === 'mysql') {
  58. include_once(APP_PATH . '/SQL/install.sql.mysql.php');
  59. if (defined('SQL_UPDATE_UTF8MB4')) {
  60. Minz_Log::warning('Updating MySQL to UTF8MB4...');
  61. $hadTransaction = $this->bd->inTransaction();
  62. if ($hadTransaction) {
  63. $this->bd->commit();
  64. }
  65. $ok = false;
  66. try {
  67. $sql = sprintf(SQL_UPDATE_UTF8MB4, $this->prefix, $db['base']);
  68. $stm = $this->bd->prepare($sql);
  69. $ok = $stm->execute();
  70. } catch (Exception $e) {
  71. Minz_Log::error('FreshRSS_EntryDAO::updateToUtf8mb4 error: ' . $e->getMessage());
  72. }
  73. if ($hadTransaction) {
  74. $this->bd->beginTransaction();
  75. //NB: Transaction not starting. Why? (tested on PHP 7.0.8-0ubuntu and MySQL 5.7.13-0ubuntu)
  76. }
  77. return $ok;
  78. }
  79. }
  80. return false;
  81. }
  82. protected function createEntryTempTable() {
  83. $ok = false;
  84. $hadTransaction = $this->bd->inTransaction();
  85. if ($hadTransaction) {
  86. $this->bd->commit();
  87. }
  88. try {
  89. $db = FreshRSS_Context::$system_conf->db;
  90. require_once(APP_PATH . '/SQL/install.sql.' . $db['type'] . '.php');
  91. Minz_Log::warning('SQL CREATE TABLE entrytmp...');
  92. if (defined('SQL_CREATE_TABLE_ENTRYTMP')) {
  93. $sql = sprintf(SQL_CREATE_TABLE_ENTRYTMP, $this->prefix);
  94. $stm = $this->bd->prepare($sql);
  95. $ok = $stm && $stm->execute();
  96. } else {
  97. global $SQL_CREATE_TABLE_ENTRYTMP;
  98. $ok = !empty($SQL_CREATE_TABLE_ENTRYTMP);
  99. foreach ($SQL_CREATE_TABLE_ENTRYTMP as $instruction) {
  100. $sql = sprintf($instruction, $this->prefix);
  101. $stm = $this->bd->prepare($sql);
  102. $ok &= $stm && $stm->execute();
  103. }
  104. }
  105. } catch (Exception $e) {
  106. Minz_Log::error('FreshRSS_EntryDAO::createEntryTempTable error: ' . $e->getMessage());
  107. }
  108. if ($hadTransaction) {
  109. $this->bd->beginTransaction();
  110. }
  111. return $ok;
  112. }
  113. protected function autoUpdateDb($errorInfo) {
  114. if (isset($errorInfo[0])) {
  115. if ($errorInfo[0] === '42S22') { //ER_BAD_FIELD_ERROR
  116. //autoAddColumn
  117. foreach (array('lastSeen', 'hash') as $column) {
  118. if (stripos($errorInfo[2], $column) !== false) {
  119. return $this->addColumn($column);
  120. }
  121. }
  122. } elseif ($errorInfo[0] === '42S02' && stripos($errorInfo[2], 'entrytmp') !== false) { //ER_BAD_TABLE_ERROR
  123. return $this->createEntryTempTable(); //v1.7
  124. }
  125. }
  126. if (isset($errorInfo[1])) {
  127. if ($errorInfo[1] == '1366') { //ER_TRUNCATED_WRONG_VALUE_FOR_FIELD
  128. return $this->updateToUtf8mb4();
  129. }
  130. }
  131. return false;
  132. }
  133. private $addEntryPrepared = null;
  134. public function addEntry($valuesTmp) {
  135. if ($this->addEntryPrepared == null) {
  136. $sql = 'INSERT INTO `' . $this->prefix . 'entrytmp` (id, guid, title, author, '
  137. . ($this->isCompressed() ? 'content_bin' : 'content')
  138. . ', link, date, `lastSeen`, hash, is_read, is_favorite, id_feed, tags) '
  139. . 'VALUES(:id, :guid, :title, :author, '
  140. . ($this->isCompressed() ? 'COMPRESS(:content)' : ':content')
  141. . ', :link, :date, :last_seen, '
  142. . $this->sqlHexDecode(':hash')
  143. . ', :is_read, :is_favorite, :id_feed, :tags)';
  144. $this->addEntryPrepared = $this->bd->prepare($sql);
  145. }
  146. if ($this->addEntryPrepared) {
  147. $this->addEntryPrepared->bindParam(':id', $valuesTmp['id']);
  148. $valuesTmp['guid'] = substr($valuesTmp['guid'], 0, 760);
  149. $valuesTmp['guid'] = safe_ascii($valuesTmp['guid']);
  150. $this->addEntryPrepared->bindParam(':guid', $valuesTmp['guid']);
  151. $valuesTmp['title'] = substr($valuesTmp['title'], 0, 255);
  152. $this->addEntryPrepared->bindParam(':title', $valuesTmp['title']);
  153. $valuesTmp['author'] = substr($valuesTmp['author'], 0, 255);
  154. $this->addEntryPrepared->bindParam(':author', $valuesTmp['author']);
  155. $this->addEntryPrepared->bindParam(':content', $valuesTmp['content']);
  156. $valuesTmp['link'] = substr($valuesTmp['link'], 0, 1023);
  157. $valuesTmp['link'] = safe_ascii($valuesTmp['link']);
  158. $this->addEntryPrepared->bindParam(':link', $valuesTmp['link']);
  159. $this->addEntryPrepared->bindParam(':date', $valuesTmp['date'], PDO::PARAM_INT);
  160. $valuesTmp['lastSeen'] = time();
  161. $this->addEntryPrepared->bindParam(':last_seen', $valuesTmp['lastSeen'], PDO::PARAM_INT);
  162. $valuesTmp['is_read'] = $valuesTmp['is_read'] ? 1 : 0;
  163. $this->addEntryPrepared->bindParam(':is_read', $valuesTmp['is_read'], PDO::PARAM_INT);
  164. $valuesTmp['is_favorite'] = $valuesTmp['is_favorite'] ? 1 : 0;
  165. $this->addEntryPrepared->bindParam(':is_favorite', $valuesTmp['is_favorite'], PDO::PARAM_INT);
  166. $this->addEntryPrepared->bindParam(':id_feed', $valuesTmp['id_feed'], PDO::PARAM_INT);
  167. $valuesTmp['tags'] = substr($valuesTmp['tags'], 0, 1023);
  168. $this->addEntryPrepared->bindParam(':tags', $valuesTmp['tags']);
  169. if ($this->hasNativeHex()) {
  170. $this->addEntryPrepared->bindParam(':hash', $valuesTmp['hash']);
  171. } else {
  172. $valuesTmp['hashBin'] = pack('H*', $valuesTmp['hash']); //hex2bin() is PHP5.4+
  173. $this->addEntryPrepared->bindParam(':hash', $valuesTmp['hashBin']);
  174. }
  175. }
  176. if ($this->addEntryPrepared && $this->addEntryPrepared->execute()) {
  177. return true;
  178. } else {
  179. $info = $this->addEntryPrepared == null ? array(0 => '', 1 => '', 2 => 'syntax error') : $this->addEntryPrepared->errorInfo();
  180. if ($this->autoUpdateDb($info)) {
  181. $this->addEntryPrepared = null;
  182. return $this->addEntry($valuesTmp);
  183. } elseif ((int)((int)$info[0] / 1000) !== 23) { //Filter out "SQLSTATE Class code 23: Constraint Violation" because of expected duplicate entries
  184. Minz_Log::error('SQL error addEntry: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  185. . ' while adding entry in feed ' . $valuesTmp['id_feed'] . ' with title: ' . $valuesTmp['title']);
  186. }
  187. return false;
  188. }
  189. }
  190. public function commitNewEntries() {
  191. $sql = 'SET @rank=(SELECT MAX(id) - COUNT(*) FROM `' . $this->prefix . 'entrytmp`); ' . //MySQL-specific
  192. 'INSERT IGNORE INTO `' . $this->prefix . 'entry` (id, guid, title, author, content_bin, link, date, `lastSeen`, hash, is_read, is_favorite, id_feed, tags) ' .
  193. 'SELECT @rank:=@rank+1 AS id, guid, title, author, content_bin, link, date, `lastSeen`, hash, is_read, is_favorite, id_feed, tags FROM `' . $this->prefix . 'entrytmp` ORDER BY date; ' .
  194. 'DELETE FROM `' . $this->prefix . 'entrytmp` WHERE id <= @rank;';
  195. $hadTransaction = $this->bd->inTransaction();
  196. if (!$hadTransaction) {
  197. $this->bd->beginTransaction();
  198. }
  199. $result = $this->bd->exec($sql) !== false;
  200. if (!$hadTransaction) {
  201. $this->bd->commit();
  202. }
  203. return $result;
  204. }
  205. private $updateEntryPrepared = null;
  206. public function updateEntry($valuesTmp) {
  207. if (!isset($valuesTmp['is_read'])) {
  208. $valuesTmp['is_read'] = null;
  209. }
  210. if ($this->updateEntryPrepared === null) {
  211. $sql = 'UPDATE `' . $this->prefix . 'entry` '
  212. . 'SET title=:title, author=:author, '
  213. . ($this->isCompressed() ? 'content_bin=COMPRESS(:content)' : 'content=:content')
  214. . ', link=:link, date=:date, `lastSeen`=:last_seen, '
  215. . 'hash=' . $this->sqlHexDecode(':hash')
  216. . ', ' . ($valuesTmp['is_read'] === null ? '' : 'is_read=:is_read, ')
  217. . 'tags=:tags '
  218. . 'WHERE id_feed=:id_feed AND guid=:guid';
  219. $this->updateEntryPrepared = $this->bd->prepare($sql);
  220. }
  221. $valuesTmp['guid'] = substr($valuesTmp['guid'], 0, 760);
  222. $this->updateEntryPrepared->bindParam(':guid', $valuesTmp['guid']);
  223. $valuesTmp['title'] = substr($valuesTmp['title'], 0, 255);
  224. $this->updateEntryPrepared->bindParam(':title', $valuesTmp['title']);
  225. $valuesTmp['author'] = substr($valuesTmp['author'], 0, 255);
  226. $this->updateEntryPrepared->bindParam(':author', $valuesTmp['author']);
  227. $this->updateEntryPrepared->bindParam(':content', $valuesTmp['content']);
  228. $valuesTmp['link'] = substr($valuesTmp['link'], 0, 1023);
  229. $valuesTmp['link'] = safe_ascii($valuesTmp['link']);
  230. $this->updateEntryPrepared->bindParam(':link', $valuesTmp['link']);
  231. $this->updateEntryPrepared->bindParam(':date', $valuesTmp['date'], PDO::PARAM_INT);
  232. $valuesTmp['lastSeen'] = time();
  233. $this->updateEntryPrepared->bindParam(':last_seen', $valuesTmp['lastSeen'], PDO::PARAM_INT);
  234. if ($valuesTmp['is_read'] !== null) {
  235. $this->updateEntryPrepared->bindValue(':is_read', $valuesTmp['is_read'] ? 1 : 0, PDO::PARAM_INT);
  236. }
  237. $this->updateEntryPrepared->bindParam(':id_feed', $valuesTmp['id_feed'], PDO::PARAM_INT);
  238. $valuesTmp['tags'] = substr($valuesTmp['tags'], 0, 1023);
  239. $this->updateEntryPrepared->bindParam(':tags', $valuesTmp['tags']);
  240. if ($this->hasNativeHex()) {
  241. $this->updateEntryPrepared->bindParam(':hash', $valuesTmp['hash']);
  242. } else {
  243. $valuesTmp['hashBin'] = pack('H*', $valuesTmp['hash']); //hex2bin() is PHP5.4+
  244. $this->updateEntryPrepared->bindParam(':hash', $valuesTmp['hashBin']);
  245. }
  246. if ($this->updateEntryPrepared && $this->updateEntryPrepared->execute()) {
  247. return true;
  248. } else {
  249. $info = $this->updateEntryPrepared == null ? array(0 => '', 1 => '', 2 => 'syntax error') : $this->updateEntryPrepared->errorInfo();
  250. if ($this->autoUpdateDb($info)) {
  251. return $this->updateEntry($valuesTmp);
  252. }
  253. Minz_Log::error('SQL error updateEntry: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  254. . ' while updating entry with GUID ' . $valuesTmp['guid'] . ' in feed ' . $valuesTmp['id_feed']);
  255. return false;
  256. }
  257. }
  258. /**
  259. * Toggle favorite marker on one or more article
  260. *
  261. * @todo simplify the query by removing the str_repeat. I am pretty sure
  262. * there is an other way to do that.
  263. *
  264. * @param integer|array $ids
  265. * @param boolean $is_favorite
  266. * @return false|integer
  267. */
  268. public function markFavorite($ids, $is_favorite = true) {
  269. if (!is_array($ids)) {
  270. $ids = array($ids);
  271. }
  272. if (count($ids) < 1) {
  273. return 0;
  274. }
  275. FreshRSS_UserDAO::touch();
  276. $sql = 'UPDATE `' . $this->prefix . 'entry` '
  277. . 'SET is_favorite=? '
  278. . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1). '?)';
  279. $values = array($is_favorite ? 1 : 0);
  280. $values = array_merge($values, $ids);
  281. $stm = $this->bd->prepare($sql);
  282. if ($stm && $stm->execute($values)) {
  283. return $stm->rowCount();
  284. } else {
  285. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  286. Minz_Log::error('SQL error markFavorite: ' . $info[2]);
  287. return false;
  288. }
  289. }
  290. /**
  291. * Update the unread article cache held on every feed details.
  292. * Depending on the parameters, it updates the cache on one feed, on all
  293. * feeds from one category or on all feeds.
  294. *
  295. * @todo It can use the query builder refactoring to build that query
  296. *
  297. * @param false|integer $catId category ID
  298. * @param false|integer $feedId feed ID
  299. * @return boolean
  300. */
  301. protected function updateCacheUnreads($catId = false, $feedId = false) {
  302. $sql = 'UPDATE `' . $this->prefix . 'feed` f '
  303. . 'LEFT OUTER JOIN ('
  304. . 'SELECT e.id_feed, '
  305. . 'COUNT(*) AS nbUnreads '
  306. . 'FROM `' . $this->prefix . 'entry` e '
  307. . 'WHERE e.is_read=0 '
  308. . 'GROUP BY e.id_feed'
  309. . ') x ON x.id_feed=f.id '
  310. . 'SET f.`cache_nbUnreads`=COALESCE(x.nbUnreads, 0)';
  311. $hasWhere = false;
  312. $values = array();
  313. if ($feedId !== false) {
  314. $sql .= $hasWhere ? ' AND' : ' WHERE';
  315. $hasWhere = true;
  316. $sql .= ' f.id=?';
  317. $values[] = $id;
  318. }
  319. if ($catId !== false) {
  320. $sql .= $hasWhere ? ' AND' : ' WHERE';
  321. $hasWhere = true;
  322. $sql .= ' f.category=?';
  323. $values[] = $catId;
  324. }
  325. $stm = $this->bd->prepare($sql);
  326. if ($stm && $stm->execute($values)) {
  327. return true;
  328. } else {
  329. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  330. Minz_Log::error('SQL error updateCacheUnreads: ' . $info[2]);
  331. return false;
  332. }
  333. }
  334. /**
  335. * Toggle the read marker on one or more article.
  336. * Then the cache is updated.
  337. *
  338. * @todo change the way the query is build because it seems there is
  339. * unnecessary code in here. For instance, the part with the str_repeat.
  340. * @todo remove code duplication. It seems the code is basically the
  341. * same if it is an array or not.
  342. *
  343. * @param integer|array $ids
  344. * @param boolean $is_read
  345. * @return integer affected rows
  346. */
  347. public function markRead($ids, $is_read = true) {
  348. FreshRSS_UserDAO::touch();
  349. if (is_array($ids)) { //Many IDs at once (used by API)
  350. if (count($ids) < 6) { //Speed heuristics
  351. $affected = 0;
  352. foreach ($ids as $id) {
  353. $affected += $this->markRead($id, $is_read);
  354. }
  355. return $affected;
  356. }
  357. $sql = 'UPDATE `' . $this->prefix . 'entry` '
  358. . 'SET is_read=? '
  359. . 'WHERE id IN (' . str_repeat('?,', count($ids) - 1). '?)';
  360. $values = array($is_read ? 1 : 0);
  361. $values = array_merge($values, $ids);
  362. $stm = $this->bd->prepare($sql);
  363. if (!($stm && $stm->execute($values))) {
  364. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  365. Minz_Log::error('SQL error markRead: ' . $info[2]);
  366. return false;
  367. }
  368. $affected = $stm->rowCount();
  369. if (($affected > 0) && (!$this->updateCacheUnreads(false, false))) {
  370. return false;
  371. }
  372. return $affected;
  373. } else {
  374. $sql = 'UPDATE `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id '
  375. . 'SET e.is_read=?,'
  376. . 'f.`cache_nbUnreads`=f.`cache_nbUnreads`' . ($is_read ? '-' : '+') . '1 '
  377. . 'WHERE e.id=? AND e.is_read=?';
  378. $values = array($is_read ? 1 : 0, $ids, $is_read ? 0 : 1);
  379. $stm = $this->bd->prepare($sql);
  380. if ($stm && $stm->execute($values)) {
  381. return $stm->rowCount();
  382. } else {
  383. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  384. Minz_Log::error('SQL error markRead: ' . $info[2]);
  385. return false;
  386. }
  387. }
  388. }
  389. /**
  390. * Mark all entries as read depending on parameters.
  391. * If $onlyFavorites is true, it is used when the user mark as read in
  392. * the favorite pseudo-category.
  393. * If $priorityMin is greater than 0, it is used when the user mark as
  394. * read in the main feed pseudo-category.
  395. * Then the cache is updated.
  396. *
  397. * If $idMax equals 0, a deprecated debug message is logged
  398. *
  399. * @todo refactor this method along with markReadCat and markReadFeed
  400. * since they are all doing the same thing. I think we need to build a
  401. * tool to generate the query instead of having queries all over the
  402. * place. It will be reused also for the filtering making every thing
  403. * separated.
  404. *
  405. * @param integer $idMax fail safe article ID
  406. * @param boolean $onlyFavorites
  407. * @param integer $priorityMin
  408. * @return integer affected rows
  409. */
  410. public function markReadEntries($idMax = 0, $onlyFavorites = false, $priorityMin = 0, $filter = null, $state = 0) {
  411. FreshRSS_UserDAO::touch();
  412. if ($idMax == 0) {
  413. $idMax = time() . '000000';
  414. Minz_Log::debug('Calling markReadEntries(0) is deprecated!');
  415. }
  416. $sql = 'UPDATE `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id '
  417. . 'SET e.is_read=1 '
  418. . 'WHERE e.is_read=0 AND e.id <= ?';
  419. if ($onlyFavorites) {
  420. $sql .= ' AND e.is_favorite=1';
  421. } elseif ($priorityMin >= 0) {
  422. $sql .= ' AND f.priority > ' . intval($priorityMin);
  423. }
  424. $values = array($idMax);
  425. list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filter, $state);
  426. $stm = $this->bd->prepare($sql . $search);
  427. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  428. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  429. Minz_Log::error('SQL error markReadEntries: ' . $info[2]);
  430. return false;
  431. }
  432. $affected = $stm->rowCount();
  433. if (($affected > 0) && (!$this->updateCacheUnreads(false, false))) {
  434. return false;
  435. }
  436. return $affected;
  437. }
  438. /**
  439. * Mark all the articles in a category as read.
  440. * There is a fail safe to prevent to mark as read articles that are
  441. * loaded during the mark as read action. Then the cache is updated.
  442. *
  443. * If $idMax equals 0, a deprecated debug message is logged
  444. *
  445. * @param integer $id category ID
  446. * @param integer $idMax fail safe article ID
  447. * @return integer affected rows
  448. */
  449. public function markReadCat($id, $idMax = 0, $filter = null, $state = 0) {
  450. FreshRSS_UserDAO::touch();
  451. if ($idMax == 0) {
  452. $idMax = time() . '000000';
  453. Minz_Log::debug('Calling markReadCat(0) is deprecated!');
  454. }
  455. $sql = 'UPDATE `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id '
  456. . 'SET e.is_read=1 '
  457. . 'WHERE f.category=? AND e.is_read=0 AND e.id <= ?';
  458. $values = array($id, $idMax);
  459. list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filter, $state);
  460. $stm = $this->bd->prepare($sql . $search);
  461. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  462. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  463. Minz_Log::error('SQL error markReadCat: ' . $info[2]);
  464. return false;
  465. }
  466. $affected = $stm->rowCount();
  467. if (($affected > 0) && (!$this->updateCacheUnreads($id, false))) {
  468. return false;
  469. }
  470. return $affected;
  471. }
  472. /**
  473. * Mark all the articles in a feed as read.
  474. * There is a fail safe to prevent to mark as read articles that are
  475. * loaded during the mark as read action. Then the cache is updated.
  476. *
  477. * If $idMax equals 0, a deprecated debug message is logged
  478. *
  479. * @param integer $id_feed feed ID
  480. * @param integer $idMax fail safe article ID
  481. * @return integer affected rows
  482. */
  483. public function markReadFeed($id_feed, $idMax = 0, $filter = null, $state = 0) {
  484. FreshRSS_UserDAO::touch();
  485. if ($idMax == 0) {
  486. $idMax = time() . '000000';
  487. Minz_Log::debug('Calling markReadFeed(0) is deprecated!');
  488. }
  489. $this->bd->beginTransaction();
  490. $sql = 'UPDATE `' . $this->prefix . 'entry` '
  491. . 'SET is_read=1 '
  492. . 'WHERE id_feed=? AND is_read=0 AND id <= ?';
  493. $values = array($id_feed, $idMax);
  494. list($searchValues, $search) = $this->sqlListEntriesWhere('', $filter, $state);
  495. $stm = $this->bd->prepare($sql . $search);
  496. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  497. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  498. Minz_Log::error('SQL error markReadFeed: ' . $info[2] . ' with SQL: ' . $sql . $search);
  499. $this->bd->rollBack();
  500. return false;
  501. }
  502. $affected = $stm->rowCount();
  503. if ($affected > 0) {
  504. $sql = 'UPDATE `' . $this->prefix . 'feed` '
  505. . 'SET `cache_nbUnreads`=`cache_nbUnreads`-' . $affected
  506. . ' WHERE id=?';
  507. $values = array($id_feed);
  508. $stm = $this->bd->prepare($sql);
  509. if (!($stm && $stm->execute($values))) {
  510. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  511. Minz_Log::error('SQL error markReadFeed cache: ' . $info[2]);
  512. $this->bd->rollBack();
  513. return false;
  514. }
  515. }
  516. $this->bd->commit();
  517. return $affected;
  518. }
  519. public function searchByGuid($id_feed, $guid) {
  520. // un guid est unique pour un flux donné
  521. $sql = 'SELECT id, guid, title, author, '
  522. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  523. . ', link, date, is_read, is_favorite, id_feed, tags '
  524. . 'FROM `' . $this->prefix . 'entry` WHERE id_feed=? AND guid=?';
  525. $stm = $this->bd->prepare($sql);
  526. $values = array(
  527. $id_feed,
  528. $guid,
  529. );
  530. $stm->execute($values);
  531. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  532. $entries = self::daoToEntries($res);
  533. return isset($entries[0]) ? $entries[0] : null;
  534. }
  535. public function searchById($id) {
  536. $sql = 'SELECT id, guid, title, author, '
  537. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  538. . ', link, date, is_read, is_favorite, id_feed, tags '
  539. . 'FROM `' . $this->prefix . 'entry` WHERE id=?';
  540. $stm = $this->bd->prepare($sql);
  541. $values = array($id);
  542. $stm->execute($values);
  543. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  544. $entries = self::daoToEntries($res);
  545. return isset($entries[0]) ? $entries[0] : null;
  546. }
  547. protected function sqlConcat($s1, $s2) {
  548. return 'CONCAT(' . $s1 . ',' . $s2 . ')'; //MySQL
  549. }
  550. protected function sqlListEntriesWhere($alias = '', $filter = null, $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $firstId = '', $date_min = 0) {
  551. $search = ' ';
  552. $values = array();
  553. if ($state & FreshRSS_Entry::STATE_NOT_READ) {
  554. if (!($state & FreshRSS_Entry::STATE_READ)) {
  555. $search .= 'AND ' . $alias . 'is_read=0 ';
  556. }
  557. }
  558. elseif ($state & FreshRSS_Entry::STATE_READ) {
  559. $search .= 'AND ' . $alias . 'is_read=1 ';
  560. }
  561. if ($state & FreshRSS_Entry::STATE_FAVORITE) {
  562. if (!($state & FreshRSS_Entry::STATE_NOT_FAVORITE)) {
  563. $search .= 'AND ' . $alias . 'is_favorite=1 ';
  564. }
  565. }
  566. elseif ($state & FreshRSS_Entry::STATE_NOT_FAVORITE) {
  567. $search .= 'AND ' . $alias . 'is_favorite=0 ';
  568. }
  569. switch ($order) {
  570. case 'DESC':
  571. case 'ASC':
  572. break;
  573. default:
  574. throw new FreshRSS_EntriesGetter_Exception('Bad order in Entry->listByType: [' . $order . ']!');
  575. }
  576. /*if ($firstId === '' && parent::$sharedDbType === 'mysql') {
  577. $firstId = $order === 'DESC' ? '9000000000'. '000000' : '0'; //MySQL optimization. TODO: check if this is needed again, after the filtering for old articles has been removed in 0.9-dev
  578. }*/
  579. if ($firstId !== '') {
  580. $search .= 'AND ' . $alias . 'id ' . ($order === 'DESC' ? '<=' : '>=') . $firstId . ' ';
  581. }
  582. if ($date_min > 0) {
  583. $search .= 'AND ' . $alias . 'id >= ' . $date_min . '000000 ';
  584. }
  585. if ($filter) {
  586. if ($filter->getIntitle()) {
  587. foreach ($filter->getIntitle() as $title) {
  588. $search .= 'AND ' . $alias . 'title LIKE ? ';
  589. $values[] = "%{$title}%";
  590. }
  591. }
  592. if ($filter->getInurl()) {
  593. foreach ($filter->getInurl() as $url) {
  594. $search .= 'AND CONCAT(' . $alias . 'link, ' . $alias . 'guid) LIKE ? ';
  595. $values[] = "%{$url}%";
  596. }
  597. }
  598. if ($filter->getAuthor()) {
  599. foreach ($filter->getAuthor() as $author) {
  600. $search .= 'AND ' . $alias . 'author LIKE ? ';
  601. $values[] = "%{$author}%";
  602. }
  603. }
  604. if ($filter->getMinDate()) {
  605. $search .= 'AND ' . $alias . 'id >= ? ';
  606. $values[] = "{$filter->getMinDate()}000000";
  607. }
  608. if ($filter->getMaxDate()) {
  609. $search .= 'AND ' . $alias . 'id <= ? ';
  610. $values[] = "{$filter->getMaxDate()}000000";
  611. }
  612. if ($filter->getMinPubdate()) {
  613. $search .= 'AND ' . $alias . 'date >= ? ';
  614. $values[] = $filter->getMinPubdate();
  615. }
  616. if ($filter->getMaxPubdate()) {
  617. $search .= 'AND ' . $alias . 'date <= ? ';
  618. $values[] = $filter->getMaxPubdate();
  619. }
  620. if ($filter->getTags()) {
  621. foreach ($filter->getTags() as $tag) {
  622. $search .= 'AND ' . $alias . 'tags LIKE ? ';
  623. $values[] = "%{$tag}%";
  624. }
  625. }
  626. if ($filter->getSearch()) {
  627. $search_values = $filter->getSearch();
  628. foreach ($search_values as $search_value) {
  629. $search .= 'AND ' . $this->sqlconcat($alias . 'title', $this->isCompressed() ? 'UNCOMPRESS(' . $alias . 'content_bin)' : '' . $alias . 'content') . ' LIKE ? ';
  630. $values[] = "%{$search_value}%";
  631. }
  632. }
  633. }
  634. return array($values, $search);
  635. }
  636. private function sqlListWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0) {
  637. if (!$state) {
  638. $state = FreshRSS_Entry::STATE_ALL;
  639. }
  640. $where = '';
  641. $joinFeed = false;
  642. $values = array();
  643. switch ($type) {
  644. case 'a':
  645. $where .= 'f.priority > 0 ';
  646. $joinFeed = true;
  647. break;
  648. case 's': //Deprecated: use $state instead
  649. $where .= 'e.is_favorite=1 ';
  650. break;
  651. case 'c':
  652. $where .= 'f.category=? ';
  653. $values[] = intval($id);
  654. $joinFeed = true;
  655. break;
  656. case 'f':
  657. $where .= 'e.id_feed=? ';
  658. $values[] = intval($id);
  659. break;
  660. case 'A':
  661. $where .= '1=1 ';
  662. break;
  663. default:
  664. throw new FreshRSS_EntriesGetter_Exception('Bad type in Entry->listByType: [' . $type . ']!');
  665. }
  666. list($searchValues, $search) = $this->sqlListEntriesWhere('e.', $filter, $state, $order, $firstId, $date_min);
  667. return array(array_merge($values, $searchValues),
  668. 'SELECT e.id FROM `' . $this->prefix . 'entry` e '
  669. . ($joinFeed ? 'INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id ' : '')
  670. . 'WHERE ' . $where
  671. . $search
  672. . 'ORDER BY e.id ' . $order
  673. . ($limit > 0 ? ' LIMIT ' . $limit : '')); //TODO: See http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/
  674. }
  675. public function listWhereRaw($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0) {
  676. list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filter, $date_min);
  677. $sql = 'SELECT e0.id, e0.guid, e0.title, e0.author, '
  678. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  679. . ', e0.link, e0.date, e0.is_read, e0.is_favorite, e0.id_feed, e0.tags '
  680. . 'FROM `' . $this->prefix . 'entry` e0 '
  681. . 'INNER JOIN ('
  682. . $sql
  683. . ') e2 ON e2.id=e0.id '
  684. . 'ORDER BY e0.id ' . $order;
  685. $stm = $this->bd->prepare($sql);
  686. $stm->execute($values);
  687. return $stm;
  688. }
  689. public function listWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0) {
  690. $stm = $this->listWhereRaw($type, $id, $state, $order, $limit, $firstId, $filter, $date_min);
  691. return self::daoToEntries($stm->fetchAll(PDO::FETCH_ASSOC));
  692. }
  693. public function listIdsWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0) { //For API
  694. list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filter, $date_min);
  695. $stm = $this->bd->prepare($sql);
  696. $stm->execute($values);
  697. return $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  698. }
  699. public function listHashForFeedGuids($id_feed, $guids) {
  700. if (count($guids) < 1) {
  701. return array();
  702. }
  703. $guids = array_unique($guids);
  704. $sql = 'SELECT guid, ' . $this->sqlHexEncode('hash') . ' AS hex_hash FROM `' . $this->prefix . 'entry` WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1). '?)';
  705. $stm = $this->bd->prepare($sql);
  706. $values = array($id_feed);
  707. $values = array_merge($values, $guids);
  708. if ($stm && $stm->execute($values)) {
  709. $result = array();
  710. $rows = $stm->fetchAll(PDO::FETCH_ASSOC);
  711. foreach ($rows as $row) {
  712. $result[$row['guid']] = $row['hex_hash'];
  713. }
  714. return $result;
  715. } else {
  716. $info = $stm == null ? array(0 => '', 1 => '', 2 => 'syntax error') : $stm->errorInfo();
  717. if ($this->autoUpdateDb($info)) {
  718. return $this->listHashForFeedGuids($id_feed, $guids);
  719. }
  720. Minz_Log::error('SQL error listHashForFeedGuids: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  721. . ' while querying feed ' . $id_feed);
  722. return false;
  723. }
  724. }
  725. public function updateLastSeen($id_feed, $guids, $mtime = 0) {
  726. if (count($guids) < 1) {
  727. return 0;
  728. }
  729. $sql = 'UPDATE `' . $this->prefix . 'entry` SET `lastSeen`=? WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1). '?)';
  730. $stm = $this->bd->prepare($sql);
  731. if ($mtime <= 0) {
  732. $mtime = time();
  733. }
  734. $values = array($mtime, $id_feed);
  735. $values = array_merge($values, $guids);
  736. if ($stm && $stm->execute($values)) {
  737. return $stm->rowCount();
  738. } else {
  739. $info = $stm == null ? array(0 => '', 1 => '', 2 => 'syntax error') : $stm->errorInfo();
  740. if ($this->autoUpdateDb($info)) {
  741. return $this->updateLastSeen($id_feed, $guids);
  742. }
  743. Minz_Log::error('SQL error updateLastSeen: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  744. . ' while updating feed ' . $id_feed);
  745. return false;
  746. }
  747. }
  748. public function countUnreadRead() {
  749. $sql = 'SELECT COUNT(e.id) AS count FROM `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id WHERE priority > 0'
  750. . ' UNION SELECT COUNT(e.id) AS count FROM `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id WHERE priority > 0 AND is_read=0';
  751. $stm = $this->bd->prepare($sql);
  752. $stm->execute();
  753. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  754. $all = empty($res[0]) ? 0 : $res[0];
  755. $unread = empty($res[1]) ? 0 : $res[1];
  756. return array('all' => $all, 'unread' => $unread, 'read' => $all - $unread);
  757. }
  758. public function count($minPriority = null) {
  759. $sql = 'SELECT COUNT(e.id) AS count FROM `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id';
  760. if ($minPriority !== null) {
  761. $sql = ' WHERE priority > ' . intval($minPriority);
  762. }
  763. $stm = $this->bd->prepare($sql);
  764. $stm->execute();
  765. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  766. return $res[0];
  767. }
  768. public function countNotRead($minPriority = null) {
  769. $sql = 'SELECT COUNT(e.id) AS count FROM `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id WHERE is_read=0';
  770. if ($minPriority !== null) {
  771. $sql = ' AND priority > ' . intval($minPriority);
  772. }
  773. $stm = $this->bd->prepare($sql);
  774. $stm->execute();
  775. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  776. return $res[0];
  777. }
  778. public function countUnreadReadFavorites() {
  779. $sql = 'SELECT c FROM ('
  780. . 'SELECT COUNT(id) AS c, 1 as o FROM `' . $this->prefix . 'entry` WHERE is_favorite=1 '
  781. . 'UNION SELECT COUNT(id) AS c, 2 AS o FROM `' . $this->prefix . 'entry` WHERE is_favorite=1 AND is_read=0'
  782. . ') u ORDER BY o';
  783. $stm = $this->bd->prepare($sql);
  784. $stm->execute();
  785. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  786. $all = empty($res[0]) ? 0 : $res[0];
  787. $unread = empty($res[1]) ? 0 : $res[1];
  788. return array('all' => $all, 'unread' => $unread, 'read' => $all - $unread);
  789. }
  790. public function optimizeTable() {
  791. $sql = 'OPTIMIZE TABLE `' . $this->prefix . 'entry`'; //MySQL
  792. $stm = $this->bd->prepare($sql);
  793. if ($stm) {
  794. return $stm->execute();
  795. }
  796. }
  797. public function size($all = false) {
  798. $db = FreshRSS_Context::$system_conf->db;
  799. $sql = 'SELECT SUM(data_length + index_length) FROM information_schema.TABLES WHERE table_schema=?'; //MySQL
  800. $values = array($db['base']);
  801. if (!$all) {
  802. $sql .= ' AND table_name LIKE ?';
  803. $values[] = $this->prefix . '%';
  804. }
  805. $stm = $this->bd->prepare($sql);
  806. $stm->execute($values);
  807. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  808. return $res[0];
  809. }
  810. public static function daoToEntry($dao) {
  811. $entry = new FreshRSS_Entry(
  812. $dao['id_feed'],
  813. $dao['guid'],
  814. $dao['title'],
  815. $dao['author'],
  816. $dao['content'],
  817. $dao['link'],
  818. $dao['date'],
  819. $dao['is_read'],
  820. $dao['is_favorite'],
  821. $dao['tags']
  822. );
  823. if (isset($dao['id'])) {
  824. $entry->_id($dao['id']);
  825. }
  826. return $entry;
  827. }
  828. private static function daoToEntries($listDAO) {
  829. $list = array();
  830. if (!is_array($listDAO)) {
  831. $listDAO = array($listDAO);
  832. }
  833. foreach ($listDAO as $key => $dao) {
  834. $list[] = self::daoToEntry($dao);
  835. }
  836. unset($listDAO);
  837. return $list;
  838. }
  839. }