rss
[ class tree: rss ] [ index: rss ] [ all elements ]

Source for file feedcreator.class.php

Documentation is available at feedcreator.class.php

  1. <?php
  2. /**
  3.  * @version $Header: /cvsroot/bitweaver/_bit_rss/feedcreator.class.php,v 1.5 2007/01/05 20:12:27 squareing Exp $
  4.  * @package rss
  5.  */
  6.  
  7. /*************************************************************************
  8.  
  9. FeedCreator class v1.7.2
  10. originally (c) Kai Blankenhorn
  11. www.bitfolge.de
  12. kaib@bitfolge.de
  13. v1.3 work by Scott Reynen (scott@randomchaos.com) and Kai Blankenhorn
  14. v1.5 OPML support by Dirk Clemens
  15.  
  16. This library is free software; you can redistribute it and/or
  17. modify it under the terms of the GNU Lesser General Public
  18. License as published by the Free Software Foundation; either
  19. version 2.1 of the License, or (at your option) any later version.
  20.  
  21. This library is distributed in the hope that it will be useful,
  22. but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  24. Lesser General Public License for more details.
  25.  
  26. You should have received a copy of the GNU Lesser General Public
  27. License along with this library; if not, write to the Free Software
  28. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  29.  
  30. ***************************************************************************
  31.  
  32.  
  33. Changelog:
  34.  
  35. v1.7.2    10-11-04
  36.     license changed to LGPL
  37.  
  38. v1.7.1
  39.     fixed a syntax bug
  40.     fixed left over debug code
  41.  
  42. v1.7    07-18-04
  43.     added HTML and JavaScript feeds (configurable via CSS) (thanks to Pascal Van Hecke)
  44.     added HTML descriptions for all feed formats (thanks to Pascal Van Hecke)
  45.     added a switch to select an external stylesheet (thanks to Pascal Van Hecke)
  46.     changed default content-type to application/xml
  47.     added character encoding setting
  48.     fixed numerous smaller bugs (thanks to S�en Fuhrmann of golem.de)
  49.     improved changing ATOM versions handling (thanks to August Trometer)
  50.     improved the UniversalFeedCreator's useCached method (thanks to S�en Fuhrmann of golem.de)
  51.     added charset output in HTTP headers (thanks to S�en Fuhrmann of golem.de)
  52.     added Slashdot namespace to RSS 1.0 (thanks to S�en Fuhrmann of golem.de)
  53.  
  54. v1.6    05-10-04
  55.     added stylesheet to RSS 1.0 feeds
  56.     fixed generator comment (thanks Kevin L. Papendick and Tanguy Pruvot)
  57.     fixed RFC822 date bug (thanks Tanguy Pruvot)
  58.     added TimeZone customization for RFC8601 (thanks Tanguy Pruvot)
  59.     fixed Content-type could be empty (thanks Tanguy Pruvot)
  60.     fixed author/creator in RSS1.0 (thanks Tanguy Pruvot)
  61.  
  62. v1.6 beta    02-28-04
  63.     added Atom 0.3 support (not all features, though)
  64.     improved OPML 1.0 support (hopefully - added more elements)
  65.     added support for arbitrary additional elements (use with caution)
  66.     code beautification :-)
  67.     considered beta due to some internal changes
  68.  
  69. v1.5.1    01-27-04
  70.     fixed some RSS 1.0 glitches (thanks to St�hane Vanpoperynghe)
  71.     fixed some inconsistencies between documentation and code (thanks to Timothy Martin)
  72.  
  73. v1.5    01-06-04
  74.     added support for OPML 1.0
  75.     added more documentation
  76.  
  77. v1.4    11-11-03
  78.     optional feed saving and caching
  79.     improved documentation
  80.     minor improvements
  81.  
  82. v1.3    10-02-03
  83.     renamed to FeedCreator, as it not only creates RSS anymore
  84.     added support for mbox
  85.     tentative support for echo/necho/atom/pie/???
  86.  
  87. v1.2    07-20-03
  88.     intelligent auto-truncating of RSS 0.91 attributes
  89.     don't create some attributes when they're not set
  90.     documentation improved
  91.     fixed a real and a possible bug with date conversions
  92.     code cleanup
  93.  
  94. v1.1    06-29-03
  95.     added images to feeds
  96.     now includes most RSS 0.91 attributes
  97.     added RSS 2.0 feeds
  98.  
  99. v1.0    06-24-03
  100.     initial release
  101.  
  102.  
  103.  
  104. ***************************************************************************/
  105.  
  106.  
  107. /************************************************************************
  108. *          A little setup                                                 *
  109. **************************************************************************/
  110.  
  111.  
  112. // your local timezone, set to "" to disable or for GMT
  113. define("TIME_ZONE","+01:00");
  114.  
  115.  
  116.  
  117.  
  118. /**
  119.  * Version string.
  120.  **/
  121.  
  122. define("FEEDCREATOR_VERSION""FeedCreator 1.7.2");
  123.  
  124.  
  125.  
  126. /**
  127.  * @package rss
  128.  *  A FeedItem is a part of a FeedCreator feed.
  129.  *
  130.  * @author Kai Blankenhorn <kaib@bitfolge.de>
  131.  * @since 1.3
  132.  */
  133. class FeedItem extends HtmlDescribable {
  134.     /**
  135.      * Mandatory attributes of an item.
  136.      */
  137.     var $title$description$link;
  138.  
  139.     /**
  140.      * Optional attributes of an item.
  141.      */
  142.  
  143.     /**
  144.      * Publishing date of an item. May be in one of the following formats:
  145.      *
  146.      *    RFC 822:
  147.      *    "Mon, 20 Jan 03 18:05:41 +0400"
  148.      *    "20 Jan 03 18:05:41 +0000"
  149.      *
  150.      *    ISO 8601:
  151.      *    "2003-01-20T18:05:41+04:00"
  152.      *
  153.      *    Unix:
  154.      *    1043082341
  155.      */
  156.     var $date;
  157.  
  158.     /**
  159.      * Any additional elements to include as an assiciated array. All $key => $value pairs
  160.      * will be included unencoded in the feed item in the form
  161.      *     <$key>$value</$key>
  162.      * Again: No encoding will be used! This means you can invalidate or enhance the feed
  163.      * if $value contains markup. This may be abused to embed tags not implemented by
  164.      * the FeedCreator class used.
  165.      */
  166.     var $additionalElements = Array();
  167.  
  168.     // on hold
  169.     // var $source;
  170.  
  171. }
  172.  
  173.  
  174.  
  175. /**
  176.  * @package rss
  177.  *  An FeedImage may be added to a FeedCreator feed.
  178.  * @author Kai Blankenhorn <kaib@bitfolge.de>
  179.  * @since 1.3
  180.  */
  181. class FeedImage extends HtmlDescribable {
  182.     /**
  183.      * Mandatory attributes of an image.
  184.      */
  185.     var $title$url$link;
  186.  
  187.     /**
  188.      * Optional attributes of an image.
  189.      */
  190.     var $width$height$description;
  191. }
  192.  
  193.  
  194.  
  195. /**
  196.  * @package rss
  197.  *  An HtmlDescribable is an item within a feed that can have a description that may
  198.  *  include HTML markup.
  199.  */
  200. class HtmlDescribable {
  201.     /**
  202.      * Indicates whether the description field should be rendered in HTML.
  203.      */
  204.  
  205.     /**
  206.      * Indicates whether and to how many characters a description should be truncated.
  207.      */
  208.     var $descriptionTruncSize;
  209.  
  210.     /**
  211.      * Returns a formatted description field, depending on descriptionHtmlSyndicated and
  212.      * $descriptionTruncSize properties
  213.      * @return    string    the formatted description
  214.      */
  215.     function getDescription({
  216.         $descriptionField new FeedHtmlField($this->description);
  217.         $descriptionField->syndicateHtml $this->descriptionHtmlSyndicated;
  218.         $descriptionField->truncSize $this->descriptionTruncSize;
  219.         return $descriptionField->output();
  220.     }
  221.  
  222. }
  223.  
  224.  
  225. /**
  226.  * @package rss
  227.  *  An FeedHtmlField describes and generates
  228.  *  a feed, item or image html field (probably a description). Output is
  229.  *  generated based on $truncSize, $syndicateHtml properties.
  230.  * @author Pascal Van Hecke <feedcreator.class.php@vanhecke.info>
  231.  * @version 1.6
  232.  */
  233. class FeedHtmlField {
  234.     /**
  235.      * Mandatory attributes of a FeedHtmlField.
  236.      */
  237.     var $rawFieldContent;
  238.  
  239.     /**
  240.      * Optional attributes of a FeedHtmlField.
  241.      *
  242.      */
  243.     var $truncSize$syndicateHtml;
  244.  
  245.     /**
  246.      * Creates a new instance of FeedHtmlField.
  247.      * @param  $string: if given, sets the rawFieldContent property
  248.      */
  249.     function FeedHtmlField($parFieldContent{
  250.         if ($parFieldContent{
  251.             $this->rawFieldContent = $parFieldContent;
  252.         }
  253.     }
  254.  
  255.  
  256.     /**
  257.      * Creates the right output, depending on $truncSize, $syndicateHtml properties.
  258.      * @return string    the formatted field
  259.      */
  260.     function output({
  261.         // when field available and syndicated in html we assume
  262.         // - valid html in $rawFieldContent and we enclose in CDATA tags
  263.         // - no truncation (truncating risks producing invalid html)
  264.         if (!$this->rawFieldContent{
  265.             $result "";
  266.         }    elseif ($this->syndicateHtml{
  267.             $result "<![CDATA[".$this->rawFieldContent."]]>";
  268.         else {
  269.             if ($this->truncSize and is_int($this->truncSize)) {
  270.                 $result FeedCreator::iTrunc(htmlspecialchars($this->rawFieldContent),$this->truncSize);
  271.             else {
  272.                 $result htmlspecialchars($this->rawFieldContent);
  273.             }
  274.         }
  275.         return $result;
  276.     }
  277.  
  278. }
  279.  
  280. /**
  281.  * @package rss
  282.  *  UniversalFeedCreator lets you choose during runtime which
  283.  *  format to build.
  284.  *  For general usage of a feed class, see the FeedCreator class
  285.  *  below or the example above.
  286.  *
  287.  * @since 1.3
  288.  * @author Kai Blankenhorn <kaib@bitfolge.de>
  289.  */
  290. class UniversalFeedCreator extends FeedCreator {
  291.     var $_feed;
  292.  
  293.     function _setFormat($format{
  294.         switch (strtoupper($format)) {
  295.  
  296.             case "2.0":
  297.                 // fall through
  298.             case "RSS2.0":
  299.                 $this->_feed = new RSSCreator20();
  300.                 break;
  301.  
  302.             case "1.0":
  303.                 // fall through
  304.             case "RSS1.0":
  305.                 $this->_feed = new RSSCreator10();
  306.                 break;
  307.  
  308.             case "0.91":
  309.                 // fall through
  310.             case "RSS0.91":
  311.                 $this->_feed = new RSSCreator091();
  312.                 break;
  313.  
  314.             case "PIE0.1":
  315.                 $this->_feed = new PIECreator01();
  316.                 break;
  317.  
  318.             case "MBOX":
  319.                 $this->_feed = new MBOXCreator();
  320.                 break;
  321.  
  322.             case "OPML":
  323.                 $this->_feed = new OPMLCreator();
  324.                 break;
  325.  
  326.             case "ATOM":
  327.                 // fall through: always the latest ATOM version
  328.  
  329.             case "ATOM0.3":
  330.                 $this->_feed = new AtomCreator03();
  331.                 break;
  332.  
  333.             case "HTML":
  334.                 $this->_feed = new HTMLCreator();
  335.                 break;
  336.  
  337.             case "JS":
  338.                 // fall through
  339.             case "JAVASCRIPT":
  340.                 $this->_feed = new JSCreator();
  341.                 break;
  342.  
  343.             default:
  344.                 $this->_feed = new RSSCreator091();
  345.                 break;
  346.         }
  347.  
  348.         $vars get_object_vars($this);
  349.         foreach ($vars as $key => $value{
  350.             // prevent overwriting of properties "contentType", "encoding"; do not copy "_feed" itself
  351.             if (!in_array($keyarray("_feed""contentType""encoding"))) {
  352.                 $this->_feed->{$key$this->{$key};
  353.             }
  354.         }
  355.     }
  356.  
  357.     /**
  358.      * Creates a syndication feed based on the items previously added.
  359.      *
  360.      * @see        FeedCreator::addItem()
  361.      * @param    string    format    format the feed should comply to. Valid values are:
  362.      *             "PIE0.1", "mbox", "RSS0.91", "RSS1.0", "RSS2.0", "OPML", "ATOM0.3", "HTML", "JS"
  363.      * @return    string    the contents of the feed.
  364.      */
  365.     function createFeed($format "RSS0.91"{
  366.         $this->_setFormat($format);
  367.         return $this->_feed->createFeed();
  368.     }
  369.  
  370.  
  371.  
  372.     /**
  373.      * Saves this feed as a file on the local disk. After the file is saved, an HTTP redirect
  374.      * header may be sent to redirect the use to the newly created file.
  375.      * @since 1.4
  376.      *
  377.      * @param    string    format    format the feed should comply to. Valid values are:
  378.      *             "PIE0.1" (deprecated), "mbox", "RSS0.91", "RSS1.0", "RSS2.0", "OPML", "ATOM", "ATOM0.3", "HTML", "JS"
  379.      * @param    string    filename    optional    the filename where a recent version of the feed is saved. If not specified, the filename is $_SERVER["PHP_SELF"] with the extension changed to .xml (see _generateFilename()).
  380.      * @param    boolean    displayContents    optional    send the content of the file or not. If true, the file will be sent in the body of the response.
  381.      */
  382.     function saveFeed($format="RSS0.91"$filename=""$displayContents=true{
  383.         $this->_setFormat($format);
  384.         $this->_feed->saveFeed($filename$displayContents);
  385.     }
  386.  
  387.  
  388.    /**
  389.     * Turns on caching and checks if there is a recent version of this feed in the cache.
  390.     * If there is, an HTTP redirect header is sent.
  391.     * To effectively use caching, you should create the FeedCreator object and call this method
  392.     * before anything else, especially before you do the time consuming task to build the feed
  393.     * (web fetching, for example).
  394.     *
  395.     * @param   string   format   format the feed should comply to. Valid values are:
  396.     *        "PIE0.1" (deprecated), "mbox", "RSS0.91", "RSS1.0", "RSS2.0", "OPML", "ATOM0.3".
  397.     * @param filename   string   optional the filename where a recent version of the feed is saved. If not specified, the filename is $_SERVER["PHP_SELF"] with the extension changed to .xml (see _generateFilename()).
  398.     * @param timeout int      optional the timeout in seconds before a cached version is refreshed (defaults to 3600 = 1 hour)
  399.     */
  400.    function useCached($format="RSS0.91"$filename=""$timeout=3600{
  401.       $this->_setFormat($format);
  402.       $this->_feed->useCached($filename$timeout);
  403.    }
  404.  
  405. }
  406.  
  407.  
  408. /**
  409.  * @package rss
  410.  *  FeedCreator is the abstract base implementation for concrete
  411.  *  implementations that implement a specific format of syndication.
  412.  *
  413.  * @abstract
  414.  * @author Kai Blankenhorn <kaib@bitfolge.de>
  415.  * @since 1.4
  416.  */
  417. class FeedCreator extends HtmlDescribable {
  418.  
  419.     /**
  420.      * Mandatory attributes of a feed.
  421.      */
  422.     var $title$description$link;
  423.  
  424.  
  425.     /**
  426.      * Optional attributes of a feed.
  427.      */
  428.  
  429.     /**
  430.     * The url of the external xsl stylesheet used to format the naked rss feed.
  431.     * Ignored in the output when empty.
  432.     */
  433.     var $xslStyleSheet = "";
  434.  
  435.  
  436.     /**
  437.      * @access private
  438.      */
  439.     var $items Array();
  440.  
  441.  
  442.     /**
  443.      * This feed's MIME content type.
  444.      * @since 1.4
  445.      * @access private
  446.      */
  447.     var $contentType "application/xml";
  448.  
  449.  
  450.     /**
  451.      * This feed's character encoding.
  452.      * @since 1.6.1
  453.      ***/
  454.     var $encoding = "UTF-8";
  455.  
  456.  
  457.     /**
  458.      * Any additional elements to include as an assiciated array. All $key => $value pairs
  459.      * will be included unencoded in the feed in the form
  460.      *     <$key>$value</$key>
  461.      * Again: No encoding will be used! This means you can invalidate or enhance the feed
  462.      * if $value contains markup. This may be abused to embed tags not implemented by
  463.      * the FeedCreator class used.
  464.      */
  465.     var $additionalElements = Array();
  466.  
  467.  
  468.     /**
  469.      * Adds an FeedItem to the feed.
  470.      *
  471.      * @param object FeedItem $item The FeedItem to add to the feed.
  472.      * @access public
  473.      */
  474.     function addItem($item{
  475.         $this->items[$item;
  476.     }
  477.  
  478.  
  479.     /**
  480.      * Truncates a string to a certain length at the most sensible point.
  481.      * First, if there's a '.' character near the end of the string, the string is truncated after this character.
  482.      * If there is no '.', the string is truncated after the last ' ' character.
  483.      * If the string is truncated, " ..." is appended.
  484.      * If the string is already shorter than $length, it is returned unchanged.
  485.      *
  486.      * @static
  487.      * @param string    string A string to be truncated.
  488.      * @param int        length the maximum length the string should be truncated to
  489.      * @return string    the truncated string
  490.      */
  491.     function iTrunc($string$length{
  492.         if (strlen($string)<=$length{
  493.             return $string;
  494.         }
  495.  
  496.         $pos strrpos($string,".");
  497.         if ($pos>=$length-4{
  498.             $string substr($string,0,$length-4);
  499.             $pos strrpos($string,".");
  500.         }
  501.         if ($pos>=$length*0.4{
  502.             return substr($string,0,$pos+1)." ...";
  503.         }
  504.  
  505.         $pos strrpos($string," ");
  506.         if ($pos>=$length-4{
  507.             $string substr($string,0,$length-4);
  508.             $pos strrpos($string," ");
  509.         }
  510.         if ($pos>=$length*0.4{
  511.             return substr($string,0,$pos)." ...";
  512.         }
  513.  
  514.         return substr($string,0,$length-4)." ...";
  515.  
  516.     }
  517.  
  518.  
  519.     /**
  520.      * Creates a comment indicating the generator of this feed.
  521.      * The format of this comment seems to be recognized by
  522.      * Syndic8.com.
  523.      */
  524.     function _createGeneratorComment({
  525.         return "<!-- generator=\"".FEEDCREATOR_VERSION."\" -->\n";
  526.     }
  527.  
  528.  
  529.     /**
  530.      * Creates a string containing all additional elements specified in
  531.      * $additionalElements.
  532.      * @param    elements    array    an associative array containing key => value pairs
  533.      * @param indentString    string    a string that will be inserted before every generated line
  534.      * @return    string    the XML tags corresponding to $additionalElements
  535.      */
  536.     function _createAdditionalElements($elements$indentString=""{
  537.         $ae "";
  538.         if (is_array($elements)) {
  539.             foreach($elements AS $key => $value{
  540.                 $ae.= $indentString."<$key>$value</$key>\n";
  541.             }
  542.         }
  543.         return $ae;
  544.     }
  545.  
  546.     function _createStylesheetReferences({
  547.         $xml "";
  548.         if (!empty($this->cssStyleSheet)) {
  549.             $xml .= "<?xml-stylesheet href=\"".$this->cssStyleSheet."\" type=\"text/css\"?>\n";
  550.         else {
  551.             $xml .= "<?xml-stylesheet href=\"http://www.w3.org/2000/08/w3c-synd/style.css\" type=\"text/css\"?>\n";
  552.         }
  553.         if (!empty($this->xslStyleSheet)) $xml .= "<?xml-stylesheet href=\"".$this->xslStyleSheet."\" type=\"text/xsl\"?>\n";
  554.         return $xml;
  555.     }
  556.  
  557.  
  558.     /**
  559.      * Builds the feed's text.
  560.      * @abstract
  561.      * @return    string    the feed's complete text
  562.      */
  563.     function createFeed({
  564.     }
  565.  
  566.     /**
  567.      * Generate a filename for the feed cache file. The result will be $_SERVER["PHP_SELF"] with the extension changed to .xml.
  568.      * For example:
  569.      *
  570.      * echo $_SERVER["PHP_SELF"]."\n";
  571.      * echo FeedCreator::_generateFilename();
  572.      *
  573.      * would produce:
  574.      *
  575.      * /rss/latestnews.php
  576.      * latestnews.xml
  577.      *
  578.      * @return string the feed cache filename
  579.      * @since 1.4
  580.      * @access private
  581.      */
  582.     function _generateFilename({
  583.         $fileInfo pathinfo($_SERVER["PHP_SELF"]);
  584.         return substr($fileInfo["basename"],0,-(strlen($fileInfo["extension"])+1)).".xml";
  585.     }
  586.  
  587.  
  588.     /**
  589.      * @since 1.4
  590.      * @access private
  591.      */
  592.     function _redirect($filename{
  593.         // attention, heavily-commented-out-area
  594.  
  595.         // maybe use this in addition to file time checking
  596.         //Header("Expires: ".date("r",time()+$this->_timeout));
  597.  
  598.         /* no caching at all, doesn't seem to work as good:
  599.         Header("Cache-Control: no-cache");
  600.         Header("Pragma: no-cache");
  601.         */
  602.  
  603.         // HTTP redirect, some feed readers' simple HTTP implementations don't follow it
  604.         //Header("Location: ".$filename);
  605.  
  606.         Header("Content-Type: ".$this->contentType."; charset=".$this->encoding."; filename=".basename($filename));
  607.         Header("Content-Disposition: inline; filename=".basename($filename));
  608.         readfile($filename"r");
  609.         die();
  610.     }
  611.  
  612.     /**
  613.      * Turns on caching and checks if there is a recent version of this feed in the cache.
  614.      * If there is, an HTTP redirect header is sent.
  615.      * To effectively use caching, you should create the FeedCreator object and call this method
  616.      * before anything else, especially before you do the time consuming task to build the feed
  617.      * (web fetching, for example).
  618.      * @since 1.4
  619.      * @param filename    string    optional    the filename where a recent version of the feed is saved. If not specified, the filename is $_SERVER["PHP_SELF"] with the extension changed to .xml (see _generateFilename()).
  620.      * @param timeout    int        optional    the timeout in seconds before a cached version is refreshed (defaults to 3600 = 1 hour)
  621.      */
  622.     function useCached($filename=""$timeout=3600{
  623.         $this->_timeout $timeout;
  624.         if ($filename==""{<