EntryDAO.php 25 KB

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