2 // Full-Text RSS: Create Full-Text Feeds
3 // Author: Keyvan Minoukadeh
4 // Copyright (c) 2013 Keyvan Minoukadeh
8 // More info: http://fivefilters.org/content-only/
9 // Help: http://help.fivefilters.org
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.
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.
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/>.
28 // Request this file passing it a web page or feed URL in the querystring: makefulltextfeed.php?url=example.org/article
29 // For more request parameters, see http://help.fivefilters.org/customer/portal/articles/226660-usage
31 //error_reporting(E_ALL ^ E_NOTICE);
32 ini_set("display_errors", 1);
35 // Deal with magic quotes
36 if (get_magic_quotes_gpc()) {
37 $process = array(&$_GET, &$_POST, &$_REQUEST);
38 while (list($key, $val) = each($process)) {
39 foreach ($val as $k => $v) {
40 unset($process[$key][$k]);
42 $process[$key][stripslashes($k)] = $v;
43 $process[] = &$process[$key][stripslashes($k)];
45 $process[$key][stripslashes($k)] = stripslashes($v);
53 set_include_path(realpath(dirname(__FILE__
).'/libraries').PATH_SEPARATOR
.get_include_path());
55 require_once dirname(__FILE__
).'/makefulltextfeedHelpers.php';
57 ////////////////////////////////
59 ////////////////////////////////
60 require dirname(__FILE__
).'/config.php';
62 ////////////////////////////////
63 // Prevent indexing/following by search engines because:
64 // 1. The content is already public and presumably indexed (why create duplicates?)
65 // 2. Not doing so might increase number of requests from search engines, thus increasing server load
66 // Note: feed readers and services such as Yahoo Pipes will not be affected by this header.
67 // Note: Using Disallow in a robots.txt file will be more effective (search engines will check
68 // that before even requesting makefulltextfeed.php).
69 ////////////////////////////////
70 header('X-Robots-Tag: noindex, nofollow');
72 ////////////////////////////////
73 // Check if service is enabled
74 ////////////////////////////////
75 if (!$options->enabled
) {
76 die('The full-text RSS service is currently disabled');
79 ////////////////////////////////
81 // See the config file for debug options.
82 ////////////////////////////////
84 if (isset($_GET['debug'])) {
85 if ($options->debug
=== true || $options->debug
== 'user') {
87 } elseif ($options->debug
== 'admin') {
89 $debug_mode = (@$_SESSION['auth'] == 1);
92 header('Content-Type: text/plain; charset=utf-8');
94 if ($options->debug
== 'admin') {
95 die('You must be logged in to the <a href="admin/">admin area</a> to see debug output.');
97 die('Debugging is disabled.');
102 ////////////////////////////////
104 ////////////////////////////////
105 $options->apc
= $options->apc
&& function_exists('apc_add');
107 debug('APC is enabled and available on server');
109 debug('APC is disabled or not available on server');
112 ////////////////////////////////
113 // Check for smart cache
114 ////////////////////////////////
115 $options->smart_cache
= $options->smart_cache
&& function_exists('apc_inc');
117 ////////////////////////////////
118 // Check for feed URL
119 ////////////////////////////////
120 if (!isset($_GET['url'])) {
121 die('No URL supplied');
123 $url = trim($_GET['url']);
124 if (strtolower(substr($url, 0, 7)) == 'feed://') {
125 $url = 'http://'.substr($url, 7);
127 if (!preg_match('!^https?://.+!i', $url)) {
128 $url = 'http://'.$url;
131 $url = filter_var($url, FILTER_SANITIZE_URL
);
132 $test = filter_var($url, FILTER_VALIDATE_URL
, FILTER_FLAG_SCHEME_REQUIRED
);
133 // deal with bug http://bugs.php.net/51192 (present in PHP 5.2.13 and PHP 5.3.2)
134 if ($test === false) {
135 $test = filter_var(strtr($url, '-', '_'), FILTER_VALIDATE_URL
, FILTER_FLAG_SCHEME_REQUIRED
);
137 if ($test !== false && $test !== null && preg_match('!^https?://!', $url)) {
141 die('Invalid URL supplied');
143 debug("Supplied URL: $url");
145 /////////////////////////////////
146 // Redirect to hide API key
147 /////////////////////////////////
148 if (isset($_GET['key']) && ($key_index = array_search($_GET['key'], $options->api_keys)) !== false) {
149 $host = $_SERVER['HTTP_HOST'];
150 $path = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
151 $_qs_url = (strtolower(substr($url, 0, 7)) == 'http://') ? substr($url, 7) : $url;
152 $redirect = 'http://'.htmlspecialchars($host.$path).'/makefulltextfeed.php?url='.urlencode($_qs_url);
153 $redirect .= '&key='.$key_index;
154 $redirect .= '&hash='.urlencode(sha1($_GET['key'].$url));
155 if (isset($_GET['html'])) $redirect .= '&html='.urlencode($_GET['html']);
156 if (isset($_GET['max'])) $redirect .= '&max='.(int)$_GET['max'];
157 if (isset($_GET['links'])) $redirect .= '&links='.urlencode($_GET['links']);
158 if (isset($_GET['exc'])) $redirect .= '&exc='.urlencode($_GET['exc']);
159 if (isset($_GET['format'])) $redirect .= '&format='.urlencode($_GET['format']);
160 if (isset($_GET['callback'])) $redirect .= '&callback='.urlencode($_GET['callback']);
161 if (isset($_GET['l'])) $redirect .= '&l='.urlencode($_GET['l']);
162 if (isset($_GET['xss'])) $redirect .= '&xss';
163 if (isset($_GET['use_extracted_title'])) $redirect .= '&use_extracted_title';
164 if (isset($_GET['content'])) $redirect .= '&content='.urlencode($_GET['content']);
165 if (isset($_GET['summary'])) $redirect .= '&summary='.urlencode($_GET['summary']);
166 if (isset($_GET['debug'])) $redirect .= '&debug';
168 debug('Redirecting to hide access key, follow URL below to continue');
169 debug("Location
: $redirect");
171 header("Location: $redirect");
176 ///////////////////////////////////////////////
178 // Prevents warnings, but needs more testing -
179 // perhaps if timezone is set in php.ini we
180 // don't need to set it at all...
181 ///////////////////////////////////////////////
182 if (!ini_get('date.timezone') || !@date_default_timezone_set(ini_get('date.timezone'))) {
183 date_default_timezone_set('UTC');
186 ///////////////////////////////////////////////
187 // Check if the request is explicitly for an HTML page
188 ///////////////////////////////////////////////
189 $html_only = (isset($_GET['html']) && ($_GET['html'] == '1' || $_GET['html'] == 'true'));
191 ///////////////////////////////////////////////
192 // Check if valid key supplied
193 ///////////////////////////////////////////////
195 if (isset($_GET['key']) && isset($_GET['hash']) && isset($options->api_keys[(int)$_GET['key']])) {
196 $valid_key = ($_GET['hash'] == sha1($options->api_keys[(int)$_GET['key']].$url));
198 $key_index = ($valid_key) ? (int)$_GET['key'] : 0;
199 if (!$valid_key && $options->key_required) {
200 die('A valid key must be supplied');
202 if (!$valid_key && isset($_GET['key']) && $_GET['key'] != '') {
203 die('The entered key is invalid');
206 if (file_exists('custom_init.php')) require 'custom_init.php';
208 ///////////////////////////////////////////////
209 // Check URL against list of blacklisted URLs
210 ///////////////////////////////////////////////
211 if (!url_allowed($url)) die('URL blocked');
213 ///////////////////////////////////////////////
215 // see config.php to find these values
216 ///////////////////////////////////////////////
217 if (isset($_GET['max'])) {
218 $max = (int)$_GET['max'];
220 $max = min($max, $options->max_entries_with_key);
222 $max = min($max, $options->max_entries);
226 $max = $options->default_entries_with_key;
228 $max = $options->default_entries;
232 ///////////////////////////////////////////////
234 ///////////////////////////////////////////////
235 if (isset($_GET['links']) && in_array($_GET['links'], array('preserve', 'footnotes', 'remove'))) {
236 $links = $_GET['links'];
241 ///////////////////////////////////////////////
242 // Favour item titles in feed?
243 ///////////////////////////////////////////////
244 $favour_feed_titles = true;
245 if ($options->favour_feed_titles == 'user') {
246 $favour_feed_titles = !isset($_GET['use_extracted_title']);
248 $favour_feed_titles = $options->favour_feed_titles;
251 ///////////////////////////////////////////////
252 // Include full content in output?
253 ///////////////////////////////////////////////
254 if ($options->content === 'user') {
255 if (isset($_GET['content']) && $_GET['content'] === '0') {
256 $options->content = false;
258 $options->content = true;
262 ///////////////////////////////////////////////
263 // Include summaries in output?
264 ///////////////////////////////////////////////
265 if ($options->summary === 'user') {
266 if (isset($_GET['summary']) && $_GET['summary'] === '1') {
267 $options->summary = true;
269 $options->summary = false;
273 ///////////////////////////////////////////////
274 // Exclude items if extraction fails
275 ///////////////////////////////////////////////
276 if ($options->exclude_items_on_fail === 'user') {
277 $exclude_on_fail = (isset($_GET['exc']) && ($_GET['exc'] == '1'));
279 $exclude_on_fail = $options->exclude_items_on_fail;
282 ///////////////////////////////////////////////
284 ///////////////////////////////////////////////
285 if ($options->detect_language === 'user') {
286 if (isset($_GET['l'])) {
287 $detect_language = (int)$_GET['l'];
289 $detect_language = 1;
292 $detect_language = $options->detect_language;
295 $use_cld = extension_loaded('cld') && (version_compare(PHP_VERSION, '5.3.0') >= 0);
297 /////////////////////////////////////
298 // Check for valid format
299 // (stick to RSS (or RSS as JSON) for the time being)
300 /////////////////////////////////////
301 if (isset($_GET['format']) && $_GET['format'] == 'json') {
307 /////////////////////////////////////
308 // Should we do XSS filtering?
309 /////////////////////////////////////
310 if ($options->xss_filter === 'user') {
311 $xss_filter = isset($_GET['xss']);
313 $xss_filter = $options->xss_filter;
315 if (!$xss_filter && isset($_GET['xss'])) {
316 die('XSS filtering is disabled in config');
319 /////////////////////////////////////
321 // Regex from https://gist.github.com/1217080
322 /////////////////////////////////////
324 if ($format =='json' && isset($_GET['callback'])) {
325 $callback = trim($_GET['callback']);
326 foreach (explode('.', $callback) as $_identifier) {
327 if (!preg_match('/^[a-zA-Z_$][0-9a-zA-Z_$]*(?:\[(?:".+
"|\'.+\'|\d+)\])*?$/', $_identifier)) {
328 die('Invalid JSONP callback');
331 debug("JSONP callback
: $callback");
334 //////////////////////////////////
335 // Enable Cross-Origin Resource Sharing (CORS)
336 //////////////////////////////////
337 if ($options->cors
) header('Access-Control-Allow-Origin: *');
339 //////////////////////////////////
340 // Check for cached copy
341 //////////////////////////////////
342 if ($options->caching
) {
343 debug('Caching is enabled...');
344 $cache_id = md5($max.$url.(int)$valid_key.$links.(int)$favour_feed_titles.(int)$options->content
.(int)$options->summary
.(int)$xss_filter.(int)$exclude_on_fail.$format.$detect_language.(int)isset($_GET['pubsub']));
346 if ($options->apc
&& $options->smart_cache
) {
347 apc_add("cache.$cache_id", 0, 10*60);
348 $apc_cache_hits = (int)apc_fetch("cache
.$cache_id");
349 $check_cache = ($apc_cache_hits >= 2);
350 apc_inc("cache.$cache_id");
352 debug('Cache key found in APC, we\'ll try to load cache file from disk');
354 debug('Cache key not found in APC');
358 $cache = get_cache();
359 if ($data = $cache->load($cache_id)) {
361 debug('Loaded cached copy');
364 if ($format == 'json') {
365 if ($callback === null) {
366 header('Content-type: application/json; charset=UTF-8');
368 header('Content-type: application/javascript; charset=UTF-8');
371 header('Content-type: text/xml; charset=UTF-8');
372 header('X-content-type-options: nosniff');
374 if (headers_sent()) die('Some data has already been output, can\'t send RSS file');
376 echo "$callback($data);";
385 //////////////////////////////////
386 // Set Expires header
387 //////////////////////////////////
389 header('Expires: ' . gmdate('D, d M Y H:i:s', time()+(60*10)) . ' GMT');
392 //////////////////////////////////
394 //////////////////////////////////
396 $http = new HumbleHttpAgent();
397 $http->debug = $debug_mode;
398 $http->userAgentMap = $options->user_agents;
399 $http->headerOnlyTypes = array_keys($options->content_type_exc);
400 $http->rewriteUrls = $options->rewrite_url;
402 //////////////////////////////////
403 // Set up Content Extractor
404 //////////////////////////////////
406 $extractor = new ContentExtractor(dirname(__FILE__).'/site_config/custom', dirname(__FILE__).'/site_config/standard');
407 $extractor->debug = $debug_mode;
408 SiteConfig::$debug = $debug_mode;
409 SiteConfig::use_apc($options->apc);
410 $extractor->fingerprints = $options->fingerprints;
411 $extractor->allowedParsers = $options->allowed_parsers;
413 ////////////////////////////////
415 ////////////////////////////////
418 debug("Attempting to process URL
as feed
");
419 // Send user agent header showing PHP (prevents a HTML response from feedburner)
420 $http->userAgentDefault = HumbleHttpAgent::UA_PHP;
421 // configure SimplePie HTTP extension class to use our HumbleHttpAgent instance
422 SimplePie_HumbleHttpAgent::set_agent($http);
423 $feed = new SimplePie();
424 // some feeds use the text/html content type - force_feed tells SimplePie to process anyway
425 $feed->force_feed(true);
426 $feed->set_file_class('SimplePie_HumbleHttpAgent');
427 //$feed->set_feed_url($url); // colons appearing in the URL's path get encoded
428 $feed->feed_url = $url;
429 $feed->set_autodiscovery_level(SIMPLEPIE_LOCATOR_NONE);
430 $feed->set_timeout(20);
431 $feed->enable_cache(false);
432 $feed->set_stupidly_fast(true);
433 $feed->enable_order_by_date(false); // we don't want to do anything to the feed
434 $feed->set_url_replacements(array());
435 // initialise the feed
436 // the @ suppresses notices which on some servers causes a 500 internal server error
437 $result = @$feed->init();
438 //$feed->handle_content_type();
439 //$feed->get_title();
440 if ($result && (!is_array($feed->data) || count($feed->data) == 0)) {
441 die('Sorry, no feed items found');
443 // from now on, we'll identify ourselves as a browser
444 $http->userAgentDefault = HumbleHttpAgent::UA_BROWSER;
447 ////////////////////////////////////////////////////////////////////////////////
448 // Our given URL is not a feed, so let's create our own feed with a single item:
449 // the given URL. This basically treats all non-feed URLs as if they were
450 // single-item feeds.
451 ////////////////////////////////////////////////////////////////////////////////
452 $isDummyFeed = false;
453 if ($html_only || !$result) {
455 debug("Constructing a single
-item feed from URL
");
457 unset($feed, $result);
458 // create single item dummy feed object
459 $feed = new DummySingleItemFeed($url);
462 ////////////////////////////////////////////
463 // Create full-text feed
464 ////////////////////////////////////////////
465 $output = new FeedWriter();
466 $output->setTitle(strip_tags($feed->get_title()));
467 $output->setDescription(strip_tags($feed->get_description()));
468 $output->setXsl('css/feed.xsl'); // Chrome uses this, most browsers ignore it
469 if ($valid_key && isset($_GET['pubsub'])) { // used only on fivefilters.org at the moment
470 $output->addHub('http://fivefilters.superfeedr.com/');
471 $output->addHub('http://pubsubhubbub.appspot.com/');
472 $output->setSelf('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
474 $output->setLink($feed->get_link()); // Google Reader uses this for pulling in favicons
475 if ($img_url = $feed->get_image_url()) {
476 $output->setImage($feed->get_title(), $feed->get_link(), $img_url);
479 ////////////////////////////////////////////
480 // Loop through feed items
481 ////////////////////////////////////////////
482 $items = $feed->get_items(0, $max);
483 // Request all feed items in parallel (if supported)
484 $urls_sanitized = array();
486 foreach ($items as $key => $item) {
487 $permalink = htmlspecialchars_decode($item->get_permalink());
488 // Colons in URL path segments get encoded by SimplePie, yet some sites expect them unencoded
489 $permalink = str_replace('%3A', ':', $permalink);
490 // validateUrl() strips non-ascii characters
491 // simplepie already sanitizes URLs so let's not do it again here.
492 //$permalink = $http->validateUrl($permalink);
494 $urls_sanitized[] = $permalink;
496 $urls[$key] = $permalink;
499 debug('Fetching feed items');
500 $http->fetchAll($urls_sanitized);
503 // count number of items added to full feed
506 foreach ($items as $key => $item) {
508 debug('Processing feed item '.($item_count+1));
509 $do_content_extraction = true;
510 $extract_result = false;
512 $permalink = $urls[$key];
513 debug("Item URL
: $permalink");
514 $extracted_title = '';
515 $feed_item_title = $item->get_title();
516 if ($feed_item_title !== null) {
517 $feed_item_title = strip_tags(htmlspecialchars_decode($feed_item_title));
519 $newitem = $output->createNewItem();
520 $newitem->setTitle($feed_item_title);
521 if ($valid_key && isset($_GET['pubsub'])) { // used only on fivefilters.org at the moment
522 if ($permalink !== false) {
523 $newitem->setLink('http://fivefilters.org/content-only/redirect.php?url='.urlencode($permalink));
525 $newitem->setLink('http://fivefilters.org/content-only/redirect.php?url='.urlencode($item->get_permalink()));
528 if ($permalink !== false) {
529 $newitem->setLink($permalink);
531 $newitem->setLink($item->get_permalink());
534 //if ($permalink && ($response = $http->get($permalink, true)) && $response['status_code'] < 300) {
535 // Allowing error codes - some sites return correct content with error status
536 // e.g. prospectmagazine.co.uk returns 403
537 if ($permalink && ($response = $http->get($permalink, true)) && ($response['status_code'] < 300 || $response['status_code'] > 400)) {
538 $effective_url = $response['effective_url'];
539 if (!url_allowed($effective_url)) continue;
540 // check if action defined for returned Content-Type
541 $mime_info = get_mime_action_info($response['headers']);
542 if (isset($mime_info['action'])) {
543 if ($mime_info['action'] == 'exclude') {
544 continue; // skip this feed item entry
545 } elseif ($mime_info['action'] == 'link') {
546 if ($mime_info['type'] == 'image') {
547 $html = "<a href=\"$effective_url\"><img src=\"$effective_url\" alt=\"{$mime_info['name']}\" /></a>";
549 $html = "<a href=\"$effective_url\">Download {$mime_info['name']}</a>";
551 $extracted_title = $mime_info['name'];
552 $do_content_extraction = false;
555 if ($do_content_extraction) {
556 $html = $response['body'];
557 // remove strange things
558 $html = str_replace('</[>', '', $html);
559 $html = convert_to_utf8($html, $response['headers']);
560 // check site config for single page URL - fetch it if found
561 $is_single_page = false;
562 if ($single_page_response = getSinglePage($item, $html, $effective_url)) {
563 $is_single_page = true;
564 $effective_url = $single_page_response['effective_url'];
565 // check if action defined for returned Content-Type
566 $mime_info = get_mime_action_info($single_page_response['headers']);
567 if (isset($mime_info['action'])) {
568 if ($mime_info['action'] == 'exclude') {
569 continue; // skip this feed item entry
570 } elseif ($mime_info['action'] == 'link') {
571 if ($mime_info['type'] == 'image') {
572 $html = "<a href=\"$effective_url\"><img src=\"$effective_url\" alt=\"{$mime_info['name']}\" /></a>";
574 $html = "<a href=\"$effective_url\">Download {$mime_info['name']}</a>";
576 $extracted_title = $mime_info['name'];
577 $do_content_extraction = false;
580 if ($do_content_extraction) {
581 $html = $single_page_response['body'];
582 // remove strange things
583 $html = str_replace('</[>', '', $html);
584 $html = convert_to_utf8($html, $single_page_response['headers']);
585 debug("Retrieved single-page view from $effective_url");
587 unset($single_page_response);
590 if ($do_content_extraction) {
592 debug('Attempting to extract content');
593 $extract_result = $extractor->process($html, $effective_url);
594 $readability = $extractor->readability;
595 $content_block = ($extract_result) ? $extractor->getContent() : null;
596 $extracted_title = ($extract_result) ? $extractor->getTitle() : '';
597 // Deal with multi-page articles
598 //die('Next: '.$extractor->getNextPageUrl());
599 $is_multi_page = (!$is_single_page && $extract_result && $extractor->getNextPageUrl());
600 if ($options->multipage && $is_multi_page && $options->content) {
602 debug('Attempting to process multi-page article');
603 $multi_page_urls = array();
604 $multi_page_content = array();
605 while ($next_page_url = $extractor->getNextPageUrl()) {
607 debug('Processing next page: '.$next_page_url);
608 // If we've got URL, resolve against $url
609 if ($next_page_url = makeAbsoluteStr($effective_url, $next_page_url)) {
610 // check it's not what we have already!
611 if (!in_array($next_page_url, $multi_page_urls)) {
612 // it's not, so let's attempt to fetch it
613 $multi_page_urls[] = $next_page_url;
614 $_prev_ref = $http->referer;
615 if (($response = $http->get($next_page_url, true)) && $response['status_code'] < 300) {
616 // make sure mime type is not something with a different action associated
617 $page_mime_info = get_mime_action_info($response['headers']);
618 if (!isset($page_mime_info['action'])) {
619 $html = $response['body'];
620 // remove strange things
621 $html = str_replace('</[>', '', $html);
622 $html = convert_to_utf8($html, $response['headers']);
623 if ($extractor->process($html, $next_page_url)) {
624 $multi_page_content[] = $extractor->getContent();
626 } else { debug('Failed to extract content'); }
627 } else { debug('MIME type requires different action'); }
628 } else { debug('Failed to fetch URL'); }
629 } else { debug('URL already processed'); }
630 } else { debug('Failed to resolve against '.$effective_url); }
631 // failed to process next_page_url, so cancel further requests
632 $multi_page_content = array();
635 // did we successfully deal with this multi-page article?
636 if (empty($multi_page_content)) {
637 debug('Failed to extract all parts of multi-page article, so not going to include them');
638 $_page = $readability->dom->createElement('p');
639 $_page->innerHTML = '<em>This article appears to continue on subsequent pages which we could not extract</em>';
640 $multi_page_content[] = $_page;
642 foreach ($multi_page_content as $_page) {
643 $_page = $content_block->ownerDocument->importNode($_page, true);
644 $content_block->appendChild($_page);
646 unset($multi_page_urls, $multi_page_content, $page_mime_info, $next_page_url, $_page);
649 // use extracted title for both feed and item title if we're using single-item dummy feed
651 $output->setTitle($extracted_title);
652 $newitem->setTitle($extracted_title);
654 // use extracted title instead of feed item title?
655 if (!$favour_feed_titles && $extracted_title != '') {
656 debug('Using extracted title in generated feed');
657 $newitem->setTitle($extracted_title);
661 if ($do_content_extraction) {
662 // if we failed to extract content...
663 if (!$extract_result) {
664 if ($exclude_on_fail) {
665 debug('Failed to extract, so skipping (due to exclude on fail parameter)');
666 continue; // skip this and move to next item
668 //TODO: get text sample for language detection
669 $html = $options->error_message;
670 // keep the original item description
671 $html .= $item->get_description();
673 $readability->clean($content_block, 'select');
675 $base_url = get_base_url($readability->dom);
676 if (!$base_url) $base_url = $effective_url;
678 if ($options->rewrite_relative_urls) makeAbsolute($base_url, $content_block);
680 if (($links == 'footnotes') && (strpos($effective_url, 'wikipedia.org') === false)) {
681 $readability->addFootnotes($content_block);
683 // remove nesting: <div><div><div><p>test</p></div></div></div> = <p>test</p>
684 while ($content_block->childNodes->length == 1 && $content_block->firstChild->nodeType === XML_ELEMENT_NODE) {
685 // only follow these tag names
686 if (!in_array(strtolower($content_block->tagName), array('div', 'article', 'section', 'header', 'footer'))) break;
687 //$html = $content_block->firstChild->innerHTML; // FTR 2.9.5
688 $content_block = $content_block->firstChild;
690 // convert content block to HTML string
691 // Need to preserve things like body: //img[@id='feature']
692 if (in_array(strtolower($content_block->tagName), array('div', 'article', 'section', 'header', 'footer'))) {
693 $html = $content_block->innerHTML;
695 $html = $content_block->ownerDocument->saveXML($content_block); // essentially outerHTML
697 //unset($content_block);
698 // post-processing cleanup
699 $html = preg_replace('!<p>[\s\h\v]*</p>!u', '', $html);
700 if ($links == 'remove') {
701 $html = preg_replace('!</?a[^>]*>!', '', $html);
703 // get text sample for language detection
704 $text_sample = strip_tags(substr($html, 0, 500));
705 $html = make_substitutions($options->message_to_prepend).$html;
706 $html .= make_substitutions($options->message_to_append);
710 if ($valid_key && isset($_GET['pubsub'])) { // used only on fivefilters.org at the moment
711 $newitem->addElement('guid', 'http://fivefilters.org/content-only/redirect.php?url='.urlencode($item->get_permalink()), array('isPermaLink'=>'false'));
713 $newitem->addElement('guid', $item->get_permalink(), array('isPermaLink'=>'true'));
717 debug('Filtering HTML to remove XSS');
718 $html = htmLawed::hl($html, array('safe'=>1, 'deny_attribute'=>'style', 'comment'=>1, 'cdata'=>1));
722 if ($options->summary === true) {
725 if (!$do_content_extraction) {
728 // Try to get first few paragraphs
729 if (isset($content_block) && ($content_block instanceof DOMElement)) {
730 $_paras = $content_block->getElementsByTagName('p');
731 foreach ($_paras as $_para) {
732 $summary .= preg_replace("/[\n\r\t ]+
/", ' ', $_para->textContent).' ';
733 if (strlen($summary) > 200) break;
739 unset($_paras, $_para);
740 $summary = get_excerpt($summary);
741 $newitem->setDescription($summary);
742 if ($options->content) $newitem->setElement('content:encoded', $html);
744 if ($options->content) $newitem->setDescription($html);
748 if ((int)$item->get_date('U') > 0) {
749 $newitem->setDate((int)$item->get_date('U'));
750 } elseif ($extractor->getDate()) {
751 $newitem->setDate($extractor->getDate());
755 if ($authors = $item->get_authors()) {
756 foreach ($authors as $author) {
757 // for some feeds, SimplePie stores author's name as email, e.g. http://feeds.feedburner.com/nymag/intel
758 if ($author->get_name() !== null) {
759 $newitem->addElement('dc:creator', $author->get_name());
760 } elseif ($author->get_email() !== null) {
761 $newitem->addElement('dc:creator', $author->get_email());
764 } elseif ($authors = $extractor->getAuthors()) {
765 //TODO: make sure the list size is reasonable
766 foreach ($authors as $author) {
767 // TODO: xpath often selects authors from other articles linked from the page.
768 // for now choose first item
769 $newitem->addElement('dc:creator', $author);
775 if ($detect_language) {
776 $language = $extractor->getLanguage();
777 if (!$language) $language = $feed->get_language();
778 if (($detect_language == 3 || (!$language && $detect_language == 2)) && $text_sample) {
781 // Use PHP-CLD extension
782 $php_cld = 'CLD\detect'; // in quotes to prevent PHP 5.2 parse error
783 $res = $php_cld($text_sample);
784 if (is_array($res) && count($res) > 0) {
785 $language = $res[0]['code'];
789 // Use PEAR's Text_LanguageDetect
791 $l = new Text_LanguageDetect();
792 $l->setNameMode(2); // return ISO 639-1 codes (e.g. "en
")
794 $l_result = $l->detect($text_sample, 1);
795 if (count($l_result) > 0) {
796 $language = key($l_result);
799 } catch (Exception $e) {
804 if ($language && (strlen($language) < 7)) {
805 $newitem->addElement('dc:language', $language);
809 // add MIME type (if it appeared in our exclusions lists)
810 if (isset($mime_info['mime'])) $newitem->addElement('dc:format', $mime_info['mime']);
811 // add effective URL (URL after redirects)
812 if (isset($effective_url)) {
813 //TODO: ensure $effective_url is valid witout - sometimes it causes problems, e.g.
814 //http://www.siasat.pk/forum/showthread.php?108883-Pakistan-Chowk-by-Rana-Mubashir-�-25th-March-2012-Special-Program-from-Liari-(Karachi)
815 //temporary measure: use utf8_encode()
816 $newitem->addElement('dc:identifier', remove_url_cruft(utf8_encode($effective_url)));
818 $newitem->addElement('dc:identifier', remove_url_cruft($item->get_permalink()));
822 if ($categories = $item->get_categories()) {
823 foreach ($categories as $category) {
824 if ($category->get_label() !== null) {
825 $newitem->addElement('category', $category->get_label());
830 // check for enclosures
831 if ($options->keep_enclosures) {
832 if ($enclosures = $item->get_enclosures()) {
833 foreach ($enclosures as $enclosure) {
835 foreach ((array)$enclosure->get_thumbnails() as $thumbnail) {
836 $newitem->addElement('media:thumbnail', '', array('url'=>$thumbnail));
838 if (!$enclosure->get_link()) continue;
840 // Media RSS spec ($enc): http://search.yahoo.com/mrss
841 // SimplePie methods ($enclosure): http://simplepie.org/wiki/reference/start#methods4
842 $enc['url'] = $enclosure->get_link();
843 if ($enclosure->get_length()) $enc['fileSize'] = $enclosure->get_length();
844 if ($enclosure->get_type()) $enc['type'] = $enclosure->get_type();
845 if ($enclosure->get_medium()) $enc['medium'] = $enclosure->get_medium();
846 if ($enclosure->get_expression()) $enc['expression'] = $enclosure->get_expression();
847 if ($enclosure->get_bitrate()) $enc['bitrate'] = $enclosure->get_bitrate();
848 if ($enclosure->get_framerate()) $enc['framerate'] = $enclosure->get_framerate();
849 if ($enclosure->get_sampling_rate()) $enc['samplingrate'] = $enclosure->get_sampling_rate();
850 if ($enclosure->get_channels()) $enc['channels'] = $enclosure->get_channels();
851 if ($enclosure->get_duration()) $enc['duration'] = $enclosure->get_duration();
852 if ($enclosure->get_height()) $enc['height'] = $enclosure->get_height();
853 if ($enclosure->get_width()) $enc['width'] = $enclosure->get_width();
854 if ($enclosure->get_language()) $enc['lang'] = $enclosure->get_language();
855 $newitem->addElement('media:content', '', $enc);
859 $output->addItem($newitem);
868 $_apc_data = apc_cache_info('user');
869 var_dump($_apc_data); exit;
873 if ($callback) echo "$callback("; // if $callback is set, $format also == 'json'
874 if ($format == 'json') $output->setFormat(($callback === null) ? JSON : JSONP);
875 $add_to_cache = $options->caching;
876 // is smart cache mode enabled?
877 if ($add_to_cache && $options->apc && $options->smart_cache) {
878 // yes, so only cache if this is the second request for this URL
879 $add_to_cache = ($apc_cache_hits >= 2);
881 if ($options->cache_cleanup > 0) {
882 if (rand(1, $options->cache_cleanup) == 1) {
883 // apc purge code adapted from from http://www.thimbleopensource.com/tutorials-snippets/php-apc-expunge-script
884 $_apc_data = apc_cache_info('user');
885 foreach ($_apc_data['cache_list'] as $_apc_item) {
886 if ($_apc_item['ttl'] > 0 && ($_apc_item['ttl'] + $_apc_item['creation_time'] < time())) {
887 apc_delete($_apc_item['info']);
895 $output->genarateFeed(false);
896 $output = ob_get_contents();
898 if ($html_only && $item_count == 0) {
899 // do not cache - in case of temporary server glitch at source URL
901 $cache = get_cache();
902 if ($add_to_cache) $cache->save($output, $cache_id);
906 $output->genarateFeed(false);
908 if ($callback) echo ');';