<?PHP

#
#   Axis--RSS.php
#   An Object to Support RSS 0.92 (Rich Site Summary) Output
#
#   Copyright 2002 Axis Data
#   This code is free software that can be used or redistributed under the
#   terms of Version 2 of the GNU General Public License, as published by the
#   Free Software Foundation (http://www.fsf.org).
#
#   Author:  Edward Almasy (almasy@axisdata.com)
#
#   Part of the AxisPHP library v1.2.5
#   For more information see http://www.axisdata.com/AxisPHP/
#


class RSS {

    # ---- PUBLIC INTERFACE --------------------------------------------------

    function RSS()
    {
        $this->ChannelCount = -1;

        # default encoding is UTF-8
        $this->Encoding = "UTF-8";
    }

    # required channel values
    function AddChannel($Title, $Link, $Description, $RssLink)
    {
        $this->ChannelCount++;
        $this->ItemCounts[$this->ChannelCount] = -1;
        $this->Channels[$this->ChannelCount]["Title"] = $Title;
        $this->Channels[$this->ChannelCount]["Link"] = $Link;
        $this->Channels[$this->ChannelCount]["Description"] = $Description;
        $this->Channels[$this->ChannelCount]["RssLink"] = $RssLink;
    }
    function SetImage($Url, $Height = NULL, $Width = NULL, $Description = NULL)
    {
        $this->Channels[$this->ChannelCount]["ImageUrl"] = $Url;
        $this->Channels[$this->ChannelCount]["ImageHeight"] = $Height;
        $this->Channels[$this->ChannelCount]["ImageWidth"] = $Width;
        $this->Channels[$this->ChannelCount]["ImageDescription"] = $Description;
    }

    # optional channel values
    function SetEncoding($Value) { $this->Encoding = $Value; }
    function SetLanguage($Value) {  $this->Channels[$this->ChannelCount]["Language"] = $Value;  }
    function SetCopyright($Value) {  $this->Channels[$this->ChannelCount]["Copyright"] = $Value;  }
    function SetManagingEditor($Value) {  $this->Channels[$this->ChannelCount]["ManagingEditor"] = $Value;  }
    function SetWebmaster($Value) {  $this->Channels[$this->ChannelCount]["Webmaster"] = $Value;  }
    function SetPicsRating($Value) {  $this->Channels[$this->ChannelCount]["PicsRating"] = $Value;  }
    function SetPublicationDate($Value) {  $this->Channels[$this->ChannelCount]["PublicationDate"] = $this->FormatDate($Value);  }
    function SetLastChangeDate($Value) {  $this->Channels[$this->ChannelCount]["LastChangeDate"] = $this->FormatDate($Value);  }
    function SetTextInput($Title, $Description, $Name)
    {
        $this->Channels[$this->ChannelCount]["TextInputTitle"] = $Title;
        $this->Channels[$this->ChannelCount]["TextInputDescription"] = $Description;
        $this->Channels[$this->ChannelCount]["TextInputName"] = $Name;
    }
    function SetSkipTimes($Days, $Hours)
    {
        # ???
    }
    function SetCloud($Domain, $Port, $Path, $Procedure, $Protocol)
    {
        # ???
    }

    # add item to channel
    function AddItem($Title = NULL, $Link = NULL, $Description = NULL, $Date = NULL)
    {
        $this->ItemCounts[$this->ChannelCount]++;
        $this->Items[$this->ChannelCount][$this->ItemCounts[$this->ChannelCount]]["Title"] = $Title;
        $this->Items[$this->ChannelCount][$this->ItemCounts[$this->ChannelCount]]["Link"] = $Link;
        $this->Items[$this->ChannelCount][$this->ItemCounts[$this->ChannelCount]]["Description"] = $Description;
        $this->Items[$this->ChannelCount][$this->ItemCounts[$this->ChannelCount]]["Date"] = $this->FormatDate($Date);
    }
    function AddItemCategory($Category, $Url)
    {
        $this->Items[$this->ChannelCount][$this->ItemCounts[$this->ChannelCount]]["Category"] = $Category;
        $this->Items[$this->ChannelCount][$this->ItemCounts[$this->ChannelCount]]["CategoryUrl"] = $Url;
    }
    function AddItemEnclosure($Url, $Length, $Type)
    {
        $this->Items[$this->ChannelCount][$this->ItemCounts[$this->ChannelCount]]["EnclosureUrl"] = $Url;
        $this->Items[$this->ChannelCount][$this->ItemCounts[$this->ChannelCount]]["EnclosureLength"] = $Length;
        $this->Items[$this->ChannelCount][$this->ItemCounts[$this->ChannelCount]]["EnclosureType"] = $Type;
    }
    function AddItemSource($Source, $Url)
    {
        $this->Items[$this->ChannelCount][$this->ItemCounts[$this->ChannelCount]]["Source"] = $Source;
        $this->Items[$this->ChannelCount][$this->ItemCounts[$this->ChannelCount]]["SourceUrl"] = $Url;
    }

