<?php
/*
* Copyright 2003 - 2005 Mark O'Sullivan
* This file is part of Vanilla.
* Vanilla is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
* Vanilla is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with Vanilla; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
* The latest source code for Vanilla is available at www.lussumo.com
* Contact Mark O'Sullivan at mark [at] lussumo [dot] com
*
* Description: A method for displaying recent/ongoing discussions as RSS entries. Really just a hack of Mark's feed builder feeds/index.php
*/

include("./appg/settings.php");
include(
agAPPLICATION_PATH."appg/headers.php");
include(
sgLIBRARY."Utility.Functions.php");
include(
sgLIBRARY."Utility.Database.class.php");
include(
sgLIBRARY."Utility.SqlBuilder.class.php");
include(
sgLIBRARY."Utility.MessageCollector.class.php");
include(
sgLIBRARY."Utility.ErrorManager.class.php");
include(
sgLIBRARY."Utility.ObjectFactory.class.php");
include(
sgLIBRARY."Utility.StringManipulator.class.php");
include(
sgLIBRARY."Utility.Context.class.php");
include(
sgLIBRARY."Utility.Page.class.php");
include(
sgLIBRARY."Utility.Writer.class.php");
include(
sgLIBRARY."Utility.Control.class.php");
include(
sgLIBRARY."Vanilla.Functions.php");
include(
sgLIBRARY."Vanilla.Session.class.php");
include(
sgLIBRARY."Vanilla.User.class.php");

$Context = new Context();

define("DATE_FORMAT""Y-m-d\TH:i:sO");
$Type ForceIncomingString("Type""");
$WritePage 1;
$UserIsAuthenticated 1;
// Create a class to hold a feed entry
class FeedEntry {
   var 
$Title;
   var 
$Link;
   var 
$Id;
   var 
$Published;
   var 
$Updated;
   var 
$AuthorName;
   var 
$AuthorUrl;
   var 
$Summary;
   var 
$Content;
   var 
$Category;
   var 
$CategoryLink;
   
   function 
Clear() {
      
$this->Title "";
      
$this->Link "";
      
$this->Id "";
      
$this->Published "";
      
$this->Updated "";
      
$this->AuthorName "";
      
$this->AuthorUrl "";
      
$this->Summary "";
      
$this->Content "";
      
$this->Category "";
      
$this->CategoryLink "";
   }
   
   function 
GetPropertiesFromDataSet($DataSet, &$Context) {
      
$this->Title FormatHtmlStringInline(ForceString($DataSet["Name"], ""));
      
$this->Link PrependString("http://"AppendFolder(agDOMAIN"comments.php?DiscussionID=".ForceInt($DataSet["DiscussionID"], 0)));
      
$this->Id $this->Link;
      
$this->Published FixDate(@$DataSet["DateCreated"]);
      
$this->Updated FixDate(@$DataSet["DateLastActive"]);
      
$this->AuthorName FormatHtmlStringInline(ForceString($DataSet["AuthUsername"], ""));
      
$this->AuthorUrl PrependString("http://"AppendFolder(agDOMAIN"account.php?u=".ForceInt($DataSet["AuthUserID"], 0)));
      
$this->Content $this->RemoveHtml(ForceString(@$DataSet["Body"], ""));
      
$this->Summary SliceString($this->Content200);
      
$this->Summary str_replace("\r\n"" "$this->Content);
      
$this->Content str_replace("\r\n""<br />"$this->Content);
      
      if (
agUSE_CATEGORIES) {
         
$this->Category FormatStringForDisplay(ForceString($DataSet["Category"], ""), true);
         
$this->CategoryLink "http://".AppendFolder(agDOMAIN"?CategoryID=".ForceInt($DataSet["CategoryID"], 0));
      }
   }
   
   function 
RemoveHtml($InString) {
      
$sReturn strip_tags($InString);
      
$sReturn htmlspecialchars($sReturn);
      return 
$sReturn;
   }
}

