aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rwxr-xr-xinc/3rdparty/makefulltextfeed.php353
-rwxr-xr-xinc/3rdparty/makefulltextfeedHelpers.php355
2 files changed, 357 insertions, 351 deletions
diff --git a/inc/3rdparty/makefulltextfeed.php b/inc/3rdparty/makefulltextfeed.php
index 313397d2..b024547f 100755
--- a/inc/3rdparty/makefulltextfeed.php
+++ b/inc/3rdparty/makefulltextfeed.php
@@ -55,42 +55,8 @@ if (get_magic_quotes_gpc()) {
55 55
56// set include path 56// set include path
57set_include_path(realpath(dirname(__FILE__).'/libraries').PATH_SEPARATOR.get_include_path()); 57set_include_path(realpath(dirname(__FILE__).'/libraries').PATH_SEPARATOR.get_include_path());
58// Autoloading of classes allows us to include files only when they're 58
59// needed. If we've got a cached copy, for example, only Zend_Cache is loaded. 59require_once dirname(__FILE__).'/makefulltextfeedHelpers.php';
60function autoload($class_name) {
61 static $dir = null;
62 if ($dir === null) $dir = dirname(__FILE__).'/libraries/';
63 static $mapping = array(
64 // Include FeedCreator for RSS/Atom creation
65 'FeedWriter' => 'feedwriter/FeedWriter.php',
66 'FeedItem' => 'feedwriter/FeedItem.php',
67 // Include ContentExtractor and Readability for identifying and extracting content from URLs
68 'ContentExtractor' => 'content-extractor/ContentExtractor.php',
69 'SiteConfig' => 'content-extractor/SiteConfig.php',
70 'Readability' => 'readability/Readability.php',
71 // Include Humble HTTP Agent to allow parallel requests and response caching
72 'HumbleHttpAgent' => 'humble-http-agent/HumbleHttpAgent.php',
73 'SimplePie_HumbleHttpAgent' => 'humble-http-agent/SimplePie_HumbleHttpAgent.php',
74 'CookieJar' => 'humble-http-agent/CookieJar.php',
75 // Include Zend Cache to improve performance (cache results)
76 'Zend_Cache' => 'Zend/Cache.php',
77 // Language detect
78 'Text_LanguageDetect' => 'language-detect/LanguageDetect.php',
79 // HTML5 Lib
80 'HTML5_Parser' => 'html5/Parser.php',
81 // htmLawed - used if XSS filter is enabled (xss_filter)
82 'htmLawed' => 'htmLawed/htmLawed.php'
83 );
84 if (isset($mapping[$class_name])) {
85 debug("** Loading class $class_name ({$mapping[$class_name]})");
86 require $dir.$mapping[$class_name];
87 return true;
88 } else {
89 return false;
90 }
91}
92spl_autoload_register('autoload');
93require dirname(__FILE__).'/libraries/simplepie/autoloader.php';
94 60
95//////////////////////////////// 61////////////////////////////////
96// Load config file 62// Load config file
@@ -415,7 +381,6 @@ if (!$debug_mode) {
415////////////////////////////////// 381//////////////////////////////////
416// Set up HTTP agent 382// Set up HTTP agent
417////////////////////////////////// 383//////////////////////////////////
418global $http;
419$http = new HumbleHttpAgent(); 384$http = new HumbleHttpAgent();
420$http->debug = $debug_mode; 385$http->debug = $debug_mode;
421$http->userAgentMap = $options->user_agents; 386$http->userAgentMap = $options->user_agents;
@@ -479,29 +444,6 @@ if ($html_only || !$result) {
479 $isDummyFeed = true; 444 $isDummyFeed = true;
480 unset($feed, $result); 445 unset($feed, $result);
481 // create single item dummy feed object 446 // create single item dummy feed object
482 class DummySingleItemFeed {
483 public $item;
484 function __construct($url) { $this->item = new DummySingleItem($url); }
485 public function get_title() { return ''; }
486 public function get_description() { return 'Content extracted from '.$this->item->url; }
487 public function get_link() { return $this->item->url; }
488 public function get_language() { return false; }
489 public function get_image_url() { return false; }
490 public function get_items($start=0, $max=1) { return array(0=>$this->item); }
491 }
492 class DummySingleItem {
493 public $url;
494 function __construct($url) { $this->url = $url; }
495 public function get_permalink() { return $this->url; }
496 public function get_title() { return null; }
497 public function get_date($format='') { return false; }
498 public function get_author($key=0) { return null; }
499 public function get_authors() { return null; }
500 public function get_description() { return ''; }
501 public function get_enclosure($key=0, $prefer=null) { return null; }
502 public function get_enclosures() { return null; }
503 public function get_categories() { return null; }
504 }
505 $feed = new DummySingleItemFeed($url); 447 $feed = new DummySingleItemFeed($url);
506} 448}
507 449
@@ -904,294 +846,3 @@ if (!$debug_mode) {
904 if ($callback) echo ');'; 846 if ($callback) echo ');';
905} 847}
906 848
907///////////////////////////////
908// HELPER FUNCTIONS
909///////////////////////////////
910
911function url_allowed($url) {
912 global $options;
913 if (!empty($options->allowed_urls)) {
914 $allowed = false;
915 foreach ($options->allowed_urls as $allowurl) {
916 if (stristr($url, $allowurl) !== false) {
917 $allowed = true;
918 break;
919 }
920 }
921 if (!$allowed) return false;
922 } else {
923 foreach ($options->blocked_urls as $blockurl) {
924 if (stristr($url, $blockurl) !== false) {
925 return false;
926 }
927 }
928 }
929 return true;
930}
931
932//////////////////////////////////////////////
933// Convert $html to UTF8
934// (uses HTTP headers and HTML to find encoding)
935// adapted from http://stackoverflow.com/questions/910793/php-detect-encoding-and-make-everything-utf-8
936//////////////////////////////////////////////
937function convert_to_utf8($html, $header=null)
938{
939 $encoding = null;
940 if ($html || $header) {
941 if (is_array($header)) $header = implode("\n", $header);
942 if (!$header || !preg_match_all('/^Content-Type:\s+([^;]+)(?:;\s*charset=["\']?([^;"\'\n]*))?/im', $header, $match, PREG_SET_ORDER)) {
943 // error parsing the response
944 debug('Could not find Content-Type header in HTTP response');
945 } else {
946 $match = end($match); // get last matched element (in case of redirects)
947 if (isset($match[2])) $encoding = trim($match[2], "\"' \r\n\0\x0B\t");
948 }
949 // TODO: check to see if encoding is supported (can we convert it?)
950 // If it's not, result will be empty string.
951 // For now we'll check for invalid encoding types returned by some sites, e.g. 'none'
952 // Problem URL: http://facta.co.jp/blog/archives/20111026001026.html
953 if (!$encoding || $encoding == 'none') {
954 // search for encoding in HTML - only look at the first 50000 characters
955 // Why 50000? See, for example, http://www.lemonde.fr/festival-de-cannes/article/2012/05/23/deux-cretes-en-goguette-sur-la-croisette_1705732_766360.html
956 // TODO: improve this so it looks at smaller chunks first
957 $html_head = substr($html, 0, 50000);
958 if (preg_match('/^<\?xml\s+version=(?:"[^"]*"|\'[^\']*\')\s+encoding=("[^"]*"|\'[^\']*\')/s', $html_head, $match)) {
959 $encoding = trim($match[1], '"\'');
960 } elseif (preg_match('/<meta\s+http-equiv=["\']?Content-Type["\']? content=["\'][^;]+;\s*charset=["\']?([^;"\'>]+)/i', $html_head, $match)) {
961 $encoding = trim($match[1]);
962 } elseif (preg_match_all('/<meta\s+([^>]+)>/i', $html_head, $match)) {
963 foreach ($match[1] as $_test) {
964 if (preg_match('/charset=["\']?([^"\']+)/i', $_test, $_m)) {
965 $encoding = trim($_m[1]);
966 break;
967 }
968 }
969 }
970 }
971 if (isset($encoding)) $encoding = trim($encoding);
972 // trim is important here!
973 if (!$encoding || (strtolower($encoding) == 'iso-8859-1')) {
974 // replace MS Word smart qutoes
975 $trans = array();
976 $trans[chr(130)] = '&sbquo;'; // Single Low-9 Quotation Mark
977 $trans[chr(131)] = '&fnof;'; // Latin Small Letter F With Hook
978 $trans[chr(132)] = '&bdquo;'; // Double Low-9 Quotation Mark
979 $trans[chr(133)] = '&hellip;'; // Horizontal Ellipsis
980 $trans[chr(134)] = '&dagger;'; // Dagger
981 $trans[chr(135)] = '&Dagger;'; // Double Dagger
982 $trans[chr(136)] = '&circ;'; // Modifier Letter Circumflex Accent
983 $trans[chr(137)] = '&permil;'; // Per Mille Sign
984 $trans[chr(138)] = '&Scaron;'; // Latin Capital Letter S With Caron
985 $trans[chr(139)] = '&lsaquo;'; // Single Left-Pointing Angle Quotation Mark
986 $trans[chr(140)] = '&OElig;'; // Latin Capital Ligature OE
987 $trans[chr(145)] = '&lsquo;'; // Left Single Quotation Mark
988 $trans[chr(146)] = '&rsquo;'; // Right Single Quotation Mark
989 $trans[chr(147)] = '&ldquo;'; // Left Double Quotation Mark
990 $trans[chr(148)] = '&rdquo;'; // Right Double Quotation Mark
991 $trans[chr(149)] = '&bull;'; // Bullet
992 $trans[chr(150)] = '&ndash;'; // En Dash
993 $trans[chr(151)] = '&mdash;'; // Em Dash
994 $trans[chr(152)] = '&tilde;'; // Small Tilde
995 $trans[chr(153)] = '&trade;'; // Trade Mark Sign
996 $trans[chr(154)] = '&scaron;'; // Latin Small Letter S With Caron
997 $trans[chr(155)] = '&rsaquo;'; // Single Right-Pointing Angle Quotation Mark
998 $trans[chr(156)] = '&oelig;'; // Latin Small Ligature OE
999 $trans[chr(159)] = '&Yuml;'; // Latin Capital Letter Y With Diaeresis
1000 $html = strtr($html, $trans);
1001 }
1002 if (!$encoding) {
1003 debug('No character encoding found, so treating as UTF-8');
1004 $encoding = 'utf-8';
1005 } else {
1006 debug('Character encoding: '.$encoding);
1007 if (strtolower($encoding) != 'utf-8') {
1008 debug('Converting to UTF-8');
1009 $html = SimplePie_Misc::change_encoding($html, $encoding, 'utf-8');
1010 /*
1011 if (function_exists('iconv')) {
1012 // iconv appears to handle certain character encodings better than mb_convert_encoding
1013 $html = iconv($encoding, 'utf-8', $html);
1014 } else {
1015 $html = mb_convert_encoding($html, 'utf-8', $encoding);
1016 }
1017 */
1018 }
1019 }
1020 }
1021 return $html;
1022}
1023
1024function makeAbsolute($base, $elem) {
1025 $base = new SimplePie_IRI($base);
1026 // remove '//' in URL path (used to prevent URLs from resolving properly)
1027 // TODO: check if this is still the case
1028 if (isset($base->path)) $base->path = preg_replace('!//+!', '/', $base->path);
1029 foreach(array('a'=>'href', 'img'=>'src') as $tag => $attr) {
1030 $elems = $elem->getElementsByTagName($tag);
1031 for ($i = $elems->length-1; $i >= 0; $i--) {
1032 $e = $elems->item($i);
1033 //$e->parentNode->replaceChild($articleContent->ownerDocument->createTextNode($e->textContent), $e);
1034 makeAbsoluteAttr($base, $e, $attr);
1035 }
1036 if (strtolower($elem->tagName) == $tag) makeAbsoluteAttr($base, $elem, $attr);
1037 }
1038}
1039function makeAbsoluteAttr($base, $e, $attr) {
1040 if ($e->hasAttribute($attr)) {
1041 // Trim leading and trailing white space. I don't really like this but
1042 // unfortunately it does appear on some sites. e.g. <img src=" /path/to/image.jpg" />
1043 $url = trim(str_replace('%20', ' ', $e->getAttribute($attr)));
1044 $url = str_replace(' ', '%20', $url);
1045 if (!preg_match('!https?://!i', $url)) {
1046 if ($absolute = SimplePie_IRI::absolutize($base, $url)) {
1047 $e->setAttribute($attr, $absolute);
1048 }
1049 }
1050 }
1051}
1052function makeAbsoluteStr($base, $url) {
1053 $base = new SimplePie_IRI($base);
1054 // remove '//' in URL path (causes URLs not to resolve properly)
1055 if (isset($base->path)) $base->path = preg_replace('!//+!', '/', $base->path);
1056 if (preg_match('!^https?://!i', $url)) {
1057 // already absolute
1058 return $url;
1059 } else {
1060 if ($absolute = SimplePie_IRI::absolutize($base, $url)) {
1061 return $absolute;
1062 }
1063 return false;
1064 }
1065}
1066// returns single page response, or false if not found
1067function getSinglePage($item, $html, $url) {
1068 global $http, $extractor;
1069 debug('Looking for site config files to see if single page link exists');
1070 $site_config = $extractor->buildSiteConfig($url, $html);
1071 $splink = null;
1072 if (!empty($site_config->single_page_link)) {
1073 $splink = $site_config->single_page_link;
1074 } elseif (!empty($site_config->single_page_link_in_feed)) {
1075 // single page link xpath is targeted at feed
1076 $splink = $site_config->single_page_link_in_feed;
1077 // so let's replace HTML with feed item description
1078 $html = $item->get_description();
1079 }
1080 if (isset($splink)) {
1081 // Build DOM tree from HTML
1082 $readability = new Readability($html, $url);
1083 $xpath = new DOMXPath($readability->dom);
1084 // Loop through single_page_link xpath expressions
1085 $single_page_url = null;
1086 foreach ($splink as $pattern) {
1087 $elems = @$xpath->evaluate($pattern, $readability->dom);
1088 if (is_string($elems)) {
1089 $single_page_url = trim($elems);
1090 break;
1091 } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
1092 foreach ($elems as $item) {
1093 if ($item instanceof DOMElement && $item->hasAttribute('href')) {
1094 $single_page_url = $item->getAttribute('href');
1095 break 2;
1096 } elseif ($item instanceof DOMAttr && $item->value) {
1097 $single_page_url = $item->value;
1098 break 2;
1099 }
1100 }
1101 }
1102 }
1103 // If we've got URL, resolve against $url
1104 if (isset($single_page_url) && ($single_page_url = makeAbsoluteStr($url, $single_page_url))) {
1105 // check it's not what we have already!
1106 if ($single_page_url != $url) {
1107 // it's not, so let's try to fetch it...
1108 $_prev_ref = $http->referer;
1109 $http->referer = $single_page_url;
1110 if (($response = $http->get($single_page_url, true)) && $response['status_code'] < 300) {
1111 $http->referer = $_prev_ref;
1112 return $response;
1113 }
1114 $http->referer = $_prev_ref;
1115 }
1116 }
1117 }
1118 return false;
1119}
1120
1121// based on content-type http header, decide what to do
1122// param: HTTP headers string
1123// return: array with keys: 'mime', 'type', 'subtype', 'action', 'name'
1124// e.g. array('mime'=>'image/jpeg', 'type'=>'image', 'subtype'=>'jpeg', 'action'=>'link', 'name'=>'Image')
1125function get_mime_action_info($headers) {
1126 global $options;
1127 // check if action defined for returned Content-Type
1128 $info = array();
1129 if (preg_match('!^Content-Type:\s*(([-\w]+)/([-\w\+]+))!im', $headers, $match)) {
1130 // look for full mime type (e.g. image/jpeg) or just type (e.g. image)
1131 // match[1] = full mime type, e.g. image/jpeg
1132 // match[2] = first part, e.g. image
1133 // match[3] = last part, e.g. jpeg
1134 $info['mime'] = strtolower(trim($match[1]));
1135 $info['type'] = strtolower(trim($match[2]));
1136 $info['subtype'] = strtolower(trim($match[3]));
1137 foreach (array($info['mime'], $info['type']) as $_mime) {
1138 if (isset($options->content_type_exc[$_mime])) {
1139 $info['action'] = $options->content_type_exc[$_mime]['action'];
1140 $info['name'] = $options->content_type_exc[$_mime]['name'];
1141 break;
1142 }
1143 }
1144 }
1145 return $info;
1146}
1147
1148function remove_url_cruft($url) {
1149 // remove google analytics for the time being
1150 // regex adapted from http://navitronic.co.uk/2010/12/removing-google-analytics-cruft-from-urls/
1151 // https://gist.github.com/758177
1152 return preg_replace('/(\?|\&)utm_[a-z]+=[^\&]+/', '', $url);
1153}
1154
1155function make_substitutions($string) {
1156 if ($string == '') return $string;
1157 global $item, $effective_url;
1158 $string = str_replace('{url}', htmlspecialchars($item->get_permalink()), $string);
1159 $string = str_replace('{effective-url}', htmlspecialchars($effective_url), $string);
1160 return $string;
1161}
1162
1163function get_cache() {
1164 global $options, $valid_key;
1165 static $cache = null;
1166 if ($cache === null) {
1167 $frontendOptions = array(
1168 'lifetime' => 10*60, // cache lifetime of 10 minutes
1169 'automatic_serialization' => false,
1170 'write_control' => false,
1171 'automatic_cleaning_factor' => $options->cache_cleanup,
1172 'ignore_user_abort' => false
1173 );
1174 $backendOptions = array(
1175 'cache_dir' => ($valid_key) ? $options->cache_dir.'/rss-with-key/' : $options->cache_dir.'/rss/', // directory where to put the cache files
1176 'file_locking' => false,
1177 'read_control' => true,
1178 'read_control_type' => 'strlen',
1179 'hashed_directory_level' => $options->cache_directory_level,
1180 'hashed_directory_perm' => 0777,
1181 'cache_file_perm' => 0664,
1182 'file_name_prefix' => 'ff'
1183 );
1184 // getting a Zend_Cache_Core object
1185 $cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
1186 }
1187 return $cache;
1188}
1189
1190function debug($msg) {
1191 global $debug_mode;
1192 if ($debug_mode) {
1193 echo '* ',$msg,"\n";
1194 ob_flush();
1195 flush();
1196 }
1197} \ No newline at end of file
diff --git a/inc/3rdparty/makefulltextfeedHelpers.php b/inc/3rdparty/makefulltextfeedHelpers.php
new file mode 100755
index 00000000..1c11b8f6
--- /dev/null
+++ b/inc/3rdparty/makefulltextfeedHelpers.php
@@ -0,0 +1,355 @@
1<?php
2
3// Autoloading of classes allows us to include files only when they're
4// needed. If we've got a cached copy, for example, only Zend_Cache is loaded.
5function autoload($class_name) {
6 static $dir = null;
7 if ($dir === null) $dir = dirname(__FILE__).'/libraries/';
8 static $mapping = array(
9 // Include FeedCreator for RSS/Atom creation
10 'FeedWriter' => 'feedwriter/FeedWriter.php',
11 'FeedItem' => 'feedwriter/FeedItem.php',
12 // Include ContentExtractor and Readability for identifying and extracting content from URLs
13 'ContentExtractor' => 'content-extractor/ContentExtractor.php',
14 'SiteConfig' => 'content-extractor/SiteConfig.php',
15 'Readability' => 'readability/Readability.php',
16 // Include Humble HTTP Agent to allow parallel requests and response caching
17 'HumbleHttpAgent' => 'humble-http-agent/HumbleHttpAgent.php',
18 'SimplePie_HumbleHttpAgent' => 'humble-http-agent/SimplePie_HumbleHttpAgent.php',
19 'CookieJar' => 'humble-http-agent/CookieJar.php',
20 // Include Zend Cache to improve performance (cache results)
21 'Zend_Cache' => 'Zend/Cache.php',
22 // Language detect
23 'Text_LanguageDetect' => 'language-detect/LanguageDetect.php',
24 // HTML5 Lib
25 'HTML5_Parser' => 'html5/Parser.php',
26 // htmLawed - used if XSS filter is enabled (xss_filter)
27 'htmLawed' => 'htmLawed/htmLawed.php'
28 );
29 if (isset($mapping[$class_name])) {
30 debug("** Loading class $class_name ({$mapping[$class_name]})");
31 require $dir.$mapping[$class_name];
32 return true;
33 } else {
34 return false;
35 }
36}
37spl_autoload_register('autoload');
38require dirname(__FILE__).'/libraries/simplepie/autoloader.php';
39
40
41class DummySingleItemFeed {
42 public $item;
43 function __construct($url) { $this->item = new DummySingleItem($url); }
44 public function get_title() { return ''; }
45 public function get_description() { return 'Content extracted from '.$this->item->url; }
46 public function get_link() { return $this->item->url; }
47 public function get_language() { return false; }
48 public function get_image_url() { return false; }
49 public function get_items($start=0, $max=1) { return array(0=>$this->item); }
50}
51class DummySingleItem {
52 public $url;
53 function __construct($url) { $this->url = $url; }
54 public function get_permalink() { return $this->url; }
55 public function get_title() { return null; }
56 public function get_date($format='') { return false; }
57 public function get_author($key=0) { return null; }
58 public function get_authors() { return null; }
59 public function get_description() { return ''; }
60 public function get_enclosure($key=0, $prefer=null) { return null; }
61 public function get_enclosures() { return null; }
62 public function get_categories() { return null; }
63}
64
65///////////////////////////////
66// HELPER FUNCTIONS
67///////////////////////////////
68
69function url_allowed($url) {
70 global $options;
71 if (!empty($options->allowed_urls)) {
72 $allowed = false;
73 foreach ($options->allowed_urls as $allowurl) {
74 if (stristr($url, $allowurl) !== false) {
75 $allowed = true;
76 break;
77 }
78 }
79 if (!$allowed) return false;
80 } else {
81 foreach ($options->blocked_urls as $blockurl) {
82 if (stristr($url, $blockurl) !== false) {
83 return false;
84 }
85 }
86 }
87 return true;
88}
89
90//////////////////////////////////////////////
91// Convert $html to UTF8
92// (uses HTTP headers and HTML to find encoding)
93// adapted from http://stackoverflow.com/questions/910793/php-detect-encoding-and-make-everything-utf-8
94//////////////////////////////////////////////
95function convert_to_utf8($html, $header=null)
96{
97 $encoding = null;
98 if ($html || $header) {
99 if (is_array($header)) $header = implode("\n", $header);
100 if (!$header || !preg_match_all('/^Content-Type:\s+([^;]+)(?:;\s*charset=["\']?([^;"\'\n]*))?/im', $header, $match, PREG_SET_ORDER)) {
101 // error parsing the response
102 debug('Could not find Content-Type header in HTTP response');
103 } else {
104 $match = end($match); // get last matched element (in case of redirects)
105 if (isset($match[2])) $encoding = trim($match[2], "\"' \r\n\0\x0B\t");
106 }
107 // TODO: check to see if encoding is supported (can we convert it?)
108 // If it's not, result will be empty string.
109 // For now we'll check for invalid encoding types returned by some sites, e.g. 'none'
110 // Problem URL: http://facta.co.jp/blog/archives/20111026001026.html
111 if (!$encoding || $encoding == 'none') {
112 // search for encoding in HTML - only look at the first 50000 characters
113 // Why 50000? See, for example, http://www.lemonde.fr/festival-de-cannes/article/2012/05/23/deux-cretes-en-goguette-sur-la-croisette_1705732_766360.html
114 // TODO: improve this so it looks at smaller chunks first
115 $html_head = substr($html, 0, 50000);
116 if (preg_match('/^<\?xml\s+version=(?:"[^"]*"|\'[^\']*\')\s+encoding=("[^"]*"|\'[^\']*\')/s', $html_head, $match)) {
117 $encoding = trim($match[1], '"\'');
118 } elseif (preg_match('/<meta\s+http-equiv=["\']?Content-Type["\']? content=["\'][^;]+;\s*charset=["\']?([^;"\'>]+)/i', $html_head, $match)) {
119 $encoding = trim($match[1]);
120 } elseif (preg_match_all('/<meta\s+([^>]+)>/i', $html_head, $match)) {
121 foreach ($match[1] as $_test) {
122 if (preg_match('/charset=["\']?([^"\']+)/i', $_test, $_m)) {
123 $encoding = trim($_m[1]);
124 break;
125 }
126 }
127 }
128 }
129 if (isset($encoding)) $encoding = trim($encoding);
130 // trim is important here!
131 if (!$encoding || (strtolower($encoding) == 'iso-8859-1')) {
132 // replace MS Word smart qutoes
133 $trans = array();
134 $trans[chr(130)] = '&sbquo;'; // Single Low-9 Quotation Mark
135 $trans[chr(131)] = '&fnof;'; // Latin Small Letter F With Hook
136 $trans[chr(132)] = '&bdquo;'; // Double Low-9 Quotation Mark
137 $trans[chr(133)] = '&hellip;'; // Horizontal Ellipsis
138 $trans[chr(134)] = '&dagger;'; // Dagger
139 $trans[chr(135)] = '&Dagger;'; // Double Dagger
140 $trans[chr(136)] = '&circ;'; // Modifier Letter Circumflex Accent
141 $trans[chr(137)] = '&permil;'; // Per Mille Sign
142 $trans[chr(138)] = '&Scaron;'; // Latin Capital Letter S With Caron
143 $trans[chr(139)] = '&lsaquo;'; // Single Left-Pointing Angle Quotation Mark
144 $trans[chr(140)] = '&OElig;'; // Latin Capital Ligature OE
145 $trans[chr(145)] = '&lsquo;'; // Left Single Quotation Mark
146 $trans[chr(146)] = '&rsquo;'; // Right Single Quotation Mark
147 $trans[chr(147)] = '&ldquo;'; // Left Double Quotation Mark
148 $trans[chr(148)] = '&rdquo;'; // Right Double Quotation Mark
149 $trans[chr(149)] = '&bull;'; // Bullet
150 $trans[chr(150)] = '&ndash;'; // En Dash
151 $trans[chr(151)] = '&mdash;'; // Em Dash
152 $trans[chr(152)] = '&tilde;'; // Small Tilde
153 $trans[chr(153)] = '&trade;'; // Trade Mark Sign
154 $trans[chr(154)] = '&scaron;'; // Latin Small Letter S With Caron
155 $trans[chr(155)] = '&rsaquo;'; // Single Right-Pointing Angle Quotation Mark
156 $trans[chr(156)] = '&oelig;'; // Latin Small Ligature OE
157 $trans[chr(159)] = '&Yuml;'; // Latin Capital Letter Y With Diaeresis
158 $html = strtr($html, $trans);
159 }
160 if (!$encoding) {
161 debug('No character encoding found, so treating as UTF-8');
162 $encoding = 'utf-8';
163 } else {
164 debug('Character encoding: '.$encoding);
165 if (strtolower($encoding) != 'utf-8') {
166 debug('Converting to UTF-8');
167 $html = SimplePie_Misc::change_encoding($html, $encoding, 'utf-8');
168 /*
169 if (function_exists('iconv')) {
170 // iconv appears to handle certain character encodings better than mb_convert_encoding
171 $html = iconv($encoding, 'utf-8', $html);
172 } else {
173 $html = mb_convert_encoding($html, 'utf-8', $encoding);
174 }
175 */
176 }
177 }
178 }
179 return $html;
180}
181
182function makeAbsolute($base, $elem) {
183 $base = new SimplePie_IRI($base);
184 // remove '//' in URL path (used to prevent URLs from resolving properly)
185 // TODO: check if this is still the case
186 if (isset($base->path)) $base->path = preg_replace('!//+!', '/', $base->path);
187 foreach(array('a'=>'href', 'img'=>'src') as $tag => $attr) {
188 $elems = $elem->getElementsByTagName($tag);
189 for ($i = $elems->length-1; $i >= 0; $i--) {
190 $e = $elems->item($i);
191 //$e->parentNode->replaceChild($articleContent->ownerDocument->createTextNode($e->textContent), $e);
192 makeAbsoluteAttr($base, $e, $attr);
193 }
194 if (strtolower($elem->tagName) == $tag) makeAbsoluteAttr($base, $elem, $attr);
195 }
196}
197function makeAbsoluteAttr($base, $e, $attr) {
198 if ($e->hasAttribute($attr)) {
199 // Trim leading and trailing white space. I don't really like this but
200 // unfortunately it does appear on some sites. e.g. <img src=" /path/to/image.jpg" />
201 $url = trim(str_replace('%20', ' ', $e->getAttribute($attr)));
202 $url = str_replace(' ', '%20', $url);
203 if (!preg_match('!https?://!i', $url)) {
204 if ($absolute = SimplePie_IRI::absolutize($base, $url)) {
205 $e->setAttribute($attr, $absolute);
206 }
207 }
208 }
209}
210function makeAbsoluteStr($base, $url) {
211 $base = new SimplePie_IRI($base);
212 // remove '//' in URL path (causes URLs not to resolve properly)
213 if (isset($base->path)) $base->path = preg_replace('!//+!', '/', $base->path);
214 if (preg_match('!^https?://!i', $url)) {
215 // already absolute
216 return $url;
217 } else {
218 if ($absolute = SimplePie_IRI::absolutize($base, $url)) {
219 return $absolute;
220 }
221 return false;
222 }
223}
224// returns single page response, or false if not found
225function getSinglePage($item, $html, $url) {
226 global $http, $extractor;
227 debug('Looking for site config files to see if single page link exists');
228 $site_config = $extractor->buildSiteConfig($url, $html);
229 $splink = null;
230 if (!empty($site_config->single_page_link)) {
231 $splink = $site_config->single_page_link;
232 } elseif (!empty($site_config->single_page_link_in_feed)) {
233 // single page link xpath is targeted at feed
234 $splink = $site_config->single_page_link_in_feed;
235 // so let's replace HTML with feed item description
236 $html = $item->get_description();
237 }
238 if (isset($splink)) {
239 // Build DOM tree from HTML
240 $readability = new Readability($html, $url);
241 $xpath = new DOMXPath($readability->dom);
242 // Loop through single_page_link xpath expressions
243 $single_page_url = null;
244 foreach ($splink as $pattern) {
245 $elems = @$xpath->evaluate($pattern, $readability->dom);
246 if (is_string($elems)) {
247 $single_page_url = trim($elems);
248 break;
249 } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
250 foreach ($elems as $item) {
251 if ($item instanceof DOMElement && $item->hasAttribute('href')) {
252 $single_page_url = $item->getAttribute('href');
253 break 2;
254 } elseif ($item instanceof DOMAttr && $item->value) {
255 $single_page_url = $item->value;
256 break 2;
257 }
258 }
259 }
260 }
261 // If we've got URL, resolve against $url
262 if (isset($single_page_url) && ($single_page_url = makeAbsoluteStr($url, $single_page_url))) {
263 // check it's not what we have already!
264 if ($single_page_url != $url) {
265 // it's not, so let's try to fetch it...
266 $_prev_ref = $http->referer;
267 $http->referer = $single_page_url;
268 if (($response = $http->get($single_page_url, true)) && $response['status_code'] < 300) {
269 $http->referer = $_prev_ref;
270 return $response;
271 }
272 $http->referer = $_prev_ref;
273 }
274 }
275 }
276 return false;
277}
278
279// based on content-type http header, decide what to do
280// param: HTTP headers string
281// return: array with keys: 'mime', 'type', 'subtype', 'action', 'name'
282// e.g. array('mime'=>'image/jpeg', 'type'=>'image', 'subtype'=>'jpeg', 'action'=>'link', 'name'=>'Image')
283function get_mime_action_info($headers) {
284 global $options;
285 // check if action defined for returned Content-Type
286 $info = array();
287 if (preg_match('!^Content-Type:\s*(([-\w]+)/([-\w\+]+))!im', $headers, $match)) {
288 // look for full mime type (e.g. image/jpeg) or just type (e.g. image)
289 // match[1] = full mime type, e.g. image/jpeg
290 // match[2] = first part, e.g. image
291 // match[3] = last part, e.g. jpeg
292 $info['mime'] = strtolower(trim($match[1]));
293 $info['type'] = strtolower(trim($match[2]));
294 $info['subtype'] = strtolower(trim($match[3]));
295 foreach (array($info['mime'], $info['type']) as $_mime) {
296 if (isset($options->content_type_exc[$_mime])) {
297 $info['action'] = $options->content_type_exc[$_mime]['action'];
298 $info['name'] = $options->content_type_exc[$_mime]['name'];
299 break;
300 }
301 }
302 }
303 return $info;
304}
305
306function remove_url_cruft($url) {
307 // remove google analytics for the time being
308 // regex adapted from http://navitronic.co.uk/2010/12/removing-google-analytics-cruft-from-urls/
309 // https://gist.github.com/758177
310 return preg_replace('/(\?|\&)utm_[a-z]+=[^\&]+/', '', $url);
311}
312
313function make_substitutions($string) {
314 if ($string == '') return $string;
315 global $item, $effective_url;
316 $string = str_replace('{url}', htmlspecialchars($item->get_permalink()), $string);
317 $string = str_replace('{effective-url}', htmlspecialchars($effective_url), $string);
318 return $string;
319}
320
321function get_cache() {
322 global $options, $valid_key;
323 static $cache = null;
324 if ($cache === null) {
325 $frontendOptions = array(
326 'lifetime' => 10*60, // cache lifetime of 10 minutes
327 'automatic_serialization' => false,
328 'write_control' => false,
329 'automatic_cleaning_factor' => $options->cache_cleanup,
330 'ignore_user_abort' => false
331 );
332 $backendOptions = array(
333 'cache_dir' => ($valid_key) ? $options->cache_dir.'/rss-with-key/' : $options->cache_dir.'/rss/', // directory where to put the cache files
334 'file_locking' => false,
335 'read_control' => true,
336 'read_control_type' => 'strlen',
337 'hashed_directory_level' => $options->cache_directory_level,
338 'hashed_directory_perm' => 0777,
339 'cache_file_perm' => 0664,
340 'file_name_prefix' => 'ff'
341 );
342 // getting a Zend_Cache_Core object
343 $cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
344 }
345 return $cache;
346}
347
348function debug($msg) {
349 global $debug_mode;
350 if ($debug_mode) {
351 echo '* ',$msg,"\n";
352 ob_flush();
353 flush();
354 }
355}