lib_rss.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. <?php
  2. if (!function_exists('json_decode')) {
  3. require_once('JSON.php');
  4. function json_decode($var) {
  5. $JSON = new Services_JSON;
  6. return (array)($JSON->decode($var));
  7. }
  8. }
  9. if (!function_exists('json_encode')) {
  10. require_once('JSON.php');
  11. function json_encode($var) {
  12. $JSON = new Services_JSON;
  13. return $JSON->encodeUnsafe($var);
  14. }
  15. }
  16. //<Auto-loading>
  17. function classAutoloader($class) {
  18. if (strpos($class, 'FreshRSS') === 0) {
  19. $components = explode('_', $class);
  20. switch (count($components)) {
  21. case 1:
  22. include(APP_PATH . '/' . $components[0] . '.php');
  23. return;
  24. case 2:
  25. include(APP_PATH . '/Models/' . $components[1] . '.php');
  26. return;
  27. case 3: //Controllers, Exceptions
  28. @include(APP_PATH . '/' . $components[2] . 's/' . $components[1] . $components[2] . '.php');
  29. return;
  30. }
  31. } elseif (strpos($class, 'Minz') === 0) {
  32. include(LIB_PATH . '/' . str_replace('_', '/', $class) . '.php');
  33. } elseif (strpos($class, 'SimplePie') === 0) {
  34. include(LIB_PATH . '/SimplePie/' . str_replace('_', '/', $class) . '.php');
  35. }
  36. }
  37. spl_autoload_register('classAutoloader');
  38. //</Auto-loading>
  39. function checkUrl($url) {
  40. if (empty ($url)) {
  41. return '';
  42. }
  43. if (!preg_match ('#^https?://#i', $url)) {
  44. $url = 'http://' . $url;
  45. }
  46. if (filter_var($url, FILTER_VALIDATE_URL) ||
  47. (version_compare(PHP_VERSION, '5.3.3', '<') && (strpos($url, '-') > 0) && //PHP bug #51192
  48. ($url === filter_var($url, FILTER_SANITIZE_URL)))) {
  49. return $url;
  50. } else {
  51. return false;
  52. }
  53. }
  54. function formatNumber($n, $precision = 0) {
  55. return str_replace(' ', ' ', //Espace insécable //TODO: remplacer par une espace _fine_ insécable
  56. number_format($n, $precision, '.', ' ')); //number_format does not seem to be Unicode-compatible
  57. }
  58. function format_number($n, $precision = 0) {
  59. // TODO: coding style, prefer THIS function. Remove formatNumber.
  60. return formatNumber($n, $precision);
  61. }
  62. function formatBytes($bytes, $precision = 2, $system = 'IEC') {
  63. if ($system === 'IEC') {
  64. $base = 1024;
  65. $units = array('B', 'KiB', 'MiB', 'GiB', 'TiB');
  66. } elseif ($system === 'SI') {
  67. $base = 1000;
  68. $units = array('B', 'KB', 'MB', 'GB', 'TB');
  69. }
  70. $bytes = max(intval($bytes), 0);
  71. $pow = $bytes === 0 ? 0 : floor(log($bytes) / log($base));
  72. $pow = min($pow, count($units) - 1);
  73. $bytes /= pow($base, $pow);
  74. return formatNumber($bytes, $precision) . ' ' . $units[$pow];
  75. }
  76. function timestamptodate ($t, $hour = true) {
  77. $month = _t(date('M', $t));
  78. if ($hour) {
  79. $date = _t('format_date_hour', $month);
  80. } else {
  81. $date = _t('format_date', $month);
  82. }
  83. return @date ($date, $t);
  84. }
  85. function html_only_entity_decode($text) {
  86. static $htmlEntitiesOnly = null;
  87. if ($htmlEntitiesOnly === null) {
  88. if (version_compare(PHP_VERSION, '5.3.4') >= 0) {
  89. $htmlEntitiesOnly = array_flip(array_diff(
  90. get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES, 'UTF-8'), //Decode HTML entities
  91. get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES, 'UTF-8') //Preserve XML entities
  92. ));
  93. } else {
  94. $htmlEntitiesOnly = array_map('utf8_encode', array_flip(array_diff(
  95. get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES), //Decode HTML entities
  96. get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES) //Preserve XML entities
  97. )));
  98. }
  99. }
  100. return strtr($text, $htmlEntitiesOnly);
  101. }
  102. function customSimplePie() {
  103. $simplePie = new SimplePie();
  104. $simplePie->set_useragent(_t('freshrss') . '/' . FRESHRSS_VERSION . ' (' . PHP_OS . '; ' . FRESHRSS_WEBSITE . ') ' . SIMPLEPIE_NAME . '/' . SIMPLEPIE_VERSION);
  105. $simplePie->set_cache_location(CACHE_PATH);
  106. $simplePie->set_cache_duration(800);
  107. $simplePie->set_timeout(10); //TODO: Make a user setting
  108. $simplePie->strip_htmltags(array(
  109. 'base', 'blink', 'body', 'doctype', 'embed',
  110. 'font', 'form', 'frame', 'frameset', 'html',
  111. 'link', 'input', 'marquee', 'meta', 'noscript',
  112. 'object', 'param', 'plaintext', 'script', 'style',
  113. ));
  114. $simplePie->strip_attributes(array_merge($simplePie->strip_attributes, array(
  115. 'autoplay', 'onload', 'onunload', 'onclick', 'ondblclick', 'onmousedown', 'onmouseup',
  116. 'onmouseover', 'onmousemove', 'onmouseout', 'onfocus', 'onblur',
  117. 'onkeypress', 'onkeydown', 'onkeyup', 'onselect', 'onchange', 'seamless')));
  118. $simplePie->add_attributes(array(
  119. 'img' => array('lazyload' => '', 'postpone' => ''), //http://www.w3.org/TR/resource-priorities/
  120. 'audio' => array('lazyload' => '', 'postpone' => '', 'preload' => 'none'),
  121. 'iframe' => array('lazyload' => '', 'postpone' => '', 'sandbox' => 'allow-scripts allow-same-origin'),
  122. 'video' => array('lazyload' => '', 'postpone' => '', 'preload' => 'none'),
  123. ));
  124. $simplePie->set_url_replacements(array(
  125. 'a' => 'href',
  126. 'area' => 'href',
  127. 'audio' => 'src',
  128. 'blockquote' => 'cite',
  129. 'del' => 'cite',
  130. 'form' => 'action',
  131. 'iframe' => 'src',
  132. 'img' => array(
  133. 'longdesc',
  134. 'src'
  135. ),
  136. 'input' => 'src',
  137. 'ins' => 'cite',
  138. 'q' => 'cite',
  139. 'source' => 'src',
  140. 'track' => 'src',
  141. 'video' => array(
  142. 'poster',
  143. 'src',
  144. ),
  145. ));
  146. return $simplePie;
  147. }
  148. function sanitizeHTML($data, $base = '') {
  149. static $simplePie = null;
  150. if ($simplePie == null) {
  151. $simplePie = customSimplePie();
  152. $simplePie->init();
  153. }
  154. return html_only_entity_decode($simplePie->sanitize->sanitize($data, SIMPLEPIE_CONSTRUCT_HTML, $base));
  155. }
  156. /* permet de récupérer le contenu d'un article pour un flux qui n'est pas complet */
  157. function get_content_by_parsing ($url, $path) {
  158. require_once (LIB_PATH . '/lib_phpQuery.php');
  159. syslog(LOG_INFO, 'FreshRSS GET ' . $url);
  160. $html = file_get_contents ($url);
  161. if ($html) {
  162. $doc = phpQuery::newDocument ($html);
  163. $content = $doc->find ($path);
  164. return sanitizeHTML($content->__toString(), $url);
  165. } else {
  166. throw new Exception ();
  167. }
  168. }
  169. /**
  170. * Add support of image lazy loading
  171. * Move content from src attribute to data-original
  172. * @param content is the text we want to parse
  173. */
  174. function lazyimg($content) {
  175. return preg_replace(
  176. '/<((?:img|iframe)[^>]+?)src=[\'"]([^"\']+)[\'"]([^>]*)>/i',
  177. '<$1src="' . Minz_Url::display('/themes/icons/grey.gif') . '" data-original="$2"$3>',
  178. $content
  179. );
  180. }
  181. function uTimeString() {
  182. $t = @gettimeofday();
  183. return $t['sec'] . str_pad($t['usec'], 6, '0');
  184. }
  185. function uSecString() {
  186. $t = @gettimeofday();
  187. return str_pad($t['usec'], 6, '0');
  188. }
  189. function invalidateHttpCache() {
  190. Minz_Session::_param('touch', uTimeString());
  191. return touch(LOG_PATH . '/' . Minz_Session::param('currentUser', '_') . '.log');
  192. }
  193. function usernameFromPath($userPath) {
  194. if (preg_match('%/([A-Za-z0-9]{1,16})_user\.php$%', $userPath, $matches)) {
  195. return $matches[1];
  196. } else {
  197. return '';
  198. }
  199. }
  200. function listUsers() {
  201. return array_map('usernameFromPath', glob(DATA_PATH . '/*_user.php'));
  202. }
  203. function httpAuthUser() {
  204. return isset($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'] : '';
  205. }
  206. function cryptAvailable() {
  207. if (version_compare(PHP_VERSION, '5.3.3', '>=')) {
  208. try {
  209. $hash = '$2y$04$usesomesillystringfore7hnbRJHxXVLeakoG8K30oukPsA.ztMG';
  210. return $hash === @crypt('password', $hash);
  211. } catch (Exception $e) {
  212. }
  213. }
  214. return false;
  215. }
  216. function is_referer_from_same_domain() {
  217. if (empty($_SERVER['HTTP_REFERER'])) {
  218. return false;
  219. }
  220. $host = parse_url(((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https://' : 'http://') .
  221. (empty($_SERVER['HTTP_HOST']) ? $_SERVER['SERVER_NAME'] : $_SERVER['HTTP_HOST']));
  222. $referer = parse_url($_SERVER['HTTP_REFERER']);
  223. if (empty($host['scheme']) || empty($referer['scheme']) || $host['scheme'] !== $referer['scheme'] ||
  224. empty($host['host']) || empty($referer['host']) || $host['host'] !== $referer['host']) {
  225. return false;
  226. }
  227. return (isset($host['port']) ? $host['port'] : 0) === (isset($referer['port']) ? $referer['port'] : 0);
  228. }
  229. /**
  230. * Check PHP and its extensions are well-installed.
  231. *
  232. * @return array of tested values.
  233. */
  234. function check_install_php() {
  235. return array(
  236. 'php' => version_compare(PHP_VERSION, '5.2.1') >= 0,
  237. 'minz' => file_exists(LIB_PATH . '/Minz'),
  238. 'curl' => extension_loaded('curl'),
  239. 'pdo_mysql' => extension_loaded('pdo_mysql'),
  240. 'pdo_sqlite' => extension_loaded('pdo_sqlite'),
  241. 'pdo' => extension_loaded('pdo_mysql') || extension_loaded('pdo_sqlite'),
  242. 'pcre' => extension_loaded('pcre'),
  243. 'ctype' => extension_loaded('ctype'),
  244. 'dom' => class_exists('DOMDocument'),
  245. 'json' => extension_loaded('json'),
  246. 'zip' => extension_loaded('zip'),
  247. );
  248. }
  249. /**
  250. * Check different data files and directories exist.
  251. *
  252. * @return array of tested values.
  253. */
  254. function check_install_files() {
  255. return array(
  256. 'data' => DATA_PATH && is_writable(DATA_PATH),
  257. 'cache' => CACHE_PATH && is_writable(CACHE_PATH),
  258. 'logs' => LOG_PATH && is_writable(LOG_PATH),
  259. 'favicons' => is_writable(DATA_PATH . '/favicons'),
  260. 'persona' => is_writable(DATA_PATH . '/persona'),
  261. 'tokens' => is_writable(DATA_PATH . '/tokens'),
  262. );
  263. }
  264. /**
  265. * Check database is well-installed.
  266. *
  267. * @return array of tested values.
  268. */
  269. function check_install_database() {
  270. $status = array(
  271. 'connection' => true,
  272. 'tables' => false,
  273. 'categories' => false,
  274. 'feeds' => false,
  275. 'entries' => false,
  276. );
  277. try {
  278. $dbDAO = FreshRSS_Factory::createDatabaseDAO();
  279. $status['tables'] = $dbDAO->tablesAreCorrect();
  280. $status['categories'] = $dbDAO->categoryIsCorrect();
  281. $status['feeds'] = $dbDAO->feedIsCorrect();
  282. $status['entries'] = $dbDAO->entryIsCorrect();
  283. } catch(Minz_PDOConnectionException $e) {
  284. $status['connection'] = false;
  285. }
  286. return $status;
  287. }