]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/3rdparty/makefulltextfeed.php
Full-Text RSS included as a script instead of file_get_contents call. Tnx to @Faless...
[github/wallabag/wallabag.git] / inc / 3rdparty / makefulltextfeed.php
1 <?php
2 // Full-Text RSS: Create Full-Text Feeds
3 // Author: Keyvan Minoukadeh
4 // Copyright (c) 2013 Keyvan Minoukadeh
5 // License: AGPLv3
6 // Version: 3.1
7 // Date: 2013-03-05
8 // More info: http://fivefilters.org/content-only/
9 // Help: http://help.fivefilters.org
10
11 /*
12 This program is free software: you can redistribute it and/or modify
13 it under the terms of the GNU Affero General Public License as published by
14 the Free Software Foundation, either version 3 of the License, or
15 (at your option) any later version.
16
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU Affero General Public License for more details.
21
22 You should have received a copy of the GNU Affero General Public License
23 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 */
25
26 // Usage
27 // -----
28 // Request this file passing it your feed in the querystring: makefulltextfeed.php?url=mysite.org
29 // The following options can be passed in the querystring:
30 // * URL: url=[feed or website url] (required, should be URL-encoded - in php: urlencode($url))
31 // * URL points to HTML (not feed): html=true (optional, by default it's automatically detected)
32 // * API key: key=[api key] (optional, refer to config.php)
33 // * Max entries to process: max=[max number of items] (optional)
34
35 error_reporting(E_ALL ^ E_NOTICE);
36 ini_set("display_errors", 1);
37 @set_time_limit(120);
38
39 // Deal with magic quotes
40 if (get_magic_quotes_gpc()) {
41 $process = array(&$_GET, &$_POST, &$_REQUEST);
42 while (list($key, $val) = each($process)) {
43 foreach ($val as $k => $v) {
44 unset($process[$key][$k]);
45 if (is_array($v)) {
46 $process[$key][stripslashes($k)] = $v;
47 $process[] = &$process[$key][stripslashes($k)];
48 } else {
49 $process[$key][stripslashes($k)] = stripslashes($v);
50 }
51 }
52 }
53 unset($process);
54 }
55
56 // set include path
57 set_include_path(realpath(dirname(__FILE__).'/libraries').PATH_SEPARATOR.get_include_path());
58 // Autoloading of classes allows us to include files only when they're
59 // needed. If we've got a cached copy, for example, only Zend_Cache is loaded.
60 function 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 }
92 spl_autoload_register('autoload');
93 require dirname(__FILE__).'/libraries/simplepie/autoloader.php';
94
95 ////////////////////////////////
96 // Load config file
97 ////////////////////////////////
98 require dirname(__FILE__).'/config.php';
99
100 ////////////////////////////////
101 // Prevent indexing/following by search engines because:
102 // 1. The content is already public and presumably indexed (why create duplicates?)
103 // 2. Not doing so might increase number of requests from search engines, thus increasing server load
104 // Note: feed readers and services such as Yahoo Pipes will not be affected by this header.
105 // Note: Using Disallow in a robots.txt file will be more effective (search engines will check
106 // that before even requesting makefulltextfeed.php).
107 ////////////////////////////////
108 header('X-Robots-Tag: noindex, nofollow');
109
110 ////////////////////////////////
111 // Check if service is enabled
112 ////////////////////////////////
113 if (!$options->enabled) {
114 die('The full-text RSS service is currently disabled');
115 }
116
117 ////////////////////////////////
118 // Debug mode?
119 // See the config file for debug options.
120 ////////////////////////////////
121 $debug_mode = false;
122 if (isset($_GET['debug'])) {
123 if ($options->debug === true || $options->debug == 'user') {
124 $debug_mode = true;
125 } elseif ($options->debug == 'admin') {
126 session_start();
127 $debug_mode = (@$_SESSION['auth'] == 1);
128 }
129 if ($debug_mode) {
130 header('Content-Type: text/plain; charset=utf-8');
131 } else {
132 if ($options->debug == 'admin') {
133 die('You must be logged in to the <a href="admin/">admin area</a> to see debug output.');
134 } else {
135 die('Debugging is disabled.');
136 }
137 }
138 }
139
140 ////////////////////////////////
141 // Check for APC
142 ////////////////////////////////
143 $options->apc = $options->apc && function_exists('apc_add');
144 if ($options->apc) {
145 debug('APC is enabled and available on server');
146 } else {
147 debug('APC is disabled or not available on server');
148 }
149
150 ////////////////////////////////
151 // Check for smart cache
152 ////////////////////////////////
153 $options->smart_cache = $options->smart_cache && function_exists('apc_inc');
154
155 ////////////////////////////////
156 // Check for feed URL
157 ////////////////////////////////
158 if (!isset($_GET['url'])) {
159 die('No URL supplied');
160 }
161 $url = trim($_GET['url']);
162 if (strtolower(substr($url, 0, 7)) == 'feed://') {
163 $url = 'http://'.substr($url, 7);
164 }
165 if (!preg_match('!^https?://.+!i', $url)) {
166 $url = 'http://'.$url;
167 }
168
169 $url = filter_var($url, FILTER_SANITIZE_URL);
170 $test = filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED);
171 // deal with bug http://bugs.php.net/51192 (present in PHP 5.2.13 and PHP 5.3.2)
172 if ($test === false) {
173 $test = filter_var(strtr($url, '-', '_'), FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED);
174 }
175 if ($test !== false && $test !== null && preg_match('!^https?://!', $url)) {
176 // all okay
177 unset($test);
178 } else {
179 die('Invalid URL supplied');
180 }
181 debug("Supplied URL: $url");
182
183 /////////////////////////////////
184 // Redirect to hide API key
185 /////////////////////////////////
186 if (isset($_GET['key']) && ($key_index = array_search($_GET['key'], $options->api_keys)) !== false) {
187 $host = $_SERVER['HTTP_HOST'];
188 $path = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
189 $_qs_url = (strtolower(substr($url, 0, 7)) == 'http://') ? substr($url, 7) : $url;
190 $redirect = 'http://'.htmlspecialchars($host.$path).'/makefulltextfeed.php?url='.urlencode($_qs_url);
191 $redirect .= '&key='.$key_index;
192 $redirect .= '&hash='.urlencode(sha1($_GET['key'].$url));
193 if (isset($_GET['html'])) $redirect .= '&html='.urlencode($_GET['html']);
194 if (isset($_GET['max'])) $redirect .= '&max='.(int)$_GET['max'];
195 if (isset($_GET['links'])) $redirect .= '&links='.urlencode($_GET['links']);
196 if (isset($_GET['exc'])) $redirect .= '&exc='.urlencode($_GET['exc']);
197 if (isset($_GET['format'])) $redirect .= '&format='.urlencode($_GET['format']);
198 if (isset($_GET['callback'])) $redirect .= '&callback='.urlencode($_GET['callback']);
199 if (isset($_GET['l'])) $redirect .= '&l='.urlencode($_GET['l']);
200 if (isset($_GET['xss'])) $redirect .= '&xss';
201 if (isset($_GET['use_extracted_title'])) $redirect .= '&use_extracted_title';
202 if (isset($_GET['debug'])) $redirect .= '&debug';
203 if ($debug_mode) {
204 debug('Redirecting to hide access key, follow URL below to continue');
205 debug("Location: $redirect");
206 } else {
207 header("Location: $redirect");
208 }
209 exit;
210 }
211
212 ///////////////////////////////////////////////
213 // Set timezone.
214 // Prevents warnings, but needs more testing -
215 // perhaps if timezone is set in php.ini we
216 // don't need to set it at all...
217 ///////////////////////////////////////////////
218 if (!ini_get('date.timezone') || !@date_default_timezone_set(ini_get('date.timezone'))) {
219 date_default_timezone_set('UTC');
220 }
221
222 ///////////////////////////////////////////////
223 // Check if the request is explicitly for an HTML page
224 ///////////////////////////////////////////////
225 $html_only = (isset($_GET['html']) && ($_GET['html'] == '1' || $_GET['html'] == 'true'));
226
227 ///////////////////////////////////////////////
228 // Check if valid key supplied
229 ///////////////////////////////////////////////
230 $valid_key = false;
231 if (isset($_GET['key']) && isset($_GET['hash']) && isset($options->api_keys[(int)$_GET['key']])) {
232 $valid_key = ($_GET['hash'] == sha1($options->api_keys[(int)$_GET['key']].$url));
233 }
234 $key_index = ($valid_key) ? (int)$_GET['key'] : 0;
235 if (!$valid_key && $options->key_required) {
236 die('A valid key must be supplied');
237 }
238 if (!$valid_key && isset($_GET['key']) && $_GET['key'] != '') {
239 die('The entered key is invalid');
240 }
241
242 if (file_exists('custom_init.php')) require 'custom_init.php';
243
244 ///////////////////////////////////////////////
245 // Check URL against list of blacklisted URLs
246 ///////////////////////////////////////////////
247 if (!url_allowed($url)) die('URL blocked');
248
249 ///////////////////////////////////////////////
250 // Max entries
251 // see config.php to find these values
252 ///////////////////////////////////////////////
253 if (isset($_GET['max'])) {
254 $max = (int)$_GET['max'];
255 if ($valid_key) {
256 $max = min($max, $options->max_entries_with_key);
257 } else {
258 $max = min($max, $options->max_entries);
259 }
260 } else {
261 if ($valid_key) {
262 $max = $options->default_entries_with_key;
263 } else {
264 $max = $options->default_entries;
265 }
266 }
267
268 ///////////////////////////////////////////////
269 // Link handling
270 ///////////////////////////////////////////////
271 if (isset($_GET['links']) && in_array($_GET['links'], array('preserve', 'footnotes', 'remove'))) {
272 $links = $_GET['links'];
273 } else {
274 $links = 'preserve';
275 }
276
277 ///////////////////////////////////////////////
278 // Favour item titles in feed?
279 ///////////////////////////////////////////////
280 $favour_feed_titles = true;
281 if ($options->favour_feed_titles == 'user') {
282 $favour_feed_titles = !isset($_GET['use_extracted_title']);
283 } else {
284 $favour_feed_titles = $options->favour_feed_titles;
285 }
286
287 ///////////////////////////////////////////////
288 // Exclude items if extraction fails
289 ///////////////////////////////////////////////
290 if ($options->exclude_items_on_fail === 'user') {
291 $exclude_on_fail = (isset($_GET['exc']) && ($_GET['exc'] == '1'));
292 } else {
293 $exclude_on_fail = $options->exclude_items_on_fail;
294 }
295
296 ///////////////////////////////////////////////
297 // Detect language
298 ///////////////////////////////////////////////
299 if ($options->detect_language === 'user') {
300 if (isset($_GET['l'])) {
301 $detect_language = (int)$_GET['l'];
302 } else {
303 $detect_language = 1;
304 }
305 } else {
306 $detect_language = $options->detect_language;
307 }
308
309 if ($detect_language >= 2) {
310 $language_codes = array('albanian' => 'sq','arabic' => 'ar','azeri' => 'az','bengali' => 'bn','bulgarian' => 'bg',
311 'cebuano' => 'ceb', // ISO 639-2
312 'croatian' => 'hr','czech' => 'cs','danish' => 'da','dutch' => 'nl','english' => 'en','estonian' => 'et','farsi' => 'fa','finnish' => 'fi','french' => 'fr','german' => 'de','hausa' => 'ha',
313 'hawaiian' => 'haw', // ISO 639-2
314 'hindi' => 'hi','hungarian' => 'hu','icelandic' => 'is','indonesian' => 'id','italian' => 'it','kazakh' => 'kk','kyrgyz' => 'ky','latin' => 'la','latvian' => 'lv','lithuanian' => 'lt','macedonian' => 'mk','mongolian' => 'mn','nepali' => 'ne','norwegian' => 'no','pashto' => 'ps',
315 'pidgin' => 'cpe', // ISO 639-2
316 'polish' => 'pl','portuguese' => 'pt','romanian' => 'ro','russian' => 'ru','serbian' => 'sr','slovak' => 'sk','slovene' => 'sl','somali' => 'so','spanish' => 'es','swahili' => 'sw','swedish' => 'sv','tagalog' => 'tl','turkish' => 'tr','ukrainian' => 'uk','urdu' => 'ur','uzbek' => 'uz','vietnamese' => 'vi','welsh' => 'cy');
317 }
318 $use_cld = extension_loaded('cld') && (version_compare(PHP_VERSION, '5.3.0') >= 0);
319
320 /////////////////////////////////////
321 // Check for valid format
322 // (stick to RSS (or RSS as JSON) for the time being)
323 /////////////////////////////////////
324 if (isset($_GET['format']) && $_GET['format'] == 'json') {
325 $format = 'json';
326 } else {
327 $format = 'rss';
328 }
329
330 /////////////////////////////////////
331 // Should we do XSS filtering?
332 /////////////////////////////////////
333 if ($options->xss_filter === 'user') {
334 $xss_filter = isset($_GET['xss']);
335 } else {
336 $xss_filter = $options->xss_filter;
337 }
338 if (!$xss_filter && isset($_GET['xss'])) {
339 die('XSS filtering is disabled in config');
340 }
341
342 /////////////////////////////////////
343 // Check for JSONP
344 // Regex from https://gist.github.com/1217080
345 /////////////////////////////////////
346 $callback = null;
347 if ($format =='json' && isset($_GET['callback'])) {
348 $callback = trim($_GET['callback']);
349 foreach (explode('.', $callback) as $_identifier) {
350 if (!preg_match('/^[a-zA-Z_$][0-9a-zA-Z_$]*(?:\[(?:".+"|\'.+\'|\d+)\])*?$/', $_identifier)) {
351 die('Invalid JSONP callback');
352 }
353 }
354 debug("JSONP callback: $callback");
355 }
356
357 //////////////////////////////////
358 // Enable Cross-Origin Resource Sharing (CORS)
359 //////////////////////////////////
360 if ($options->cors) header('Access-Control-Allow-Origin: *');
361
362 //////////////////////////////////
363 // Check for cached copy
364 //////////////////////////////////
365 if ($options->caching) {
366 debug('Caching is enabled...');
367 $cache_id = md5($max.$url.$valid_key.$links.$favour_feed_titles.$xss_filter.$exclude_on_fail.$format.$detect_language.(int)isset($_GET['pubsub']));
368 $check_cache = true;
369 if ($options->apc && $options->smart_cache) {
370 apc_add("cache.$cache_id", 0, 10*60);
371 $apc_cache_hits = (int)apc_fetch("cache.$cache_id");
372 $check_cache = ($apc_cache_hits >= 2);
373 apc_inc("cache.$cache_id");
374 if ($check_cache) {
375 debug('Cache key found in APC, we\'ll try to load cache file from disk');
376 } else {
377 debug('Cache key not found in APC');
378 }
379 }
380 if ($check_cache) {
381 $cache = get_cache();
382 if ($data = $cache->load($cache_id)) {
383 if ($debug_mode) {
384 debug('Loaded cached copy');
385 exit;
386 }
387 if ($format == 'json') {
388 if ($callback === null) {
389 header('Content-type: application/json; charset=UTF-8');
390 } else {
391 header('Content-type: application/javascript; charset=UTF-8');
392 }
393 } else {
394 header('Content-type: text/xml; charset=UTF-8');
395 header('X-content-type-options: nosniff');
396 }
397 if (headers_sent()) die('Some data has already been output, can\'t send RSS file');
398 if ($callback) {
399 echo "$callback($data);";
400 } else {
401 echo $data;
402 }
403 exit;
404 }
405 }
406 }
407
408 //////////////////////////////////
409 // Set Expires header
410 //////////////////////////////////
411 if (!$debug_mode) {
412 header('Expires: ' . gmdate('D, d M Y H:i:s', time()+(60*10)) . ' GMT');
413 }
414
415 //////////////////////////////////
416 // Set up HTTP agent
417 //////////////////////////////////
418 $http = new HumbleHttpAgent();
419 $http->debug = $debug_mode;
420 $http->userAgentMap = $options->user_agents;
421 $http->headerOnlyTypes = array_keys($options->content_type_exc);
422 $http->rewriteUrls = $options->rewrite_url;
423
424 //////////////////////////////////
425 // Set up Content Extractor
426 //////////////////////////////////
427 global $extractor;
428 $extractor = new ContentExtractor(dirname(__FILE__).'/site_config/custom', dirname(__FILE__).'/site_config/standard');
429 $extractor->debug = $debug_mode;
430 SiteConfig::$debug = $debug_mode;
431 SiteConfig::use_apc($options->apc);
432 $extractor->fingerprints = $options->fingerprints;
433 $extractor->allowedParsers = $options->allowed_parsers;
434
435 ////////////////////////////////
436 // Get RSS/Atom feed
437 ////////////////////////////////
438 if (!$html_only) {
439 debug('--------');
440 debug("Attempting to process URL as feed");
441 // Send user agent header showing PHP (prevents a HTML response from feedburner)
442 $http->userAgentDefault = HumbleHttpAgent::UA_PHP;
443 // configure SimplePie HTTP extension class to use our HumbleHttpAgent instance
444 SimplePie_HumbleHttpAgent::set_agent($http);
445 $feed = new SimplePie();
446 // some feeds use the text/html content type - force_feed tells SimplePie to process anyway
447 $feed->force_feed(true);
448 $feed->set_file_class('SimplePie_HumbleHttpAgent');
449 //$feed->set_feed_url($url); // colons appearing in the URL's path get encoded
450 $feed->feed_url = $url;
451 $feed->set_autodiscovery_level(SIMPLEPIE_LOCATOR_NONE);
452 $feed->set_timeout(20);
453 $feed->enable_cache(false);
454 $feed->set_stupidly_fast(true);
455 $feed->enable_order_by_date(false); // we don't want to do anything to the feed
456 $feed->set_url_replacements(array());
457 // initialise the feed
458 // the @ suppresses notices which on some servers causes a 500 internal server error
459 $result = @$feed->init();
460 //$feed->handle_content_type();
461 //$feed->get_title();
462 if ($result && (!is_array($feed->data) || count($feed->data) == 0)) {
463 die('Sorry, no feed items found');
464 }
465 // from now on, we'll identify ourselves as a browser
466 $http->userAgentDefault = HumbleHttpAgent::UA_BROWSER;
467 }
468
469 ////////////////////////////////////////////////////////////////////////////////
470 // Our given URL is not a feed, so let's create our own feed with a single item:
471 // the given URL. This basically treats all non-feed URLs as if they were
472 // single-item feeds.
473 ////////////////////////////////////////////////////////////////////////////////
474 $isDummyFeed = false;
475 if ($html_only || !$result) {
476 debug('--------');
477 debug("Constructing a single-item feed from URL");
478 $isDummyFeed = true;
479 unset($feed, $result);
480 // create single item dummy feed object
481 class DummySingleItemFeed {
482 public $item;
483 function __construct($url) { $this->item = new DummySingleItem($url); }
484 public function get_title() { return ''; }
485 public function get_description() { return 'Content extracted from '.$this->item->url; }
486 public function get_link() { return $this->item->url; }
487 public function get_language() { return false; }
488 public function get_image_url() { return false; }
489 public function get_items($start=0, $max=1) { return array(0=>$this->item); }
490 }
491 class DummySingleItem {
492 public $url;
493 function __construct($url) { $this->url = $url; }
494 public function get_permalink() { return $this->url; }
495 public function get_title() { return null; }
496 public function get_date($format='') { return false; }
497 public function get_author($key=0) { return null; }
498 public function get_authors() { return null; }
499 public function get_description() { return ''; }
500 public function get_enclosure($key=0, $prefer=null) { return null; }
501 public function get_enclosures() { return null; }
502 public function get_categories() { return null; }
503 }
504 $feed = new DummySingleItemFeed($url);
505 }
506
507 ////////////////////////////////////////////
508 // Create full-text feed
509 ////////////////////////////////////////////
510 $output = new FeedWriter();
511 $output->setTitle(strip_tags($feed->get_title()));
512 $output->setDescription(strip_tags($feed->get_description()));
513 $output->setXsl('css/feed.xsl'); // Chrome uses this, most browsers ignore it
514 if ($valid_key && isset($_GET['pubsub'])) { // used only on fivefilters.org at the moment
515 $output->addHub('http://fivefilters.superfeedr.com/');
516 $output->addHub('http://pubsubhubbub.appspot.com/');
517 $output->setSelf('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
518 }
519 $output->setLink($feed->get_link()); // Google Reader uses this for pulling in favicons
520 if ($img_url = $feed->get_image_url()) {
521 $output->setImage($feed->get_title(), $feed->get_link(), $img_url);
522 }
523
524 ////////////////////////////////////////////
525 // Loop through feed items
526 ////////////////////////////////////////////
527 $items = $feed->get_items(0, $max);
528 // Request all feed items in parallel (if supported)
529 $urls_sanitized = array();
530 $urls = array();
531 foreach ($items as $key => $item) {
532 $permalink = htmlspecialchars_decode($item->get_permalink());
533 // Colons in URL path segments get encoded by SimplePie, yet some sites expect them unencoded
534 $permalink = str_replace('%3A', ':', $permalink);
535 // validateUrl() strips non-ascii characters
536 // simplepie already sanitizes URLs so let's not do it again here.
537 //$permalink = $http->validateUrl($permalink);
538 if ($permalink) {
539 $urls_sanitized[] = $permalink;
540 }
541 $urls[$key] = $permalink;
542 }
543 debug('--------');
544 debug('Fetching feed items');
545 $http->fetchAll($urls_sanitized);
546 //$http->cacheAll();
547
548 // count number of items added to full feed
549 $item_count = 0;
550
551 foreach ($items as $key => $item) {
552 debug('--------');
553 debug('Processing feed item '.($item_count+1));
554 $do_content_extraction = true;
555 $extract_result = false;
556 $text_sample = null;
557 $permalink = $urls[$key];
558 debug("Item URL: $permalink");
559 $extracted_title = '';
560 $feed_item_title = $item->get_title();
561 if ($feed_item_title !== null) {
562 $feed_item_title = strip_tags(htmlspecialchars_decode($feed_item_title));
563 }
564 $newitem = $output->createNewItem();
565 $newitem->setTitle($feed_item_title);
566 if ($valid_key && isset($_GET['pubsub'])) { // used only on fivefilters.org at the moment
567 if ($permalink !== false) {
568 $newitem->setLink('http://fivefilters.org/content-only/redirect.php?url='.urlencode($permalink));
569 } else {
570 $newitem->setLink('http://fivefilters.org/content-only/redirect.php?url='.urlencode($item->get_permalink()));
571 }
572 } else {
573 if ($permalink !== false) {
574 $newitem->setLink($permalink);
575 } else {
576 $newitem->setLink($item->get_permalink());
577 }
578 }
579 //if ($permalink && ($response = $http->get($permalink, true)) && $response['status_code'] < 300) {
580 // Allowing error codes - some sites return correct content with error status
581 // e.g. prospectmagazine.co.uk returns 403
582 if ($permalink && ($response = $http->get($permalink, true)) && ($response['status_code'] < 300 || $response['status_code'] > 400)) {
583 $effective_url = $response['effective_url'];
584 if (!url_allowed($effective_url)) continue;
585 // check if action defined for returned Content-Type
586 $mime_info = get_mime_action_info($response['headers']);
587 if (isset($mime_info['action'])) {
588 if ($mime_info['action'] == 'exclude') {
589 continue; // skip this feed item entry
590 } elseif ($mime_info['action'] == 'link') {
591 if ($mime_info['type'] == 'image') {
592 $html = "<a href=\"$effective_url\"><img src=\"$effective_url\" alt=\"{$mime_info['name']}\" /></a>";
593 } else {
594 $html = "<a href=\"$effective_url\">Download {$mime_info['name']}</a>";
595 }
596 $extracted_title = $mime_info['name'];
597 $do_content_extraction = false;
598 }
599 }
600 if ($do_content_extraction) {
601 $html = $response['body'];
602 // remove strange things
603 $html = str_replace('</[>', '', $html);
604 $html = convert_to_utf8($html, $response['headers']);
605 // check site config for single page URL - fetch it if found
606 $is_single_page = false;
607 if ($single_page_response = getSinglePage($item, $html, $effective_url)) {
608 $is_single_page = true;
609 $html = $single_page_response['body'];
610 // remove strange things
611 $html = str_replace('</[>', '', $html);
612 $html = convert_to_utf8($html, $single_page_response['headers']);
613 $effective_url = $single_page_response['effective_url'];
614 debug("Retrieved single-page view from $effective_url");
615 unset($single_page_response);
616 }
617 debug('--------');
618 debug('Attempting to extract content');
619 $extract_result = $extractor->process($html, $effective_url);
620 $readability = $extractor->readability;
621 $content_block = ($extract_result) ? $extractor->getContent() : null;
622 $extracted_title = ($extract_result) ? $extractor->getTitle() : '';
623 // Deal with multi-page articles
624 //die('Next: '.$extractor->getNextPageUrl());
625 $is_multi_page = (!$is_single_page && $extract_result && $extractor->getNextPageUrl());
626 if ($options->multipage && $is_multi_page) {
627 debug('--------');
628 debug('Attempting to process multi-page article');
629 $multi_page_urls = array();
630 $multi_page_content = array();
631 while ($next_page_url = $extractor->getNextPageUrl()) {
632 debug('--------');
633 debug('Processing next page: '.$next_page_url);
634 // If we've got URL, resolve against $url
635 if ($next_page_url = makeAbsoluteStr($effective_url, $next_page_url)) {
636 // check it's not what we have already!
637 if (!in_array($next_page_url, $multi_page_urls)) {
638 // it's not, so let's attempt to fetch it
639 $multi_page_urls[] = $next_page_url;
640 $_prev_ref = $http->referer;
641 if (($response = $http->get($next_page_url, true)) && $response['status_code'] < 300) {
642 // make sure mime type is not something with a different action associated
643 $page_mime_info = get_mime_action_info($response['headers']);
644 if (!isset($page_mime_info['action'])) {
645 $html = $response['body'];
646 // remove strange things
647 $html = str_replace('</[>', '', $html);
648 $html = convert_to_utf8($html, $response['headers']);
649 if ($extractor->process($html, $next_page_url)) {
650 $multi_page_content[] = $extractor->getContent();
651 continue;
652 } else { debug('Failed to extract content'); }
653 } else { debug('MIME type requires different action'); }
654 } else { debug('Failed to fetch URL'); }
655 } else { debug('URL already processed'); }
656 } else { debug('Failed to resolve against '.$effective_url); }
657 // failed to process next_page_url, so cancel further requests
658 $multi_page_content = array();
659 break;
660 }
661 // did we successfully deal with this multi-page article?
662 if (empty($multi_page_content)) {
663 debug('Failed to extract all parts of multi-page article, so not going to include them');
664 $multi_page_content[] = $readability->dom->createElement('p')->innerHTML = '<em>This article appears to continue on subsequent pages which we could not extract</em>';
665 }
666 foreach ($multi_page_content as $_page) {
667 $_page = $content_block->ownerDocument->importNode($_page, true);
668 $content_block->appendChild($_page);
669 }
670 unset($multi_page_urls, $multi_page_content, $page_mime_info, $next_page_url);
671 }
672 }
673 // use extracted title for both feed and item title if we're using single-item dummy feed
674 if ($isDummyFeed) {
675 $output->setTitle($extracted_title);
676 $newitem->setTitle($extracted_title);
677 } else {
678 // use extracted title instead of feed item title?
679 if (!$favour_feed_titles && $extracted_title != '') {
680 debug('Using extracted title in generated feed');
681 $newitem->setTitle($extracted_title);
682 }
683 }
684 }
685 if ($do_content_extraction) {
686 // if we failed to extract content...
687 if (!$extract_result) {
688 if ($exclude_on_fail) {
689 debug('Failed to extract, so skipping (due to exclude on fail parameter)');
690 continue; // skip this and move to next item
691 }
692 //TODO: get text sample for language detection
693 $html = $options->error_message;
694 // keep the original item description
695 $html .= $item->get_description();
696 } else {
697 $readability->clean($content_block, 'select');
698 if ($options->rewrite_relative_urls) makeAbsolute($effective_url, $content_block);
699 // footnotes
700 if (($links == 'footnotes') && (strpos($effective_url, 'wikipedia.org') === false)) {
701 $readability->addFootnotes($content_block);
702 }
703 // remove nesting: <div><div><div><p>test</p></div></div></div> = <p>test</p>
704 while ($content_block->childNodes->length == 1 && $content_block->firstChild->nodeType === XML_ELEMENT_NODE) {
705 // only follow these tag names
706 if (!in_array(strtolower($content_block->tagName), array('div', 'article', 'section', 'header', 'footer'))) break;
707 //$html = $content_block->firstChild->innerHTML; // FTR 2.9.5
708 $content_block = $content_block->firstChild;
709 }
710 // convert content block to HTML string
711 // Need to preserve things like body: //img[@id='feature']
712 if (in_array(strtolower($content_block->tagName), array('div', 'article', 'section', 'header', 'footer'))) {
713 $html = $content_block->innerHTML;
714 } else {
715 $html = $content_block->ownerDocument->saveXML($content_block); // essentially outerHTML
716 }
717 unset($content_block);
718 // post-processing cleanup
719 $html = preg_replace('!<p>[\s\h\v]*</p>!u', '', $html);
720 if ($links == 'remove') {
721 $html = preg_replace('!</?a[^>]*>!', '', $html);
722 }
723 // get text sample for language detection
724 $text_sample = strip_tags(substr($html, 0, 500));
725 $html = make_substitutions($options->message_to_prepend).$html;
726 $html .= make_substitutions($options->message_to_append);
727 }
728 }
729
730 if ($valid_key && isset($_GET['pubsub'])) { // used only on fivefilters.org at the moment
731 $newitem->addElement('guid', 'http://fivefilters.org/content-only/redirect.php?url='.urlencode($item->get_permalink()), array('isPermaLink'=>'false'));
732 } else {
733 $newitem->addElement('guid', $item->get_permalink(), array('isPermaLink'=>'true'));
734 }
735 // filter xss?
736 if ($xss_filter) {
737 debug('Filtering HTML to remove XSS');
738 $html = htmLawed::hl($html, array('safe'=>1, 'deny_attribute'=>'style', 'comment'=>1, 'cdata'=>1));
739 }
740 $newitem->setDescription($html);
741
742 // set date
743 if ((int)$item->get_date('U') > 0) {
744 $newitem->setDate((int)$item->get_date('U'));
745 } elseif ($extractor->getDate()) {
746 $newitem->setDate($extractor->getDate());
747 }
748
749 // add authors
750 if ($authors = $item->get_authors()) {
751 foreach ($authors as $author) {
752 // for some feeds, SimplePie stores author's name as email, e.g. http://feeds.feedburner.com/nymag/intel
753 if ($author->get_name() !== null) {
754 $newitem->addElement('dc:creator', $author->get_name());
755 } elseif ($author->get_email() !== null) {
756 $newitem->addElement('dc:creator', $author->get_email());
757 }
758 }
759 } elseif ($authors = $extractor->getAuthors()) {
760 //TODO: make sure the list size is reasonable
761 foreach ($authors as $author) {
762 // TODO: xpath often selects authors from other articles linked from the page.
763 // for now choose first item
764 $newitem->addElement('dc:creator', $author);
765 break;
766 }
767 }
768
769 // add language
770 if ($detect_language) {
771 $language = $extractor->getLanguage();
772 if (!$language) $language = $feed->get_language();
773 if (($detect_language == 3 || (!$language && $detect_language == 2)) && $text_sample) {
774 try {
775 if ($use_cld) {
776 // Use PHP-CLD extension
777 $php_cld = 'CLD\detect'; // in quotes to prevent PHP 5.2 parse error
778 $res = $php_cld($text_sample);
779 if (is_array($res) && count($res) > 0) {
780 $language = $res[0]['code'];
781 }
782 } else {
783 //die('what');
784 // Use PEAR's Text_LanguageDetect
785 if (!isset($l)) {
786 $l = new Text_LanguageDetect('libraries/language-detect/lang.dat', 'libraries/language-detect/unicode_blocks.dat');
787 }
788 $l_result = $l->detect($text_sample, 1);
789 if (count($l_result) > 0) {
790 $language = $language_codes[key($l_result)];
791 }
792 }
793 } catch (Exception $e) {
794 //die('error: '.$e);
795 // do nothing
796 }
797 }
798 if ($language && (strlen($language) < 7)) {
799 $newitem->addElement('dc:language', $language);
800 }
801 }
802
803 // add MIME type (if it appeared in our exclusions lists)
804 if (isset($mime_info['mime'])) $newitem->addElement('dc:format', $mime_info['mime']);
805 // add effective URL (URL after redirects)
806 if (isset($effective_url)) {
807 //TODO: ensure $effective_url is valid witout - sometimes it causes problems, e.g.
808 //http://www.siasat.pk/forum/showthread.php?108883-Pakistan-Chowk-by-Rana-Mubashir-\96-25th-March-2012-Special-Program-from-Liari-(Karachi)
809 //temporary measure: use utf8_encode()
810 $newitem->addElement('dc:identifier', remove_url_cruft(utf8_encode($effective_url)));
811 } else {
812 $newitem->addElement('dc:identifier', remove_url_cruft($item->get_permalink()));
813 }
814
815 // add categories
816 if ($categories = $item->get_categories()) {
817 foreach ($categories as $category) {
818 if ($category->get_label() !== null) {
819 $newitem->addElement('category', $category->get_label());
820 }
821 }
822 }
823
824 // check for enclosures
825 if ($options->keep_enclosures) {
826 if ($enclosures = $item->get_enclosures()) {
827 foreach ($enclosures as $enclosure) {
828 // thumbnails
829 foreach ((array)$enclosure->get_thumbnails() as $thumbnail) {
830 $newitem->addElement('media:thumbnail', '', array('url'=>$thumbnail));
831 }
832 if (!$enclosure->get_link()) continue;
833 $enc = array();
834 // Media RSS spec ($enc): http://search.yahoo.com/mrss
835 // SimplePie methods ($enclosure): http://simplepie.org/wiki/reference/start#methods4
836 $enc['url'] = $enclosure->get_link();
837 if ($enclosure->get_length()) $enc['fileSize'] = $enclosure->get_length();
838 if ($enclosure->get_type()) $enc['type'] = $enclosure->get_type();
839 if ($enclosure->get_medium()) $enc['medium'] = $enclosure->get_medium();
840 if ($enclosure->get_expression()) $enc['expression'] = $enclosure->get_expression();
841 if ($enclosure->get_bitrate()) $enc['bitrate'] = $enclosure->get_bitrate();
842 if ($enclosure->get_framerate()) $enc['framerate'] = $enclosure->get_framerate();
843 if ($enclosure->get_sampling_rate()) $enc['samplingrate'] = $enclosure->get_sampling_rate();
844 if ($enclosure->get_channels()) $enc['channels'] = $enclosure->get_channels();
845 if ($enclosure->get_duration()) $enc['duration'] = $enclosure->get_duration();
846 if ($enclosure->get_height()) $enc['height'] = $enclosure->get_height();
847 if ($enclosure->get_width()) $enc['width'] = $enclosure->get_width();
848 if ($enclosure->get_language()) $enc['lang'] = $enclosure->get_language();
849 $newitem->addElement('media:content', '', $enc);
850 }
851 }
852 }
853 /* } */
854 $output->addItem($newitem);
855 unset($html);
856 $item_count++;
857 }
858
859 // output feed
860 debug('Done!');
861 /*
862 if ($debug_mode) {
863 $_apc_data = apc_cache_info('user');
864 var_dump($_apc_data); exit;
865 }
866 */
867 if (!$debug_mode) {
868 if ($callback) echo "$callback("; // if $callback is set, $format also == 'json'
869 if ($format == 'json') $output->setFormat(($callback === null) ? JSON : JSONP);
870 $add_to_cache = $options->caching;
871 // is smart cache mode enabled?
872 if ($add_to_cache && $options->apc && $options->smart_cache) {
873 // yes, so only cache if this is the second request for this URL
874 $add_to_cache = ($apc_cache_hits >= 2);
875 // purge cache
876 if ($options->cache_cleanup > 0) {
877 if (rand(1, $options->cache_cleanup) == 1) {
878 // apc purge code adapted from from http://www.thimbleopensource.com/tutorials-snippets/php-apc-expunge-script
879 $_apc_data = apc_cache_info('user');
880 foreach ($_apc_data['cache_list'] as $_apc_item) {
881 if ($_apc_item['ttl'] > 0 && ($_apc_item['ttl'] + $_apc_item['creation_time'] < time())) {
882 apc_delete($_apc_item['info']);
883 }
884 }
885 }
886 }
887 }
888 if ($add_to_cache) {
889 ob_start();
890 $output->genarateFeed();
891 $output = ob_get_contents();
892 ob_end_clean();
893 if ($html_only && $item_count == 0) {
894 // do not cache - in case of temporary server glitch at source URL
895 } else {
896 $cache = get_cache();
897 if ($add_to_cache) $cache->save($output, $cache_id);
898 }
899 echo $output;
900 } else {
901 $output->genarateFeed();
902 }
903 if ($callback) echo ');';
904 }
905
906 ///////////////////////////////
907 // HELPER FUNCTIONS
908 ///////////////////////////////
909
910 function url_allowed($url) {
911 global $options;
912 if (!empty($options->allowed_urls)) {
913 $allowed = false;
914 foreach ($options->allowed_urls as $allowurl) {
915 if (stristr($url, $allowurl) !== false) {
916 $allowed = true;
917 break;
918 }
919 }
920 if (!$allowed) return false;
921 } else {
922 foreach ($options->blocked_urls as $blockurl) {
923 if (stristr($url, $blockurl) !== false) {
924 return false;
925 }
926 }
927 }
928 return true;
929 }
930
931 //////////////////////////////////////////////
932 // Convert $html to UTF8
933 // (uses HTTP headers and HTML to find encoding)
934 // adapted from http://stackoverflow.com/questions/910793/php-detect-encoding-and-make-everything-utf-8
935 //////////////////////////////////////////////
936 function convert_to_utf8($html, $header=null)
937 {
938 $encoding = null;
939 if ($html || $header) {
940 if (is_array($header)) $header = implode("\n", $header);
941 if (!$header || !preg_match_all('/^Content-Type:\s+([^;]+)(?:;\s*charset=["\']?([^;"\'\n]*))?/im', $header, $match, PREG_SET_ORDER)) {
942 // error parsing the response
943 debug('Could not find Content-Type header in HTTP response');
944 } else {
945 $match = end($match); // get last matched element (in case of redirects)
946 if (isset($match[2])) $encoding = trim($match[2], "\"' \r\n\0\x0B\t");
947 }
948 // TODO: check to see if encoding is supported (can we convert it?)
949 // If it's not, result will be empty string.
950 // For now we'll check for invalid encoding types returned by some sites, e.g. 'none'
951 // Problem URL: http://facta.co.jp/blog/archives/20111026001026.html
952 if (!$encoding || $encoding == 'none') {
953 // search for encoding in HTML - only look at the first 50000 characters
954 // 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
955 // TODO: improve this so it looks at smaller chunks first
956 $html_head = substr($html, 0, 50000);
957 if (preg_match('/^<\?xml\s+version=(?:"[^"]*"|\'[^\']*\')\s+encoding=("[^"]*"|\'[^\']*\')/s', $html_head, $match)) {
958 $encoding = trim($match[1], '"\'');
959 } elseif (preg_match('/<meta\s+http-equiv=["\']?Content-Type["\']? content=["\'][^;]+;\s*charset=["\']?([^;"\'>]+)/i', $html_head, $match)) {
960 $encoding = trim($match[1]);
961 } elseif (preg_match_all('/<meta\s+([^>]+)>/i', $html_head, $match)) {
962 foreach ($match[1] as $_test) {
963 if (preg_match('/charset=["\']?([^"\']+)/i', $_test, $_m)) {
964 $encoding = trim($_m[1]);
965 break;
966 }
967 }
968 }
969 }
970 if (isset($encoding)) $encoding = trim($encoding);
971 // trim is important here!
972 if (!$encoding || (strtolower($encoding) == 'iso-8859-1')) {
973 // replace MS Word smart qutoes
974 $trans = array();
975 $trans[chr(130)] = '&sbquo;'; // Single Low-9 Quotation Mark
976 $trans[chr(131)] = '&fnof;'; // Latin Small Letter F With Hook
977 $trans[chr(132)] = '&bdquo;'; // Double Low-9 Quotation Mark
978 $trans[chr(133)] = '&hellip;'; // Horizontal Ellipsis
979 $trans[chr(134)] = '&dagger;'; // Dagger
980 $trans[chr(135)] = '&Dagger;'; // Double Dagger
981 $trans[chr(136)] = '&circ;'; // Modifier Letter Circumflex Accent
982 $trans[chr(137)] = '&permil;'; // Per Mille Sign
983 $trans[chr(138)] = '&Scaron;'; // Latin Capital Letter S With Caron
984 $trans[chr(139)] = '&lsaquo;'; // Single Left-Pointing Angle Quotation Mark
985 $trans[chr(140)] = '&OElig;'; // Latin Capital Ligature OE
986 $trans[chr(145)] = '&lsquo;'; // Left Single Quotation Mark
987 $trans[chr(146)] = '&rsquo;'; // Right Single Quotation Mark
988 $trans[chr(147)] = '&ldquo;'; // Left Double Quotation Mark
989 $trans[chr(148)] = '&rdquo;'; // Right Double Quotation Mark
990 $trans[chr(149)] = '&bull;'; // Bullet
991 $trans[chr(150)] = '&ndash;'; // En Dash
992 $trans[chr(151)] = '&mdash;'; // Em Dash
993 $trans[chr(152)] = '&tilde;'; // Small Tilde
994 $trans[chr(153)] = '&trade;'; // Trade Mark Sign
995 $trans[chr(154)] = '&scaron;'; // Latin Small Letter S With Caron
996 $trans[chr(155)] = '&rsaquo;'; // Single Right-Pointing Angle Quotation Mark
997 $trans[chr(156)] = '&oelig;'; // Latin Small Ligature OE
998 $trans[chr(159)] = '&Yuml;'; // Latin Capital Letter Y With Diaeresis
999 $html = strtr($html, $trans);
1000 }
1001 if (!$encoding) {
1002 debug('No character encoding found, so treating as UTF-8');
1003 $encoding = 'utf-8';
1004 } else {
1005 debug('Character encoding: '.$encoding);
1006 if (strtolower($encoding) != 'utf-8') {
1007 debug('Converting to UTF-8');
1008 $html = SimplePie_Misc::change_encoding($html, $encoding, 'utf-8');
1009 /*
1010 if (function_exists('iconv')) {
1011 // iconv appears to handle certain character encodings better than mb_convert_encoding
1012 $html = iconv($encoding, 'utf-8', $html);
1013 } else {
1014 $html = mb_convert_encoding($html, 'utf-8', $encoding);
1015 }
1016 */
1017 }
1018 }
1019 }
1020 return $html;
1021 }
1022
1023 function makeAbsolute($base, $elem) {
1024 $base = new SimplePie_IRI($base);
1025 // remove '//' in URL path (used to prevent URLs from resolving properly)
1026 // TODO: check if this is still the case
1027 if (isset($base->path)) $base->path = preg_replace('!//+!', '/', $base->path);
1028 foreach(array('a'=>'href', 'img'=>'src') as $tag => $attr) {
1029 $elems = $elem->getElementsByTagName($tag);
1030 for ($i = $elems->length-1; $i >= 0; $i--) {
1031 $e = $elems->item($i);
1032 //$e->parentNode->replaceChild($articleContent->ownerDocument->createTextNode($e->textContent), $e);
1033 makeAbsoluteAttr($base, $e, $attr);
1034 }
1035 if (strtolower($elem->tagName) == $tag) makeAbsoluteAttr($base, $elem, $attr);
1036 }
1037 }
1038 function makeAbsoluteAttr($base, $e, $attr) {
1039 if ($e->hasAttribute($attr)) {
1040 // Trim leading and trailing white space. I don't really like this but
1041 // unfortunately it does appear on some sites. e.g. <img src=" /path/to/image.jpg" />
1042 $url = trim(str_replace('%20', ' ', $e->getAttribute($attr)));
1043 $url = str_replace(' ', '%20', $url);
1044 if (!preg_match('!https?://!i', $url)) {
1045 if ($absolute = SimplePie_IRI::absolutize($base, $url)) {
1046 $e->setAttribute($attr, $absolute);
1047 }
1048 }
1049 }
1050 }
1051 function makeAbsoluteStr($base, $url) {
1052 $base = new SimplePie_IRI($base);
1053 // remove '//' in URL path (causes URLs not to resolve properly)
1054 if (isset($base->path)) $base->path = preg_replace('!//+!', '/', $base->path);
1055 if (preg_match('!^https?://!i', $url)) {
1056 // already absolute
1057 return $url;
1058 } else {
1059 if ($absolute = SimplePie_IRI::absolutize($base, $url)) {
1060 return $absolute;
1061 }
1062 return false;
1063 }
1064 }
1065 // returns single page response, or false if not found
1066 function getSinglePage($item, $html, $url) {
1067 global $http, $extractor;
1068 debug('Looking for site config files to see if single page link exists');
1069 $site_config = $extractor->buildSiteConfig($url, $html);
1070 $splink = null;
1071 if (!empty($site_config->single_page_link)) {
1072 $splink = $site_config->single_page_link;
1073 } elseif (!empty($site_config->single_page_link_in_feed)) {
1074 // single page link xpath is targeted at feed
1075 $splink = $site_config->single_page_link_in_feed;
1076 // so let's replace HTML with feed item description
1077 $html = $item->get_description();
1078 }
1079 if (isset($splink)) {
1080 // Build DOM tree from HTML
1081 $readability = new Readability($html, $url);
1082 $xpath = new DOMXPath($readability->dom);
1083 // Loop through single_page_link xpath expressions
1084 $single_page_url = null;
1085 foreach ($splink as $pattern) {
1086 $elems = @$xpath->evaluate($pattern, $readability->dom);
1087 if (is_string($elems)) {
1088 $single_page_url = trim($elems);
1089 break;
1090 } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
1091 foreach ($elems as $item) {
1092 if ($item instanceof DOMElement && $item->hasAttribute('href')) {
1093 $single_page_url = $item->getAttribute('href');
1094 break 2;
1095 } elseif ($item instanceof DOMAttr && $item->value) {
1096 $single_page_url = $item->value;
1097 break 2;
1098 }
1099 }
1100 }
1101 }
1102 // If we've got URL, resolve against $url
1103 if (isset($single_page_url) && ($single_page_url = makeAbsoluteStr($url, $single_page_url))) {
1104 // check it's not what we have already!
1105 if ($single_page_url != $url) {
1106 // it's not, so let's try to fetch it...
1107 $_prev_ref = $http->referer;
1108 $http->referer = $single_page_url;
1109 if (($response = $http->get($single_page_url, true)) && $response['status_code'] < 300) {
1110 $http->referer = $_prev_ref;
1111 return $response;
1112 }
1113 $http->referer = $_prev_ref;
1114 }
1115 }
1116 }
1117 return false;
1118 }
1119
1120 // based on content-type http header, decide what to do
1121 // param: HTTP headers string
1122 // return: array with keys: 'mime', 'type', 'subtype', 'action', 'name'
1123 // e.g. array('mime'=>'image/jpeg', 'type'=>'image', 'subtype'=>'jpeg', 'action'=>'link', 'name'=>'Image')
1124 function get_mime_action_info($headers) {
1125 global $options;
1126 // check if action defined for returned Content-Type
1127 $info = array();
1128 if (preg_match('!^Content-Type:\s*(([-\w]+)/([-\w\+]+))!im', $headers, $match)) {
1129 // look for full mime type (e.g. image/jpeg) or just type (e.g. image)
1130 // match[1] = full mime type, e.g. image/jpeg
1131 // match[2] = first part, e.g. image
1132 // match[3] = last part, e.g. jpeg
1133 $info['mime'] = strtolower(trim($match[1]));
1134 $info['type'] = strtolower(trim($match[2]));
1135 $info['subtype'] = strtolower(trim($match[3]));
1136 foreach (array($info['mime'], $info['type']) as $_mime) {
1137 if (isset($options->content_type_exc[$_mime])) {
1138 $info['action'] = $options->content_type_exc[$_mime]['action'];
1139 $info['name'] = $options->content_type_exc[$_mime]['name'];
1140 break;
1141 }
1142 }
1143 }
1144 return $info;
1145 }
1146
1147 function remove_url_cruft($url) {
1148 // remove google analytics for the time being
1149 // regex adapted from http://navitronic.co.uk/2010/12/removing-google-analytics-cruft-from-urls/
1150 // https://gist.github.com/758177
1151 return preg_replace('/(\?|\&)utm_[a-z]+=[^\&]+/', '', $url);
1152 }
1153
1154 function make_substitutions($string) {
1155 if ($string == '') return $string;
1156 global $item, $effective_url;
1157 $string = str_replace('{url}', htmlspecialchars($item->get_permalink()), $string);
1158 $string = str_replace('{effective-url}', htmlspecialchars($effective_url), $string);
1159 return $string;
1160 }
1161
1162 function get_cache() {
1163 global $options, $valid_key;
1164 static $cache = null;
1165 if ($cache === null) {
1166 $frontendOptions = array(
1167 'lifetime' => 10*60, // cache lifetime of 10 minutes
1168 'automatic_serialization' => false,
1169 'write_control' => false,
1170 'automatic_cleaning_factor' => $options->cache_cleanup,
1171 'ignore_user_abort' => false
1172 );
1173 $backendOptions = array(
1174 'cache_dir' => ($valid_key) ? $options->cache_dir.'/rss-with-key/' : $options->cache_dir.'/rss/', // directory where to put the cache files
1175 'file_locking' => false,
1176 'read_control' => true,
1177 'read_control_type' => 'strlen',
1178 'hashed_directory_level' => $options->cache_directory_level,
1179 'hashed_directory_perm' => 0777,
1180 'cache_file_perm' => 0664,
1181 'file_name_prefix' => 'ff'
1182 );
1183 // getting a Zend_Cache_Core object
1184 $cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
1185 }
1186 return $cache;
1187 }
1188
1189 function debug($msg) {
1190 global $debug_mode;
1191 if ($debug_mode) {
1192 echo '* ',$msg,"\n";
1193 ob_flush();
1194 flush();
1195 }
1196 }