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