EntryDAO.php 24 KB

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