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