]> git.immae.eu Git - github/wallabag/wallabag.git/blame - inc/3rdparty/makefulltextfeed.php
update to 3.2 version of full-text-rss, issue #694
[github/wallabag/wallabag.git] / inc / 3rdparty / makefulltextfeed.php
CommitLineData
42c80841
NL
1<?php\r
2// Full-Text RSS: Create Full-Text Feeds\r
3// Author: Keyvan Minoukadeh\r
4// Copyright (c) 2013 Keyvan Minoukadeh\r
5// License: AGPLv3\r
3ec62cf9
MR
6// Version: 3.2\r
7// Date: 2013-05-13\r
42c80841
NL
8// More info: http://fivefilters.org/content-only/\r
9// Help: http://help.fivefilters.org\r
10\r
11/*\r
12This program is free software: you can redistribute it and/or modify\r
13it under the terms of the GNU Affero General Public License as published by\r
14the Free Software Foundation, either version 3 of the License, or\r
15(at your option) any later version.\r
16\r
17This program is distributed in the hope that it will be useful,\r
18but WITHOUT ANY WARRANTY; without even the implied warranty of\r
19MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
20GNU Affero General Public License for more details.\r
21\r
22You should have received a copy of the GNU Affero General Public License\r
23along with this program. If not, see <http://www.gnu.org/licenses/>.\r
24*/\r
25\r
26// Usage\r
27// -----\r
3ec62cf9
MR
28// Request this file passing it a web page or feed URL in the querystring: makefulltextfeed.php?url=example.org/article\r
29// For more request parameters, see http://help.fivefilters.org/customer/portal/articles/226660-usage\r
42c80841
NL
30\r
31error_reporting(E_ALL ^ E_NOTICE);\r
32ini_set("display_errors", 1);\r
33@set_time_limit(120);\r
34\r
35// Deal with magic quotes\r
36if (get_magic_quotes_gpc()) {\r
37 $process = array(&$_GET, &$_POST, &$_REQUEST);\r
38 while (list($key, $val) = each($process)) {\r
39 foreach ($val as $k => $v) {\r
40 unset($process[$key][$k]);\r
41 if (is_array($v)) {\r
42 $process[$key][stripslashes($k)] = $v;\r
43 $process[] = &$process[$key][stripslashes($k)];\r
44 } else {\r
45 $process[$key][stripslashes($k)] = stripslashes($v);\r
46 }\r
47 }\r
48 }\r
49 unset($process);\r
50}\r
51\r
52// set include path\r
53set_include_path(realpath(dirname(__FILE__).'/libraries').PATH_SEPARATOR.get_include_path());\r
4b842b20
MR
54\r
55require_once dirname(__FILE__).'/makefulltextfeedHelpers.php';\r
42c80841
NL
56\r
57////////////////////////////////\r
58// Load config file\r
59////////////////////////////////\r
60require dirname(__FILE__).'/config.php';\r
61\r
62////////////////////////////////\r
63// Prevent indexing/following by search engines because:\r
64// 1. The content is already public and presumably indexed (why create duplicates?)\r
65// 2. Not doing so might increase number of requests from search engines, thus increasing server load\r
66// Note: feed readers and services such as Yahoo Pipes will not be affected by this header.\r
67// Note: Using Disallow in a robots.txt file will be more effective (search engines will check\r
68// that before even requesting makefulltextfeed.php).\r
69////////////////////////////////\r
70header('X-Robots-Tag: noindex, nofollow');\r
71\r
72////////////////////////////////\r
73// Check if service is enabled\r
74////////////////////////////////\r
3ec62cf9
MR
75if (!$options->enabled) {\r
76 die('The full-text RSS service is currently disabled');\r
42c80841
NL
77}\r
78\r
79////////////////////////////////\r
80// Debug mode?\r
81// See the config file for debug options.\r
82////////////////////////////////\r
83$debug_mode = false;\r
84if (isset($_GET['debug'])) {\r
85 if ($options->debug === true || $options->debug == 'user') {\r
86 $debug_mode = true;\r
87 } elseif ($options->debug == 'admin') {\r
88 session_start();\r
89 $debug_mode = (@$_SESSION['auth'] == 1);\r
90 }\r
91 if ($debug_mode) {\r
92 header('Content-Type: text/plain; charset=utf-8');\r
93 } else {\r
94 if ($options->debug == 'admin') {\r
95 die('You must be logged in to the <a href="admin/">admin area</a> to see debug output.');\r
96 } else {\r
97 die('Debugging is disabled.');\r
98 }\r
99 }\r
100}\r
101\r
102////////////////////////////////\r
103// Check for APC\r
104////////////////////////////////\r
105$options->apc = $options->apc && function_exists('apc_add');\r
106if ($options->apc) {\r
107 debug('APC is enabled and available on server');\r
108} else {\r
109 debug('APC is disabled or not available on server');\r
110}\r
111\r
112////////////////////////////////\r
113// Check for smart cache\r
114////////////////////////////////\r
115$options->smart_cache = $options->smart_cache && function_exists('apc_inc');\r
116\r
117////////////////////////////////\r
118// Check for feed URL\r
119////////////////////////////////\r
3ec62cf9
MR
120if (!isset($_GET['url'])) {\r
121 die('No URL supplied');\r
42c80841
NL
122}\r
123$url = trim($_GET['url']);\r
124if (strtolower(substr($url, 0, 7)) == 'feed://') {\r
125 $url = 'http://'.substr($url, 7);\r
126}\r
127if (!preg_match('!^https?://.+!i', $url)) {\r
128 $url = 'http://'.$url;\r
129}\r
130\r
131$url = filter_var($url, FILTER_SANITIZE_URL);\r
132$test = filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED);\r
133// deal with bug http://bugs.php.net/51192 (present in PHP 5.2.13 and PHP 5.3.2)\r
134if ($test === false) {\r
135 $test = filter_var(strtr($url, '-', '_'), FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED);\r
136}\r
137if ($test !== false && $test !== null && preg_match('!^https?://!', $url)) {\r
138 // all okay\r
139 unset($test);\r
140} else {\r
141 die('Invalid URL supplied');\r
142}\r
143debug("Supplied URL: $url");\r
144\r
145/////////////////////////////////\r
146// Redirect to hide API key\r
147/////////////////////////////////\r
148if (isset($_GET['key']) && ($key_index = array_search($_GET['key'], $options->api_keys)) !== false) {\r
149 $host = $_SERVER['HTTP_HOST'];\r
150 $path = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');\r
151 $_qs_url = (strtolower(substr($url, 0, 7)) == 'http://') ? substr($url, 7) : $url;\r
152 $redirect = 'http://'.htmlspecialchars($host.$path).'/makefulltextfeed.php?url='.urlencode($_qs_url);\r
153 $redirect .= '&key='.$key_index;\r
154 $redirect .= '&hash='.urlencode(sha1($_GET['key'].$url));\r
155 if (isset($_GET['html'])) $redirect .= '&html='.urlencode($_GET['html']);\r
156 if (isset($_GET['max'])) $redirect .= '&max='.(int)$_GET['max'];\r
157 if (isset($_GET['links'])) $redirect .= '&links='.urlencode($_GET['links']);\r
158 if (isset($_GET['exc'])) $redirect .= '&exc='.urlencode($_GET['exc']);\r
159 if (isset($_GET['format'])) $redirect .= '&format='.urlencode($_GET['format']);\r
3ec62cf9 160 if (isset($_GET['callback'])) $redirect .= '&callback='.urlencode($_GET['callback']);\r
42c80841
NL
161 if (isset($_GET['l'])) $redirect .= '&l='.urlencode($_GET['l']);\r
162 if (isset($_GET['xss'])) $redirect .= '&xss';\r
163 if (isset($_GET['use_extracted_title'])) $redirect .= '&use_extracted_title';\r
3ec62cf9
MR
164 if (isset($_GET['content'])) $redirect .= '&content='.urlencode($_GET['content']);\r
165 if (isset($_GET['summary'])) $redirect .= '&summary='.urlencode($_GET['summary']);\r
42c80841
NL
166 if (isset($_GET['debug'])) $redirect .= '&debug';\r
167 if ($debug_mode) {\r
168 debug('Redirecting to hide access key, follow URL below to continue');\r
169 debug("Location: $redirect");\r
170 } else {\r
171 header("Location: $redirect");\r
172 }\r
173 exit;\r
174}\r
175\r
176///////////////////////////////////////////////\r
177// Set timezone.\r
3ec62cf9 178// Prevents warnings, but needs more testing -\r
42c80841
NL
179// perhaps if timezone is set in php.ini we\r
180// don't need to set it at all...\r
181///////////////////////////////////////////////\r
182if (!ini_get('date.timezone') || !@date_default_timezone_set(ini_get('date.timezone'))) {\r
183 date_default_timezone_set('UTC');\r
184}\r
185\r
186///////////////////////////////////////////////\r
187// Check if the request is explicitly for an HTML page\r
188///////////////////////////////////////////////\r
189$html_only = (isset($_GET['html']) && ($_GET['html'] == '1' || $_GET['html'] == 'true'));\r
190\r
191///////////////////////////////////////////////\r
192// Check if valid key supplied\r
193///////////////////////////////////////////////\r
194$valid_key = false;\r
195if (isset($_GET['key']) && isset($_GET['hash']) && isset($options->api_keys[(int)$_GET['key']])) {\r
196 $valid_key = ($_GET['hash'] == sha1($options->api_keys[(int)$_GET['key']].$url));\r
197}\r
198$key_index = ($valid_key) ? (int)$_GET['key'] : 0;\r
199if (!$valid_key && $options->key_required) {\r
3ec62cf9 200 die('A valid key must be supplied');\r
42c80841
NL
201}\r
202if (!$valid_key && isset($_GET['key']) && $_GET['key'] != '') {\r
203 die('The entered key is invalid');\r
204}\r
205\r
206if (file_exists('custom_init.php')) require 'custom_init.php';\r
207\r
208///////////////////////////////////////////////\r
209// Check URL against list of blacklisted URLs\r
210///////////////////////////////////////////////\r
211if (!url_allowed($url)) die('URL blocked');\r
212\r
213///////////////////////////////////////////////\r
214// Max entries\r
215// see config.php to find these values\r
216///////////////////////////////////////////////\r
217if (isset($_GET['max'])) {\r
218 $max = (int)$_GET['max'];\r
219 if ($valid_key) {\r
220 $max = min($max, $options->max_entries_with_key);\r
221 } else {\r
222 $max = min($max, $options->max_entries);\r
223 }\r
224} else {\r
225 if ($valid_key) {\r
226 $max = $options->default_entries_with_key;\r
227 } else {\r
228 $max = $options->default_entries;\r
229 }\r
230}\r
231\r
232///////////////////////////////////////////////\r
233// Link handling\r
234///////////////////////////////////////////////\r
235if (isset($_GET['links']) && in_array($_GET['links'], array('preserve', 'footnotes', 'remove'))) {\r
236 $links = $_GET['links'];\r
237} else {\r
238 $links = 'preserve';\r
239}\r
240\r
241///////////////////////////////////////////////\r
242// Favour item titles in feed?\r
243///////////////////////////////////////////////\r
244$favour_feed_titles = true;\r
245if ($options->favour_feed_titles == 'user') {\r
246 $favour_feed_titles = !isset($_GET['use_extracted_title']);\r
247} else {\r
248 $favour_feed_titles = $options->favour_feed_titles;\r
249}\r
250\r
3ec62cf9
MR
251///////////////////////////////////////////////\r
252// Include full content in output?\r
253///////////////////////////////////////////////\r
254if ($options->content === 'user') {\r
255 if (isset($_GET['content']) && $_GET['content'] === '0') {\r
256 $options->content = false;\r
257 } else {\r
258 $options->content = true;\r
259 }\r
260}\r
261\r
262///////////////////////////////////////////////\r
263// Include summaries in output?\r
264///////////////////////////////////////////////\r
265if ($options->summary === 'user') {\r
266 if (isset($_GET['summary']) && $_GET['summary'] === '1') {\r
267 $options->summary = true;\r
268 } else {\r
269 $options->summary = false;\r
270 }\r
271}\r
272\r
42c80841
NL
273///////////////////////////////////////////////\r
274// Exclude items if extraction fails\r
275///////////////////////////////////////////////\r
276if ($options->exclude_items_on_fail === 'user') {\r
277 $exclude_on_fail = (isset($_GET['exc']) && ($_GET['exc'] == '1'));\r
278} else {\r
279 $exclude_on_fail = $options->exclude_items_on_fail;\r
280}\r
281\r
282///////////////////////////////////////////////\r
283// Detect language\r
284///////////////////////////////////////////////\r
285if ($options->detect_language === 'user') {\r
286 if (isset($_GET['l'])) {\r
287 $detect_language = (int)$_GET['l'];\r
288 } else {\r
289 $detect_language = 1;\r
290 }\r
291} else {\r
292 $detect_language = $options->detect_language;\r
293}\r
294\r
42c80841
NL
295$use_cld = extension_loaded('cld') && (version_compare(PHP_VERSION, '5.3.0') >= 0);\r
296\r
297/////////////////////////////////////\r
298// Check for valid format\r
299// (stick to RSS (or RSS as JSON) for the time being)\r
300/////////////////////////////////////\r
301if (isset($_GET['format']) && $_GET['format'] == 'json') {\r
302 $format = 'json';\r
303} else {\r
304 $format = 'rss';\r
305}\r
306\r
307/////////////////////////////////////\r
308// Should we do XSS filtering?\r
309/////////////////////////////////////\r
310if ($options->xss_filter === 'user') {\r
311 $xss_filter = isset($_GET['xss']);\r
312} else {\r
313 $xss_filter = $options->xss_filter;\r
314}\r
315if (!$xss_filter && isset($_GET['xss'])) {\r
316 die('XSS filtering is disabled in config');\r
317}\r
318\r
319/////////////////////////////////////\r
320// Check for JSONP\r
321// Regex from https://gist.github.com/1217080\r
322/////////////////////////////////////\r
323$callback = null;\r
324if ($format =='json' && isset($_GET['callback'])) {\r
325 $callback = trim($_GET['callback']);\r
326 foreach (explode('.', $callback) as $_identifier) {\r
327 if (!preg_match('/^[a-zA-Z_$][0-9a-zA-Z_$]*(?:\[(?:".+"|\'.+\'|\d+)\])*?$/', $_identifier)) {\r
328 die('Invalid JSONP callback');\r
329 }\r
330 }\r
331 debug("JSONP callback: $callback");\r
332}\r
333\r
334//////////////////////////////////\r
335// Enable Cross-Origin Resource Sharing (CORS)\r
336//////////////////////////////////\r
337if ($options->cors) header('Access-Control-Allow-Origin: *');\r
338\r
339//////////////////////////////////\r
340// Check for cached copy\r
341//////////////////////////////////\r
342if ($options->caching) {\r
343 debug('Caching is enabled...');\r
3ec62cf9 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']));\r
42c80841
NL
345 $check_cache = true;\r
346 if ($options->apc && $options->smart_cache) {\r
347 apc_add("cache.$cache_id", 0, 10*60);\r
348 $apc_cache_hits = (int)apc_fetch("cache.$cache_id");\r
349 $check_cache = ($apc_cache_hits >= 2);\r
350 apc_inc("cache.$cache_id");\r
351 if ($check_cache) {\r
352 debug('Cache key found in APC, we\'ll try to load cache file from disk');\r
353 } else {\r
354 debug('Cache key not found in APC');\r
355 }\r
356 }\r
357 if ($check_cache) {\r
358 $cache = get_cache();\r
359 if ($data = $cache->load($cache_id)) {\r
360 if ($debug_mode) {\r
361 debug('Loaded cached copy');\r
362 exit;\r
363 }\r
364 if ($format == 'json') {\r
365 if ($callback === null) {\r
366 header('Content-type: application/json; charset=UTF-8');\r
367 } else {\r
368 header('Content-type: application/javascript; charset=UTF-8');\r
369 }\r
370 } else {\r
371 header('Content-type: text/xml; charset=UTF-8');\r
372 header('X-content-type-options: nosniff');\r
373 }\r
374 if (headers_sent()) die('Some data has already been output, can\'t send RSS file');\r
375 if ($callback) {\r
376 echo "$callback($data);";\r
377 } else {\r
378 echo $data;\r
379 }\r
380 exit;\r
381 }\r
382 }\r
383}\r
384\r
385//////////////////////////////////\r
386// Set Expires header\r
387//////////////////////////////////\r
388if (!$debug_mode) {\r
389 header('Expires: ' . gmdate('D, d M Y H:i:s', time()+(60*10)) . ' GMT');\r
390}\r
391\r
392//////////////////////////////////\r
393// Set up HTTP agent\r
394//////////////////////////////////\r
f5b5622a 395global $http;\r
42c80841
NL
396$http = new HumbleHttpAgent();\r
397$http->debug = $debug_mode;\r
398$http->userAgentMap = $options->user_agents;\r
399$http->headerOnlyTypes = array_keys($options->content_type_exc);\r
400$http->rewriteUrls = $options->rewrite_url;\r
401\r
402//////////////////////////////////\r
403// Set up Content Extractor\r
404//////////////////////////////////\r
b4fd2154 405global $extractor;\r
42c80841
NL
406$extractor = new ContentExtractor(dirname(__FILE__).'/site_config/custom', dirname(__FILE__).'/site_config/standard');\r
407$extractor->debug = $debug_mode;\r
408SiteConfig::$debug = $debug_mode;\r
409SiteConfig::use_apc($options->apc);\r
410$extractor->fingerprints = $options->fingerprints;\r
411$extractor->allowedParsers = $options->allowed_parsers;\r
412\r
413////////////////////////////////\r
414// Get RSS/Atom feed\r
415////////////////////////////////\r
416if (!$html_only) {\r
417 debug('--------');\r
418 debug("Attempting to process URL as feed");\r
419 // Send user agent header showing PHP (prevents a HTML response from feedburner)\r
420 $http->userAgentDefault = HumbleHttpAgent::UA_PHP;\r
421 // configure SimplePie HTTP extension class to use our HumbleHttpAgent instance\r
422 SimplePie_HumbleHttpAgent::set_agent($http);\r
423 $feed = new SimplePie();\r
424 // some feeds use the text/html content type - force_feed tells SimplePie to process anyway\r
425 $feed->force_feed(true);\r
426 $feed->set_file_class('SimplePie_HumbleHttpAgent');\r
427 //$feed->set_feed_url($url); // colons appearing in the URL's path get encoded\r
428 $feed->feed_url = $url;\r
429 $feed->set_autodiscovery_level(SIMPLEPIE_LOCATOR_NONE);\r
430 $feed->set_timeout(20);\r
431 $feed->enable_cache(false);\r
432 $feed->set_stupidly_fast(true);\r
433 $feed->enable_order_by_date(false); // we don't want to do anything to the feed\r
434 $feed->set_url_replacements(array());\r
435 // initialise the feed\r
436 // the @ suppresses notices which on some servers causes a 500 internal server error\r
437 $result = @$feed->init();\r
438 //$feed->handle_content_type();\r
439 //$feed->get_title();\r
440 if ($result && (!is_array($feed->data) || count($feed->data) == 0)) {\r
441 die('Sorry, no feed items found');\r
442 }\r
443 // from now on, we'll identify ourselves as a browser\r
444 $http->userAgentDefault = HumbleHttpAgent::UA_BROWSER;\r
445}\r
446\r
447////////////////////////////////////////////////////////////////////////////////\r
448// Our given URL is not a feed, so let's create our own feed with a single item:\r
449// the given URL. This basically treats all non-feed URLs as if they were\r
450// single-item feeds.\r
451////////////////////////////////////////////////////////////////////////////////\r
452$isDummyFeed = false;\r
453if ($html_only || !$result) {\r
454 debug('--------');\r
455 debug("Constructing a single-item feed from URL");\r
456 $isDummyFeed = true;\r
457 unset($feed, $result);\r
458 // create single item dummy feed object\r
42c80841
NL
459 $feed = new DummySingleItemFeed($url);\r
460}\r
461\r
462////////////////////////////////////////////\r
463// Create full-text feed\r
464////////////////////////////////////////////\r
465$output = new FeedWriter();\r
466$output->setTitle(strip_tags($feed->get_title()));\r
467$output->setDescription(strip_tags($feed->get_description()));\r
468$output->setXsl('css/feed.xsl'); // Chrome uses this, most browsers ignore it\r
469if ($valid_key && isset($_GET['pubsub'])) { // used only on fivefilters.org at the moment\r
470 $output->addHub('http://fivefilters.superfeedr.com/');\r
471 $output->addHub('http://pubsubhubbub.appspot.com/');\r
472 $output->setSelf('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);\r
473}\r
474$output->setLink($feed->get_link()); // Google Reader uses this for pulling in favicons\r
475if ($img_url = $feed->get_image_url()) {\r
476 $output->setImage($feed->get_title(), $feed->get_link(), $img_url);\r
477}\r
478\r
479////////////////////////////////////////////\r
480// Loop through feed items\r
481////////////////////////////////////////////\r
3ec62cf9 482$items = $feed->get_items(0, $max);\r
42c80841
NL
483// Request all feed items in parallel (if supported)\r
484$urls_sanitized = array();\r
485$urls = array();\r
486foreach ($items as $key => $item) {\r
487 $permalink = htmlspecialchars_decode($item->get_permalink());\r
488 // Colons in URL path segments get encoded by SimplePie, yet some sites expect them unencoded\r
489 $permalink = str_replace('%3A', ':', $permalink);\r
490 // validateUrl() strips non-ascii characters\r
491 // simplepie already sanitizes URLs so let's not do it again here.\r
492 //$permalink = $http->validateUrl($permalink);\r
493 if ($permalink) {\r
494 $urls_sanitized[] = $permalink;\r
495 }\r
496 $urls[$key] = $permalink;\r
497}\r
498debug('--------');\r
499debug('Fetching feed items');\r
500$http->fetchAll($urls_sanitized);\r
501//$http->cacheAll();\r
502\r
503// count number of items added to full feed\r
504$item_count = 0;\r
505\r
506foreach ($items as $key => $item) {\r
507 debug('--------');\r
508 debug('Processing feed item '.($item_count+1));\r
509 $do_content_extraction = true;\r
510 $extract_result = false;\r
511 $text_sample = null;\r
512 $permalink = $urls[$key];\r
513 debug("Item URL: $permalink");\r
514 $extracted_title = '';\r
515 $feed_item_title = $item->get_title();\r
516 if ($feed_item_title !== null) {\r
517 $feed_item_title = strip_tags(htmlspecialchars_decode($feed_item_title));\r
518 }\r
519 $newitem = $output->createNewItem();\r
520 $newitem->setTitle($feed_item_title);\r
521 if ($valid_key && isset($_GET['pubsub'])) { // used only on fivefilters.org at the moment\r
522 if ($permalink !== false) {\r
523 $newitem->setLink('http://fivefilters.org/content-only/redirect.php?url='.urlencode($permalink));\r
524 } else {\r
525 $newitem->setLink('http://fivefilters.org/content-only/redirect.php?url='.urlencode($item->get_permalink()));\r
526 }\r
527 } else {\r
528 if ($permalink !== false) {\r
529 $newitem->setLink($permalink);\r
530 } else {\r
531 $newitem->setLink($item->get_permalink());\r
532 }\r
533 }\r
534 //if ($permalink && ($response = $http->get($permalink, true)) && $response['status_code'] < 300) {\r
535 // Allowing error codes - some sites return correct content with error status\r
536 // e.g. prospectmagazine.co.uk returns 403\r
537 if ($permalink && ($response = $http->get($permalink, true)) && ($response['status_code'] < 300 || $response['status_code'] > 400)) {\r
538 $effective_url = $response['effective_url'];\r
539 if (!url_allowed($effective_url)) continue;\r
540 // check if action defined for returned Content-Type\r
541 $mime_info = get_mime_action_info($response['headers']);\r
542 if (isset($mime_info['action'])) {\r
543 if ($mime_info['action'] == 'exclude') {\r
544 continue; // skip this feed item entry\r
545 } elseif ($mime_info['action'] == 'link') {\r
546 if ($mime_info['type'] == 'image') {\r
547 $html = "<a href=\"$effective_url\"><img src=\"$effective_url\" alt=\"{$mime_info['name']}\" /></a>";\r
548 } else {\r
549 $html = "<a href=\"$effective_url\">Download {$mime_info['name']}</a>";\r
550 }\r
551 $extracted_title = $mime_info['name'];\r
552 $do_content_extraction = false;\r
553 }\r
554 }\r
555 if ($do_content_extraction) {\r
556 $html = $response['body'];\r
557 // remove strange things\r
558 $html = str_replace('</[>', '', $html);\r
559 $html = convert_to_utf8($html, $response['headers']);\r
560 // check site config for single page URL - fetch it if found\r
561 $is_single_page = false;\r
562 if ($single_page_response = getSinglePage($item, $html, $effective_url)) {\r
563 $is_single_page = true;\r
42c80841 564 $effective_url = $single_page_response['effective_url'];\r
3ec62cf9
MR
565 // check if action defined for returned Content-Type\r
566 $mime_info = get_mime_action_info($single_page_response['headers']);\r
567 if (isset($mime_info['action'])) {\r
568 if ($mime_info['action'] == 'exclude') {\r
569 continue; // skip this feed item entry\r
570 } elseif ($mime_info['action'] == 'link') {\r
571 if ($mime_info['type'] == 'image') {\r
572 $html = "<a href=\"$effective_url\"><img src=\"$effective_url\" alt=\"{$mime_info['name']}\" /></a>";\r
573 } else {\r
574 $html = "<a href=\"$effective_url\">Download {$mime_info['name']}</a>";\r
575 }\r
576 $extracted_title = $mime_info['name'];\r
577 $do_content_extraction = false;\r
578 }\r
579 }\r
580 if ($do_content_extraction) {\r
581 $html = $single_page_response['body'];\r
582 // remove strange things\r
583 $html = str_replace('</[>', '', $html);\r
584 $html = convert_to_utf8($html, $single_page_response['headers']);\r
585 debug("Retrieved single-page view from $effective_url");\r
586 }\r
42c80841
NL
587 unset($single_page_response);\r
588 }\r
3ec62cf9
MR
589 }\r
590 if ($do_content_extraction) {\r
42c80841
NL
591 debug('--------');\r
592 debug('Attempting to extract content');\r
593 $extract_result = $extractor->process($html, $effective_url);\r
594 $readability = $extractor->readability;\r
3ec62cf9 595 $content_block = ($extract_result) ? $extractor->getContent() : null;\r
42c80841
NL
596 $extracted_title = ($extract_result) ? $extractor->getTitle() : '';\r
597 // Deal with multi-page articles\r
598 //die('Next: '.$extractor->getNextPageUrl());\r
599 $is_multi_page = (!$is_single_page && $extract_result && $extractor->getNextPageUrl());\r
3ec62cf9 600 if ($options->multipage && $is_multi_page && $options->content) {\r
42c80841
NL
601 debug('--------');\r
602 debug('Attempting to process multi-page article');\r
603 $multi_page_urls = array();\r
604 $multi_page_content = array();\r
605 while ($next_page_url = $extractor->getNextPageUrl()) {\r
606 debug('--------');\r
607 debug('Processing next page: '.$next_page_url);\r
608 // If we've got URL, resolve against $url\r
609 if ($next_page_url = makeAbsoluteStr($effective_url, $next_page_url)) {\r
610 // check it's not what we have already!\r
611 if (!in_array($next_page_url, $multi_page_urls)) {\r
612 // it's not, so let's attempt to fetch it\r
3ec62cf9 613 $multi_page_urls[] = $next_page_url;\r
42c80841
NL
614 $_prev_ref = $http->referer;\r
615 if (($response = $http->get($next_page_url, true)) && $response['status_code'] < 300) {\r
616 // make sure mime type is not something with a different action associated\r
617 $page_mime_info = get_mime_action_info($response['headers']);\r
618 if (!isset($page_mime_info['action'])) {\r
619 $html = $response['body'];\r
620 // remove strange things\r
621 $html = str_replace('</[>', '', $html);\r
622 $html = convert_to_utf8($html, $response['headers']);\r
623 if ($extractor->process($html, $next_page_url)) {\r
624 $multi_page_content[] = $extractor->getContent();\r
625 continue;\r
626 } else { debug('Failed to extract content'); }\r
627 } else { debug('MIME type requires different action'); }\r
628 } else { debug('Failed to fetch URL'); }\r
629 } else { debug('URL already processed'); }\r
630 } else { debug('Failed to resolve against '.$effective_url); }\r
631 // failed to process next_page_url, so cancel further requests\r
632 $multi_page_content = array();\r
633 break;\r
634 }\r
635 // did we successfully deal with this multi-page article?\r
636 if (empty($multi_page_content)) {\r
637 debug('Failed to extract all parts of multi-page article, so not going to include them');\r
3ec62cf9
MR
638 $_page = $readability->dom->createElement('p');\r
639 $_page->innerHTML = '<em>This article appears to continue on subsequent pages which we could not extract</em>';\r
640 $multi_page_content[] = $_page;\r
42c80841
NL
641 }\r
642 foreach ($multi_page_content as $_page) {\r
643 $_page = $content_block->ownerDocument->importNode($_page, true);\r
644 $content_block->appendChild($_page);\r
645 }\r
3ec62cf9 646 unset($multi_page_urls, $multi_page_content, $page_mime_info, $next_page_url, $_page);\r
42c80841
NL
647 }\r
648 }\r
649 // use extracted title for both feed and item title if we're using single-item dummy feed\r
650 if ($isDummyFeed) {\r
651 $output->setTitle($extracted_title);\r
652 $newitem->setTitle($extracted_title);\r
653 } else {\r
654 // use extracted title instead of feed item title?\r
655 if (!$favour_feed_titles && $extracted_title != '') {\r
656 debug('Using extracted title in generated feed');\r
657 $newitem->setTitle($extracted_title);\r
658 }\r
659 }\r
660 }\r
661 if ($do_content_extraction) {\r
662 // if we failed to extract content...\r
663 if (!$extract_result) {\r
664 if ($exclude_on_fail) {\r
665 debug('Failed to extract, so skipping (due to exclude on fail parameter)');\r
666 continue; // skip this and move to next item\r
667 }\r
668 //TODO: get text sample for language detection\r
669 $html = $options->error_message;\r
670 // keep the original item description\r
671 $html .= $item->get_description();\r
672 } else {\r
673 $readability->clean($content_block, 'select');\r
674 if ($options->rewrite_relative_urls) makeAbsolute($effective_url, $content_block);\r
675 // footnotes\r
676 if (($links == 'footnotes') && (strpos($effective_url, 'wikipedia.org') === false)) {\r
677 $readability->addFootnotes($content_block);\r
678 }\r
679 // remove nesting: <div><div><div><p>test</p></div></div></div> = <p>test</p>\r
680 while ($content_block->childNodes->length == 1 && $content_block->firstChild->nodeType === XML_ELEMENT_NODE) {\r
681 // only follow these tag names\r
682 if (!in_array(strtolower($content_block->tagName), array('div', 'article', 'section', 'header', 'footer'))) break;\r
683 //$html = $content_block->firstChild->innerHTML; // FTR 2.9.5\r
684 $content_block = $content_block->firstChild;\r
685 }\r
686 // convert content block to HTML string\r
687 // Need to preserve things like body: //img[@id='feature']\r
688 if (in_array(strtolower($content_block->tagName), array('div', 'article', 'section', 'header', 'footer'))) {\r
689 $html = $content_block->innerHTML;\r
690 } else {\r
691 $html = $content_block->ownerDocument->saveXML($content_block); // essentially outerHTML\r
692 }\r
3ec62cf9 693 //unset($content_block);\r
42c80841
NL
694 // post-processing cleanup\r
695 $html = preg_replace('!<p>[\s\h\v]*</p>!u', '', $html);\r
696 if ($links == 'remove') {\r
697 $html = preg_replace('!</?a[^>]*>!', '', $html);\r
698 }\r
699 // get text sample for language detection\r
700 $text_sample = strip_tags(substr($html, 0, 500));\r
701 $html = make_substitutions($options->message_to_prepend).$html;\r
702 $html .= make_substitutions($options->message_to_append);\r
703 }\r
704 }\r
705\r
3ec62cf9
MR
706 if ($valid_key && isset($_GET['pubsub'])) { // used only on fivefilters.org at the moment\r
707 $newitem->addElement('guid', 'http://fivefilters.org/content-only/redirect.php?url='.urlencode($item->get_permalink()), array('isPermaLink'=>'false'));\r
708 } else {\r
709 $newitem->addElement('guid', $item->get_permalink(), array('isPermaLink'=>'true'));\r
710 }\r
711 // filter xss?\r
712 if ($xss_filter) {\r
713 debug('Filtering HTML to remove XSS');\r
714 $html = htmLawed::hl($html, array('safe'=>1, 'deny_attribute'=>'style', 'comment'=>1, 'cdata'=>1));\r
715 }\r
716\r
717 // add content\r
718 if ($options->summary === true) {\r
719 // get summary\r
720 $summary = '';\r
721 if (!$do_content_extraction) {\r
722 $summary = $html;\r
42c80841 723 } else {\r
3ec62cf9
MR
724 // Try to get first few paragraphs\r
725 if (isset($content_block) && ($content_block instanceof DOMElement)) {\r
726 $_paras = $content_block->getElementsByTagName('p');\r
727 foreach ($_paras as $_para) {\r
728 $summary .= preg_replace("/[\n\r\t ]+/", ' ', $_para->textContent).' ';\r
729 if (strlen($summary) > 200) break;\r
42c80841 730 }\r
3ec62cf9
MR
731 } else {\r
732 $summary = $html;\r
42c80841 733 }\r
3ec62cf9
MR
734 }\r
735 unset($_paras, $_para);\r
736 $summary = get_excerpt($summary);\r
737 $newitem->setDescription($summary);\r
738 if ($options->content) $newitem->setElement('content:encoded', $html);\r
739 } else {\r
740 if ($options->content) $newitem->setDescription($html);\r
741 }\r
742\r
743 // set date\r
744 if ((int)$item->get_date('U') > 0) {\r
745 $newitem->setDate((int)$item->get_date('U'));\r
746 } elseif ($extractor->getDate()) {\r
747 $newitem->setDate($extractor->getDate());\r
748 }\r
749\r
750 // add authors\r
751 if ($authors = $item->get_authors()) {\r
752 foreach ($authors as $author) {\r
753 // for some feeds, SimplePie stores author's name as email, e.g. http://feeds.feedburner.com/nymag/intel\r
754 if ($author->get_name() !== null) {\r
755 $newitem->addElement('dc:creator', $author->get_name());\r
756 } elseif ($author->get_email() !== null) {\r
757 $newitem->addElement('dc:creator', $author->get_email());\r
42c80841
NL
758 }\r
759 }\r
3ec62cf9
MR
760 } elseif ($authors = $extractor->getAuthors()) {\r
761 //TODO: make sure the list size is reasonable\r
762 foreach ($authors as $author) {\r
763 // TODO: xpath often selects authors from other articles linked from the page.\r
764 // for now choose first item\r
765 $newitem->addElement('dc:creator', $author);\r
766 break;\r
767 }\r
768 }\r
769\r
770 // add language\r
771 if ($detect_language) {\r
772 $language = $extractor->getLanguage();\r
773 if (!$language) $language = $feed->get_language();\r
774 if (($detect_language == 3 || (!$language && $detect_language == 2)) && $text_sample) {\r
775 try {\r
776 if ($use_cld) {\r
777 // Use PHP-CLD extension\r
778 $php_cld = 'CLD\detect'; // in quotes to prevent PHP 5.2 parse error\r
779 $res = $php_cld($text_sample);\r
780 if (is_array($res) && count($res) > 0) {\r
781 $language = $res[0]['code'];\r
782 }\r
783 } else {\r
784 //die('what');\r
785 // Use PEAR's Text_LanguageDetect\r
786 if (!isset($l)) {\r
787 $l = new Text_LanguageDetect();\r
788 $l->setNameMode(2); // return ISO 639-1 codes (e.g. "en")\r
789 }\r
790 $l_result = $l->detect($text_sample, 1);\r
791 if (count($l_result) > 0) {\r
792 $language = key($l_result);\r
42c80841 793 }\r
42c80841 794 }\r
3ec62cf9
MR
795 } catch (Exception $e) {\r
796 //die('error: '.$e);\r
797 // do nothing\r
42c80841
NL
798 }\r
799 }\r
3ec62cf9
MR
800 if ($language && (strlen($language) < 7)) {\r
801 $newitem->addElement('dc:language', $language);\r
42c80841 802 }\r
3ec62cf9
MR
803 }\r
804\r
805 // add MIME type (if it appeared in our exclusions lists)\r
806 if (isset($mime_info['mime'])) $newitem->addElement('dc:format', $mime_info['mime']);\r
807 // add effective URL (URL after redirects)\r
808 if (isset($effective_url)) {\r
809 //TODO: ensure $effective_url is valid witout - sometimes it causes problems, e.g.\r
810 //http://www.siasat.pk/forum/showthread.php?108883-Pakistan-Chowk-by-Rana-Mubashir-�-25th-March-2012-Special-Program-from-Liari-(Karachi)\r
811 //temporary measure: use utf8_encode()\r
812 $newitem->addElement('dc:identifier', remove_url_cruft(utf8_encode($effective_url)));\r
813 } else {\r
814 $newitem->addElement('dc:identifier', remove_url_cruft($item->get_permalink()));\r
815 }\r
816\r
817 // add categories\r
818 if ($categories = $item->get_categories()) {\r
819 foreach ($categories as $category) {\r
820 if ($category->get_label() !== null) {\r
821 $newitem->addElement('category', $category->get_label());\r
42c80841
NL
822 }\r
823 }\r
3ec62cf9
MR
824 }\r
825\r
826 // check for enclosures\r
827 if ($options->keep_enclosures) {\r
828 if ($enclosures = $item->get_enclosures()) {\r
829 foreach ($enclosures as $enclosure) {\r
830 // thumbnails\r
831 foreach ((array)$enclosure->get_thumbnails() as $thumbnail) {\r
832 $newitem->addElement('media:thumbnail', '', array('url'=>$thumbnail));\r
42c80841 833 }\r
3ec62cf9
MR
834 if (!$enclosure->get_link()) continue;\r
835 $enc = array();\r
836 // Media RSS spec ($enc): http://search.yahoo.com/mrss\r
837 // SimplePie methods ($enclosure): http://simplepie.org/wiki/reference/start#methods4\r
838 $enc['url'] = $enclosure->get_link();\r
839 if ($enclosure->get_length()) $enc['fileSize'] = $enclosure->get_length();\r
840 if ($enclosure->get_type()) $enc['type'] = $enclosure->get_type();\r
841 if ($enclosure->get_medium()) $enc['medium'] = $enclosure->get_medium();\r
842 if ($enclosure->get_expression()) $enc['expression'] = $enclosure->get_expression();\r
843 if ($enclosure->get_bitrate()) $enc['bitrate'] = $enclosure->get_bitrate();\r
844 if ($enclosure->get_framerate()) $enc['framerate'] = $enclosure->get_framerate();\r
845 if ($enclosure->get_sampling_rate()) $enc['samplingrate'] = $enclosure->get_sampling_rate();\r
846 if ($enclosure->get_channels()) $enc['channels'] = $enclosure->get_channels();\r
847 if ($enclosure->get_duration()) $enc['duration'] = $enclosure->get_duration();\r
848 if ($enclosure->get_height()) $enc['height'] = $enclosure->get_height();\r
849 if ($enclosure->get_width()) $enc['width'] = $enclosure->get_width();\r
850 if ($enclosure->get_language()) $enc['lang'] = $enclosure->get_language();\r
851 $newitem->addElement('media:content', '', $enc);\r
42c80841
NL
852 }\r
853 }\r
3ec62cf9 854 }\r
42c80841
NL
855 $output->addItem($newitem);\r
856 unset($html);\r
857 $item_count++;\r
858}\r
859\r
860// output feed\r
861debug('Done!');\r
862/*\r
863if ($debug_mode) {\r
864 $_apc_data = apc_cache_info('user');\r
865 var_dump($_apc_data); exit;\r
866}\r
867*/\r
868if (!$debug_mode) {\r
869 if ($callback) echo "$callback("; // if $callback is set, $format also == 'json'\r
870 if ($format == 'json') $output->setFormat(($callback === null) ? JSON : JSONP);\r
871 $add_to_cache = $options->caching;\r
872 // is smart cache mode enabled?\r
873 if ($add_to_cache && $options->apc && $options->smart_cache) {\r
874 // yes, so only cache if this is the second request for this URL\r
875 $add_to_cache = ($apc_cache_hits >= 2);\r
876 // purge cache\r
877 if ($options->cache_cleanup > 0) {\r
878 if (rand(1, $options->cache_cleanup) == 1) {\r
879 // apc purge code adapted from from http://www.thimbleopensource.com/tutorials-snippets/php-apc-expunge-script\r
880 $_apc_data = apc_cache_info('user');\r
881 foreach ($_apc_data['cache_list'] as $_apc_item) {\r
882 if ($_apc_item['ttl'] > 0 && ($_apc_item['ttl'] + $_apc_item['creation_time'] < time())) {\r
883 apc_delete($_apc_item['info']);\r
884 }\r
885 }\r
886 }\r
887 }\r
888 }\r
889 if ($add_to_cache) {\r
890 ob_start();\r
827f5b42 891 $output->genarateFeed(false);\r
42c80841
NL
892 $output = ob_get_contents();\r
893 ob_end_clean();\r
894 if ($html_only && $item_count == 0) {\r
895 // do not cache - in case of temporary server glitch at source URL\r
896 } else {\r
897 $cache = get_cache();\r
898 if ($add_to_cache) $cache->save($output, $cache_id);\r
899 }\r
900 echo $output;\r
901 } else {\r
827f5b42 902 $output->genarateFeed(false);\r
42c80841
NL
903 }\r
904 if ($callback) echo ');';\r
905}\r
906\r