]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/3rdparty/makefulltextfeed.php
Polish, Russian and Ukrainian locales updated, Franch locale po file uopdated. issue...
[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 global $http;
419 $http = new HumbleHttpAgent();
420 $http->debug = $debug_mode;
421 $http->userAgentMap = $options->user_agents;
422 $http->headerOnlyTypes = array_keys($options->content_type_exc);
423 $http->rewriteUrls = $options->rewrite_url;
424
425 //////////////////////////////////
426 // Set up Content Extractor
427 //////////////////////////////////
428 global $extractor;
429 $extractor = new ContentExtractor(dirname(__FILE__).'/site_config/custom', dirname(__FILE__).'/site_config/standard');
430 $extractor->debug = $debug_mode;
431 SiteConfig::$debug = $debug_mode;
432 SiteConfig::use_apc($options->apc);
433 $extractor->fingerprints = $options->fingerprints;
434 $extractor->allowedParsers = $options->allowed_parsers;
435
436 ////////////////////////////////
437 // Get RSS/Atom feed
438 ////////////////////////////////
439 if (!$html_only) {
440 debug('--------');
441 debug("Attempting to process URL as feed");
442 // Send user agent header showing PHP (prevents a HTML response from feedburner)
443 $http->userAgentDefault = HumbleHttpAgent::UA_PHP;
444 // configure SimplePie HTTP extension class to use our HumbleHttpAgent instance
445 SimplePie_HumbleHttpAgent::set_agent($http);
446 $feed = new SimplePie();
447 // some feeds use the text/html content type - force_feed tells SimplePie to process anyway
448 $feed->force_feed(true);
449 $feed->set_file_class('SimplePie_HumbleHttpAgent');
450 //$feed->set_feed_url($url); // colons appearing in the URL's path get encoded
451 $feed->feed_url = $url;
452 $feed->set_autodiscovery_level(SIMPLEPIE_LOCATOR_NONE);
453 $feed->set_timeout(20);
454 $feed->enable_cache(false);
455 $feed->set_stupidly_fast(true);
456 $feed->enable_order_by_date(false); // we don't want to do anything to the feed
457 $feed->set_url_replacements(array());
458 // initialise the feed
459 // the @ suppresses notices which on some servers causes a 500 internal server error
460 $result = @$feed->init();
461 //$feed->handle_content_type();
462 //$feed->get_title();
463 if ($result && (!is_array($feed->data) || count($feed->data) == 0)) {
464 die('Sorry, no feed items found');
465 }
466 // from now on, we'll identify ourselves as a browser
467 $http->userAgentDefault = HumbleHttpAgent::UA_BROWSER;
468 }
469
470 ////////////////////////////////////////////////////////////////////////////////
471 // Our given URL is not a feed, so let's create our own feed with a single item:
472 // the given URL. This basically treats all non-feed URLs as if they were
473 // single-item feeds.
474 ////////////////////////////////////////////////////////////////////////////////
475 $isDummyFeed = false;
476 if ($html_only || !$result) {
477 debug('--------');
478 debug("Constructing a single-item feed from URL");
479 $isDummyFeed = true;
480 unset($feed, $result);
481 // 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);
506 }
507
508 ////////////////////////////////////////////
509 // Create full-text feed
510 ////////////////////////////////////////////
511 $output = new FeedWriter();
512 $output->setTitle(strip_tags($feed->get_title()));
513 $output->setDescription(strip_tags($feed->get_description()));
514 $output->setXsl('css/feed.xsl'); // Chrome uses this, most browsers ignore it
515 if ($valid_key && isset($_GET['pubsub'])) { // used only on fivefilters.org at the moment
516 $output->addHub('http://fivefilters.superfeedr.com/');
517 $output->addHub('http://pubsubhubbub.appspot.com/');
518 $output->setSelf('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
519 }
520 $output->setLink($feed->get_link()); // Google Reader uses this for pulling in favicons
521 if ($img_url = $feed->get_image_url()) {
522 $output->setImage($feed->get_title(), $feed->get_link(), $img_url);
523 }
524
525 ////////////////////////////////////////////
526 // Loop through feed items
527 ////////////////////////////////////////////
528 $items = $feed->get_items(0, $max);
529 // Request all feed items in parallel (if supported)
530 $urls_sanitized = array();
531 $urls = array();
532 foreach ($items as $key => $item) {
533 $permalink = htmlspecialchars_decode($item->get_permalink());
534 // Colons in URL path segments get encoded by SimplePie, yet some sites expect them unencoded
535 $permalink = str_replace('%3A', ':', $permalink);
536 // validateUrl() strips non-ascii characters
537 // simplepie already sanitizes URLs so let's not do it again here.
538 //$permalink = $http->validateUrl($permalink);
539 if ($permalink) {
540 $urls_sanitized[] = $permalink;
541 }
542 $urls[$key] = $permalink;
543 }
544 debug('--------');
545 debug('Fetching feed items');
546 $http->fetchAll($urls_sanitized);
547 //$http->cacheAll();
548
549 // count number of items added to full feed
550 $item_count = 0;
551
552 foreach ($items as $key => $item) {
553 debug('--------');
554 debug('Processing feed item '.($item_count+1));
555 $do_content_extraction = true;
556 $extract_result = false;
557 $text_sample = null;
558 $permalink = $urls[$key];
559 debug("Item URL: $permalink");
560 $extracted_title = '';
561 $feed_item_title = $item->get_title();
562 if ($feed_item_title !== null) {
563 $feed_item_title = strip_tags(htmlspecialchars_decode($feed_item_title));
564 }
565 $newitem = $output->createNewItem();
566 $newitem->setTitle($feed_item_title);
567 if ($valid_key && isset($_GET['pubsub'])) { // used only on fivefilters.org at the moment
568 if ($permalink !== false) {
569 $newitem->setLink('http://fivefilters.org/content-only/redirect.php?url='.urlencode($permalink));
570 } else {
571 $newitem->setLink('http://fivefilters.org/content-only/redirect.php?url='.urlencode($item->get_permalink()));
572 }
573 } else {
574 if ($permalink !== false) {
575 $newitem->setLink($permalink);
576 } else {
577 $newitem->setLink($item->get_permalink());
578 }
579 }
580 //if ($permalink && ($response = $http->get($permalink, true)) && $response['status_code'] < 300) {
581 // Allowing error codes - some sites return correct content with error status
582 // e.g. prospectmagazine.co.uk returns 403
583 if ($permalink && ($response = $http->get($permalink, true)) && ($response['status_code'] < 300 || $response['status_code'] > 400)) {
584 $effective_url = $response['effective_url'];
585 if (!url_allowed($effective_url)) continue;
586 // check if action defined for returned Content-Type
587 $mime_info = get_mime_action_info($response['headers']);
588 if (isset($mime_info['action'])) {
589 if ($mime_info['action'] == 'exclude') {
590 continue; // skip this feed item entry
591 } elseif ($mime_info['action'] == 'link') {
592 if ($mime_info['type'] == 'image') {
593 $html = "<a href=\"$effective_url\"><img src=\"$effective_url\" alt=\"{$mime_info['name']}\" /></a>";
594 } else {
595 $html = "<a href=\"$effective_url\">Download {$mime_info['name']}</a>";
596 }
597 $extracted_title = $mime_info['name'];
598 $do_content_extraction = false;
599 }
600 }
601 if ($do_content_extraction) {
602 $html = $response['body'];
603 // remove strange things
604 $html = str_replace('</[>', '', $html);
605 $html = convert_to_utf8($html, $response['headers']);
606 // check site config for single page URL - fetch it if found
607 $is_single_page = false;
608 if ($single_page_response = getSinglePage($item, $html, $effective_url)) {
609 $is_single_page = true;
610 $html = $single_page_response['body'];
611 // remove strange things
612 $html = str_replace('</[>', '', $html);
613 $html = convert_to_utf8($html, $single_page_response['headers']);
614 $effective_url = $single_page_response['effective_url'];
615 debug("Retrieved single-page view from $effective_url");
616 unset($single_page_response);
617 }
618 debug('--------');
619 debug('Attempting to extract content');
620 $extract_result = $extractor->process($html, $effective_url);
621 $readability = $extractor->readability;
622 $content_block = ($extract_result) ? $extractor->getContent() : null;
623 $extracted_title = ($extract_result) ? $extractor->getTitle() : '';
624 // Deal with multi-page articles
625 //die('Next: '.$extractor->getNextPageUrl());
626 $is_multi_page = (!$is_single_page && $extract_result && $extractor->getNextPageUrl());
627 if ($options->multipage && $is_multi_page) {
628 debug('--------');
629 debug('Attempting to process multi-page article');
630 $multi_page_urls = array();
631 $multi_page_content = array();
632 while ($next_page_url = $extractor->getNextPageUrl()) {
633 debug('--------');
634 debug('Processing next page: '.$next_page_url);
635 // If we've got URL, resolve against $url
636 if ($next_page_url = makeAbsoluteStr($effective_url, $next_page_url)) {
637 // check it's not what we have already!
638 if (!in_array($next_page_url, $multi_page_urls)) {
639 // it's not, so let's attempt to fetch it
640 $multi_page_urls[] = $next_page_url;
641 $_prev_ref = $http->referer;
642 if (($response = $http->get($next_page_url, true)) && $response['status_code'] < 300) {
643 // make sure mime type is not something with a different action associated
644 $page_mime_info = get_mime_action_info($response['headers']);
645 if (!isset($page_mime_info['action'])) {
646 $html = $response['body'];
647 // remove strange things
648 $html = str_replace('</[>', '', $html);
649 $html = convert_to_utf8($html, $response['headers']);
650 if ($extractor->process($html, $next_page_url)) {
651 $multi_page_content[] = $extractor->getContent();
652 continue;
653 } else { debug('Failed to extract content'); }
654 } else { debug('MIME type requires different action'); }
655 } else { debug('Failed to fetch URL'); }
656 } else { debug('URL already processed'); }
657 } else { debug('Failed to resolve against '.$effective_url); }
658 // failed to process next_page_url, so cancel further requests
659 $multi_page_content = array();
660 break;
661 }
662 // did we successfully deal with this multi-page article?
663 if (empty($multi_page_content)) {
664 debug('Failed to extract all parts of multi-page article, so not going to include them');
665 $multi_page_content[] = $readability->dom->createElement('p')->innerHTML = '<em>This article appears to continue on subsequent pages which we could not extract</em>';
666 }
667 foreach ($multi_page_content as $_page) {
668 $_page = $content_block->ownerDocument->importNode($_page, true);
669 $content_block->appendChild($_page);
670 }
671 unset($multi_page_urls, $multi_page_content, $page_mime_info, $next_page_url);
672 }
673 }
674 // use extracted title for both feed and item title if we're using single-item dummy feed
675 if ($isDummyFeed) {
676 $output->setTitle($extracted_title);
677 $newitem->setTitle($extracted_title);
678 } else {
679 // use extracted title instead of feed item title?
680 if (!$favour_feed_titles && $extracted_title != '') {
681 debug('Using extracted title in generated feed');
682 $newitem->setTitle($extracted_title);
683 }
684 }
685 }
686 if ($do_content_extraction) {
687 // if we failed to extract content...
688 if (!$extract_result) {
689 if ($exclude_on_fail) {
690 debug('Failed to extract, so skipping (due to exclude on fail parameter)');
691 continue; // skip this and move to next item
692 }
693 //TODO: get text sample for language detection
694 $html = $options->error_message;
695 // keep the original item description
696 $html .= $item->get_description();
697 } else {
698 $readability->clean($content_block, 'select');
699 if ($options->rewrite_relative_urls) makeAbsolute($effective_url, $content_block);
700 // footnotes
701 if (($links == 'footnotes') && (strpos($effective_url, 'wikipedia.org') === false)) {
702 $readability->addFootnotes($content_block);
703 }
704 // remove nesting: <div><div><div><p>test</p></div></div></div> = <p>test</p>
705 while ($content_block->childNodes->length == 1 && $content_block->firstChild->nodeType === XML_ELEMENT_NODE) {
706 // only follow these tag names
707 if (!in_array(strtolower($content_block->tagName), array('div', 'article', 'section', 'header', 'footer'))) break;
708 //$html = $content_block->firstChild->innerHTML; // FTR 2.9.5
709 $content_block = $content_block->firstChild;
710 }
711 // convert content block to HTML string
712 // Need to preserve things like body: //img[@id='feature']
713 if (in_array(strtolower($content_block->tagName), array('div', 'article', 'section', 'header', 'footer'))) {
714 $html = $content_block->innerHTML;
715 } else {
716 $html = $content_block->ownerDocument->saveXML($content_block); // essentially outerHTML
717 }
718 unset($content_block);
719 // post-processing cleanup
720 $html = preg_replace('!<p>[\s\h\v]*</p>!u', '', $html);
721 if ($links == 'remove') {
722 $html = preg_replace('!</?a[^>]*>!', '', $html);
723 }
724 // get text sample for language detection
725 $text_sample = strip_tags(substr($html, 0, 500));
726 $html = make_substitutions($options->message_to_prepend).$html;
727 $html .= make_substitutions($options->message_to_append);
728 }
729 }
730
731 if ($valid_key && isset($_GET['pubsub'])) { // used only on fivefilters.org at the moment
732 $newitem->addElement('guid', 'http://fivefilters.org/content-only/redirect.php?url='.urlencode($item->get_permalink()), array('isPermaLink'=>'false'));
733 } else {
734 $newitem->addElement('guid', $item->get_permalink(), array('isPermaLink'=>'true'));
735 }
736 // filter xss?
737 if ($xss_filter) {
738 debug('Filtering HTML to remove XSS');
739 $html = htmLawed::hl($html, array('safe'=>1, 'deny_attribute'=>'style', 'comment'=>1, 'cdata'=>1));
740 }
741 $newitem->setDescription($html);
742
743 // set date
744 if ((int)$item->get_date('U') > 0) {
745 $newitem->setDate((int)$item->get_date('U'));
746 } elseif ($extractor->getDate()) {
747 $newitem->setDate($extractor->getDate());
748 }
749
750 // add authors
751 if ($authors = $item->get_authors()) {
752 foreach ($authors as $author) {
753 // for some feeds, SimplePie stores author's name as email, e.g. http://feeds.feedburner.com/nymag/intel
754 if ($author->get_name() !== null) {
755 $newitem->addElement('dc:creator', $author->get_name());
756 } elseif ($author->get_email() !== null) {
757 $newitem->addElement('dc:creator', $author->get_email());
758 }
759 }
760 } elseif ($authors = $extractor->getAuthors()) {
761 //TODO: make sure the list size is reasonable
762 foreach ($authors as $author) {
763 // TODO: xpath often selects authors from other articles linked from the page.
764 // for now choose first item
765 $newitem->addElement('dc:creator', $author);
766 break;
767 }
768 }
769
770 // add language
771 if ($detect_language) {
772 $language = $extractor->getLanguage();
773 if (!$language) $language = $feed->get_language();
774 if (($detect_language == 3 || (!$language && $detect_language == 2)) && $text_sample) {
775 try {
776 if ($use_cld) {
777 // Use PHP-CLD extension
778 $php_cld = 'CLD\detect'; // in quotes to prevent PHP 5.2 parse error
779 $res = $php_cld($text_sample);
780 if (is_array($res) && count($res) > 0) {
781 $language = $res[0]['code'];
782 }
783 } else {
784 //die('what');
785 // Use PEAR's Text_LanguageDetect
786 if (!isset($l)) {
787 $l = new Text_LanguageDetect('libraries/language-detect/lang.dat', 'libraries/language-detect/unicode_blocks.dat');
788 }
789 $l_result = $l->detect($text_sample, 1);
790 if (count($l_result) > 0) {
791 $language = $language_codes[key($l_result)];
792 }
793 }
794 } catch (Exception $e) {
795 //die('error: '.$e);
796 // do nothing
797 }
798 }
799 if ($language && (strlen($language) < 7)) {
800 $newitem->addElement('dc:language', $language);
801 }
802 }
803
804 // add MIME type (if it appeared in our exclusions lists)
805 if (isset($mime_info['mime'])) $newitem->addElement('dc:format', $mime_info['mime']);
806 // add effective URL (URL after redirects)
807 if (isset($effective_url)) {
808 //TODO: ensure $effective_url is valid witout - sometimes it causes problems, e.g.
809 //http://www.siasat.pk/forum/showthread.php?108883-Pakistan-Chowk-by-Rana-Mubashir-\96-25th-March-2012-Special-Program-from-Liari-(Karachi)
810 //temporary measure: use utf8_encode()
811 $newitem->addElement('dc:identifier', remove_url_cruft(utf8_encode($effective_url)));
812 } else {
813 $newitem->addElement('dc:identifier', remove_url_cruft($item->get_permalink()));
814 }
815
816 // add categories
817 if ($categories = $item->get_categories()) {
818 foreach ($categories as $category) {
819 if ($category->get_label() !== null) {
820 $newitem->addElement('category', $category->get_label());
821 }
822 }
823 }
824
825 // check for enclosures
826 if ($options->keep_enclosures) {
827 if ($enclosures = $item->get_enclosures()) {
828 foreach ($enclosures as $enclosure) {
829 // thumbnails
830 foreach ((array)$enclosure->get_thumbnails() as $thumbnail) {
831 $newitem->addElement('media:thumbnail', '', array('url'=>$thumbnail));
832 }
833 if (!$enclosure->get_link()) continue;
834 $enc = array();
835 // Media RSS spec ($enc): http://search.yahoo.com/mrss
836 // SimplePie methods ($enclosure): http://simplepie.org/wiki/reference/start#methods4
837 $enc['url'] = $enclosure->get_link();
838 if ($enclosure->get_length()) $enc['fileSize'] = $enclosure->get_length();
839 if ($enclosure->get_type()) $enc['type'] = $enclosure->get_type();
840 if ($enclosure->get_medium()) $enc['medium'] = $enclosure->get_medium();
841 if ($enclosure->get_expression()) $enc['expression'] = $enclosure->get_expression();
842 if ($enclosure->get_bitrate()) $enc['bitrate'] = $enclosure->get_bitrate();
843 if ($enclosure->get_framerate()) $enc['framerate'] = $enclosure->get_framerate();
844 if ($enclosure->get_sampling_rate()) $enc['samplingrate'] = $enclosure->get_sampling_rate();
845 if ($enclosure->get_channels()) $enc['channels'] = $enclosure->get_channels();
846 if ($enclosure->get_duration()) $enc['duration'] = $enclosure->get_duration();
847 if ($enclosure->get_height()) $enc['height'] = $enclosure->get_height();
848 if ($enclosure->get_width()) $enc['width'] = $enclosure->get_width();
849 if ($enclosure->get_language()) $enc['lang'] = $enclosure->get_language();
850 $newitem->addElement('media:content', '', $enc);
851 }
852 }
853 }
854 /* } */
855 $output->addItem($newitem);
856 unset($html);
857 $item_count++;
858 }
859
860 // output feed
861 debug('Done!');
862 /*
863 if ($debug_mode) {
864 $_apc_data = apc_cache_info('user');
865 var_dump($_apc_data); exit;
866 }
867 */
868 if (!$debug_mode) {
869 if ($callback) echo "$callback("; // if $callback is set, $format also == 'json'
870 if ($format == 'json') $output->setFormat(($callback === null) ? JSON : JSONP);
871 $add_to_cache = $options->caching;
872 // is smart cache mode enabled?
873 if ($add_to_cache && $options->apc && $options->smart_cache) {
874 // yes, so only cache if this is the second request for this URL
875 $add_to_cache = ($apc_cache_hits >= 2);
876 // purge cache
877 if ($options->cache_cleanup > 0) {
878 if (rand(1, $options->cache_cleanup) == 1) {
879 // apc purge code adapted from from http://www.thimbleopensource.com/tutorials-snippets/php-apc-expunge-script
880 $_apc_data = apc_cache_info('user');
881 foreach ($_apc_data['cache_list'] as $_apc_item) {
882 if ($_apc_item['ttl'] > 0 && ($_apc_item['ttl'] + $_apc_item['creation_time'] < time())) {
883 apc_delete($_apc_item['info']);
884 }
885 }
886 }
887 }
888 }
889 if ($add_to_cache) {
890 ob_start();
891 $output->genarateFeed();
892 $output = ob_get_contents();
893 ob_end_clean();
894 if ($html_only && $item_count == 0) {
895 // do not cache - in case of temporary server glitch at source URL
896 } else {
897 $cache = get_cache();
898 if ($add_to_cache) $cache->save($output, $cache_id);
899 }
900 echo $output;
901 } else {
902 $output->genarateFeed();
903 }
904 if ($callback) echo ');';
905 }
906
907 ///////////////////////////////
908 // HELPER FUNCTIONS
909 ///////////////////////////////
910
911 function 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 //////////////////////////////////////////////
937 function 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
1024 function 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 }
1039 function 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 }
1052 function 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
1067 function 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')
1125 function 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
1148 function 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
1155 function 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
1163 function 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
1190 function debug($msg) {
1191 global $debug_mode;
1192 if ($debug_mode) {
1193 echo '* ',$msg,"\n";
1194 ob_flush();
1195 flush();
1196 }
1197 }