    # write out and RSS page
    function PrintRSS()
    {
        # print opening elements
        header("Content-type: application/rss+xml; charset=".$this->Encoding, TRUE);
        FTOut("<?xml version='1.0' encoding='".$this->Encoding."' ?>");
        FTOut("<rss version='2.0' xmlns:atom='http://www.w3.org/2005/Atom'>", 0);

        # for each channel
        for ($this->ChannelIndex = 0;  $this->ChannelIndex <= $this->ChannelCount;  $this->ChannelIndex++)
        {
            # open channel element
            FTOut("<channel>");

            # print required channel elements
            $this->PrintChannelElement("Title", "title");
            $this->PrintChannelElement("Link", "link");
            $this->PrintChannelElement("Description", "description");
            FTOut(
                "<atom:link href='"
                .$this->Channels[$this->ChannelCount]["RssLink"]
                ."' rel='self' type='application/rss+xml' />");

            # print image element if set (url, title, link required)
            # title and link should be the same as those for the channel
            if ($this->IsChannelElementSet("ImageUrl"))
            {
                FTOut("<image>");
                $this->PrintChannelElement("ImageUrl", "url");
                $this->PrintChannelElement("Title", "title");
                $this->PrintChannelElement("Link", "link");
                $this->PrintChannelElement("ImageWidth", "width");
                $this->PrintChannelElement("ImageHeight", "height");
                $this->PrintChannelElement("ImageDescription", "description");
                FTOut("</image>");
            }

            # print optional channel elements
            $this->PrintChannelElement("Language", "language");
            $this->PrintChannelElement("Copyright", "copyright");
            $this->PrintChannelElement("ManagingEditor", "managingEditor");
            $this->PrintChannelElement("Webmaster", "webMaster");
            $this->PrintChannelElement("PicsRating", "rating");
            $this->PrintChannelElement("PublicationDate", "pubDate");
            $this->PrintChannelElement("LastChangeDate", "lastBuildDate");
            # ???  STILL TO DO:  SkipDays, SkipHours, Cloud
            FTOut("<docs>http://www.rssboard.org/rss-2-0-1</docs>");

            # for each item in this channel
            for ($this->ItemIndex = 0;  $this->ItemIndex <= $this->ItemCounts[$this->ChannelCount];  $this->ItemIndex++)
            {
                # open item element
                FTOut("<item>");

                # print item elements
                $this->PrintItemElement("Title", "title");
                $this->PrintItemElement("Link", "link");
                $this->PrintItemElement("Link", "guid");
                $this->PrintItemElement("Description", "description");
                $this->PrintItemElement("Date", "pubDate");
                if (isset($this->Items[$this->ChannelIndex][$this->ItemIndex]["Category"])
                        && ($this->Items[$this->ChannelIndex][$this->ItemIndex]["Category"] != NULL))
                {
                    FTOut("<category url='".$this->Items[$this->ChannelIndex][$this->ItemIndex]["CategoryUrl"]."'>");
                    FTOut($this->Items[$this->ChannelIndex][$this->ItemIndex]["Category"]);
                    FTOut("</category>");
                }
                if (isset($this->Items[$this->ChannelIndex][$this->ItemIndex]["EnclosureUrl"])
                        && ($this->Items[$this->ChannelIndex][$this->ItemIndex]["EnclosureUrl"] != NULL))
                {
                    FTOut("<enclosure "
                        ."url='".$this->Items[$this->ChannelIndex][$this->ItemIndex]["EnclosureUrl"]."' "
                        ."length='".$this->Items[$this->ChannelIndex][$this->ItemIndex]["EnclosureLength"]."' "
                        ."type='".$this->Items[$this->ChannelIndex][$this->ItemIndex]["EnclosureType"]."' />");
                }
                if (isset($this->Items[$this->ChannelIndex][$this->ItemIndex]["Source"])
                        && ($this->Items[$this->ChannelIndex][$this->ItemIndex]["Source"] != NULL))
                {
                    FTOut("<source url='".$this->Items[$this->ChannelIndex][$this->ItemIndex]["SourceUrl"]."'>");
                    FTOut($this->Items[$this->ChannelIndex][$this->ItemIndex]["Source"]);
                    FTOut("</source>");
                }

                # close item element
                FTOut("</item>");
            }

            # close channel element
            FTOut("</channel>");
        }

        # print closing elements
        FTOut("</rss>");
    }


