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