EntryDAO.php 28 KB

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