function 
FixDate($Date "") {
   if (
$Date == "") {
      
$NewDate date(DATE_FORMATmktime());
   } else {
      
$NewDate date(DATE_FORMATUnixTimestamp($Date));
   }
   
   
// Dates that look like this:
   // 2005-07-23T18:44:53-0400
   // Need to look like this:
   // 2005-07-23T18:44:53-04:00
   
if (strlen($NewDate) != 24) {
      return 
$NewDate;
   } else {
      return 
substr($NewDate022).":".substr($NewDate22);
   }
}
if (
$WritePage) {
   
// Perform some http authentication if public browsing is not enabled.
   
if (!agPUBLIC_BROWSING && $Context->Session->UserID == 0) {
      
$UserIsAuthenticated 0// Assume user is not authenticated
      
$PHP_AUTH_USER ForceString(@$_SERVER["PHP_AUTH_USER"], "");
      
$PHP_AUTH_PW ForceString(@$_SERVER["PHP_AUTH_PW"], "");
      if (
$PHP_AUTH_USER != "" && $PHP_AUTH_PW != "") {
         
// Validate the inputs
         
$s $Context->ObjectFactory->NewContextObject($Context"SqlBuilder");
         
$s->SetMainTable("User""u");
         
$s->AddSelect("UserID""u");
         
$s->AddWhere("Name"FormatStringForDatabaseInput($PHP_AUTH_USER), "=");
         
$s->AddWhere("Password"FormatStringForDatabaseInput($PHP_AUTH_PW), "=""and""md5");
         
$ValidationData $Context->Database->Select($Context$s"Feed""ValidateCredentials""An error occurred while validating user credentials.");
         if (
$Context->Database->RowCount($ValidationData) > 0$UserIsAuthenticated true;
      }         
      if (!
$UserIsAuthenticated) {
         
header('WWW-Authenticate: Basic realm="Private"');
         
header('HTTP/1.0 401 Unauthorized');
      }      
   }

   if (
$UserIsAuthenticated) {
      
// Create a new sqlbuilder to retrieve feed data
      
$s $Context->ObjectFactory->NewContextObject($Context"SqlBuilder");
      
$s->SetMainTable("Discussion""d");
      
$s->AddSelect(array("DiscussionID""CategoryID""AuthUserID""Name""DateCreated""DateLastActive""CountComments"), "d");

      
// Get the first comment
      
$s->AddJoin("Comment""fc""CommentID""d""FirstCommentID""inner join");
      
$s->AddSelect("Body""fc");

      
// Get author
      
$s->AddJoin("User""u""UserID""d""AuthUserID""left join");
      
$s->AddSelect("Name""u""AuthUsername");

      
// Get category
      
$s->AddJoin("Category""c""CategoryID""d""CategoryID""left join");
      
$s->AddSelect("Name""c""Category");
         
      
// Limit to roles with access to this category
      
if ($Context->Session->UserID 0) {
         
$s->AddJoin("CategoryRoleBlock""crb""CategoryID and crb.RoleID = ".$Context->Session->User->RoleID"d""CategoryID""left join");
      } else {
         
$s->AddJoin("CategoryRoleBlock""crb""CategoryID and crb.RoleID = 1""d""CategoryID""left join");
      }
      
$s->AddWhere("coalesce(crb.Blocked, 0)""0""=""and"""00);
      
$s->AddGroupBy("DiscussionID""d");
         
      
// Only show active Discussions
      
$s->AddWhere("d.Active""1""=");
      
      
// Apply category blocks for the current user
      
if ($Context->Session->UserID 0) {
         
$s->AddJoin("CategoryBlock""cb""CategoryID and cb.UserID = ".$Context->Session->UserID"d""CategoryID""left join");
         
$s->AddWhere("coalesce(cb.Blocked,0)"1"<>");
      }
      
      
// Make sure whispers don't come through
      
if ($Context->Session->UserID 0) {
         
$s->AddWhere("d.AuthUserID = ".$Context->Session->UserID." or d.WhisperUserID = ".$Context->Session->UserID." or d.WhisperUserID"0"=""and"""11);
         
$s->EndWhereGroup();
      } else {
         
$s->AddWhere("d.WhisperUserID"0"=""and"""11);
         
$s->AddWhere("d.WhisperUserID"0"=""or""" ,0);
         
$s->AddWhere("d.WhisperUserID""null""is""or""" ,0);
         
$s->EndWhereGroup();
      }
         
      
$s->AddOrderBy("d.DateLastActive""""desc");
      
$s->AddLimit(0agDISCUSSIONS_PER_FEED);
      
$FeedData $Context->Database->Select($Context$s"Feed""GetData""An error occurred while retrieving the feed.");
      
      
$FeedEntry = new FeedEntry();
      if (
$FeedData) {
         
$WritePage 0;
         
         
// Set the content-type so it delivers properly
         
$FirstRow 1;
         if (
$Context->Database->RowCount($FeedData) == 0) {

               
// Begin writing the feed

                  
echo("<h1>No Discussions Yet</h1>");
               
            
         } else {
         
header("Content-Type: text/xml");
?>
<?php 
echo('<?xml version="1.0" encoding="UTF-8"?>'); ?>
<!-- Vanilla -> Google-Sitemap Hack 0.1 -->
<urlset xmlns="http://www.google.com/schemas/sitemap/0.84"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84
    http://www.google.com/schemas/sitemap/0.84/sitemap.xsd">
    <url>
        <loc>http://<?php echo(agDOMAIN); ?></loc>
        <lastmod><?php echo(date("D, d M Y H:i:s O")); ?></lastmod>
        <changefreq>always</changefreq>
        <priority>1.0</priority>
    </url>
    <!-- 
        <title><?php echo(agAPPLICATION_TITLE); ?></title>
        <link>http://<?php echo(agDOMAIN); ?></link>
        <description><?php echo(agAPPLICATION_TITLE); ?></description>
        <pubDate><?php echo(date("D, d M Y H:i:s O")); ?></pubDate>
        <generator>http://getvanilla.com/</generator>
        <language>en</language>
    -->
<?php
 
// Loop through entries      
 
while ($row $Context->Database->GetRow($FeedData)) {
            
$FeedEntry->Clear();
            
$FeedEntry->GetPropertiesFromDataSet($row$Context);
        
// 2005-07-29T20:17:06-07:00
        // Wed, 02 Oct 2002 15:00:00 +0200
        
?>
        <url>
            <title><?php echo($FeedEntry->Title); ?></title>
            <link><?php echo($FeedEntry->Link); ?></link>
            <comments><?php echo($FeedEntry->Link); ?></comments>
            <pubDate><?php echo(date("D, d M Y H:i:s O",$FeedEntry->Published)); ?></pubDate>
            <dc:creator><?php echo($FeedEntry->AuthorName); ?></dc:creator>
            <category><?php echo($FeedEntry->Category); ?></category>
            <guid><?php echo($FeedEntry->Link); ?></guid>
            <description><![CDATA[ <?php echo(strip_tags($FeedEntry->Content)); ?> ]]></description>
            <content:encoded><![CDATA[ <?php echo($FeedEntry->Content); ?> ]]></content:encoded>
        </url>
        <?php
            
}
         } 
?>
</urlset>
      <?php }
   }
}
?>