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
13 * @deprecated 3.0.0 Use SimplePie instead.
17 * Deprecated. Use SimplePie (class-simplepie.php) instead.
19 _deprecated_file( basename( __FILE__ ), '3.0', WPINC . '/class-simplepie.php' );
22 * Fires before MagpieRSS is loaded, to optionally replace it.
27 do_action( 'load_feed_engine' );
29 /** RSS feed constant. */
31 define('ATOM', 'Atom');
32 define('MAGPIE_USER_AGENT', 'WordPress/' . $GLOBALS['wp_version']);
36 var $current_item = array(); // item currently being parsed
37 var $items = array(); // collection of parsed items
38 var $channel = array(); // hash of channel fields
39 var $textinput = array();
45 var $stack = array(); // parser stack
46 var $inchannel = false;
48 var $incontent = false; // if in Atom <content mode="xml"> field
49 var $intextinput = false;
51 var $current_field = '';
52 var $current_namespace = false;
56 var $_CONTENT_CONSTRUCTS = array('content', 'summary', 'info', 'title', 'tagline', 'copyright');
58 function MagpieRSS ($source) {
60 # if PHP xml isn't compiled in, die
62 if ( !function_exists('xml_parser_create') )
63 trigger_error( "Failed to load PHP's XML Extension. http://www.php.net/manual/en/ref.xml.php" );
65 $parser = @xml_parser_create();
67 if ( !is_resource($parser) )
68 trigger_error( "Failed to create an instance of PHP's XML parser. http://www.php.net/manual/en/ref.xml.php");
70 $this->parser = $parser;
72 # pass in parser, and a reference to this object
75 xml_set_object( $this->parser, $this );
76 xml_set_element_handler($this->parser,
77 'feed_start_element', 'feed_end_element' );
79 xml_set_character_data_handler( $this->parser, 'feed_cdata' );
81 $status = xml_parse( $this->parser, $source );
84 $errorcode = xml_get_error_code( $this->parser );
85 if ( $errorcode != XML_ERROR_NONE ) {
86 $xml_error = xml_error_string( $errorcode );
87 $error_line = xml_get_current_line_number($this->parser);
88 $error_col = xml_get_current_column_number($this->parser);
89 $errormsg = "$xml_error at line $error_line, column $error_col";
91 $this->error( $errormsg );
95 xml_parser_free( $this->parser );
100 function feed_start_element($p, $element, &$attrs) {
101 $el = $element = strtolower($element);
102 $attrs = array_change_key_case($attrs, CASE_LOWER);
104 // check for a namespace, and split if found
106 if ( strpos( $element, ':' ) ) {
107 list($ns, $el) = split( ':', $element, 2);
109 if ( $ns and $ns != 'rdf' ) {
110 $this->current_namespace = $ns;
113 # if feed type isn't set, then this is first element of feed
114 # identify feed from root element
116 if (!isset($this->feed_type) ) {
117 if ( $el == 'rdf' ) {
118 $this->feed_type = RSS;
119 $this->feed_version = '1.0';
121 elseif ( $el == 'rss' ) {
122 $this->feed_type = RSS;
123 $this->feed_version = $attrs['version'];
125 elseif ( $el == 'feed' ) {
126 $this->feed_type = ATOM;
127 $this->feed_version = $attrs['version'];
128 $this->inchannel = true;
133 if ( $el == 'channel' )
135 $this->inchannel = true;
137 elseif ($el == 'item' or $el == 'entry' )
139 $this->initem = true;
140 if ( isset($attrs['rdf:about']) ) {
141 $this->current_item['about'] = $attrs['rdf:about'];
145 // if we're in the default namespace of an RSS feed,
146 // record textinput or image fields
148 $this->feed_type == RSS and
149 $this->current_namespace == '' and
152 $this->intextinput = true;
156 $this->feed_type == RSS and
157 $this->current_namespace == '' and
160 $this->inimage = true;
163 # handle atom content constructs
164 elseif ( $this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) )
166 // avoid clashing w/ RSS mod_content
167 if ($el == 'content' ) {
168 $el = 'atom_content';
171 $this->incontent = $el;
175 // if inside an Atom content construct (e.g. content or summary) field treat tags as text
176 elseif ($this->feed_type == ATOM and $this->incontent )
178 // if tags are inlined, then flatten
179 $attrs_str = join(' ',
180 array_map(array('MagpieRSS', 'map_attrs'),
182 array_values($attrs) ) );
184 $this->append_content( "<$element $attrs_str>" );
186 array_unshift( $this->stack, $el );
189 // Atom support many links per containging element.
190 // Magpie treats link elements of type rel='alternate'
191 // as being equivalent to RSS's simple link element.
193 elseif ($this->feed_type == ATOM and $el == 'link' )
195 if ( isset($attrs['rel']) and $attrs['rel'] == 'alternate' )
200 $link_el = 'link_' . $attrs['rel'];
203 $this->append($link_el, $attrs['href']);
205 // set stack[0] to current element
207 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: This may not actually be necessary
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 it's 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);
439 $cache_status = 0; // response of check_cache
440 $request_headers = array(); // HTTP headers to send with fetch
441 $rss = 0; // parsed RSS object
442 $errormsg = 0; // errors, if any
444 if (!$cache->ERROR) {
445 // return cache HIT, MISS, or STALE
446 $cache_status = $cache->check_cache( $url );
449 // if object cached, and cache is fresh, return cached obj
450 if ( $cache_status == 'HIT' ) {
451 $rss = $cache->get( $url );
452 if ( isset($rss) and $rss ) {
453 $rss->from_cache = 1;
454 if ( MAGPIE_DEBUG > 1) {
455 debug("MagpieRSS: Cache HIT", E_USER_NOTICE);
461 // else attempt a conditional get
464 if ( $cache_status == 'STALE' ) {
465 $rss = $cache->get( $url );
466 if ( isset($rss->etag) and $rss->last_modified ) {
467 $request_headers['If-None-Match'] = $rss->etag;
468 $request_headers['If-Last-Modified'] = $rss->last_modified;
472 $resp = _fetch_remote_file( $url, $request_headers );
474 if (isset($resp) and $resp) {
475 if ($resp->status == '304' ) {
476 // we have the most current copy
477 if ( MAGPIE_DEBUG > 1) {
478 debug("Got 304 for $url");
480 // reset cache on 304 (at minutillo insistent prodding)
481 $cache->set($url, $rss);
484 elseif ( is_success( $resp->status ) ) {
485 $rss = _response_to_rss( $resp );
487 if (MAGPIE_DEBUG > 1) {
488 debug("Fetch successful");
490 // add object to cache
491 $cache->set( $url, $rss );
496 $errormsg = "Failed to fetch $url. ";
497 if ( $resp->error ) {
498 # compensate for Snoopy's annoying habbit to tacking
500 $http_error = substr($resp->error, 0, -2);
501 $errormsg .= "(HTTP Error: $http_error)";
504 $errormsg .= "(HTTP Response: " . $resp->response_code .')';
509 $errormsg = "Unable to retrieve RSS file for unknown reasons.";
514 // attempt to return cached object
516 if ( MAGPIE_DEBUG ) {
517 debug("Returning STALE object for $url");
522 // else we totally failed
523 // error( $errormsg );
527 } // end if ( !MAGPIE_CACHE_ON ) {
532 * Retrieve URL headers and content using WP HTTP Request API.
536 * @subpackage MagpieRSS
538 * @param string $url URL to retrieve
539 * @param array $headers Optional. Headers to send to the URL.
540 * @return Snoopy style response
542 function _fetch_remote_file($url, $headers = "" ) {
543 $resp = wp_safe_remote_request( $url, array( 'headers' => $headers, 'timeout' => MAGPIE_FETCH_TIME_OUT ) );
544 if ( is_wp_error($resp) ) {
545 $error = array_shift($resp->errors);
547 $resp = new stdClass;
549 $resp->response_code = 500;
550 $resp->error = $error[0] . "\n"; //\n = Snoopy compatibility
554 // Snoopy returns headers unprocessed.
555 // Also note, WP_HTTP lowercases all keys, Snoopy did not.
556 $return_headers = array();
557 foreach ( wp_remote_retrieve_headers( $resp ) as $key => $value ) {
558 if ( !is_array($value) ) {
559 $return_headers[] = "$key: $value";
561 foreach ( $value as $v )
562 $return_headers[] = "$key: $v";
566 $response = new stdClass;
567 $response->status = wp_remote_retrieve_response_code( $resp );
568 $response->response_code = wp_remote_retrieve_response_code( $resp );
569 $response->headers = $return_headers;
570 $response->results = wp_remote_retrieve_body( $resp );
580 * @subpackage MagpieRSS
583 * @return MagpieRSS|bool
585 function _response_to_rss ($resp) {
586 $rss = new MagpieRSS( $resp->results );
588 // if RSS parsed successfully
589 if ( $rss && (!isset($rss->ERROR) || !$rss->ERROR) ) {
591 // find Etag, and Last-Modified
592 foreach( (array) $resp->headers as $h) {
593 // 2003-03-02 - Nicola Asuni (www.tecnick.com) - fixed bug "Undefined offset: 1"
594 if (strpos($h, ": ")) {
595 list($field, $val) = explode(": ", $h, 2);
602 if ( $field == 'etag' ) {
606 if ( $field == 'last-modified' ) {
607 $rss->last_modified = $val;
612 } // else construct error message
614 $errormsg = "Failed to parse RSS file.";
617 $errormsg .= " (" . $rss->ERROR . ")";
622 } // end if ($rss and !$rss->error)
626 * Set up constants with default values, unless user overrides.
630 * @subpackage MagpieRSS
633 if ( defined('MAGPIE_INITALIZED') ) {
637 define('MAGPIE_INITALIZED', 1);
640 if ( !defined('MAGPIE_CACHE_ON') ) {
641 define('MAGPIE_CACHE_ON', 1);
644 if ( !defined('MAGPIE_CACHE_DIR') ) {
645 define('MAGPIE_CACHE_DIR', './cache');
648 if ( !defined('MAGPIE_CACHE_AGE') ) {
649 define('MAGPIE_CACHE_AGE', 60*60); // one hour
652 if ( !defined('MAGPIE_CACHE_FRESH_ONLY') ) {
653 define('MAGPIE_CACHE_FRESH_ONLY', 0);
656 if ( !defined('MAGPIE_DEBUG') ) {
657 define('MAGPIE_DEBUG', 0);
660 if ( !defined('MAGPIE_USER_AGENT') ) {
661 $ua = 'WordPress/' . $GLOBALS['wp_version'];
663 if ( MAGPIE_CACHE_ON ) {
667 $ua = $ua . '; No cache)';
670 define('MAGPIE_USER_AGENT', $ua);
673 if ( !defined('MAGPIE_FETCH_TIME_OUT') ) {
674 define('MAGPIE_FETCH_TIME_OUT', 2); // 2 second timeout
677 // use gzip encoding to fetch rss files if supported?
678 if ( !defined('MAGPIE_USE_GZIP') ) {
679 define('MAGPIE_USE_GZIP', true);
683 function is_info ($sc) {
684 return $sc >= 100 && $sc < 200;
687 function is_success ($sc) {
688 return $sc >= 200 && $sc < 300;
691 function is_redirect ($sc) {
692 return $sc >= 300 && $sc < 400;
695 function is_error ($sc) {
696 return $sc >= 400 && $sc < 600;
699 function is_client_error ($sc) {
700 return $sc >= 400 && $sc < 500;
703 function is_server_error ($sc) {
704 return $sc >= 500 && $sc < 600;
708 var $BASE_CACHE; // where the cache files are stored
709 var $MAX_AGE = 43200; // when are files stale, default twelve hours
710 var $ERROR = ''; // accumulate error messages
712 function RSSCache ($base='', $age='') {
713 $this->BASE_CACHE = WP_CONTENT_DIR . '/cache';
715 $this->BASE_CACHE = $base;
718 $this->MAX_AGE = $age;
723 /*=======================================================================*\
725 Purpose: add an item to the cache, keyed on url
726 Input: url from wich the rss file was fetched
727 Output: true on success
728 \*=======================================================================*/
729 function set ($url, $rss) {
730 $cache_option = 'rss_' . $this->file_name( $url );
732 set_transient($cache_option, $rss, $this->MAX_AGE);
734 return $cache_option;
737 /*=======================================================================*\
739 Purpose: fetch an item from the cache
740 Input: url from wich the rss file was fetched
741 Output: cached object on HIT, false on MISS
742 \*=======================================================================*/
743 function get ($url) {
745 $cache_option = 'rss_' . $this->file_name( $url );
747 if ( ! $rss = get_transient( $cache_option ) ) {
749 "Cache doesn't contain: $url (cache option: $cache_option)"
757 /*=======================================================================*\
758 Function: check_cache
759 Purpose: check a url for membership in the cache
760 and whether the object is older then MAX_AGE (ie. STALE)
761 Input: url from wich the rss file was fetched
762 Output: cached object on HIT, false on MISS
763 \*=======================================================================*/
764 function check_cache ( $url ) {
766 $cache_option = 'rss_' . $this->file_name( $url );
768 if ( get_transient($cache_option) ) {
769 // object exists and is current
772 // object does not exist
777 /*=======================================================================*\
779 \*=======================================================================*/
780 function serialize ( $rss ) {
781 return serialize( $rss );
784 /*=======================================================================*\
785 Function: unserialize
786 \*=======================================================================*/
787 function unserialize ( $data ) {
788 return unserialize( $data );
791 /*=======================================================================*\
793 Purpose: map url to location in cache
794 Input: url from wich the rss file was fetched
796 \*=======================================================================*/
797 function file_name ($url) {
801 /*=======================================================================*\
803 Purpose: register error
804 \*=======================================================================*/
805 function error ($errormsg, $lvl=E_USER_WARNING) {
806 // append PHP's error message if track_errors enabled
807 if ( isset($php_errormsg) ) {
808 $errormsg .= " ($php_errormsg)";
810 $this->ERROR = $errormsg;
811 if ( MAGPIE_DEBUG ) {
812 trigger_error( $errormsg, $lvl);
815 error_log( $errormsg, 0);
818 function debug ($debugmsg, $lvl=E_USER_NOTICE) {
819 if ( MAGPIE_DEBUG ) {
820 $this->error("MagpieRSS [debug] $debugmsg", $lvl);
825 if ( !function_exists('parse_w3cdtf') ) :
826 function parse_w3cdtf ( $date_str ) {
828 # regex to match wc3dtf
829 $pat = "/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/";
831 if ( preg_match( $pat, $date_str, $match ) ) {
832 list( $year, $month, $day, $hours, $minutes, $seconds) =
833 array( $match[1], $match[2], $match[3], $match[4], $match[5], $match[7]);
835 # calc epoch for current date assuming GMT
836 $epoch = gmmktime( $hours, $minutes, $seconds, $month, $day, $year);
839 if ( $match[11] == 'Z' ) {
843 list( $tz_mod, $tz_hour, $tz_min ) =
844 array( $match[8], $match[9], $match[10]);
846 # zero out the variables
847 if ( ! $tz_hour ) { $tz_hour = 0; }
848 if ( ! $tz_min ) { $tz_min = 0; }
850 $offset_secs = (($tz_hour*60)+$tz_min)*60;
852 # is timezone ahead of GMT? then subtract offset
854 if ( $tz_mod == '+' ) {
855 $offset_secs = $offset_secs * -1;
858 $offset = $offset_secs;
860 $epoch = $epoch + $offset;
869 if ( !function_exists('wp_rss') ) :
871 * Display all RSS items in a HTML ordered list.
875 * @subpackage MagpieRSS
877 * @param string $url URL of feed to display. Will not auto sense feed URL.
878 * @param int $num_items Optional. Number of items to display, default is all.
880 function wp_rss( $url, $num_items = -1 ) {
881 if ( $rss = fetch_rss( $url ) ) {
884 if ( $num_items !== -1 ) {
885 $rss->items = array_slice( $rss->items, 0, $num_items );
888 foreach ( (array) $rss->items as $item ) {
890 '<li><a href="%1$s" title="%2$s">%3$s</a></li>',
891 esc_url( $item['link'] ),
892 esc_attr( strip_tags( $item['description'] ) ),
893 esc_html( $item['title'] )
899 _e( 'An error has occurred, which probably means the feed is down. Try again later.' );
904 if ( !function_exists('get_rss') ) :
906 * Display RSS items in HTML list items.
908 * You have to specify which HTML list you want, either ordered or unordered
909 * before using the function. You also have to specify how many items you wish
910 * to display. You can't display all of them like you can with wp_rss()
915 * @subpackage MagpieRSS
917 * @param string $url URL of feed to display. Will not auto sense feed URL.
918 * @param int $num_items Optional. Number of items to display, default is all.
919 * @return bool False on failure.
921 function get_rss ($url, $num_items = 5) { // Like get posts, but for RSS
922 $rss = fetch_rss($url);
924 $rss->items = array_slice($rss->items, 0, $num_items);
925 foreach ( (array) $rss->items as $item ) {
927 echo "<a href='$item[link]' title='$item[description]'>";
928 echo esc_html($item['title']);