EntryDAO.php 30 KB

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