lib_rss.php 9.5 KB

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