    # ---- PRIVATE INTERFACE -------------------------------------------------

    var $Encoding;
    var $Channels;
    var $Items;
    var $ChannelCount;
    var $ItemCounts;
    var $ChannelIndex;
    var $ItemIndex;

    /**
     * Determine whether a channel element is set.
     * @param $VarName channel element name
     * @return TRUE if the element is set, FALSE otherwise
     */
    private function IsChannelElementSet($VarName)
    {
        return (isset($this->Channels[$this->ChannelIndex][$VarName])
                && $this->Channels[$this->ChannelIndex][$VarName] != NULL
                && strlen($this->Channels[$this->ChannelIndex][$VarName]));
    }

    /**
     * Determine whether an item element is set.
     * @param $VarName item element name
     * @return TRUE if the element is set, FALSE otherwise
     */
    private function IsItemElementSet($VarName)
    {
        return (isset($this->Items[$this->ChannelIndex][$this->ItemIndex][$VarName])
                && $this->Items[$this->ChannelIndex][$this->ItemIndex][$VarName] != NULL);
    }

    /**
     * Print a channel element if it is set.
     * @param $VarName item element name
     * @param $TagName item tag name
     */
    private function PrintChannelElement($VarName, $TagName)
    {
        # only print channel elements if set
        if (!$this->IsChannelElementSet($VarName))
        {
            return;
        }

        $InnerText = $this->EscapeInnerText(
            $this->Channels[$this->ChannelIndex][$VarName]);

        FTOut("<${TagName}>".$InnerText."</${TagName}>");
    }

    /**
     * Print an item element if it is set.
     * @param $VarName item element name
     * @param $TagName item tag name
     */
    private function PrintItemElement($VarName, $TagName)
    {
        # only print elements that are set
        if (!$this->IsItemElementSet($VarName))
        {
            return;
        }

        $InnerText = $this->EscapeInnerText(
            $this->Items[$this->ChannelIndex][$this->ItemIndex][$VarName]);

        FTOut("<${TagName}>".$InnerText."</${TagName}>");
    }

    /**
     * Transform dates to the format specified by the RSS specification and
     * best practices. See:
     * http://www.rssboard.org/rss-profile#data-types-datetime
     * @param $Value date value
     * @return formatted date value
     */
    private function FormatDate($Value)
    {
        return date("D, j M Y H:i:s O", strtotime($Value));
    }

    /**
     * Escape text destined for a RSS element. See:
     * http://www.rssboard.org/rss-profile#data-types-characterdata
     * @param $Text text destined for a RSS element
     * @return escaped text
     */
    private function EscapeInnerText($Text)
    {
        # remove control characters
        $Intermediate = preg_replace("/[\\x00-\\x1F]+/", "", $Text);

        # escape XML special characters for PHP version < 5.2.3
        if (version_compare(phpversion(), "5.2.3", "<"))
        {
            $Intermediate = htmlspecialchars(
                $Intermediate, ENT_QUOTES, $this->Encoding);
        }

        # escape XML special characters for PHP version >= 5.2.3
        else
        {
            $Intermediate = htmlspecialchars(
                $Intermediate, ENT_QUOTES, $this->Encoding, FALSE);
        }

        # map named entities to their hex references
        $Replacements = array(
            "&amp;" => "&#x26;",
            "&lt;" => "&#x3C;",
            "&gt;" => "&#x3E;",
            "&quot;" => "&#x22;",
            "&#039;" => "&#x27;");

        # replace named entities with hex references for compatibility as
        # specified by the RSS spec/best practices
        $Intermediate = str_replace(
            array_keys($Replacements),
            array_values($Replacements),
            $Intermediate);

        return $Intermediate;
    }

}

# (FTOut == Formatted Tag Output)
function FTOut($String, $NewIndent = NULL)
{
    static $Indent = 0;

    $IndentSize = 4;

    # decrease indent if string contains end tag and does not start with begin tag
    if (preg_match("/<\/[A-Za-z0-9]+>/", $String) && !preg_match("/^<[^\/]+/", $String)) {  $Indent--;  }

    # reset indent if value is supplied
    if ($NewIndent != NULL) {  $Indent = $NewIndent;  }

    # print string
    print(substr("                                                                                                                        ",
            0, ($Indent * $IndentSize)).$String."\n");

    # inrease indent if string starts with begin tag and does not contain end tag
    if (preg_match("/^<[^\/]+/", $String)
            && !preg_match("/<\/[A-Za-z0-9]+>/", $String)
            && !preg_match("/\/>$/", $String))
    {
        $Indent++;
    }
}
