[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> rss.php (source)

   1  <?php
   2  /**
   3   * MagpieRSS: a simple RSS integration tool
   4   *
   5   * A compiled file for RSS syndication
   6   *
   7   * @author Kellan Elliott-McCrea <kellan@protest.net>
   8   * @version 0.51
   9   * @license GPL
  10   *
  11   * @package External
  12   * @subpackage MagpieRSS
  13   * @deprecated 3.0.0 Use SimplePie instead.
  14   */
  15  
  16  /**
  17   * Deprecated. Use SimplePie (class-simplepie.php) instead.
  18   */
  19  _deprecated_file( basename( __FILE__ ), '3.0.0', WPINC . '/class-simplepie.php' );
  20  
  21  /**
  22   * Fires before MagpieRSS is loaded, to optionally replace it.
  23   *
  24   * @since 2.3.0
  25   * @deprecated 3.0.0
  26   */
  27  do_action( 'load_feed_engine' );
  28  
  29  /** RSS feed constant. */
  30  define('RSS', 'RSS');
  31  define('ATOM', 'Atom');
  32  define('MAGPIE_USER_AGENT', 'WordPress/' . $GLOBALS['wp_version']);
  33  
  34  class MagpieRSS {
  35      var $parser;
  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();
  40      var $image            = array();
  41      var $feed_type;
  42      var $feed_version;
  43  
  44      // parser variables
  45      var $stack                = array(); // parser stack
  46      var $inchannel            = false;
  47      var $initem             = false;
  48      var $incontent            = false; // if in Atom <content mode="xml"> field
  49      var $intextinput        = false;
  50      var $inimage             = false;
  51      var $current_field        = '';
  52      var $current_namespace    = false;
  53  
  54      //var $ERROR = "";
  55  
  56      var $_CONTENT_CONSTRUCTS = array('content', 'summary', 'info', 'title', 'tagline', 'copyright');
  57  
  58      /**
  59       * PHP5 constructor.
  60       */
  61  	function __construct( $source ) {
  62  
  63          # Check if PHP xml isn't compiled
  64          #
  65          if ( ! function_exists('xml_parser_create') ) {
  66              wp_trigger_error( '', "PHP's XML extension is not available. Please contact your hosting provider to enable PHP's XML extension." );
  67              return;
  68          }
  69  
  70          $parser = xml_parser_create();
  71  
  72          $this->parser = $parser;
  73  
  74          # pass in parser, and a reference to this object
  75          # set up handlers
  76          #
  77          xml_set_element_handler($this->parser,
  78                  array( $this, 'feed_start_element' ), array( $this, 'feed_end_element' ) );
  79  
  80          xml_set_character_data_handler( $this->parser, array( $this, 'feed_cdata' ) );
  81  
  82          $status = xml_parse( $this->parser, $source );
  83  
  84          if (! $status ) {
  85              $errorcode = xml_get_error_code( $this->parser );
  86              if ( $errorcode != XML_ERROR_NONE ) {
  87                  $xml_error = xml_error_string( $errorcode );
  88                  $error_line = xml_get_current_line_number($this->parser);
  89                  $error_col = xml_get_current_column_number($this->parser);
  90                  $errormsg = "$xml_error at line $error_line, column $error_col";
  91  
  92                  $this->error( $errormsg );
  93              }
  94          }
  95  
  96          xml_parser_free( $this->parser );
  97          unset( $this->parser );
  98  
  99          $this->normalize();
 100      }
 101  
 102      /**
 103       * PHP4 constructor.
 104       */
 105  	public function MagpieRSS( $source ) {
 106          self::__construct( $source );
 107      }
 108  
 109  	function feed_start_element($p, $element, &$attrs) {
 110          $el = $element = strtolower($element);
 111          $attrs = array_change_key_case($attrs, CASE_LOWER);
 112  
 113          // check for a namespace, and split if found
 114          $ns    = false;
 115          if ( strpos( $element, ':' ) ) {
 116              list($ns, $el) = explode( ':', $element, 2);
 117          }
 118          if ( $ns and $ns != 'rdf' ) {
 119              $this->current_namespace = $ns;
 120          }
 121  
 122          # if feed type isn't set, then this is first element of feed
 123          # identify feed from root element
 124          #
 125          if (!isset($this->feed_type) ) {
 126              if ( $el == 'rdf' ) {
 127                  $this->feed_type = RSS;
 128                  $this->feed_version = '1.0';
 129              }
 130              elseif ( $el == 'rss' ) {
 131                  $this->feed_type = RSS;
 132                  $this->feed_version = $attrs['version'];
 133              }
 134              elseif ( $el == 'feed' ) {
 135                  $this->feed_type = ATOM;
 136                  $this->feed_version = $attrs['version'];
 137                  $this->inchannel = true;
 138              }
 139              return;
 140          }
 141  
 142          if ( $el == 'channel' )
 143          {
 144              $this->inchannel = true;
 145          }
 146          elseif ($el == 'item' or $el == 'entry' )
 147          {
 148              $this->initem = true;
 149              if ( isset($attrs['rdf:about']) ) {
 150                  $this->current_item['about'] = $attrs['rdf:about'];
 151              }
 152          }
 153  
 154          // if we're in the default namespace of an RSS feed,
 155          //  record textinput or image fields
 156          elseif (
 157              $this->feed_type == RSS and
 158              $this->current_namespace == '' and
 159              $el == 'textinput' )
 160          {
 161              $this->intextinput = true;
 162          }
 163  
 164          elseif (
 165              $this->feed_type == RSS and
 166              $this->current_namespace == '' and
 167              $el == 'image' )
 168          {
 169              $this->inimage = true;
 170          }
 171  
 172          # handle atom content constructs
 173          elseif ( $this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) )
 174          {
 175              // avoid clashing w/ RSS mod_content
 176              if ($el == 'content' ) {
 177                  $el = 'atom_content';
 178              }
 179  
 180              $this->incontent = $el;
 181  
 182          }
 183  
 184          // if inside an Atom content construct (e.g. content or summary) field treat tags as text
 185          elseif ($this->feed_type == ATOM and $this->incontent )
 186          {
 187              // if tags are inlined, then flatten
 188              $attrs_str = join(' ',
 189                      array_map(array('MagpieRSS', 'map_attrs'),
 190                      array_keys($attrs),
 191                      array_values($attrs) ) );
 192  
 193              $this->append_content( "<$element $attrs_str>"  );
 194  
 195              array_unshift( $this->stack, $el );
 196          }
 197  
 198          // Atom support many links per containing element.
 199          // Magpie treats link elements of type rel='alternate'
 200          // as being equivalent to RSS's simple link element.
 201          //
 202          elseif ($this->feed_type == ATOM and $el == 'link' )
 203          {
 204              if ( isset($attrs['rel']) and $attrs['rel'] == 'alternate' )
 205              {
 206                  $link_el = 'link';
 207              }
 208              else {
 209                  $link_el = 'link_' . $attrs['rel'];
 210              }
 211  
 212              $this->append($link_el, $attrs['href']);
 213          }
 214          // set stack[0] to current element
 215          else {
 216              array_unshift($this->stack, $el);
 217          }
 218      }
 219  
 220  	function feed_cdata ($p, $text) {
 221  
 222          if ($this->feed_type == ATOM and $this->incontent)
 223          {
 224              $this->append_content( $text );
 225          }
 226          else {
 227              $current_el = join('_', array_reverse($this->stack));
 228              $this->append($current_el, $text);
 229          }
 230      }
 231  
 232  	function feed_end_element ($p, $el) {
 233          $el = strtolower($el);
 234  
 235          if ( $el == 'item' or $el == 'entry' )
 236          {
 237              $this->items[] = $this->current_item;
 238              $this->current_item = array();
 239              $this->initem = false;
 240          }
 241          elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'textinput' )
 242          {
 243              $this->intextinput = false;
 244          }
 245          elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'image' )
 246          {
 247              $this->inimage = false;
 248          }
 249          elseif ($this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) )
 250          {
 251              $this->incontent = false;
 252          }
 253          elseif ($el == 'channel' or $el == 'feed' )
 254          {
 255              $this->inchannel = false;
 256          }
 257          elseif ($this->feed_type == ATOM and $this->incontent  ) {
 258              // balance tags properly
 259              // note: This may not actually be necessary
 260              if ( $this->stack[0] == $el )
 261              {
 262                  $this->append_content("</$el>");
 263              }
 264              else {
 265                  $this->append_content("<$el />");
 266              }
 267  
 268              array_shift( $this->stack );
 269          }
 270          else {
 271              array_shift( $this->stack );
 272          }
 273  
 274          $this->current_namespace = false;
 275      }
 276  
 277  	function concat (&$str1, $str2="") {
 278          if (!isset($str1) ) {
 279              $str1="";
 280          }
 281          $str1 .= $str2;
 282      }
 283  
 284  	function append_content($text) {
 285          if ( $this->initem ) {
 286              $this->concat( $this->current_item[ $this->incontent ], $text );
 287          }
 288          elseif ( $this->inchannel ) {
 289              $this->concat( $this->channel[ $this->incontent ], $text );
 290          }
 291      }
 292  
 293      // smart append - field and namespace aware
 294  	function append($el, $text) {
 295          if (!$el) {
 296              return;
 297          }
 298          if ( $this->current_namespace )
 299          {
 300              if ( $this->initem ) {
 301                  $this->concat(
 302                      $this->current_item[ $this->current_namespace ][ $el ], $text);
 303              }
 304              elseif ($this->inchannel) {
 305                  $this->concat(
 306                      $this->channel[ $this->current_namespace][ $el ], $text );
 307              }
 308              elseif ($this->intextinput) {
 309                  $this->concat(
 310                      $this->textinput[ $this->current_namespace][ $el ], $text );
 311              }
 312              elseif ($this->inimage) {
 313                  $this->concat(
 314                      $this->image[ $this->current_namespace ][ $el ], $text );
 315              }
 316          }
 317          else {
 318              if ( $this->initem ) {
 319                  $this->concat(
 320                      $this->current_item[ $el ], $text);
 321              }
 322              elseif ($this->intextinput) {
 323                  $this->concat(
 324                      $this->textinput[ $el ], $text );
 325              }
 326              elseif ($this->inimage) {
 327                  $this->concat(
 328                      $this->image[ $el ], $text );
 329              }
 330              elseif ($this->inchannel) {
 331                  $this->concat(
 332                      $this->channel[ $el ], $text );
 333              }
 334  
 335          }
 336      }
 337  
 338  	function normalize () {
 339          // if atom populate rss fields
 340          if ( $this->is_atom() ) {
 341              $this->channel['description'] = $this->channel['tagline'];
 342              for ( $i = 0; $i < count($this->items); $i++) {
 343                  $item = $this->items[$i];
 344                  if ( isset($item['summary']) )
 345                      $item['description'] = $item['summary'];
 346                  if ( isset($item['atom_content']))
 347                      $item['content']['encoded'] = $item['atom_content'];
 348  
 349                  $this->items[$i] = $item;
 350              }
 351          }
 352          elseif ( $this->is_rss() ) {
 353              $this->channel['tagline'] = $this->channel['description'];
 354              for ( $i = 0; $i < count($this->items); $i++) {
 355                  $item = $this->items[$i];
 356                  if ( isset($item['description']))
 357                      $item['summary'] = $item['description'];
 358                  if ( isset($item['content']['encoded'] ) )
 359                      $item['atom_content'] = $item['content']['encoded'];
 360  
 361                  $this->items[$i] = $item;
 362              }
 363          }
 364      }
 365  
 366  	function is_rss () {
 367          if ( $this->feed_type == RSS ) {
 368              return $this->feed_version;
 369          }
 370          else {
 371              return false;
 372          }
 373      }
 374  
 375  	function is_atom() {
 376          if ( $this->feed_type == ATOM ) {
 377              return $this->feed_version;
 378          }
 379          else {
 380              return false;
 381          }
 382      }
 383  
 384  	function map_attrs($k, $v) {
 385          return "$k=\"$v\"";
 386      }
 387  
 388  	function error( $errormsg, $lvl = E_USER_WARNING ) {
 389          if ( MAGPIE_DEBUG ) {
 390              wp_trigger_error('', $errormsg, $lvl);
 391          } else {
 392              error_log( $errormsg, 0);
 393          }
 394      }
 395  
 396  }
 397  
 398  if ( !function_exists('fetch_rss') ) :
 399  /**
 400   * Build Magpie object based on RSS from URL.
 401   *
 402   * @since 1.5.0
 403   * @package External
 404   * @subpackage MagpieRSS
 405   *
 406   * @param string $url URL to retrieve feed.
 407   * @return MagpieRSS|false MagpieRSS object on success, false on failure.
 408   */
 409  function fetch_rss ($url) {
 410      // initialize constants
 411      init();
 412  
 413      if ( !isset($url) ) {
 414          // error("fetch_rss called without a url");
 415          return false;
 416      }
 417  
 418      // if cache is disabled
 419      if ( !MAGPIE_CACHE_ON ) {
 420          // fetch file, and parse it
 421          $resp = _fetch_remote_file( $url );
 422          if ( is_success( $resp->status ) ) {
 423              return _response_to_rss( $resp );
 424          }
 425          else {
 426              // error("Failed to fetch $url and cache is off");
 427              return false;
 428          }
 429      }
 430      // else cache is ON
 431      else {
 432          // Flow
 433          // 1. check cache
 434          // 2. if there is a hit, make sure it's fresh
 435          // 3. if cached obj fails freshness check, fetch remote
 436          // 4. if remote fails, return stale object, or error
 437  
 438          $cache = new RSSCache( MAGPIE_CACHE_DIR, MAGPIE_CACHE_AGE );
 439  
 440          if (MAGPIE_DEBUG and $cache->ERROR) {
 441              debug($cache->ERROR, E_USER_WARNING);
 442          }
 443  
 444          $cache_status      = 0;        // response of check_cache
 445          $request_headers = array(); // HTTP headers to send with fetch
 446          $rss              = 0;        // parsed RSS object
 447          $errormsg         = 0;        // errors, if any
 448  
 449          if (!$cache->ERROR) {
 450              // return cache HIT, MISS, or STALE
 451              $cache_status = $cache->check_cache( $url );
 452          }
 453  
 454          // if object cached, and cache is fresh, return cached obj
 455          if ( $cache_status == 'HIT' ) {
 456              $rss = $cache->get( $url );
 457              if ( isset($rss) and $rss ) {
 458                  $rss->from_cache = 1;
 459                  if ( MAGPIE_DEBUG > 1) {
 460                  debug("MagpieRSS: Cache HIT", E_USER_NOTICE);
 461              }
 462                  return $rss;
 463              }
 464          }
 465  
 466          // else attempt a conditional get
 467  
 468          // set up headers
 469          if ( $cache_status == 'STALE' ) {
 470              $rss = $cache->get( $url );
 471              if ( isset($rss->etag) and $rss->last_modified ) {
 472                  $request_headers['If-None-Match'] = $rss->etag;
 473                  $request_headers['If-Last-Modified'] = $rss->last_modified;
 474              }
 475          }
 476  
 477          $resp = _fetch_remote_file( $url, $request_headers );
 478  
 479          if (isset($resp) and $resp) {
 480              if ($resp->status == '304' ) {
 481                  // we have the most current copy
 482                  if ( MAGPIE_DEBUG > 1) {
 483                      debug("Got 304 for $url");
 484                  }
 485                  // reset cache on 304 (at minutillo insistent prodding)
 486                  $cache->set($url, $rss);
 487                  return $rss;
 488              }
 489              elseif ( is_success( $resp->status ) ) {
 490                  $rss = _response_to_rss( $resp );
 491                  if ( $rss ) {
 492                      if (MAGPIE_DEBUG > 1) {
 493                          debug("Fetch successful");
 494                      }
 495                      // add object to cache
 496                      $cache->set( $url, $rss );
 497                      return $rss;
 498                  }
 499              }
 500              else {
 501                  $errormsg = "Failed to fetch $url. ";
 502                  if ( $resp->error ) {
 503                      # compensate for Snoopy's annoying habit to tacking
 504                      # on '\n'
 505                      $http_error = substr($resp->error, 0, -2);
 506                      $errormsg .= "(HTTP Error: $http_error)";
 507                  }
 508                  else {
 509                      $errormsg .=  "(HTTP Response: " . $resp->response_code .')';
 510                  }
 511              }
 512          }
 513          else {
 514              $errormsg = "Unable to retrieve RSS file for unknown reasons.";
 515          }
 516  
 517          // else fetch failed
 518  
 519          // attempt to return cached object
 520          if ($rss) {
 521              if ( MAGPIE_DEBUG ) {
 522                  debug("Returning STALE object for $url");
 523              }
 524              return $rss;
 525          }
 526  
 527          // else we totally failed
 528          // error( $errormsg );
 529  
 530          return false;
 531  
 532      } // end if ( !MAGPIE_CACHE_ON ) {
 533  } // end fetch_rss()
 534  endif;
 535  
 536  /**
 537   * Retrieve URL headers and content using WP HTTP Request API.
 538   *
 539   * @since 1.5.0
 540   * @package External
 541   * @subpackage MagpieRSS
 542   *
 543   * @param string $url URL to retrieve
 544   * @param array $headers Optional. Headers to send to the URL. Default empty string.
 545   * @return Snoopy style response
 546   */
 547  function _fetch_remote_file($url, $headers = "" ) {
 548      $resp = wp_safe_remote_request( $url, array( 'headers' => $headers, 'timeout' => MAGPIE_FETCH_TIME_OUT ) );
 549      if ( is_wp_error($resp) ) {
 550          $error = array_shift($resp->errors);
 551  
 552          $resp = new stdClass;
 553          $resp->status = 500;
 554          $resp->response_code = 500;
 555          $resp->error = $error[0] . "\n"; //\n = Snoopy compatibility
 556          return $resp;
 557      }
 558  
 559      // Snoopy returns headers unprocessed.
 560      // Also note, WP_HTTP lowercases all keys, Snoopy did not.
 561      $return_headers = array();
 562      foreach ( wp_remote_retrieve_headers( $resp ) as $key => $value ) {
 563          if ( !is_array($value) ) {
 564              $return_headers[] = "$key: $value";
 565          } else {
 566              foreach ( $value as $v )
 567                  $return_headers[] = "$key: $v";
 568          }
 569      }
 570  
 571      $response = new stdClass;
 572      $response->status = wp_remote_retrieve_response_code( $resp );
 573      $response->response_code = wp_remote_retrieve_response_code( $resp );
 574      $response->headers = $return_headers;
 575      $response->results = wp_remote_retrieve_body( $resp );
 576  
 577      return $response;
 578  }
 579  
 580  /**
 581   * Retrieve
 582   *
 583   * @since 1.5.0
 584   * @package External
 585   * @subpackage MagpieRSS
 586   *
 587   * @param array $resp
 588   * @return MagpieRSS|bool
 589   */
 590  function _response_to_rss ($resp) {
 591      $rss = new MagpieRSS( $resp->results );
 592  
 593      // if RSS parsed successfully
 594      if ( $rss && (!isset($rss->ERROR) || !$rss->ERROR) ) {
 595  
 596          // find Etag, and Last-Modified
 597          foreach ( (array) $resp->headers as $h) {
 598              // 2003-03-02 - Nicola Asuni (www.tecnick.com) - fixed bug "Undefined offset: 1"
 599              if (strpos($h, ": ")) {
 600                  list($field, $val) = explode(": ", $h, 2);
 601              }
 602              else {
 603                  $field = $h;
 604                  $val = "";
 605              }
 606  
 607              if ( $field == 'etag' ) {
 608                  $rss->etag = $val;
 609              }
 610  
 611              if ( $field == 'last-modified' ) {
 612                  $rss->last_modified = $val;
 613              }
 614          }
 615  
 616          return $rss;
 617      } // else construct error message
 618      else {
 619          $errormsg = "Failed to parse RSS file.";
 620  
 621          if ($rss) {
 622              $errormsg .= " (" . $rss->ERROR . ")";
 623          }
 624          // error($errormsg);
 625  
 626          return false;
 627      } // end if ($rss and !$rss->error)
 628  }
 629  
 630  /**
 631   * Set up constants with default values, unless user overrides.
 632   *
 633   * @since 1.5.0
 634   * 
 635   * @global string $wp_version The WordPress version string.
 636   * 
 637   * @package External
 638   * @subpackage MagpieRSS
 639   */
 640  function init () {
 641      if ( defined('MAGPIE_INITALIZED') ) {
 642          return;
 643      }
 644      else {
 645          define('MAGPIE_INITALIZED', 1);
 646      }
 647  
 648      if ( !defined('MAGPIE_CACHE_ON') ) {
 649          define('MAGPIE_CACHE_ON', 1);
 650      }
 651  
 652      if ( !defined('MAGPIE_CACHE_DIR') ) {
 653          define('MAGPIE_CACHE_DIR', './cache');
 654      }
 655  
 656      if ( !defined('MAGPIE_CACHE_AGE') ) {
 657          define('MAGPIE_CACHE_AGE', 60*60); // one hour
 658      }
 659  
 660      if ( !defined('MAGPIE_CACHE_FRESH_ONLY') ) {
 661          define('MAGPIE_CACHE_FRESH_ONLY', 0);
 662      }
 663  
 664          if ( !defined('MAGPIE_DEBUG') ) {
 665          define('MAGPIE_DEBUG', 0);
 666      }
 667  
 668      if ( !defined('MAGPIE_USER_AGENT') ) {
 669          $ua = 'WordPress/' . $GLOBALS['wp_version'];
 670  
 671          if ( MAGPIE_CACHE_ON ) {
 672              $ua = $ua . ')';
 673          }
 674          else {
 675              $ua = $ua . '; No cache)';
 676          }
 677  
 678          define('MAGPIE_USER_AGENT', $ua);
 679      }
 680  
 681      if ( !defined('MAGPIE_FETCH_TIME_OUT') ) {
 682          define('MAGPIE_FETCH_TIME_OUT', 2);    // 2 second timeout
 683      }
 684  
 685      // use gzip encoding to fetch rss files if supported?
 686      if ( !defined('MAGPIE_USE_GZIP') ) {
 687          define('MAGPIE_USE_GZIP', true);
 688      }
 689  }
 690  
 691  function is_info ($sc) {
 692      return $sc >= 100 && $sc < 200;
 693  }
 694  
 695  function is_success ($sc) {
 696      return $sc >= 200 && $sc < 300;
 697  }
 698  
 699  function is_redirect ($sc) {
 700      return $sc >= 300 && $sc < 400;
 701  }
 702  
 703  function is_error ($sc) {
 704      return $sc >= 400 && $sc < 600;
 705  }
 706  
 707  function is_client_error ($sc) {
 708      return $sc >= 400 && $sc < 500;
 709  }
 710  
 711  function is_server_error ($sc) {
 712      return $sc >= 500 && $sc < 600;
 713  }
 714  
 715  class RSSCache {
 716      var $BASE_CACHE;    // where the cache files are stored
 717      var $MAX_AGE    = 43200;          // when are files stale, default twelve hours
 718      var $ERROR         = '';            // accumulate error messages
 719  
 720      /**
 721       * PHP5 constructor.
 722       */
 723  	function __construct( $base = '', $age = '' ) {
 724          $this->BASE_CACHE = WP_CONTENT_DIR . '/cache';
 725          if ( $base ) {
 726              $this->BASE_CACHE = $base;
 727          }
 728          if ( $age ) {
 729              $this->MAX_AGE = $age;
 730          }
 731  
 732      }
 733  
 734      /**
 735       * PHP4 constructor.
 736       */
 737  	public function RSSCache( $base = '', $age = '' ) {
 738          self::__construct( $base, $age );
 739      }
 740  
 741  /*=======================================================================*\
 742      Function:    set
 743      Purpose:    add an item to the cache, keyed on url
 744      Input:        url from which the rss file was fetched
 745      Output:        true on success
 746  \*=======================================================================*/
 747  	function set ($url, $rss) {
 748          $cache_option = 'rss_' . $this->file_name( $url );
 749  
 750          set_transient($cache_option, $rss, $this->MAX_AGE);
 751  
 752          return $cache_option;
 753      }
 754  
 755  /*=======================================================================*\
 756      Function:    get
 757      Purpose:    fetch an item from the cache
 758      Input:        url from which the rss file was fetched
 759      Output:        cached object on HIT, false on MISS
 760  \*=======================================================================*/
 761  	function get ($url) {
 762          $this->ERROR = "";
 763          $cache_option = 'rss_' . $this->file_name( $url );
 764  
 765          if ( ! $rss = get_transient( $cache_option ) ) {
 766              $this->debug(
 767                  "Cache does not contain: $url (cache option: $cache_option)"
 768              );
 769              return 0;
 770          }
 771  
 772          return $rss;
 773      }
 774  
 775  /*=======================================================================*\
 776      Function:    check_cache
 777      Purpose:    check a url for membership in the cache
 778                  and whether the object is older then MAX_AGE (ie. STALE)
 779      Input:        url from which the rss file was fetched
 780      Output:        cached object on HIT, false on MISS
 781  \*=======================================================================*/
 782  	function check_cache ( $url ) {
 783          $this->ERROR = "";
 784          $cache_option = 'rss_' . $this->file_name( $url );
 785  
 786          if ( get_transient($cache_option) ) {
 787              // object exists and is current
 788                  return 'HIT';
 789          } else {
 790              // object does not exist
 791              return 'MISS';
 792          }
 793      }
 794  
 795  /*=======================================================================*\
 796      Function:    serialize
 797  \*=======================================================================*/
 798  	function serialize ( $rss ) {
 799          return serialize( $rss );
 800      }
 801  
 802  /*=======================================================================*\
 803      Function:    unserialize
 804  \*=======================================================================*/
 805  	function unserialize ( $data ) {
 806          return unserialize( $data );
 807      }
 808  
 809  /*=======================================================================*\
 810      Function:    file_name
 811      Purpose:    map url to location in cache
 812      Input:        url from which the rss file was fetched
 813      Output:        a file name
 814  \*=======================================================================*/
 815  	function file_name ($url) {
 816          return md5( $url );
 817      }
 818  
 819  /*=======================================================================*\
 820      Function:    error
 821      Purpose:    register error
 822  \*=======================================================================*/
 823  	function error ($errormsg, $lvl=E_USER_WARNING) {
 824          $this->ERROR = $errormsg;
 825          if ( MAGPIE_DEBUG ) {
 826              wp_trigger_error( '', $errormsg, $lvl);
 827          }
 828          else {
 829              error_log( $errormsg, 0);
 830          }
 831      }
 832  			function debug ($debugmsg, $lvl=E_USER_NOTICE) {
 833          if ( MAGPIE_DEBUG ) {
 834              $this->error("MagpieRSS [debug] $debugmsg", $lvl);
 835          }
 836      }
 837  }
 838  
 839  if ( !function_exists('parse_w3cdtf') ) :
 840  function parse_w3cdtf ( $date_str ) {
 841  
 842      # regex to match W3C date/time formats
 843      $pat = "/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/";
 844  
 845      if ( preg_match( $pat, $date_str, $match ) ) {
 846          list( $year, $month, $day, $hours, $minutes, $seconds) =
 847              array( $match[1], $match[2], $match[3], $match[4], $match[5], $match[7]);
 848  
 849          # calc epoch for current date assuming GMT
 850          $epoch = gmmktime( $hours, $minutes, $seconds, $month, $day, $year);
 851  
 852          $offset = 0;
 853          if ( $match[11] == 'Z' ) {
 854              # zulu time, aka GMT
 855          }
 856          else {
 857              list( $tz_mod, $tz_hour, $tz_min ) =
 858                  array( $match[8], $match[9], $match[10]);
 859  
 860              # zero out the variables
 861              if ( ! $tz_hour ) { $tz_hour = 0; }
 862              if ( ! $tz_min ) { $tz_min = 0; }
 863  
 864              $offset_secs = (($tz_hour*60)+$tz_min)*60;
 865  
 866              # is timezone ahead of GMT?  then subtract offset
 867              #
 868              if ( $tz_mod == '+' ) {
 869                  $offset_secs = $offset_secs * -1;
 870              }
 871  
 872              $offset = $offset_secs;
 873          }
 874          $epoch = $epoch + $offset;
 875          return $epoch;
 876      }
 877      else {
 878          return -1;
 879      }
 880  }
 881  endif;
 882  
 883  if ( !function_exists('wp_rss') ) :
 884  /**
 885   * Display all RSS items in a HTML ordered list.
 886   *
 887   * @since 1.5.0
 888   * @package External
 889   * @subpackage MagpieRSS
 890   *
 891   * @param string $url URL of feed to display. Will not auto sense feed URL.
 892   * @param int $num_items Optional. Number of items to display, default is all.
 893   */
 894  function wp_rss( $url, $num_items = -1 ) {
 895      if ( $rss = fetch_rss( $url ) ) {
 896          echo '<ul>';
 897  
 898          if ( $num_items !== -1 ) {
 899              $rss->items = array_slice( $rss->items, 0, $num_items );
 900          }
 901  
 902          foreach ( (array) $rss->items as $item ) {
 903              printf(
 904                  '<li><a href="%1$s" title="%2$s">%3$s</a></li>',
 905                  esc_url( $item['link'] ),
 906                  esc_attr( strip_tags( $item['description'] ) ),
 907                  esc_html( $item['title'] )
 908              );
 909          }
 910  
 911          echo '</ul>';
 912      } else {
 913          _e( 'An error has occurred, which probably means the feed is down. Try again later.' );
 914      }
 915  }
 916  endif;
 917  
 918  if ( !function_exists('get_rss') ) :
 919  /**
 920   * Display RSS items in HTML list items.
 921   *
 922   * You have to specify which HTML list you want, either ordered or unordered
 923   * before using the function. You also have to specify how many items you wish
 924   * to display. You can't display all of them like you can with wp_rss()
 925   * function.
 926   *
 927   * @since 1.5.0
 928   * @package External
 929   * @subpackage MagpieRSS
 930   *
 931   * @param string $url URL of feed to display. Will not auto sense feed URL.
 932   * @param int $num_items Optional. Number of items to display, default is all.
 933   * @return bool False on failure.
 934   */
 935  function get_rss ($url, $num_items = 5) { // Like get posts, but for RSS
 936      $rss = fetch_rss($url);
 937      if ( $rss ) {
 938          $rss->items = array_slice($rss->items, 0, $num_items);
 939          foreach ( (array) $rss->items as $item ) {
 940              echo "<li>\n";
 941              echo "<a href='$item[link]' title='$item[description]'>";
 942              echo esc_html($item['title']);
 943              echo "</a><br />\n";
 944              echo "</li>\n";
 945          }
 946      } else {
 947          return false;
 948      }
 949  }
 950  endif;


Generated : Sat Dec 21 08:20:01 2024 Cross-referenced by PHPXref