3 * MagpieRSS: a simple RSS integration tool
5 * A compiled file for RSS syndication
7 * @author Kellan Elliott-McCrea <kellan@protest.net>
12 * @subpackage MagpieRSS
16 * Deprecated. Use SimplePie (class-simplepie.php) instead.
18 _deprecated_file( basename( __FILE__ ), '3.0', WPINC . '/class-simplepie.php' );
21 * Hook to use another RSS object instead of MagpieRSS
23 do_action('load_feed_engine');
25 /** RSS feed constant. */
27 define('ATOM', 'Atom');
28 define('MAGPIE_USER_AGENT', 'WordPress/' . $GLOBALS['wp_version']);
32 var $current_item = array(); // item currently being parsed
33 var $items = array(); // collection of parsed items
34 var $channel = array(); // hash of channel fields
35 var $textinput = array();
41 var $stack = array(); // parser stack
42 var $inchannel = false;
44 var $incontent = false; // if in Atom <content mode="xml"> field
45 var $intextinput = false;
47 var $current_field = '';
48 var $current_namespace = false;
52 var $_CONTENT_CONSTRUCTS = array('content', 'summary', 'info', 'title', 'tagline', 'copyright');
54 function MagpieRSS ($source) {
56 # if PHP xml isn't compiled in, die
58 if ( !function_exists('xml_parser_create') )
59 trigger_error( "Failed to load PHP's XML Extension. http://www.php.net/manual/en/ref.xml.php" );
61 $parser = @xml_parser_create();
63 if ( !is_resource($parser) )
64 trigger_error( "Failed to create an instance of PHP's XML parser. http://www.php.net/manual/en/ref.xml.php");
67 $this->parser = $parser;
69 # pass in parser, and a reference to this object
72 xml_set_object( $this->parser, $this );
73 xml_set_element_handler($this->parser,
74 'feed_start_element', 'feed_end_element' );
76 xml_set_character_data_handler( $this->parser, 'feed_cdata' );
78 $status = xml_parse( $this->parser, $source );
81 $errorcode = xml_get_error_code( $this->parser );
82 if ( $errorcode != XML_ERROR_NONE ) {
83 $xml_error = xml_error_string( $errorcode );
84 $error_line = xml_get_current_line_number($this->parser);
85 $error_col = xml_get_current_column_number($this->parser);
86 $errormsg = "$xml_error at line $error_line, column $error_col";
88 $this->error( $errormsg );
92 xml_parser_free( $this->parser );
97 function feed_start_element($p, $element, &$attrs) {
98 $el = $element = strtolower($element);
99 $attrs = array_change_key_case($attrs, CASE_LOWER);
101 // check for a namespace, and split if found
103 if ( strpos( $element, ':' ) ) {
104 list($ns, $el) = split( ':', $element, 2);
106 if ( $ns and $ns != 'rdf' ) {
107 $this->current_namespace = $ns;
110 # if feed type isn't set, then this is first element of feed
111 # identify feed from root element
113 if (!isset($this->feed_type) ) {
114 if ( $el == 'rdf' ) {
115 $this->feed_type = RSS;
116 $this->feed_version = '1.0';
118 elseif ( $el == 'rss' ) {
119 $this->feed_type = RSS;
120 $this->feed_version = $attrs['version'];
122 elseif ( $el == 'feed' ) {
123 $this->feed_type = ATOM;
124 $this->feed_version = $attrs['version'];
125 $this->inchannel = true;
130 if ( $el == 'channel' )
132 $this->inchannel = true;
134 elseif ($el == 'item' or $el == 'entry' )
136 $this->initem = true;
137 if ( isset($attrs['rdf:about']) ) {
138 $this->current_item['about'] = $attrs['rdf:about'];
142 // if we're in the default namespace of an RSS feed,
143 // record textinput or image fields
145 $this->feed_type == RSS and
146 $this->current_namespace == '' and
149 $this->intextinput = true;
153 $this->feed_type == RSS and
154 $this->current_namespace == '' and
157 $this->inimage = true;
160 # handle atom content constructs
161 elseif ( $this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) )
163 // avoid clashing w/ RSS mod_content
164 if ($el == 'content' ) {
165 $el = 'atom_content';
168 $this->incontent = $el;
173 // if inside an Atom content construct (e.g. content or summary) field treat tags as text
174 elseif ($this->feed_type == ATOM and $this->incontent )
176 // if tags are inlined, then flatten
177 $attrs_str = join(' ',
178 array_map(array('MagpieRSS', 'map_attrs'),
180 array_values($attrs) ) );
182 $this->append_content( "<$element $attrs_str>" );
184 array_unshift( $this->stack, $el );
187 // Atom support many links per containging element.
188 // Magpie treats link elements of type rel='alternate'
189 // as being equivalent to RSS's simple link element.
191 elseif ($this->feed_type == ATOM and $el == 'link' )
193 if ( isset($attrs['rel']) and $attrs['rel'] == 'alternate' )
198 $link_el = 'link_' . $attrs['rel'];
201 $this->append($link_el, $attrs['href']);
203 // set stack[0] to current element
205 array_unshift($this->stack, $el);
211 function feed_cdata ($p, $text) {
213 if ($this->feed_type == ATOM and $this->incontent)
215 $this->append_content( $text );
218 $current_el = join('_', array_reverse($this->stack));
219 $this->append($current_el, $text);
223 function feed_end_element ($p, $el) {
224 $el = strtolower($el);
226 if ( $el == 'item' or $el == 'entry' )
228 $this->items[] = $this->current_item;
229 $this->current_item = array();
230 $this->initem = false;
232 elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'textinput' )
234 $this->intextinput = false;
236 elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'image' )
238 $this->inimage = false;
240 elseif ($this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) )
242 $this->incontent = false;
244 elseif ($el == 'channel' or $el == 'feed' )
246 $this->inchannel = false;
248 elseif ($this->feed_type == ATOM and $this->incontent ) {
249 // balance tags properly
250 // note: i don't think this is actually neccessary
251 if ( $this->stack[0] == $el )
253 $this->append_content("</$el>");
256 $this->append_content("<$el />");
259 array_shift( $this->stack );
262 array_shift( $this->stack );
265 $this->current_namespace = false;
268 function concat (&$str1, $str2="") {
269 if (!isset($str1) ) {
275 function append_content($text) {
276 if ( $this->initem ) {
277 $this->concat( $this->current_item[ $this->incontent ], $text );
279 elseif ( $this->inchannel ) {
280 $this->concat( $this->channel[ $this->incontent ], $text );
284 // smart append - field and namespace aware
285 function append($el, $text) {
289 if ( $this->current_namespace )
291 if ( $this->initem ) {
293 $this->current_item[ $this->current_namespace ][ $el ], $text);
295 elseif ($this->inchannel) {
297 $this->channel[ $this->current_namespace][ $el ], $text );
299 elseif ($this->intextinput) {
301 $this->textinput[ $this->current_namespace][ $el ], $text );
303 elseif ($this->inimage) {
305 $this->image[ $this->current_namespace ][ $el ], $text );
309 if ( $this->initem ) {
311 $this->current_item[ $el ], $text);
313 elseif ($this->intextinput) {
315 $this->textinput[ $el ], $text );
317 elseif ($this->inimage) {
319 $this->image[ $el ], $text );
321 elseif ($this->inchannel) {
323 $this->channel[ $el ], $text );
329 function normalize () {
330 // if atom populate rss fields
331 if ( $this->is_atom() ) {
332 $this->channel['descripton'] = $this->channel['tagline'];
333 for ( $i = 0; $i < count($this->items); $i++) {
334 $item = $this->items[$i];
335 if ( isset($item['summary']) )
336 $item['description'] = $item['summary'];
337 if ( isset($item['atom_content']))
338 $item['content']['encoded'] = $item['atom_content'];
340 $this->items[$i] = $item;
343 elseif ( $this->is_rss() ) {
344 $this->channel['tagline'] = $this->channel['description'];
345 for ( $i = 0; $i < count($this->items); $i++) {
346 $item = $this->items[$i];
347 if ( isset($item['description']))
348 $item['summary'] = $item['description'];
349 if ( isset($item['content']['encoded'] ) )
350 $item['atom_content'] = $item['content']['encoded'];
352 $this->items[$i] = $item;
358 if ( $this->feed_type == RSS ) {
359 return $this->feed_version;
367 if ( $this->feed_type == ATOM ) {
368 return $this->feed_version;
375 function map_attrs($k, $v) {
379 function error( $errormsg, $lvl = E_USER_WARNING ) {
380 // append PHP's error message if track_errors enabled
381 if ( isset($php_errormsg) ) {
382 $errormsg .= " ($php_errormsg)";
384 if ( MAGPIE_DEBUG ) {
385 trigger_error( $errormsg, $lvl);
387 error_log( $errormsg, 0);
393 if ( !function_exists('fetch_rss') ) :
395 * Build Magpie object based on RSS from URL.
399 * @subpackage MagpieRSS
401 * @param string $url URL to retrieve feed
402 * @return bool|MagpieRSS false on failure or MagpieRSS object on success.
404 function fetch_rss ($url) {
405 // initialize constants
408 if ( !isset($url) ) {
409 // error("fetch_rss called without a url");
413 // if cache is disabled
414 if ( !MAGPIE_CACHE_ON ) {
415 // fetch file, and parse it
416 $resp = _fetch_remote_file( $url );
417 if ( is_success( $resp->status ) ) {
418 return _response_to_rss( $resp );
421 // error("Failed to fetch $url and cache is off");
429 // 2. if there is a hit, make sure its fresh
430 // 3. if cached obj fails freshness check, fetch remote
431 // 4. if remote fails, return stale object, or error
433 $cache = new RSSCache( MAGPIE_CACHE_DIR, MAGPIE_CACHE_AGE );
435 if (MAGPIE_DEBUG and $cache->ERROR) {
436 debug($cache->ERROR, E_USER_WARNING);
440 $cache_status = 0; // response of check_cache
441 $request_headers = array(); // HTTP headers to send with fetch
442 $rss = 0; // parsed RSS object
443 $errormsg = 0; // errors, if any
445 if (!$cache->ERROR) {
446 // return cache HIT, MISS, or STALE
447 $cache_status = $cache->check_cache( $url );
450 // if object cached, and cache is fresh, return cached obj
451 if ( $cache_status == 'HIT' ) {
452 $rss = $cache->get( $url );
453 if ( isset($rss) and $rss ) {
454 $rss->from_cache = 1;
455 if ( MAGPIE_DEBUG > 1) {
456 debug("MagpieRSS: Cache HIT", E_USER_NOTICE);
462 // else attempt a conditional get
465 if ( $cache_status == 'STALE' ) {
466 $rss = $cache->get( $url );
467 if ( isset($rss->etag) and $rss->last_modified ) {
468 $request_headers['If-None-Match'] = $rss->etag;
469 $request_headers['If-Last-Modified'] = $rss->last_modified;
473 $resp = _fetch_remote_file( $url, $request_headers );
475 if (isset($resp) and $resp) {
476 if ($resp->status == '304' ) {
477 // we have the most current copy
478 if ( MAGPIE_DEBUG > 1) {
479 debug("Got 304 for $url");
481 // reset cache on 304 (at minutillo insistent prodding)
482 $cache->set($url, $rss);
485 elseif ( is_success( $resp->status ) ) {
486 $rss = _response_to_rss( $resp );
488 if (MAGPIE_DEBUG > 1) {
489 debug("Fetch successful");
491 // add object to cache
492 $cache->set( $url, $rss );
497 $errormsg = "Failed to fetch $url. ";
498 if ( $resp->error ) {
499 # compensate for Snoopy's annoying habbit to tacking
501 $http_error = substr($resp->error, 0, -2);
502 $errormsg .= "(HTTP Error: $http_error)";
505 $errormsg .= "(HTTP Response: " . $resp->response_code .')';
510 $errormsg = "Unable to retrieve RSS file for unknown reasons.";
515 // attempt to return cached object
517 if ( MAGPIE_DEBUG ) {
518 debug("Returning STALE object for $url");
523 // else we totally failed
524 // error( $errormsg );
528 } // end if ( !MAGPIE_CACHE_ON ) {
533 * Retrieve URL headers and content using WP HTTP Request API.
537 * @subpackage MagpieRSS
539 * @param string $url URL to retrieve
540 * @param array $headers Optional. Headers to send to the URL.
541 * @return Snoopy style response
543 function _fetch_remote_file($url, $headers = "" ) {
544 $resp = wp_remote_request($url, array('headers' => $headers, 'timeout' => MAGPIE_FETCH_TIME_OUT));
545 if ( is_wp_error($resp) ) {
546 $error = array_shift($resp->errors);
548 $resp = new stdClass;
550 $resp->response_code = 500;
551 $resp->error = $error[0] . "\n"; //\n = Snoopy compatibility
555 // Snoopy returns headers unprocessed.
556 // Also note, WP_HTTP lowercases all keys, Snoopy did not.
557 $return_headers = array();
558 foreach ( $resp['headers'] as $key => $value ) {
559 if ( !is_array($value) ) {
560 $return_headers[] = "$key: $value";
562 foreach ( $value as $v )
563 $return_headers[] = "$key: $v";
567 $response = new stdClass;
568 $response->status = $resp['response']['code'];
569 $response->response_code = $resp['response']['code'];
570 $response->headers = $return_headers;
571 $response->results = $resp['body'];
581 * @subpackage MagpieRSS
583 * @param unknown_type $resp
586 function _response_to_rss ($resp) {
587 $rss = new MagpieRSS( $resp->results );
589 // if RSS parsed successfully
590 if ( $rss && (!isset($rss->ERROR) || !$rss->ERROR) ) {
592 // find Etag, and Last-Modified
593 foreach( (array) $resp->headers as $h) {
594 // 2003-03-02 - Nicola Asuni (www.tecnick.com) - fixed bug "Undefined offset: 1"
595 if (strpos($h, ": ")) {
596 list($field, $val) = explode(": ", $h, 2);
603 if ( $field == 'etag' ) {
607 if ( $field == 'last-modified' ) {
608 $rss->last_modified = $val;
613 } // else construct error message
615 $errormsg = "Failed to parse RSS file.";
618 $errormsg .= " (" . $rss->ERROR . ")";
623 } // end if ($rss and !$rss->error)
627 * Set up constants with default values, unless user overrides.
631 * @subpackage MagpieRSS
634 if ( defined('MAGPIE_INITALIZED') ) {
638 define('MAGPIE_INITALIZED', 1);
641 if ( !defined('MAGPIE_CACHE_ON') ) {
642 define('MAGPIE_CACHE_ON', 1);
645 if ( !defined('MAGPIE_CACHE_DIR') ) {
646 define('MAGPIE_CACHE_DIR', './cache');
649 if ( !defined('MAGPIE_CACHE_AGE') ) {
650 define('MAGPIE_CACHE_AGE', 60*60); // one hour
653 if ( !defined('MAGPIE_CACHE_FRESH_ONLY') ) {
654 define('MAGPIE_CACHE_FRESH_ONLY', 0);
657 if ( !defined('MAGPIE_DEBUG') ) {
658 define('MAGPIE_DEBUG', 0);
661 if ( !defined('MAGPIE_USER_AGENT') ) {
662 $ua = 'WordPress/' . $GLOBALS['wp_version'];
664 if ( MAGPIE_CACHE_ON ) {
668 $ua = $ua . '; No cache)';
671 define('MAGPIE_USER_AGENT', $ua);
674 if ( !defined('MAGPIE_FETCH_TIME_OUT') ) {
675 define('MAGPIE_FETCH_TIME_OUT', 2); // 2 second timeout
678 // use gzip encoding to fetch rss files if supported?
679 if ( !defined('MAGPIE_USE_GZIP') ) {
680 define('MAGPIE_USE_GZIP', true);
684 function is_info ($sc) {
685 return $sc >= 100 && $sc < 200;
688 function is_success ($sc) {
689 return $sc >= 200 && $sc < 300;
692 function is_redirect ($sc) {
693 return $sc >= 300 && $sc < 400;
696 function is_error ($sc) {
697 return $sc >= 400 && $sc < 600;
700 function is_client_error ($sc) {
701 return $sc >= 400 && $sc < 500;
704 function is_server_error ($sc) {
705 return $sc >= 500 && $sc < 600;
709 var $BASE_CACHE; // where the cache files are stored
710 var $MAX_AGE = 43200; // when are files stale, default twelve hours
711 var $ERROR = ''; // accumulate error messages
713 function RSSCache ($base='', $age='') {
714 $this->BASE_CACHE = WP_CONTENT_DIR . '/cache';
716 $this->BASE_CACHE = $base;
719 $this->MAX_AGE = $age;
724 /*=======================================================================*\
726 Purpose: add an item to the cache, keyed on url
727 Input: url from wich the rss file was fetched
728 Output: true on sucess
729 \*=======================================================================*/
730 function set ($url, $rss) {
731 $cache_option = 'rss_' . $this->file_name( $url );
733 set_transient($cache_option, $rss, $this->MAX_AGE);
735 return $cache_option;
738 /*=======================================================================*\
740 Purpose: fetch an item from the cache
741 Input: url from wich the rss file was fetched
742 Output: cached object on HIT, false on MISS
743 \*=======================================================================*/
744 function get ($url) {
746 $cache_option = 'rss_' . $this->file_name( $url );
748 if ( ! $rss = get_transient( $cache_option ) ) {
750 "Cache doesn't contain: $url (cache option: $cache_option)"
758 /*=======================================================================*\
759 Function: check_cache
760 Purpose: check a url for membership in the cache
761 and whether the object is older then MAX_AGE (ie. STALE)
762 Input: url from wich the rss file was fetched
763 Output: cached object on HIT, false on MISS
764 \*=======================================================================*/
765 function check_cache ( $url ) {
767 $cache_option = 'rss_' . $this->file_name( $url );
769 if ( get_transient($cache_option) ) {
770 // object exists and is current
773 // object does not exist
778 /*=======================================================================*\
780 \*=======================================================================*/
781 function serialize ( $rss ) {
782 return serialize( $rss );
785 /*=======================================================================*\
786 Function: unserialize
787 \*=======================================================================*/
788 function unserialize ( $data ) {
789 return unserialize( $data );
792 /*=======================================================================*\
794 Purpose: map url to location in cache
795 Input: url from wich the rss file was fetched
797 \*=======================================================================*/
798 function file_name ($url) {
802 /*=======================================================================*\
804 Purpose: register error
805 \*=======================================================================*/
806 function error ($errormsg, $lvl=E_USER_WARNING) {
807 // append PHP's error message if track_errors enabled
808 if ( isset($php_errormsg) ) {
809 $errormsg .= " ($php_errormsg)";
811 $this->ERROR = $errormsg;
812 if ( MAGPIE_DEBUG ) {
813 trigger_error( $errormsg, $lvl);
816 error_log( $errormsg, 0);
819 function debug ($debugmsg, $lvl=E_USER_NOTICE) {
820 if ( MAGPIE_DEBUG ) {
821 $this->error("MagpieRSS [debug] $debugmsg", $lvl);
826 if ( !function_exists('parse_w3cdtf') ) :
827 function parse_w3cdtf ( $date_str ) {
829 # regex to match wc3dtf
830 $pat = "/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/";
832 if ( preg_match( $pat, $date_str, $match ) ) {
833 list( $year, $month, $day, $hours, $minutes, $seconds) =
834 array( $match[1], $match[2], $match[3], $match[4], $match[5], $match[7]);
836 # calc epoch for current date assuming GMT
837 $epoch = gmmktime( $hours, $minutes, $seconds, $month, $day, $year);
840 if ( $match[11] == 'Z' ) {
844 list( $tz_mod, $tz_hour, $tz_min ) =
845 array( $match[8], $match[9], $match[10]);
847 # zero out the variables
848 if ( ! $tz_hour ) { $tz_hour = 0; }
849 if ( ! $tz_min ) { $tz_min = 0; }
851 $offset_secs = (($tz_hour*60)+$tz_min)*60;
853 # is timezone ahead of GMT? then subtract offset
855 if ( $tz_mod == '+' ) {
856 $offset_secs = $offset_secs * -1;
859 $offset = $offset_secs;
861 $epoch = $epoch + $offset;
870 if ( !function_exists('wp_rss') ) :
872 * Display all RSS items in a HTML ordered list.
876 * @subpackage MagpieRSS
878 * @param string $url URL of feed to display. Will not auto sense feed URL.
879 * @param int $num_items Optional. Number of items to display, default is all.
881 function wp_rss( $url, $num_items = -1 ) {
882 if ( $rss = fetch_rss( $url ) ) {
885 if ( $num_items !== -1 ) {
886 $rss->items = array_slice( $rss->items, 0, $num_items );
889 foreach ( (array) $rss->items as $item ) {
891 '<li><a href="%1$s" title="%2$s">%3$s</a></li>',
892 esc_url( $item['link'] ),
893 esc_attr( strip_tags( $item['description'] ) ),
894 esc_html( $item['title'] )
900 _e( 'An error has occurred, which probably means the feed is down. Try again later.' );
905 if ( !function_exists('get_rss') ) :
907 * Display RSS items in HTML list items.
909 * You have to specify which HTML list you want, either ordered or unordered
910 * before using the function. You also have to specify how many items you wish
911 * to display. You can't display all of them like you can with wp_rss()
916 * @subpackage MagpieRSS
918 * @param string $url URL of feed to display. Will not auto sense feed URL.
919 * @param int $num_items Optional. Number of items to display, default is all.
920 * @return bool False on failure.
922 function get_rss ($url, $num_items = 5) { // Like get posts, but for RSS
923 $rss = fetch_rss($url);
925 $rss->items = array_slice($rss->items, 0, $num_items);
926 foreach ( (array) $rss->items as $item ) {
928 echo "<a href='$item[link]' title='$item[description]'>";
929 echo esc_html($item['title']);