FeedDAO.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. <?php
  2. class FreshRSS_FeedDAO extends Minz_ModelPdo implements FreshRSS_Searchable {
  3. protected function addColumn($name) {
  4. Minz_Log::warning('FreshRSS_FeedDAO::addColumn: ' . $name);
  5. try {
  6. if ($name === 'attributes') { //v1.11.0
  7. $stm = $this->bd->prepare('ALTER TABLE `' . $this->prefix . 'feed` ADD COLUMN attributes TEXT');
  8. return $stm && $stm->execute();
  9. }
  10. } catch (Exception $e) {
  11. Minz_Log::error('FreshRSS_FeedDAO::addColumn error: ' . $e->getMessage());
  12. }
  13. return false;
  14. }
  15. protected function autoUpdateDb($errorInfo) {
  16. if (isset($errorInfo[0])) {
  17. if ($errorInfo[0] === FreshRSS_DatabaseDAO::ER_BAD_FIELD_ERROR || $errorInfo[0] === FreshRSS_DatabaseDAOPGSQL::UNDEFINED_COLUMN) {
  18. foreach (array('attributes') as $column) {
  19. if (stripos($errorInfo[2], $column) !== false) {
  20. return $this->addColumn($column);
  21. }
  22. }
  23. }
  24. }
  25. return false;
  26. }
  27. public function addFeed($valuesTmp) {
  28. $sql = '
  29. INSERT INTO `' . $this->prefix . 'feed`
  30. (
  31. url,
  32. category,
  33. name,
  34. website,
  35. description,
  36. `lastUpdate`,
  37. priority,
  38. `httpAuth`,
  39. error,
  40. keep_history,
  41. ttl,
  42. attributes
  43. )
  44. VALUES
  45. (?, ?, ?, ?, ?, ?, 10, ?, 0, ?, ?, ?)';
  46. $stm = $this->bd->prepare($sql);
  47. $valuesTmp['url'] = safe_ascii($valuesTmp['url']);
  48. $valuesTmp['website'] = safe_ascii($valuesTmp['website']);
  49. $values = array(
  50. substr($valuesTmp['url'], 0, 511),
  51. $valuesTmp['category'],
  52. mb_strcut(trim($valuesTmp['name']), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8'),
  53. substr($valuesTmp['website'], 0, 255),
  54. mb_strcut($valuesTmp['description'], 0, 1023, 'UTF-8'),
  55. $valuesTmp['lastUpdate'],
  56. base64_encode($valuesTmp['httpAuth']),
  57. FreshRSS_Feed::KEEP_HISTORY_DEFAULT,
  58. FreshRSS_Feed::TTL_DEFAULT,
  59. isset($valuesTmp['attributes']) ? json_encode($valuesTmp['attributes']) : '',
  60. );
  61. if ($stm && $stm->execute($values)) {
  62. return $this->bd->lastInsertId('"' . $this->prefix . 'feed_id_seq"');
  63. } else {
  64. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  65. if ($this->autoUpdateDb($info)) {
  66. return $this->addFeed($valuesTmp);
  67. }
  68. Minz_Log::error('SQL error addFeed: ' . $info[2]);
  69. return false;
  70. }
  71. }
  72. public function addFeedObject($feed) {
  73. // TODO: not sure if we should write this method in DAO since DAO
  74. // should not be aware about feed class
  75. // Add feed only if we don't find it in DB
  76. $feed_search = $this->searchByUrl($feed->url());
  77. if (!$feed_search) {
  78. $values = array(
  79. 'id' => $feed->id(),
  80. 'url' => $feed->url(),
  81. 'category' => $feed->category(),
  82. 'name' => $feed->name(),
  83. 'website' => $feed->website(),
  84. 'description' => $feed->description(),
  85. 'lastUpdate' => 0,
  86. 'httpAuth' => $feed->httpAuth(),
  87. 'attributes' => $feed->attributes(),
  88. );
  89. $id = $this->addFeed($values);
  90. if ($id) {
  91. $feed->_id($id);
  92. $feed->faviconPrepare();
  93. }
  94. return $id;
  95. }
  96. return $feed_search->id();
  97. }
  98. public function updateFeed($id, $valuesTmp) {
  99. if (isset($valuesTmp['name'])) {
  100. $valuesTmp['name'] = mb_strcut(trim($valuesTmp['name']), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8');
  101. }
  102. if (isset($valuesTmp['url'])) {
  103. $valuesTmp['url'] = safe_ascii($valuesTmp['url']);
  104. }
  105. if (isset($valuesTmp['website'])) {
  106. $valuesTmp['website'] = safe_ascii($valuesTmp['website']);
  107. }
  108. $set = '';
  109. foreach ($valuesTmp as $key => $v) {
  110. $set .= '`' . $key . '`=?, ';
  111. if ($key === 'httpAuth') {
  112. $valuesTmp[$key] = base64_encode($v);
  113. } elseif ($key === 'attributes') {
  114. $valuesTmp[$key] = json_encode($v);
  115. }
  116. }
  117. $set = substr($set, 0, -2);
  118. $sql = 'UPDATE `' . $this->prefix . 'feed` SET ' . $set . ' WHERE id=?';
  119. $stm = $this->bd->prepare($sql);
  120. foreach ($valuesTmp as $v) {
  121. $values[] = $v;
  122. }
  123. $values[] = $id;
  124. if ($stm && $stm->execute($values)) {
  125. return $stm->rowCount();
  126. } else {
  127. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  128. if ($this->autoUpdateDb($info)) {
  129. return $this->updateFeed($id, $valuesTmp);
  130. }
  131. Minz_Log::error('SQL error updateFeed: ' . $info[2] . ' for feed ' . $id);
  132. return false;
  133. }
  134. }
  135. public function updateFeedAttribute($feed, $key, $value) {
  136. if ($feed instanceof FreshRSS_Feed) {
  137. $feed->_attributes($key, $value);
  138. return $this->updateFeed(
  139. $feed->id(),
  140. array('attributes' => $feed->attributes())
  141. );
  142. }
  143. return false;
  144. }
  145. public function updateLastUpdate($id, $inError = false, $mtime = 0) { //See also updateCachedValue()
  146. $sql = 'UPDATE `' . $this->prefix . 'feed` '
  147. . 'SET `lastUpdate`=?, error=? '
  148. . 'WHERE id=?';
  149. $values = array(
  150. $mtime <= 0 ? time() : $mtime,
  151. $inError ? 1 : 0,
  152. $id,
  153. );
  154. $stm = $this->bd->prepare($sql);
  155. if ($stm && $stm->execute($values)) {
  156. return $stm->rowCount();
  157. } else {
  158. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  159. Minz_Log::error('SQL error updateLastUpdate: ' . $info[2]);
  160. return false;
  161. }
  162. }
  163. public function changeCategory($idOldCat, $idNewCat) {
  164. $catDAO = FreshRSS_Factory::createCategoryDao();
  165. $newCat = $catDAO->searchById($idNewCat);
  166. if (!$newCat) {
  167. $newCat = $catDAO->getDefault();
  168. }
  169. $sql = 'UPDATE `' . $this->prefix . 'feed` SET category=? WHERE category=?';
  170. $stm = $this->bd->prepare($sql);
  171. $values = array(
  172. $newCat->id(),
  173. $idOldCat
  174. );
  175. if ($stm && $stm->execute($values)) {
  176. return $stm->rowCount();
  177. } else {
  178. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  179. Minz_Log::error('SQL error changeCategory: ' . $info[2]);
  180. return false;
  181. }
  182. }
  183. public function deleteFeed($id) {
  184. $sql = 'DELETE FROM `' . $this->prefix . 'feed` WHERE id=?';
  185. $stm = $this->bd->prepare($sql);
  186. $values = array($id);
  187. if ($stm && $stm->execute($values)) {
  188. return $stm->rowCount();
  189. } else {
  190. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  191. Minz_Log::error('SQL error deleteFeed: ' . $info[2]);
  192. return false;
  193. }
  194. }
  195. public function deleteFeedByCategory($id) {
  196. $sql = 'DELETE FROM `' . $this->prefix . 'feed` WHERE category=?';
  197. $stm = $this->bd->prepare($sql);
  198. $values = array($id);
  199. if ($stm && $stm->execute($values)) {
  200. return $stm->rowCount();
  201. } else {
  202. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  203. Minz_Log::error('SQL error deleteFeedByCategory: ' . $info[2]);
  204. return false;
  205. }
  206. }
  207. public function searchById($id) {
  208. $sql = 'SELECT * FROM `' . $this->prefix . 'feed` WHERE id=?';
  209. $stm = $this->bd->prepare($sql);
  210. $values = array($id);
  211. $stm->execute($values);
  212. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  213. $feed = self::daoToFeed($res);
  214. if (isset($feed[$id])) {
  215. return $feed[$id];
  216. } else {
  217. return null;
  218. }
  219. }
  220. public function searchByUrl($url) {
  221. $sql = 'SELECT * FROM `' . $this->prefix . 'feed` WHERE url=?';
  222. $stm = $this->bd->prepare($sql);
  223. $values = array($url);
  224. $stm->execute($values);
  225. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  226. $feed = current(self::daoToFeed($res));
  227. if (isset($feed) && $feed !== false) {
  228. return $feed;
  229. } else {
  230. return null;
  231. }
  232. }
  233. public function listFeedsIds() {
  234. $sql = 'SELECT id FROM `' . $this->prefix . 'feed`';
  235. $stm = $this->bd->prepare($sql);
  236. $stm->execute();
  237. return $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  238. }
  239. public function listFeeds() {
  240. $sql = 'SELECT * FROM `' . $this->prefix . 'feed` ORDER BY name';
  241. $stm = $this->bd->prepare($sql);
  242. $stm->execute();
  243. return self::daoToFeed($stm->fetchAll(PDO::FETCH_ASSOC));
  244. }
  245. public function arrayFeedCategoryNames() { //For API
  246. $sql = 'SELECT f.id, f.name, c.name as c_name FROM `' . $this->prefix . 'feed` f '
  247. . 'INNER JOIN `' . $this->prefix . 'category` c ON c.id = f.category';
  248. $stm = $this->bd->prepare($sql);
  249. $stm->execute();
  250. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  251. $feedCategoryNames = array();
  252. foreach ($res as $line) {
  253. $feedCategoryNames[$line['id']] = array(
  254. 'name' => $line['name'],
  255. 'c_name' => $line['c_name'],
  256. );
  257. }
  258. return $feedCategoryNames;
  259. }
  260. /**
  261. * Use $defaultCacheDuration == -1 to return all feeds, without filtering them by TTL.
  262. */
  263. public function listFeedsOrderUpdate($defaultCacheDuration = 3600, $limit = 0) {
  264. $this->updateTTL();
  265. $sql = 'SELECT id, url, name, website, `lastUpdate`, `pathEntries`, `httpAuth`, keep_history, ttl, attributes '
  266. . 'FROM `' . $this->prefix . 'feed` '
  267. . ($defaultCacheDuration < 0 ? '' : 'WHERE ttl >= ' . FreshRSS_Feed::TTL_DEFAULT
  268. . ' AND `lastUpdate` < (' . (time() + 60) . '-(CASE WHEN ttl=' . FreshRSS_Feed::TTL_DEFAULT . ' THEN ' . intval($defaultCacheDuration) . ' ELSE ttl END)) ')
  269. . 'ORDER BY `lastUpdate` '
  270. . ($limit < 1 ? '' : 'LIMIT ' . intval($limit));
  271. $stm = $this->bd->prepare($sql);
  272. if ($stm && $stm->execute()) {
  273. return self::daoToFeed($stm->fetchAll(PDO::FETCH_ASSOC));
  274. } else {
  275. $info = $stm == null ? array(0 => '', 1 => '', 2 => 'syntax error') : $stm->errorInfo();
  276. if ($this->autoUpdateDb($info)) {
  277. return $this->listFeedsOrderUpdate($defaultCacheDuration);
  278. }
  279. Minz_Log::error('SQL error listFeedsOrderUpdate: ' . $info[2]);
  280. return array();
  281. }
  282. }
  283. public function listByCategory($cat) {
  284. $sql = 'SELECT * FROM `' . $this->prefix . 'feed` WHERE category=? ORDER BY name';
  285. $stm = $this->bd->prepare($sql);
  286. $values = array($cat);
  287. $stm->execute($values);
  288. return self::daoToFeed($stm->fetchAll(PDO::FETCH_ASSOC));
  289. }
  290. public function countEntries($id) {
  291. $sql = 'SELECT COUNT(*) AS count FROM `' . $this->prefix . 'entry` WHERE id_feed=?';
  292. $stm = $this->bd->prepare($sql);
  293. $values = array($id);
  294. $stm->execute($values);
  295. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  296. return $res[0]['count'];
  297. }
  298. public function countNotRead($id) {
  299. $sql = 'SELECT COUNT(*) AS count FROM `' . $this->prefix . 'entry` WHERE id_feed=? AND is_read=0';
  300. $stm = $this->bd->prepare($sql);
  301. $values = array($id);
  302. $stm->execute($values);
  303. $res = $stm->fetchAll(PDO::FETCH_ASSOC);
  304. return $res[0]['count'];
  305. }
  306. public function updateCachedValue($id) { //For multiple feeds, call updateCachedValues()
  307. $sql = 'UPDATE `' . $this->prefix . 'feed` ' //2 sub-requests with FOREIGN KEY(e.id_feed), INDEX(e.is_read) faster than 1 request with GROUP BY or CASE
  308. . 'SET `cache_nbEntries`=(SELECT COUNT(e1.id) FROM `' . $this->prefix . 'entry` e1 WHERE e1.id_feed=`' . $this->prefix . 'feed`.id),'
  309. . '`cache_nbUnreads`=(SELECT COUNT(e2.id) FROM `' . $this->prefix . 'entry` e2 WHERE e2.id_feed=`' . $this->prefix . 'feed`.id AND e2.is_read=0) '
  310. . 'WHERE id=?';
  311. $values = array($id);
  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 updateCachedValue: ' . $info[2]);
  318. return false;
  319. }
  320. }
  321. public function updateCachedValues() { //For one single feed, call updateCachedValue($id)
  322. $sql = 'UPDATE `' . $this->prefix . 'feed` '
  323. . 'SET `cache_nbEntries`=(SELECT COUNT(e1.id) FROM `' . $this->prefix . 'entry` e1 WHERE e1.id_feed=`' . $this->prefix . 'feed`.id),'
  324. . '`cache_nbUnreads`=(SELECT COUNT(e2.id) FROM `' . $this->prefix . 'entry` e2 WHERE e2.id_feed=`' . $this->prefix . 'feed`.id AND e2.is_read=0)';
  325. $stm = $this->bd->prepare($sql);
  326. if ($stm && $stm->execute()) {
  327. return $stm->rowCount();
  328. } else {
  329. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  330. Minz_Log::error('SQL error updateCachedValues: ' . $info[2]);
  331. return false;
  332. }
  333. }
  334. public function truncate($id) {
  335. $sql = 'DELETE FROM `' . $this->prefix . 'entry` WHERE id_feed=?';
  336. $stm = $this->bd->prepare($sql);
  337. $values = array($id);
  338. $this->bd->beginTransaction();
  339. if (!($stm && $stm->execute($values))) {
  340. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  341. Minz_Log::error('SQL error truncate: ' . $info[2]);
  342. $this->bd->rollBack();
  343. return false;
  344. }
  345. $affected = $stm->rowCount();
  346. $sql = 'UPDATE `' . $this->prefix . 'feed` '
  347. . 'SET `cache_nbEntries`=0, `cache_nbUnreads`=0 WHERE id=?';
  348. $values = array($id);
  349. $stm = $this->bd->prepare($sql);
  350. if (!($stm && $stm->execute($values))) {
  351. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  352. Minz_Log::error('SQL error truncate: ' . $info[2]);
  353. $this->bd->rollBack();
  354. return false;
  355. }
  356. $this->bd->commit();
  357. return $affected;
  358. }
  359. public static function daoToFeed($listDAO, $catID = null) {
  360. $list = array();
  361. if (!is_array($listDAO)) {
  362. $listDAO = array($listDAO);
  363. }
  364. foreach ($listDAO as $key => $dao) {
  365. if (!isset($dao['name'])) {
  366. continue;
  367. }
  368. if (isset($dao['id'])) {
  369. $key = $dao['id'];
  370. }
  371. if ($catID === null) {
  372. $category = isset($dao['category']) ? $dao['category'] : 0;
  373. } else {
  374. $category = $catID;
  375. }
  376. $myFeed = new FreshRSS_Feed(isset($dao['url']) ? $dao['url'] : '', false);
  377. $myFeed->_category($category);
  378. $myFeed->_name($dao['name']);
  379. $myFeed->_website(isset($dao['website']) ? $dao['website'] : '', false);
  380. $myFeed->_description(isset($dao['description']) ? $dao['description'] : '');
  381. $myFeed->_lastUpdate(isset($dao['lastUpdate']) ? $dao['lastUpdate'] : 0);
  382. $myFeed->_priority(isset($dao['priority']) ? $dao['priority'] : 10);
  383. $myFeed->_pathEntries(isset($dao['pathEntries']) ? $dao['pathEntries'] : '');
  384. $myFeed->_httpAuth(isset($dao['httpAuth']) ? base64_decode($dao['httpAuth']) : '');
  385. $myFeed->_error(isset($dao['error']) ? $dao['error'] : 0);
  386. $myFeed->_keepHistory(isset($dao['keep_history']) ? $dao['keep_history'] : FreshRSS_Feed::KEEP_HISTORY_DEFAULT);
  387. $myFeed->_ttl(isset($dao['ttl']) ? $dao['ttl'] : FreshRSS_Feed::TTL_DEFAULT);
  388. $myFeed->_attributes('', isset($dao['attributes']) ? $dao['attributes'] : '');
  389. $myFeed->_nbNotRead(isset($dao['cache_nbUnreads']) ? $dao['cache_nbUnreads'] : 0);
  390. $myFeed->_nbEntries(isset($dao['cache_nbEntries']) ? $dao['cache_nbEntries'] : 0);
  391. if (isset($dao['id'])) {
  392. $myFeed->_id($dao['id']);
  393. }
  394. $list[$key] = $myFeed;
  395. }
  396. return $list;
  397. }
  398. public function updateTTL() {
  399. $sql = <<<SQL
  400. UPDATE `{$this->prefix}feed`
  401. SET ttl = :new_value
  402. WHERE ttl = :old_value
  403. SQL;
  404. $stm = $this->bd->prepare($sql);
  405. if (!($stm && $stm->execute(array(':new_value' => FreshRSS_Feed::TTL_DEFAULT, ':old_value' => -2)))) {
  406. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  407. Minz_Log::error('SQL warning updateTTL 1: ' . $info[2] . ' ' . $sql);
  408. $sql2 = 'ALTER TABLE `' . $this->prefix . 'feed` ADD COLUMN ttl INT NOT NULL DEFAULT ' . FreshRSS_Feed::TTL_DEFAULT; //v0.7.3
  409. $stm = $this->bd->prepare($sql2);
  410. if (!($stm && $stm->execute())) {
  411. $info = $stm == null ? array(2 => 'syntax error') : $stm->errorInfo();
  412. Minz_Log::error('SQL error updateTTL 2: ' . $info[2] . ' ' . $sql2);
  413. }
  414. } else {
  415. $stm->execute(array(':new_value' => -3600, ':old_value' => -1));
  416. }
  417. }
  418. }