X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=inc%2F3rdparty%2Fmakefulltextfeed.php;h=a081f88b29f6800dab4cd2249366e35d45cd33dd;hb=90a1a78b1e2f4d40e1d9b8e6f46aca129a9d7bcf;hp=2852c4c2a76fbda3e902de30aea99873abb87d2e;hpb=6203ef8e51c8b2712e54a01a183f30d282926b0b;p=github%2Fwallabag%2Fwallabag.git diff --git a/inc/3rdparty/makefulltextfeed.php b/inc/3rdparty/makefulltextfeed.php index 2852c4c2..a081f88b 100755 --- a/inc/3rdparty/makefulltextfeed.php +++ b/inc/3rdparty/makefulltextfeed.php @@ -3,8 +3,8 @@ // Author: Keyvan Minoukadeh // Copyright (c) 2013 Keyvan Minoukadeh // License: AGPLv3 -// Version: 3.1 -// Date: 2013-03-05 +// Version: 3.2 +// Date: 2013-05-13 // More info: http://fivefilters.org/content-only/ // Help: http://help.fivefilters.org @@ -25,14 +25,10 @@ along with this program. If not, see . // Usage // ----- -// Request this file passing it your feed in the querystring: makefulltextfeed.php?url=mysite.org -// The following options can be passed in the querystring: -// * URL: url=[feed or website url] (required, should be URL-encoded - in php: urlencode($url)) -// * URL points to HTML (not feed): html=true (optional, by default it's automatically detected) -// * API key: key=[api key] (optional, refer to config.php) -// * Max entries to process: max=[max number of items] (optional) +// Request this file passing it a web page or feed URL in the querystring: makefulltextfeed.php?url=example.org/article +// For more request parameters, see http://help.fivefilters.org/customer/portal/articles/226660-usage -error_reporting(E_ALL ^ E_NOTICE); +//error_reporting(E_ALL ^ E_NOTICE); ini_set("display_errors", 1); @set_time_limit(120); @@ -55,42 +51,8 @@ if (get_magic_quotes_gpc()) { // set include path set_include_path(realpath(dirname(__FILE__).'/libraries').PATH_SEPARATOR.get_include_path()); -// Autoloading of classes allows us to include files only when they're -// needed. If we've got a cached copy, for example, only Zend_Cache is loaded. -function autoload($class_name) { - static $dir = null; - if ($dir === null) $dir = dirname(__FILE__).'/libraries/'; - static $mapping = array( - // Include FeedCreator for RSS/Atom creation - 'FeedWriter' => 'feedwriter/FeedWriter.php', - 'FeedItem' => 'feedwriter/FeedItem.php', - // Include ContentExtractor and Readability for identifying and extracting content from URLs - 'ContentExtractor' => 'content-extractor/ContentExtractor.php', - 'SiteConfig' => 'content-extractor/SiteConfig.php', - 'Readability' => 'readability/Readability.php', - // Include Humble HTTP Agent to allow parallel requests and response caching - 'HumbleHttpAgent' => 'humble-http-agent/HumbleHttpAgent.php', - 'SimplePie_HumbleHttpAgent' => 'humble-http-agent/SimplePie_HumbleHttpAgent.php', - 'CookieJar' => 'humble-http-agent/CookieJar.php', - // Include Zend Cache to improve performance (cache results) - 'Zend_Cache' => 'Zend/Cache.php', - // Language detect - 'Text_LanguageDetect' => 'language-detect/LanguageDetect.php', - // HTML5 Lib - 'HTML5_Parser' => 'html5/Parser.php', - // htmLawed - used if XSS filter is enabled (xss_filter) - 'htmLawed' => 'htmLawed/htmLawed.php' - ); - if (isset($mapping[$class_name])) { - debug("** Loading class $class_name ({$mapping[$class_name]})"); - require $dir.$mapping[$class_name]; - return true; - } else { - return false; - } -} -spl_autoload_register('autoload'); -require dirname(__FILE__).'/libraries/simplepie/autoloader.php'; + +require_once dirname(__FILE__).'/makefulltextfeedHelpers.php'; //////////////////////////////// // Load config file @@ -110,8 +72,8 @@ header('X-Robots-Tag: noindex, nofollow'); //////////////////////////////// // Check if service is enabled //////////////////////////////// -if (!$options->enabled) { - die('The full-text RSS service is currently disabled'); +if (!$options->enabled) { + die('The full-text RSS service is currently disabled'); } //////////////////////////////// @@ -155,8 +117,8 @@ $options->smart_cache = $options->smart_cache && function_exists('apc_inc'); //////////////////////////////// // Check for feed URL //////////////////////////////// -if (!isset($_GET['url'])) { - die('No URL supplied'); +if (!isset($_GET['url'])) { + die('No URL supplied'); } $url = trim($_GET['url']); if (strtolower(substr($url, 0, 7)) == 'feed://') { @@ -195,10 +157,12 @@ if (isset($_GET['key']) && ($key_index = array_search($_GET['key'], $options->ap if (isset($_GET['links'])) $redirect .= '&links='.urlencode($_GET['links']); if (isset($_GET['exc'])) $redirect .= '&exc='.urlencode($_GET['exc']); if (isset($_GET['format'])) $redirect .= '&format='.urlencode($_GET['format']); - if (isset($_GET['callback'])) $redirect .= '&callback='.urlencode($_GET['callback']); + if (isset($_GET['callback'])) $redirect .= '&callback='.urlencode($_GET['callback']); if (isset($_GET['l'])) $redirect .= '&l='.urlencode($_GET['l']); if (isset($_GET['xss'])) $redirect .= '&xss'; if (isset($_GET['use_extracted_title'])) $redirect .= '&use_extracted_title'; + if (isset($_GET['content'])) $redirect .= '&content='.urlencode($_GET['content']); + if (isset($_GET['summary'])) $redirect .= '&summary='.urlencode($_GET['summary']); if (isset($_GET['debug'])) $redirect .= '&debug'; if ($debug_mode) { debug('Redirecting to hide access key, follow URL below to continue'); @@ -211,7 +175,7 @@ if (isset($_GET['key']) && ($key_index = array_search($_GET['key'], $options->ap /////////////////////////////////////////////// // Set timezone. -// Prevents warnings, but needs more testing - +// Prevents warnings, but needs more testing - // perhaps if timezone is set in php.ini we // don't need to set it at all... /////////////////////////////////////////////// @@ -233,7 +197,7 @@ if (isset($_GET['key']) && isset($_GET['hash']) && isset($options->api_keys[(int } $key_index = ($valid_key) ? (int)$_GET['key'] : 0; if (!$valid_key && $options->key_required) { - die('A valid key must be supplied'); + die('A valid key must be supplied'); } if (!$valid_key && isset($_GET['key']) && $_GET['key'] != '') { die('The entered key is invalid'); @@ -284,6 +248,28 @@ if ($options->favour_feed_titles == 'user') { $favour_feed_titles = $options->favour_feed_titles; } +/////////////////////////////////////////////// +// Include full content in output? +/////////////////////////////////////////////// +if ($options->content === 'user') { + if (isset($_GET['content']) && $_GET['content'] === '0') { + $options->content = false; + } else { + $options->content = true; + } +} + +/////////////////////////////////////////////// +// Include summaries in output? +/////////////////////////////////////////////// +if ($options->summary === 'user') { + if (isset($_GET['summary']) && $_GET['summary'] === '1') { + $options->summary = true; + } else { + $options->summary = false; + } +} + /////////////////////////////////////////////// // Exclude items if extraction fails /////////////////////////////////////////////// @@ -306,15 +292,6 @@ if ($options->detect_language === 'user') { $detect_language = $options->detect_language; } -if ($detect_language >= 2) { - $language_codes = array('albanian' => 'sq','arabic' => 'ar','azeri' => 'az','bengali' => 'bn','bulgarian' => 'bg', - 'cebuano' => 'ceb', // ISO 639-2 - 'croatian' => 'hr','czech' => 'cs','danish' => 'da','dutch' => 'nl','english' => 'en','estonian' => 'et','farsi' => 'fa','finnish' => 'fi','french' => 'fr','german' => 'de','hausa' => 'ha', - 'hawaiian' => 'haw', // ISO 639-2 - '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', - 'pidgin' => 'cpe', // ISO 639-2 - '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'); -} $use_cld = extension_loaded('cld') && (version_compare(PHP_VERSION, '5.3.0') >= 0); ///////////////////////////////////// @@ -364,7 +341,7 @@ if ($options->cors) header('Access-Control-Allow-Origin: *'); ////////////////////////////////// if ($options->caching) { debug('Caching is enabled...'); - $cache_id = md5($max.$url.$valid_key.$links.$favour_feed_titles.$xss_filter.$exclude_on_fail.$format.$detect_language.(int)isset($_GET['pubsub'])); + $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'])); $check_cache = true; if ($options->apc && $options->smart_cache) { apc_add("cache.$cache_id", 0, 10*60); @@ -415,6 +392,7 @@ if (!$debug_mode) { ////////////////////////////////// // Set up HTTP agent ////////////////////////////////// +global $http; $http = new HumbleHttpAgent(); $http->debug = $debug_mode; $http->userAgentMap = $options->user_agents; @@ -478,29 +456,6 @@ if ($html_only || !$result) { $isDummyFeed = true; unset($feed, $result); // create single item dummy feed object - class DummySingleItemFeed { - public $item; - function __construct($url) { $this->item = new DummySingleItem($url); } - public function get_title() { return ''; } - public function get_description() { return 'Content extracted from '.$this->item->url; } - public function get_link() { return $this->item->url; } - public function get_language() { return false; } - public function get_image_url() { return false; } - public function get_items($start=0, $max=1) { return array(0=>$this->item); } - } - class DummySingleItem { - public $url; - function __construct($url) { $this->url = $url; } - public function get_permalink() { return $this->url; } - public function get_title() { return null; } - public function get_date($format='') { return false; } - public function get_author($key=0) { return null; } - public function get_authors() { return null; } - public function get_description() { return ''; } - public function get_enclosure($key=0, $prefer=null) { return null; } - public function get_enclosures() { return null; } - public function get_categories() { return null; } - } $feed = new DummySingleItemFeed($url); } @@ -524,7 +479,7 @@ if ($img_url = $feed->get_image_url()) { //////////////////////////////////////////// // Loop through feed items //////////////////////////////////////////// -$items = $feed->get_items(0, $max); +$items = $feed->get_items(0, $max); // Request all feed items in parallel (if supported) $urls_sanitized = array(); $urls = array(); @@ -606,24 +561,43 @@ foreach ($items as $key => $item) { $is_single_page = false; if ($single_page_response = getSinglePage($item, $html, $effective_url)) { $is_single_page = true; - $html = $single_page_response['body']; - // remove strange things - $html = str_replace('', '', $html); - $html = convert_to_utf8($html, $single_page_response['headers']); $effective_url = $single_page_response['effective_url']; - debug("Retrieved single-page view from $effective_url"); + // check if action defined for returned Content-Type + $mime_info = get_mime_action_info($single_page_response['headers']); + if (isset($mime_info['action'])) { + if ($mime_info['action'] == 'exclude') { + continue; // skip this feed item entry + } elseif ($mime_info['action'] == 'link') { + if ($mime_info['type'] == 'image') { + $html = "\"{$mime_info['name']}\""; + } else { + $html = "Download {$mime_info['name']}"; + } + $extracted_title = $mime_info['name']; + $do_content_extraction = false; + } + } + if ($do_content_extraction) { + $html = $single_page_response['body']; + // remove strange things + $html = str_replace('', '', $html); + $html = convert_to_utf8($html, $single_page_response['headers']); + debug("Retrieved single-page view from $effective_url"); + } unset($single_page_response); } + } + if ($do_content_extraction) { debug('--------'); debug('Attempting to extract content'); $extract_result = $extractor->process($html, $effective_url); $readability = $extractor->readability; - $content_block = ($extract_result) ? $extractor->getContent() : null; + $content_block = ($extract_result) ? $extractor->getContent() : null; $extracted_title = ($extract_result) ? $extractor->getTitle() : ''; // Deal with multi-page articles //die('Next: '.$extractor->getNextPageUrl()); $is_multi_page = (!$is_single_page && $extract_result && $extractor->getNextPageUrl()); - if ($options->multipage && $is_multi_page) { + if ($options->multipage && $is_multi_page && $options->content) { debug('--------'); debug('Attempting to process multi-page article'); $multi_page_urls = array(); @@ -636,7 +610,7 @@ foreach ($items as $key => $item) { // check it's not what we have already! if (!in_array($next_page_url, $multi_page_urls)) { // it's not, so let's attempt to fetch it - $multi_page_urls[] = $next_page_url; + $multi_page_urls[] = $next_page_url; $_prev_ref = $http->referer; if (($response = $http->get($next_page_url, true)) && $response['status_code'] < 300) { // make sure mime type is not something with a different action associated @@ -661,13 +635,15 @@ foreach ($items as $key => $item) { // did we successfully deal with this multi-page article? if (empty($multi_page_content)) { debug('Failed to extract all parts of multi-page article, so not going to include them'); - $multi_page_content[] = $readability->dom->createElement('p')->innerHTML = 'This article appears to continue on subsequent pages which we could not extract'; + $_page = $readability->dom->createElement('p'); + $_page->innerHTML = 'This article appears to continue on subsequent pages which we could not extract'; + $multi_page_content[] = $_page; } foreach ($multi_page_content as $_page) { $_page = $content_block->ownerDocument->importNode($_page, true); $content_block->appendChild($_page); } - unset($multi_page_urls, $multi_page_content, $page_mime_info, $next_page_url); + unset($multi_page_urls, $multi_page_content, $page_mime_info, $next_page_url, $_page); } } // use extracted title for both feed and item title if we're using single-item dummy feed @@ -695,7 +671,11 @@ foreach ($items as $key => $item) { $html .= $item->get_description(); } else { $readability->clean($content_block, 'select'); - if ($options->rewrite_relative_urls) makeAbsolute($effective_url, $content_block); + // get base URL + $base_url = get_base_url($readability->dom); + if (!$base_url) $base_url = $effective_url; + // rewrite URLs + if ($options->rewrite_relative_urls) makeAbsolute($base_url, $content_block); // footnotes if (($links == 'footnotes') && (strpos($effective_url, 'wikipedia.org') === false)) { $readability->addFootnotes($content_block); @@ -714,7 +694,7 @@ foreach ($items as $key => $item) { } else { $html = $content_block->ownerDocument->saveXML($content_block); // essentially outerHTML } - unset($content_block); + //unset($content_block); // post-processing cleanup $html = preg_replace('!

