EntryDAO.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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, $filter = null, $state = 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. list($searchValues, $search) = $this->sqlListEntriesWhere($filter, $state);
  341. $stm = $this->bd->prepare($sql . $search);
  342. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  343. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  344. Minz_Log::error('SQL error markReadEntries: ' . $info[2]);
  345. return false;
  346. }
  347. $affected = $stm->rowCount();
  348. if (($affected > 0) && (!$this->updateCacheUnreads(false, false))) {
  349. return false;
  350. }
  351. return $affected;
  352. }
  353. /**
  354. * Mark all the articles in a category as read.
  355. * There is a fail safe to prevent to mark as read articles that are
  356. * loaded during the mark as read action. Then the cache is updated.
  357. *
  358. * If $idMax equals 0, a deprecated debug message is logged
  359. *
  360. * @param integer $id category ID
  361. * @param integer $idMax fail safe article ID
  362. * @return integer affected rows
  363. */
  364. public function markReadCat($id, $idMax = 0, $filter = null, $state = 0) {
  365. if ($idMax == 0) {
  366. $idMax = time() . '000000';
  367. Minz_Log::debug('Calling markReadCat(0) is deprecated!');
  368. }
  369. $sql = 'UPDATE `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id '
  370. . 'SET e.is_read=1 '
  371. . 'WHERE f.category=? AND e.is_read=0 AND e.id <= ?';
  372. $values = array($id, $idMax);
  373. list($searchValues, $search) = $this->sqlListEntriesWhere($filter, $state);
  374. $stm = $this->bd->prepare($sql . $search);
  375. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  376. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  377. Minz_Log::error('SQL error markReadCat: ' . $info[2]);
  378. return false;
  379. }
  380. $affected = $stm->rowCount();
  381. if (($affected > 0) && (!$this->updateCacheUnreads($id, false))) {
  382. return false;
  383. }
  384. return $affected;
  385. }
  386. /**
  387. * Mark all the articles in a feed as read.
  388. * There is a fail safe to prevent to mark as read articles that are
  389. * loaded during the mark as read action. Then the cache is updated.
  390. *
  391. * If $idMax equals 0, a deprecated debug message is logged
  392. *
  393. * @param integer $id_feed feed ID
  394. * @param integer $idMax fail safe article ID
  395. * @return integer affected rows
  396. */
  397. public function markReadFeed($id_feed, $idMax = 0, $filter = null, $state = 0) {
  398. if ($idMax == 0) {
  399. $idMax = time() . '000000';
  400. Minz_Log::debug('Calling markReadFeed(0) is deprecated!');
  401. }
  402. $this->bd->beginTransaction();
  403. $sql = 'UPDATE `' . $this->prefix . 'entry` e '
  404. . 'SET e.is_read=1 '
  405. . 'WHERE e.id_feed=? AND e.is_read=0 AND e.id <= ?';
  406. $values = array($id_feed, $idMax);
  407. list($searchValues, $search) = $this->sqlListEntriesWhere($filter, $state);
  408. $stm = $this->bd->prepare($sql . $search);
  409. if (!($stm && $stm->execute(array_merge($values, $searchValues)))) {
  410. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  411. Minz_Log::error('SQL error markReadFeed: ' . $info[2]);
  412. $this->bd->rollBack();
  413. return false;
  414. }
  415. $affected = $stm->rowCount();
  416. if ($affected > 0) {
  417. $sql = 'UPDATE `' . $this->prefix . 'feed` '
  418. . 'SET cache_nbUnreads=cache_nbUnreads-' . $affected
  419. . ' WHERE id=?';
  420. $values = array($id_feed);
  421. $stm = $this->bd->prepare($sql);
  422. if (!($stm && $stm->execute($values))) {
  423. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  424. Minz_Log::error('SQL error markReadFeed: ' . $info[2]);
  425. $this->bd->rollBack();
  426. return false;
  427. }
  428. }
  429. $this->bd->commit();
  430. return $affected;
  431. }
  432. public function searchByGuid($id_feed, $guid) {
  433. // un guid est unique pour un flux donné
  434. $sql = 'SELECT id, guid, title, author, '
  435. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  436. . ', link, date, is_read, is_favorite, id_feed, tags '
  437. . 'FROM `' . $this->prefix . 'entry` WHERE id_feed=? AND guid=?';
  438. $stm = $this->bd->prepare($sql);
  439. $values = array(
  440. $id_feed,
  441. $guid,
  442. );
  443. $stm->execute($values);
  444. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  445. $entries = self::daoToEntry($res);
  446. return isset($entries[0]) ? $entries[0] : null;
  447. }
  448. public function searchById($id) {
  449. $sql = 'SELECT id, guid, title, author, '
  450. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  451. . ', link, date, is_read, is_favorite, id_feed, tags '
  452. . 'FROM `' . $this->prefix . 'entry` WHERE id=?';
  453. $stm = $this->bd->prepare($sql);
  454. $values = array($id);
  455. $stm->execute($values);
  456. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  457. $entries = self::daoToEntry($res);
  458. return isset($entries[0]) ? $entries[0] : null;
  459. }
  460. protected function sqlConcat($s1, $s2) {
  461. return 'CONCAT(' . $s1 . ',' . $s2 . ')'; //MySQL
  462. }
  463. private function sqlListEntriesWhere($filter = null, $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $firstId = '', $date_min = 0) {
  464. $search = ' ';
  465. $values = array();
  466. if ($state & FreshRSS_Entry::STATE_NOT_READ) {
  467. if (!($state & FreshRSS_Entry::STATE_READ)) {
  468. $search .= 'AND e.is_read=0 ';
  469. }
  470. }
  471. elseif ($state & FreshRSS_Entry::STATE_READ) {
  472. $search .= 'AND e.is_read=1 ';
  473. }
  474. if ($state & FreshRSS_Entry::STATE_FAVORITE) {
  475. if (!($state & FreshRSS_Entry::STATE_NOT_FAVORITE)) {
  476. $search .= 'AND e.is_favorite=1 ';
  477. }
  478. }
  479. elseif ($state & FreshRSS_Entry::STATE_NOT_FAVORITE) {
  480. $search .= 'AND e.is_favorite=0 ';
  481. }
  482. switch ($order) {
  483. case 'DESC':
  484. case 'ASC':
  485. break;
  486. default:
  487. throw new FreshRSS_EntriesGetter_Exception('Bad order in Entry->listByType: [' . $order . ']!');
  488. }
  489. /*if ($firstId === '' && parent::$sharedDbType === 'mysql') {
  490. $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
  491. }*/
  492. if ($firstId !== '') {
  493. $search .= 'AND e.id ' . ($order === 'DESC' ? '<=' : '>=') . $firstId . ' ';
  494. }
  495. if ($date_min > 0) {
  496. $search .= 'AND e.id >= ' . $date_min . '000000 ';
  497. }
  498. if ($filter) {
  499. if ($filter->getIntitle()) {
  500. $search .= 'AND e.title LIKE ? ';
  501. $values[] = "%{$filter->getIntitle()}%";
  502. }
  503. if ($filter->getInurl()) {
  504. $search .= 'AND CONCAT(e.link, e.guid) LIKE ? ';
  505. $values[] = "%{$filter->getInurl()}%";
  506. }
  507. if ($filter->getAuthor()) {
  508. $search .= 'AND e.author LIKE ? ';
  509. $values[] = "%{$filter->getAuthor()}%";
  510. }
  511. if ($filter->getMinDate()) {
  512. $search .= 'AND e.id >= ? ';
  513. $values[] = "{$filter->getMinDate()}000000";
  514. }
  515. if ($filter->getMaxDate()) {
  516. $search .= 'AND e.id <= ? ';
  517. $values[] = "{$filter->getMaxDate()}000000";
  518. }
  519. if ($filter->getMinPubdate()) {
  520. $search .= 'AND e.date >= ? ';
  521. $values[] = $filter->getMinPubdate();
  522. }
  523. if ($filter->getMaxPubdate()) {
  524. $search .= 'AND e.date <= ? ';
  525. $values[] = $filter->getMaxPubdate();
  526. }
  527. if ($filter->getTags()) {
  528. $tags = $filter->getTags();
  529. foreach ($tags as $tag) {
  530. $search .= 'AND e.tags LIKE ? ';
  531. $values[] = "%{$tag}%";
  532. }
  533. }
  534. if ($filter->getSearch()) {
  535. $search_values = $filter->getSearch();
  536. foreach ($search_values as $search_value) {
  537. $search .= 'AND ' . $this->sqlconcat('e.title', $this->isCompressed() ? 'UNCOMPRESS(content_bin)' : 'content') . ' LIKE ? ';
  538. $values[] = "%{$search_value}%";
  539. }
  540. }
  541. }
  542. return array($values, $search);
  543. }
  544. private function sqlListWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0) {
  545. if (!$state) {
  546. $state = FreshRSS_Entry::STATE_ALL;
  547. }
  548. $where = '';
  549. $joinFeed = false;
  550. $values = array();
  551. switch ($type) {
  552. case 'a':
  553. $where .= 'f.priority > 0 ';
  554. $joinFeed = true;
  555. break;
  556. case 's': //Deprecated: use $state instead
  557. $where .= 'e.is_favorite=1 ';
  558. break;
  559. case 'c':
  560. $where .= 'f.category=? ';
  561. $values[] = intval($id);
  562. $joinFeed = true;
  563. break;
  564. case 'f':
  565. $where .= 'e.id_feed=? ';
  566. $values[] = intval($id);
  567. break;
  568. case 'A':
  569. $where .= '1 ';
  570. break;
  571. default:
  572. throw new FreshRSS_EntriesGetter_Exception('Bad type in Entry->listByType: [' . $type . ']!');
  573. }
  574. list($searchValues, $search) = $this->sqlListEntriesWhere($filter, $state, $order, $firstId, $date_min);
  575. return array(array_merge($values, $searchValues),
  576. 'SELECT e.id FROM `' . $this->prefix . 'entry` e '
  577. . ($joinFeed ? 'INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id ' : '')
  578. . 'WHERE ' . $where
  579. . $search
  580. . 'ORDER BY e.id ' . $order
  581. . ($limit > 0 ? ' LIMIT ' . $limit : '')); //TODO: See http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/
  582. }
  583. public function listWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0) {
  584. list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filter, $date_min);
  585. $sql = 'SELECT e0.id, e0.guid, e0.title, e0.author, '
  586. . ($this->isCompressed() ? 'UNCOMPRESS(content_bin) AS content' : 'content')
  587. . ', e0.link, e0.date, e0.is_read, e0.is_favorite, e0.id_feed, e0.tags '
  588. . 'FROM `' . $this->prefix . 'entry` e0 '
  589. . 'INNER JOIN ('
  590. . $sql
  591. . ') e2 ON e2.id=e0.id '
  592. . 'ORDER BY e0.id ' . $order;
  593. $stm = $this->bd->prepare($sql);
  594. $stm->execute($values);
  595. return self::daoToEntry($stm->fetchAll(PDO::FETCH_ASSOC));
  596. }
  597. public function listIdsWhere($type = 'a', $id = '', $state = FreshRSS_Entry::STATE_ALL, $order = 'DESC', $limit = 1, $firstId = '', $filter = '', $date_min = 0) { //For API
  598. list($values, $sql) = $this->sqlListWhere($type, $id, $state, $order, $limit, $firstId, $filter, $date_min);
  599. $stm = $this->bd->prepare($sql);
  600. $stm->execute($values);
  601. return $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  602. }
  603. public function listHashForFeedGuids($id_feed, $guids) {
  604. if (count($guids) < 1) {
  605. return array();
  606. }
  607. $sql = 'SELECT guid, hex(hash) AS hexHash FROM `' . $this->prefix . 'entry` WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1). '?)';
  608. $stm = $this->bd->prepare($sql);
  609. $values = array($id_feed);
  610. $values = array_merge($values, $guids);
  611. if ($stm && $stm->execute($values)) {
  612. $result = array();
  613. $rows = $stm->fetchAll(PDO::FETCH_ASSOC);
  614. foreach ($rows as $row) {
  615. $result[$row['guid']] = $row['hexHash'];
  616. }
  617. return $result;
  618. } else {
  619. $info = $stm == null ? array(0 => '', 1 => '', 2 => 'syntax error') : $stm->errorInfo();
  620. if ($this->autoUpdateDb($info)) {
  621. return $this->listHashForFeedGuids($id_feed, $guids);
  622. }
  623. Minz_Log::error('SQL error listHashForFeedGuids: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  624. . ' while querying feed ' . $id_feed);
  625. return false;
  626. }
  627. }
  628. public function updateLastSeen($id_feed, $guids) {
  629. if (count($guids) < 1) {
  630. return 0;
  631. }
  632. $sql = 'UPDATE `' . $this->prefix . 'entry` SET lastSeen=? WHERE id_feed=? AND guid IN (' . str_repeat('?,', count($guids) - 1). '?)';
  633. $stm = $this->bd->prepare($sql);
  634. $values = array(time(), $id_feed);
  635. $values = array_merge($values, $guids);
  636. if ($stm && $stm->execute($values)) {
  637. return $stm->rowCount();
  638. } else {
  639. $info = $stm == null ? array(0 => '', 1 => '', 2 => 'syntax error') : $stm->errorInfo();
  640. if ($this->autoUpdateDb($info)) {
  641. return $this->updateLastSeen($id_feed, $guids);
  642. }
  643. Minz_Log::error('SQL error updateLastSeen: ' . $info[0] . ': ' . $info[1] . ' ' . $info[2]
  644. . ' while updating feed ' . $id_feed);
  645. return false;
  646. }
  647. }
  648. public function countUnreadRead() {
  649. $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'
  650. . ' 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';
  651. $stm = $this->bd->prepare($sql);
  652. $stm->execute();
  653. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  654. $all = empty($res[0]) ? 0 : $res[0];
  655. $unread = empty($res[1]) ? 0 : $res[1];
  656. return array('all' => $all, 'unread' => $unread, 'read' => $all - $unread);
  657. }
  658. public function count($minPriority = null) {
  659. $sql = 'SELECT COUNT(e.id) AS count FROM `' . $this->prefix . 'entry` e INNER JOIN `' . $this->prefix . 'feed` f ON e.id_feed=f.id';
  660. if ($minPriority !== null) {
  661. $sql = ' WHERE priority > ' . intval($minPriority);
  662. }
  663. $stm = $this->bd->prepare($sql);
  664. $stm->execute();
  665. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  666. return $res[0];
  667. }
  668. public function countNotRead($minPriority = null) {
  669. $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';
  670. if ($minPriority !== null) {
  671. $sql = ' AND priority > ' . intval($minPriority);
  672. }
  673. $stm = $this->bd->prepare($sql);
  674. $stm->execute();
  675. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  676. return $res[0];
  677. }
  678. public function countUnreadReadFavorites() {
  679. $sql = 'SELECT c FROM ('
  680. . 'SELECT COUNT(id) AS c, 1 as o FROM `' . $this->prefix . 'entry` WHERE is_favorite=1 '
  681. . 'UNION SELECT COUNT(id) AS c, 2 AS o FROM `' . $this->prefix . 'entry` WHERE is_favorite=1 AND is_read=0'
  682. . ') u ORDER BY o';
  683. $stm = $this->bd->prepare($sql);
  684. $stm->execute();
  685. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  686. $all = empty($res[0]) ? 0 : $res[0];
  687. $unread = empty($res[1]) ? 0 : $res[1];
  688. return array('all' => $all, 'unread' => $unread, 'read' => $all - $unread);
  689. }
  690. public function optimizeTable() {
  691. $sql = 'OPTIMIZE TABLE `' . $this->prefix . 'entry`'; //MySQL
  692. $stm = $this->bd->prepare($sql);
  693. if ($stm) {
  694. return $stm->execute();
  695. }
  696. }
  697. public function size($all = false) {
  698. $db = FreshRSS_Context::$system_conf->db;
  699. $sql = 'SELECT SUM(data_length + index_length) FROM information_schema.TABLES WHERE table_schema=?'; //MySQL
  700. $values = array($db['base']);
  701. if (!$all) {
  702. $sql .= ' AND table_name LIKE ?';
  703. $values[] = $this->prefix . '%';
  704. }
  705. $stm = $this->bd->prepare($sql);
  706. $stm->execute($values);
  707. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  708. return $res[0];
  709. }
  710. public static function daoToEntry($listDAO) {
  711. $list = array();
  712. if (!is_array($listDAO)) {
  713. $listDAO = array($listDAO);
  714. }
  715. foreach ($listDAO as $key => $dao) {
  716. $entry = new FreshRSS_Entry(
  717. $dao['id_feed'],
  718. $dao['guid'],
  719. $dao['title'],
  720. $dao['author'],
  721. $dao['content'],
  722. $dao['link'],
  723. $dao['date'],
  724. $dao['is_read'],
  725. $dao['is_favorite'],
  726. $dao['tags']
  727. );
  728. if (isset($dao['id'])) {
  729. $entry->_id($dao['id']);
  730. }
  731. $list[] = $entry;
  732. }
  733. unset($listDAO);
  734. return $list;
  735. }
  736. }