$errormsg = "Failed to fetch $url. ";
# compensate for Snoopy's annoying habit to tacking
$http_error = substr($resp->error, 0, -2);
$errormsg .= "(HTTP Error: $http_error)";
$errormsg .= "(HTTP Response: " . $resp->response_code .')';
$errormsg = "Unable to retrieve RSS file for unknown reasons.";
// attempt to return cached object
debug("Returning STALE object for $url");
// else we totally failed
} // end if ( !MAGPIE_CACHE_ON ) {
* Retrieve URL headers and content using WP HTTP Request API.
* @param string $url URL to retrieve
* @param array $headers Optional. Headers to send to the URL. Default empty string.
* @return Snoopy style response
function _fetch_remote_file($url, $headers = "" ) {
$resp = wp_safe_remote_request( $url, array( 'headers' => $headers, 'timeout' => MAGPIE_FETCH_TIME_OUT ) );
if ( is_wp_error($resp) ) {
$error = array_shift($resp->errors);
$resp->response_code = 500;
$resp->error = $error[0] . "\n"; //\n = Snoopy compatibility
// Snoopy returns headers unprocessed.
// Also note, WP_HTTP lowercases all keys, Snoopy did not.
$return_headers = array();
foreach ( wp_remote_retrieve_headers( $resp ) as $key => $value ) {
if ( !is_array($value) ) {
$return_headers[] = "$key: $value";
$return_headers[] = "$key: $v";
$response = new stdClass;
$response->status = wp_remote_retrieve_response_code( $resp );
$response->response_code = wp_remote_retrieve_response_code( $resp );
$response->headers = $return_headers;
$response->results = wp_remote_retrieve_body( $resp );
function _response_to_rss ($resp) {
$rss = new MagpieRSS( $resp->results );
// if RSS parsed successfully
if ( $rss && (!isset($rss->ERROR) || !$rss->ERROR) ) {
// find Etag, and Last-Modified
foreach ( (array) $resp->headers as $h) {
// 2003-03-02 - Nicola Asuni (www.tecnick.com) - fixed bug "Undefined offset: 1"
list($field, $val) = explode(": ", $h, 2);
if ( $field == 'etag' ) {
if ( $field == 'last-modified' ) {
$rss->last_modified = $val;
} // else construct error message
$errormsg = "Failed to parse RSS file.";
$errormsg .= " (" . $rss->ERROR . ")";
} // end if ($rss and !$rss->error)
* Set up constants with default values, unless user overrides.
* @global string $wp_version The WordPress version string.
if ( defined('MAGPIE_INITALIZED') ) {
define('MAGPIE_INITALIZED', 1);
if ( !defined('MAGPIE_CACHE_ON') ) {
define('MAGPIE_CACHE_ON', 1);
if ( !defined('MAGPIE_CACHE_DIR') ) {
define('MAGPIE_CACHE_DIR', './cache');
if ( !defined('MAGPIE_CACHE_AGE') ) {
define('MAGPIE_CACHE_AGE', 60*60); // one hour
if ( !defined('MAGPIE_CACHE_FRESH_ONLY') ) {
define('MAGPIE_CACHE_FRESH_ONLY', 0);
if ( !defined('MAGPIE_DEBUG') ) {
define('MAGPIE_DEBUG', 0);
if ( !defined('MAGPIE_USER_AGENT') ) {
$ua = 'WordPress/' . $GLOBALS['wp_version'];
$ua = $ua . '; No cache)';
define('MAGPIE_USER_AGENT', $ua);
if ( !defined('MAGPIE_FETCH_TIME_OUT') ) {
define('MAGPIE_FETCH_TIME_OUT', 2); // 2 second timeout
// use gzip encoding to fetch rss files if supported?
if ( !defined('MAGPIE_USE_GZIP') ) {
define('MAGPIE_USE_GZIP', true);
return $sc >= 100 && $sc < 200;
function is_success ($sc) {
return $sc >= 200 && $sc < 300;
function is_redirect ($sc) {
return $sc >= 300 && $sc < 400;
function is_error ($sc) {
return $sc >= 400 && $sc < 600;
function is_client_error ($sc) {
return $sc >= 400 && $sc < 500;
function is_server_error ($sc) {
return $sc >= 500 && $sc < 600;
var $BASE_CACHE; // where the cache files are stored
var $MAX_AGE = 43200; // when are files stale, default twelve hours
var $ERROR = ''; // accumulate error messages
function __construct( $base = '', $age = '' ) {
$this->BASE_CACHE = WP_CONTENT_DIR . '/cache';
$this->BASE_CACHE = $base;
public function RSSCache( $base = '', $age = '' ) {
self::__construct( $base, $age );
/*=======================================================================*\
Purpose: add an item to the cache, keyed on url
Input: url from which the rss file was fetched
\*=======================================================================*/
function set ($url, $rss) {
$cache_option = 'rss_' . $this->file_name( $url );
set_transient($cache_option, $rss, $this->MAX_AGE);
/*=======================================================================*\
Purpose: fetch an item from the cache
Input: url from which the rss file was fetched
Output: cached object on HIT, false on MISS
\*=======================================================================*/
$cache_option = 'rss_' . $this->file_name( $url );
if ( ! $rss = get_transient( $cache_option ) ) {
"Cache does not contain: $url (cache option: $cache_option)"
/*=======================================================================*\
Purpose: check a url for membership in the cache
and whether the object is older then MAX_AGE (ie. STALE)
Input: url from which the rss file was fetched
Output: cached object on HIT, false on MISS
\*=======================================================================*/
function check_cache ( $url ) {
$cache_option = 'rss_' . $this->file_name( $url );
if ( get_transient($cache_option) ) {
// object exists and is current
/*=======================================================================*\
\*=======================================================================*/
function serialize ( $rss ) {
return serialize( $rss );
/*=======================================================================*\
\*=======================================================================*/
function unserialize ( $data ) {
return unserialize( $data );
/*=======================================================================*\
Purpose: map url to location in cache
Input: url from which the rss file was fetched
\*=======================================================================*/
function file_name ($url) {
/*=======================================================================*\
\*=======================================================================*/
function error ($errormsg, $lvl=E_USER_WARNING) {
$this->ERROR = $errormsg;
wp_trigger_error( '', $errormsg, $lvl);
error_log( $errormsg, 0);
function debug ($debugmsg, $lvl=E_USER_NOTICE) {
$this->error("MagpieRSS [debug] $debugmsg", $lvl);
if ( !function_exists('parse_w3cdtf') ) :
function parse_w3cdtf ( $date_str ) {
# regex to match W3C date/time formats
$pat = "/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/";
if ( preg_match( $pat, $date_str, $match ) ) {
list( $year, $month, $day, $hours, $minutes, $seconds) =
array( $match[1], $match[2], $match[3], $match[4], $match[5], $match[7]);
# calc epoch for current date assuming GMT
$epoch = gmmktime( $hours, $minutes, $seconds, $month, $day, $year);
if ( $match[11] == 'Z' ) {
list( $tz_mod, $tz_hour, $tz_min ) =
array( $match[8], $match[9], $match[10]);
if ( ! $tz_hour ) { $tz_hour = 0; }
if ( ! $tz_min ) { $tz_min = 0; }
$offset_secs = (($tz_hour*60)+$tz_min)*60;
# is timezone ahead of GMT? then subtract offset
$offset_secs = $offset_secs * -1;
$epoch = $epoch + $offset;
if ( !function_exists('wp_rss') ) :
* Display all RSS items in a HTML ordered list.
* @param string $url URL of feed to display. Will not auto sense feed URL.
* @param int $num_items Optional. Number of items to display, default is all.
function wp_rss( $url, $num_items = -1 ) {
if ( $rss = fetch_rss( $url ) ) {
if ( $num_items !== -1 ) {
$rss->items = array_slice( $rss->items, 0, $num_items );
foreach ( (array) $rss->items as $item ) {
'<li><a href="%1$s" title="%2$s">%3$s</a></li>',
esc_url( $item['link'] ),
esc_attr( strip_tags( $item['description'] ) ),
esc_html( $item['title'] )
_e( 'An error has occurred, which probably means the feed is down. Try again later.' );
if ( !function_exists('get_rss') ) :
* Display RSS items in HTML list items.
* You have to specify which HTML list you want, either ordered or unordered
* before using the function. You also have to specify how many items you wish
* to display. You can't display all of them like you can with wp_rss()
* @param string $url URL of feed to display. Will not auto sense feed URL.
* @param int $num_items Optional. Number of items to display, default is all.
* @return bool False on failure.
function get_rss ($url, $num_items = 5) { // Like get posts, but for RSS
$rss->items = array_slice($rss->items, 0, $num_items);
foreach ( (array) $rss->items as $item ) {
echo "<a href='$item[link]' title='$item[description]'>";
echo esc_html($item['title']);