[\s\h\v]*

!u', '', $html); if ($links == 'remove') { @@ -727,130 +707,155 @@ foreach ($items as $key => $item) { } } - if ($valid_key && isset($_GET['pubsub'])) { // used only on fivefilters.org at the moment - $newitem->addElement('guid', 'http://fivefilters.org/content-only/redirect.php?url='.urlencode($item->get_permalink()), array('isPermaLink'=>'false')); + if ($valid_key && isset($_GET['pubsub'])) { // used only on fivefilters.org at the moment + $newitem->addElement('guid', 'http://fivefilters.org/content-only/redirect.php?url='.urlencode($item->get_permalink()), array('isPermaLink'=>'false')); + } else { + $newitem->addElement('guid', $item->get_permalink(), array('isPermaLink'=>'true')); + } + // filter xss? + if ($xss_filter) { + debug('Filtering HTML to remove XSS'); + $html = htmLawed::hl($html, array('safe'=>1, 'deny_attribute'=>'style', 'comment'=>1, 'cdata'=>1)); + } + + // add content + if ($options->summary === true) { + // get summary + $summary = ''; + if (!$do_content_extraction) { + $summary = $html; } else { - $newitem->addElement('guid', $item->get_permalink(), array('isPermaLink'=>'true')); - } - // filter xss? - if ($xss_filter) { - debug('Filtering HTML to remove XSS'); - $html = htmLawed::hl($html, array('safe'=>1, 'deny_attribute'=>'style', 'comment'=>1, 'cdata'=>1)); - } - $newitem->setDescription($html); - - // set date - if ((int)$item->get_date('U') > 0) { - $newitem->setDate((int)$item->get_date('U')); - } elseif ($extractor->getDate()) { - $newitem->setDate($extractor->getDate()); - } - - // add authors - if ($authors = $item->get_authors()) { - foreach ($authors as $author) { - // for some feeds, SimplePie stores author's name as email, e.g. http://feeds.feedburner.com/nymag/intel - if ($author->get_name() !== null) { - $newitem->addElement('dc:creator', $author->get_name()); - } elseif ($author->get_email() !== null) { - $newitem->addElement('dc:creator', $author->get_email()); + // Try to get first few paragraphs + if (isset($content_block) && ($content_block instanceof DOMElement)) { + $_paras = $content_block->getElementsByTagName('p'); + foreach ($_paras as $_para) { + $summary .= preg_replace("/[\n\r\t ]+/", ' ', $_para->textContent).' '; + if (strlen($summary) > 200) break; } + } else { + $summary = $html; } - } elseif ($authors = $extractor->getAuthors()) { - //TODO: make sure the list size is reasonable - foreach ($authors as $author) { - // TODO: xpath often selects authors from other articles linked from the page. - // for now choose first item - $newitem->addElement('dc:creator', $author); - break; + } + unset($_paras, $_para); + $summary = get_excerpt($summary); + $newitem->setDescription($summary); + if ($options->content) $newitem->setElement('content:encoded', $html); + } else { + if ($options->content) $newitem->setDescription($html); + } + + // set date + if ((int)$item->get_date('U') > 0) { + $newitem->setDate((int)$item->get_date('U')); + } elseif ($extractor->getDate()) { + $newitem->setDate($extractor->getDate()); + } + + // add authors + if ($authors = $item->get_authors()) { + foreach ($authors as $author) { + // for some feeds, SimplePie stores author's name as email, e.g. http://feeds.feedburner.com/nymag/intel + if ($author->get_name() !== null) { + $newitem->addElement('dc:creator', $author->get_name()); + } elseif ($author->get_email() !== null) { + $newitem->addElement('dc:creator', $author->get_email()); } } - - // add language - if ($detect_language) { - $language = $extractor->getLanguage(); - if (!$language) $language = $feed->get_language(); - if (($detect_language == 3 || (!$language && $detect_language == 2)) && $text_sample) { - try { - if ($use_cld) { - // Use PHP-CLD extension - $php_cld = 'CLD\detect'; // in quotes to prevent PHP 5.2 parse error - $res = $php_cld($text_sample); - if (is_array($res) && count($res) > 0) { - $language = $res[0]['code']; - } - } else { - //die('what'); - // Use PEAR's Text_LanguageDetect - if (!isset($l)) { - $l = new Text_LanguageDetect('libraries/language-detect/lang.dat', 'libraries/language-detect/unicode_blocks.dat'); - } - $l_result = $l->detect($text_sample, 1); - if (count($l_result) > 0) { - $language = $language_codes[key($l_result)]; - } + } elseif ($authors = $extractor->getAuthors()) { + //TODO: make sure the list size is reasonable + foreach ($authors as $author) { + // TODO: xpath often selects authors from other articles linked from the page. + // for now choose first item + $newitem->addElement('dc:creator', $author); + break; + } + } + + // add language + if ($detect_language) { + $language = $extractor->getLanguage(); + if (!$language) $language = $feed->get_language(); + if (($detect_language == 3 || (!$language && $detect_language == 2)) && $text_sample) { + try { + if ($use_cld) { + // Use PHP-CLD extension + $php_cld = 'CLD\detect'; // in quotes to prevent PHP 5.2 parse error + $res = $php_cld($text_sample); + if (is_array($res) && count($res) > 0) { + $language = $res[0]['code']; + } + } else { + //die('what'); + // Use PEAR's Text_LanguageDetect + if (!isset($l)) { + $l = new Text_LanguageDetect(); + $l->setNameMode(2); // return ISO 639-1 codes (e.g. "en") + } + $l_result = $l->detect($text_sample, 1); + if (count($l_result) > 0) { + $language = key($l_result); } - } catch (Exception $e) { - //die('error: '.$e); - // do nothing } - } - if ($language && (strlen($language) < 7)) { - $newitem->addElement('dc:language', $language); + } catch (Exception $e) { + //die('error: '.$e); + // do nothing } } - - // add MIME type (if it appeared in our exclusions lists) - if (isset($mime_info['mime'])) $newitem->addElement('dc:format', $mime_info['mime']); - // add effective URL (URL after redirects) - if (isset($effective_url)) { - //TODO: ensure $effective_url is valid witout - sometimes it causes problems, e.g. - //http://www.siasat.pk/forum/showthread.php?108883-Pakistan-Chowk-by-Rana-Mubashir-–-25th-March-2012-Special-Program-from-Liari-(Karachi) - //temporary measure: use utf8_encode() - $newitem->addElement('dc:identifier', remove_url_cruft(utf8_encode($effective_url))); - } else { - $newitem->addElement('dc:identifier', remove_url_cruft($item->get_permalink())); + if ($language && (strlen($language) < 7)) { + $newitem->addElement('dc:language', $language); } - - // add categories - if ($categories = $item->get_categories()) { - foreach ($categories as $category) { - if ($category->get_label() !== null) { - $newitem->addElement('category', $category->get_label()); - } + } + + // add MIME type (if it appeared in our exclusions lists) + if (isset($mime_info['mime'])) $newitem->addElement('dc:format', $mime_info['mime']); + // add effective URL (URL after redirects) + if (isset($effective_url)) { + //TODO: ensure $effective_url is valid witout - sometimes it causes problems, e.g. + //http://www.siasat.pk/forum/showthread.php?108883-Pakistan-Chowk-by-Rana-Mubashir-�-25th-March-2012-Special-Program-from-Liari-(Karachi) + //temporary measure: use utf8_encode() + $newitem->addElement('dc:identifier', remove_url_cruft(utf8_encode($effective_url))); + } else { + $newitem->addElement('dc:identifier', remove_url_cruft($item->get_permalink())); + } + + // add categories + if ($categories = $item->get_categories()) { + foreach ($categories as $category) { + if ($category->get_label() !== null) { + $newitem->addElement('category', $category->get_label()); } } - - // check for enclosures - if ($options->keep_enclosures) { - if ($enclosures = $item->get_enclosures()) { - foreach ($enclosures as $enclosure) { - // thumbnails - foreach ((array)$enclosure->get_thumbnails() as $thumbnail) { - $newitem->addElement('media:thumbnail', '', array('url'=>$thumbnail)); - } - if (!$enclosure->get_link()) continue; - $enc = array(); - // Media RSS spec ($enc): http://search.yahoo.com/mrss - // SimplePie methods ($enclosure): http://simplepie.org/wiki/reference/start#methods4 - $enc['url'] = $enclosure->get_link(); - if ($enclosure->get_length()) $enc['fileSize'] = $enclosure->get_length(); - if ($enclosure->get_type()) $enc['type'] = $enclosure->get_type(); - if ($enclosure->get_medium()) $enc['medium'] = $enclosure->get_medium(); - if ($enclosure->get_expression()) $enc['expression'] = $enclosure->get_expression(); - if ($enclosure->get_bitrate()) $enc['bitrate'] = $enclosure->get_bitrate(); - if ($enclosure->get_framerate()) $enc['framerate'] = $enclosure->get_framerate(); - if ($enclosure->get_sampling_rate()) $enc['samplingrate'] = $enclosure->get_sampling_rate(); - if ($enclosure->get_channels()) $enc['channels'] = $enclosure->get_channels(); - if ($enclosure->get_duration()) $enc['duration'] = $enclosure->get_duration(); - if ($enclosure->get_height()) $enc['height'] = $enclosure->get_height(); - if ($enclosure->get_width()) $enc['width'] = $enclosure->get_width(); - if ($enclosure->get_language()) $enc['lang'] = $enclosure->get_language(); - $newitem->addElement('media:content', '', $enc); + } + + // check for enclosures + if ($options->keep_enclosures) { + if ($enclosures = $item->get_enclosures()) { + foreach ($enclosures as $enclosure) { + // thumbnails + foreach ((array)$enclosure->get_thumbnails() as $thumbnail) { + $newitem->addElement('media:thumbnail', '', array('url'=>$thumbnail)); } + if (!$enclosure->get_link()) continue; + $enc = array(); + // Media RSS spec ($enc): http://search.yahoo.com/mrss + // SimplePie methods ($enclosure): http://simplepie.org/wiki/reference/start#methods4 + $enc['url'] = $enclosure->get_link(); + if ($enclosure->get_length()) $enc['fileSize'] = $enclosure->get_length(); + if ($enclosure->get_type()) $enc['type'] = $enclosure->get_type(); + if ($enclosure->get_medium()) $enc['medium'] = $enclosure->get_medium(); + if ($enclosure->get_expression()) $enc['expression'] = $enclosure->get_expression(); + if ($enclosure->get_bitrate()) $enc['bitrate'] = $enclosure->get_bitrate(); + if ($enclosure->get_framerate()) $enc['framerate'] = $enclosure->get_framerate(); + if ($enclosure->get_sampling_rate()) $enc['samplingrate'] = $enclosure->get_sampling_rate(); + if ($enclosure->get_channels()) $enc['channels'] = $enclosure->get_channels(); + if ($enclosure->get_duration()) $enc['duration'] = $enclosure->get_duration(); + if ($enclosure->get_height()) $enc['height'] = $enclosure->get_height(); + if ($enclosure->get_width()) $enc['width'] = $enclosure->get_width(); + if ($enclosure->get_language()) $enc['lang'] = $enclosure->get_language(); + $newitem->addElement('media:content', '', $enc); } } - /* } */ + } $output->addItem($newitem); unset($html); $item_count++; @@ -887,7 +892,7 @@ if (!$debug_mode) { } if ($add_to_cache) { ob_start(); - $output->genarateFeed(); + $output->genarateFeed(false); $output = ob_get_contents(); ob_end_clean(); if ($html_only && $item_count == 0) { @@ -898,299 +903,8 @@ if (!$debug_mode) { } echo $output; } else { - $output->genarateFeed(); + $output->genarateFeed(false); } if ($callback) echo ');'; } -/////////////////////////////// -// HELPER FUNCTIONS -/////////////////////////////// - -function url_allowed($url) { - global $options; - if (!empty($options->allowed_urls)) { - $allowed = false; - foreach ($options->allowed_urls as $allowurl) { - if (stristr($url, $allowurl) !== false) { - $allowed = true; - break; - } - } - if (!$allowed) return false; - } else { - foreach ($options->blocked_urls as $blockurl) { - if (stristr($url, $blockurl) !== false) { - return false; - } - } - } - return true; -} - -////////////////////////////////////////////// -// Convert $html to UTF8 -// (uses HTTP headers and HTML to find encoding) -// adapted from http://stackoverflow.com/questions/910793/php-detect-encoding-and-make-everything-utf-8 -////////////////////////////////////////////// -function convert_to_utf8($html, $header=null) -{ - $encoding = null; - if ($html || $header) { - if (is_array($header)) $header = implode("\n", $header); - if (!$header || !preg_match_all('/^Content-Type:\s+([^;]+)(?:;\s*charset=["\']?([^;"\'\n]*))?/im', $header, $match, PREG_SET_ORDER)) { - // error parsing the response - debug('Could not find Content-Type header in HTTP response'); - } else { - $match = end($match); // get last matched element (in case of redirects) - if (isset($match[2])) $encoding = trim($match[2], "\"' \r\n\0\x0B\t"); - } - // TODO: check to see if encoding is supported (can we convert it?) - // If it's not, result will be empty string. - // For now we'll check for invalid encoding types returned by some sites, e.g. 'none' - // Problem URL: http://facta.co.jp/blog/archives/20111026001026.html - if (!$encoding || $encoding == 'none') { - // search for encoding in HTML - only look at the first 50000 characters - // 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 - // TODO: improve this so it looks at smaller chunks first - $html_head = substr($html, 0, 50000); - if (preg_match('/^<\?xml\s+version=(?:"[^"]*"|\'[^\']*\')\s+encoding=("[^"]*"|\'[^\']*\')/s', $html_head, $match)) { - $encoding = trim($match[1], '"\''); - } elseif (preg_match('/]+)/i', $html_head, $match)) { - $encoding = trim($match[1]); - } elseif (preg_match_all('/]+)>/i', $html_head, $match)) { - foreach ($match[1] as $_test) { - if (preg_match('/charset=["\']?([^"\']+)/i', $_test, $_m)) { - $encoding = trim($_m[1]); - break; - } - } - } - } - if (isset($encoding)) $encoding = trim($encoding); - // trim is important here! - if (!$encoding || (strtolower($encoding) == 'iso-8859-1')) { - // replace MS Word smart qutoes - $trans = array(); - $trans[chr(130)] = '‚'; // Single Low-9 Quotation Mark - $trans[chr(131)] = 'ƒ'; // Latin Small Letter F With Hook - $trans[chr(132)] = '„'; // Double Low-9 Quotation Mark - $trans[chr(133)] = '…'; // Horizontal Ellipsis - $trans[chr(134)] = '†'; // Dagger - $trans[chr(135)] = '‡'; // Double Dagger - $trans[chr(136)] = 'ˆ'; // Modifier Letter Circumflex Accent - $trans[chr(137)] = '‰'; // Per Mille Sign - $trans[chr(138)] = 'Š'; // Latin Capital Letter S With Caron - $trans[chr(139)] = '‹'; // Single Left-Pointing Angle Quotation Mark - $trans[chr(140)] = 'Œ'; // Latin Capital Ligature OE - $trans[chr(145)] = '‘'; // Left Single Quotation Mark - $trans[chr(146)] = '’'; // Right Single Quotation Mark - $trans[chr(147)] = '“'; // Left Double Quotation Mark - $trans[chr(148)] = '”'; // Right Double Quotation Mark - $trans[chr(149)] = '•'; // Bullet - $trans[chr(150)] = '–'; // En Dash - $trans[chr(151)] = '—'; // Em Dash - $trans[chr(152)] = '˜'; // Small Tilde - $trans[chr(153)] = '™'; // Trade Mark Sign - $trans[chr(154)] = 'š'; // Latin Small Letter S With Caron - $trans[chr(155)] = '›'; // Single Right-Pointing Angle Quotation Mark - $trans[chr(156)] = 'œ'; // Latin Small Ligature OE - $trans[chr(159)] = 'Ÿ'; // Latin Capital Letter Y With Diaeresis - $html = strtr($html, $trans); - } - if (!$encoding) { - debug('No character encoding found, so treating as UTF-8'); - $encoding = 'utf-8'; - } else { - debug('Character encoding: '.$encoding); - if (strtolower($encoding) != 'utf-8') { - debug('Converting to UTF-8'); - $html = SimplePie_Misc::change_encoding($html, $encoding, 'utf-8'); - /* - if (function_exists('iconv')) { - // iconv appears to handle certain character encodings better than mb_convert_encoding - $html = iconv($encoding, 'utf-8', $html); - } else { - $html = mb_convert_encoding($html, 'utf-8', $encoding); - } - */ - } - } - } - return $html; -} - -function makeAbsolute($base, $elem) { - $base = new SimplePie_IRI($base); - // remove '//' in URL path (used to prevent URLs from resolving properly) - // TODO: check if this is still the case - if (isset($base->path)) $base->path = preg_replace('!//+!', '/', $base->path); - foreach(array('a'=>'href', 'img'=>'src') as $tag => $attr) { - $elems = $elem->getElementsByTagName($tag); - for ($i = $elems->length-1; $i >= 0; $i--) { - $e = $elems->item($i); - //$e->parentNode->replaceChild($articleContent->ownerDocument->createTextNode($e->textContent), $e); - makeAbsoluteAttr($base, $e, $attr); - } - if (strtolower($elem->tagName) == $tag) makeAbsoluteAttr($base, $elem, $attr); - } -} -function makeAbsoluteAttr($base, $e, $attr) { - if ($e->hasAttribute($attr)) { - // Trim leading and trailing white space. I don't really like this but - // unfortunately it does appear on some sites. e.g. - $url = trim(str_replace('%20', ' ', $e->getAttribute($attr))); - $url = str_replace(' ', '%20', $url); - if (!preg_match('!https?://!i', $url)) { - if ($absolute = SimplePie_IRI::absolutize($base, $url)) { - $e->setAttribute($attr, $absolute); - } - } - } -} -function makeAbsoluteStr($base, $url) { - $base = new SimplePie_IRI($base); - // remove '//' in URL path (causes URLs not to resolve properly) - if (isset($base->path)) $base->path = preg_replace('!//+!', '/', $base->path); - if (preg_match('!^https?://!i', $url)) { - // already absolute - return $url; - } else { - if ($absolute = SimplePie_IRI::absolutize($base, $url)) { - return $absolute; - } - return false; - } -} -// returns single page response, or false if not found -function getSinglePage($item, $html, $url) { - global $http, $extractor; - debug('Looking for site config files to see if single page link exists'); - $site_config = $extractor->buildSiteConfig($url, $html); - $splink = null; - if (!empty($site_config->single_page_link)) { - $splink = $site_config->single_page_link; - } elseif (!empty($site_config->single_page_link_in_feed)) { - // single page link xpath is targeted at feed - $splink = $site_config->single_page_link_in_feed; - // so let's replace HTML with feed item description - $html = $item->get_description(); - } - if (isset($splink)) { - // Build DOM tree from HTML - $readability = new Readability($html, $url); - $xpath = new DOMXPath($readability->dom); - // Loop through single_page_link xpath expressions - $single_page_url = null; - foreach ($splink as $pattern) { - $elems = @$xpath->evaluate($pattern, $readability->dom); - if (is_string($elems)) { - $single_page_url = trim($elems); - break; - } elseif ($elems instanceof DOMNodeList && $elems->length > 0) { - foreach ($elems as $item) { - if ($item instanceof DOMElement && $item->hasAttribute('href')) { - $single_page_url = $item->getAttribute('href'); - break 2; - } elseif ($item instanceof DOMAttr && $item->value) { - $single_page_url = $item->value; - break 2; - } - } - } - } - // If we've got URL, resolve against $url - if (isset($single_page_url) && ($single_page_url = makeAbsoluteStr($url, $single_page_url))) { - // check it's not what we have already! - if ($single_page_url != $url) { - // it's not, so let's try to fetch it... - $_prev_ref = $http->referer; - $http->referer = $single_page_url; - if (($response = $http->get($single_page_url, true)) && $response['status_code'] < 300) { - $http->referer = $_prev_ref; - return $response; - } - $http->referer = $_prev_ref; - } - } - } - return false; -} - -// based on content-type http header, decide what to do -// param: HTTP headers string -// return: array with keys: 'mime', 'type', 'subtype', 'action', 'name' -// e.g. array('mime'=>'image/jpeg', 'type'=>'image', 'subtype'=>'jpeg', 'action'=>'link', 'name'=>'Image') -function get_mime_action_info($headers) { - global $options; - // check if action defined for returned Content-Type - $info = array(); - if (preg_match('!^Content-Type:\s*(([-\w]+)/([-\w\+]+))!im', $headers, $match)) { - // look for full mime type (e.g. image/jpeg) or just type (e.g. image) - // match[1] = full mime type, e.g. image/jpeg - // match[2] = first part, e.g. image - // match[3] = last part, e.g. jpeg - $info['mime'] = strtolower(trim($match[1])); - $info['type'] = strtolower(trim($match[2])); - $info['subtype'] = strtolower(trim($match[3])); - foreach (array($info['mime'], $info['type']) as $_mime) { - if (isset($options->content_type_exc[$_mime])) { - $info['action'] = $options->content_type_exc[$_mime]['action']; - $info['name'] = $options->content_type_exc[$_mime]['name']; - break; - } - } - } - return $info; -} - -function remove_url_cruft($url) { - // remove google analytics for the time being - // regex adapted from http://navitronic.co.uk/2010/12/removing-google-analytics-cruft-from-urls/ - // https://gist.github.com/758177 - return preg_replace('/(\?|\&)utm_[a-z]+=[^\&]+/', '', $url); -} - -function make_substitutions($string) { - if ($string == '') return $string; - global $item, $effective_url; - $string = str_replace('{url}', htmlspecialchars($item->get_permalink()), $string); - $string = str_replace('{effective-url}', htmlspecialchars($effective_url), $string); - return $string; -} - -function get_cache() { - global $options, $valid_key; - static $cache = null; - if ($cache === null) { - $frontendOptions = array( - 'lifetime' => 10*60, // cache lifetime of 10 minutes - 'automatic_serialization' => false, - 'write_control' => false, - 'automatic_cleaning_factor' => $options->cache_cleanup, - 'ignore_user_abort' => false - ); - $backendOptions = array( - 'cache_dir' => ($valid_key) ? $options->cache_dir.'/rss-with-key/' : $options->cache_dir.'/rss/', // directory where to put the cache files - 'file_locking' => false, - 'read_control' => true, - 'read_control_type' => 'strlen', - 'hashed_directory_level' => $options->cache_directory_level, - 'hashed_directory_perm' => 0777, - 'cache_file_perm' => 0664, - 'file_name_prefix' => 'ff' - ); - // getting a Zend_Cache_Core object - $cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions); - } - return $cache; -} - -function debug($msg) { - global $debug_mode; - if ($debug_mode) { - echo '* ',$msg,"\n"; - ob_flush(); - flush(); - } -} \ No newline at end of file