EntryDAO.php 29 KB

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