<?php

/* 
 *	W-AGORA 4.2
 *	-----------
 *	$Id: rss.php,v 1.7 2005/12/23 10:30:07 mdruilhe Exp $
 *	Usage:		XML/RSS feed generator
 *	Authors:	Ron Friedman (friedman@filmmaker.com)
 *				Marc Druilhe <mdruilhe@w-agora.com>
 *				David Horwitz <dhorwitz@ched.uct.ac.za>
 *	Usage:		displays (10) last messages from one/all forum[s] in RSS format
 *
 *	Parameters:
 *
 *  site	site name
 *	bn		forum name, either bn or site must be set
 *	n		Number of messages to display (default: 10)
 *	noprint	if set to 1 or true, then return the list as a string ($list) instead of printing it out
 */

#-----------------------------------------------------------------------
# RSS/My Netscape Network channel box generator for W-Agora (4.x)
#
# By Ron Friedman (friedman@filmmaker.com)
#
# Reference:  http://my.netscape.com/publish/help/mnn20/quickstart.html         
#
# WHAT THIS DOES:
#
# If you've ever used Slashdot (www.slashdot.org), Mozilla, or Netscape
# Netcenter, you've probably seen those "boxes" with links to news from
# other sites.  How are they done?  They're special files that
# use a format called RSS.  Read about it at the link above.  The Mozilla
# sidebar panels use a similar format called RDF, but you can convert from
# RSS to RDF pretty easily.
#
# Anyway, this php script creates a "dynamic" RSS file using a w-agora
# forum.  The most recent posts are treated as "news items" in the RSS code.
#
# Here's an example:  http://my.netscape.com/addchannel.tmpl?service=net.2960
#
# To use, just fill out the variables below, throw this up on your site,
# maybe rename it to index.php so that you can just use a directory,
# check the validity with the validity checker (see the page above),
# and register with Netcenter.  You might also register with DMOZ
# (http://www.dmoz.org).  Read the reference link above for more info.
#
# Note-- Not *everything* in the RSS spec is used here.  The program is
# fairly simple to figure out, so you can add or modify stuff very
# quickly.
#
# Once you're done with your RSS file, you can register it with
# My Netscape here:
# http://my.netscape.com/publish  
#
# And you can make it into a Mozilla/Netscape 6 sidebar here:
# http://www.theonering.net/staff/corvar/cgi-bin/sidebar-inst.pl
#
# If someone should fix it or verify it works, please update this file's
# version # in CVS (if this ever makes it to CVS)
#
# Thanks,  Ron
#-----------------------------------------------------------------------

# STUFF YOU SHOULD CHANGE

# Adjust to the w-agora directory
// eg: define ('WA_PATH', '/path/to/w-agora');
//	define ('WA_PATH', '..');

# Basic info:
# ----------
# Link to the forum URL : usually set in $bn_base_url from globals.inc
// $link = "http://".$_SERVER["HTTP_HOST"].str_replace($WA_SELF,"",$_SERVER["PHP_SELF"]);

# How many news messages to show, can be overwritten from the url : (n=xx)
$itemcount = 10;

# Language can be taken from $lang set in globals.inc
// $language = "en-us";

# OPTIONAL:  add copyright information here (...or just comment out)
$copyright = "Copyright " . Date("Y") . ", w-agora";

# OPTIONAL:  Fill the below (and uncomment) if you have an image
# The maximum allowed image size is 144 pixels (width) x 400 pixels
# (height).  The description will be a caption.

#$imageurl = "";
#$imagetitle = "";
#$imagelink = "";
#$imageheight = 0;
#$imagewidth = 0;
#$imagedescription = "";

# OPTIONAL:  If you want to add a little form at the bottom of your slashbox,
#            customize the following.  Otherwise, comment it out
#            or set $button = "";

/*
$button = "
     <textinput>
       <title>Search</title>
       <description>Enter String</description>
       <name>search</name>
       <link>http://www.mysite.com/search.php</link>
     </textinput>
";
*/
  
#-----------------------------------
# Don't touch anything below
# unless you know what you're doing
#-----------------------------------

	if (!file_exists("globals.inc")) {
		chdir(WA_PATH);	
	}

	$no_cookie = 1;

	include ("globals.inc");
	include ("include/misc_func.$ext");

	$bn =  preg_replace("/[^a-zA-Z0-9_]/", "", getFormVar('bn'));
	$site =  preg_replace("/[^a-zA-Z0-9_]/", "", getFormVar('site'));

	if (empty($bn) && (empty($site) || $site=='agora') ) {
		die("you must select a forum or a site");
	}

	$itemcount = (int) getFormVar('n', $itemcount);
	$language = (empty ($language)) ? $lang : $language;
	$generator = wa_version();

	if (empty ($bn) ) {
		$site = basename($site);
		include ("$cfg_dir/site_${site}.$ext");
	} else {
		$bn = basename($bn);
		include ("$cfg_dir/$bn.$ext");
	}

	// Open database connection
	$_dbparam = getDBaccess($site);
	extract($_dbparam);
	include ("$inc_dir/$bn_access.$ext");
	$db_class = "${bn_access}_access";
	$db = new $db_class;
	$ret = $db->openDB($dbhost, $dbport, $dbuser, $dbpassword, $dbname, $site);

	// Check if the user is authenticated, we only can use HTTP authentication, since most RSS readers
	// don't support cookies authentication
	if (isset($_SERVER['PHP_AUTH_USER'])) {
		include ("$user_dir/agora_user.$ext");
		$auth =& new agora_user_source;
		$is_authenticated = $auth->authenticate($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
	} else {
		$is_authenticated = false;
	}

	$tables = array();
	$notes = array();

	if (empty ($bn) ) {
		$link = "$bn_base_url/$main_page?site=$site";
		$db->query("SELECT bn_title, descr FROM $site WHERE cle=0");
		if ($db->next_record() ) {
			$title = $db->f('bn_title');
			$description =  htmlspecialchars(stripslashes($db->f('descr')));
		}

		$where = "S.category=0 AND S.state != '0' AND S.rank != 0";
		if ($is_authenticated) {
			if ($auth->level < ADMIN) {			
				$userid = $this->preserveQuotes($auth->userid);
				$from = "$site S LEFT JOIN ${site}_userforum UF ON (S.bn_name=UF.bn_name AND UF.userid = '$userid')";
				$where .= " AND (S.type != 'priv' OR UF.listpriv=1)";
			} else {
				$from = "$site S";
			}
		} else {
			$from = "$site S";
			$where .= " AND (S.type != 'priv')";
		}

		$db->query("SELECT DISTINCT bn_db, bn_name FROM $from WHERE $where");
		while ($db->next_record() ) {
			$bn_db = $db->f('bn_db');
			$tables [$bn_db] = $db->f('bn_name');
		}
	} else {
		$link = "$bn_base_url/$main_page?bn=$bn";

		$has_private_access = false;
		$db->query("SELECT type FROM $site WHERE bn_name='$bn'");
		if ($db->next_record() ) {
			$type = $db->f('type');
		}
		if ($type=='priv') {
			if ($is_authenticated) {
				$has_private_access = $auth->havePermission ($bn, 'R'); 	
			} else {
				header("WWW-Authenticate: Basic realm=\"$site\"");
				header("HTTP/1.0 401 Unauthorized");
				print("You must enter a valid login username and password to access this resource.\n");
				exit;
			}
		} else {
			$has_private_access = true;
		}

		$where = "bn_name='$bn' AND category=0 AND state != '0' AND rank != 0";
		if (! $has_private_access) {
			$where .= " AND type!='priv'";
		}

		$db->query("SELECT bn_db, bn_name, bn_title, descr FROM $site WHERE $where");
		if ($db->next_record() ) {
			$bn_db = $db->f('bn_db');
			$tables[$bn_db] = $db->f('bn_name');
			$title = $db->f('bn_title');
			$description =  htmlspecialchars(stripslashes($db->f('descr')));
		}
	}

	foreach($tables as $table=>$bn) {
		// order by last updated thread
		// $q = "select cle, username, subject, unixdate, summary, body, childs from $bn where parent = 0 order by unixdate DESC LIMIT $itemcount";

		// Gets all last posts
		$q = "SELECT cle, username, useraddress, subject, unixdate, summary, body, childs from $table WHERE hidden=0 ORDER BY unixdate DESC LIMIT $itemcount";
		$result = $db->query ("$q");
		while ($db->next_record() ) {
			$k = $db->f("unixdate");
			$notes[$k] = $db->Record;
			$notes[$k]["bn"] = $bn;
		}
	}

	$db->closeDB();

	// sort by reverse order
	krsort ($notes);

	header("Expires: Mon, 2 Aug 1999 05:00:00 GMT"); // Date in the past
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
	header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
	header("Pragma: no-cache"); // HTTP/1.0

	header("Content-type: text/xml");
	echo "<" . "?xml version=\"1.0\" encoding=\"iso-8859-1\"?" . ">";
	echo "<" . "?xml-stylesheet href=\"rss.css\" type=\"text/css\"?" . ">";
	echo "<" . "?xml-stylesheet href=\"rss.xsl\" type=\"text/xsl\"?" . ">";
?>

 <rss version="2.0"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
 >
   <channel>

<?php
	echo "     <title>$title</title>\n";
	echo "     <link>$link</link>\n";
	echo "     <description>$description</description>\n";
	echo "     <language>$language</language>\n";
	echo "     <copyright>$copyright</copyright>\n";
	echo "     <generator>$generator</generator>\n";

# Publication date (rss file created at...)
	$pubdate = gmdate('D, d M Y H:i:s', $now). ' GMT';
	echo "     <pubDate>$pubdate</pubDate>\n";

# RSS Last updated at...
	reset($notes);
	$last_note = key($notes);
	$lastbuilddate = gmdate('D, d M Y H:i:s', $last_note) . ' GMT';
	echo "     <lastBuildDate>$lastbuilddate</lastBuildDate>\n";

if ($imageurl)
    echo "
    <image>
       <title>$imagetitle</title>
       <url>$imageurl</url>
       <link>$imagelink</link>
       <width>$imagewidth</width>
       <height>$imageheight</height>
       <description>$imagedescription</description>
     </image>
";

	$i = 0;
	// loop for items
	foreach($notes as $note) {
		if (++$i > $itemcount) break;

		$key = $note["cle"];
		$bn = $note["bn"];
		$link = "$bn_base_url/view.$ext?bn=$bn&amp;key=$key";
		$title = htmlspecialchars(stripslashes($note["subject"]));
		//$description =  htmlspecialchars(substr(strip_smileys($note["body"]), 0, 200));
		$description =  htmlspecialchars(stripslashes($note["summary"]));
		$date = gmdate('D, d M Y H:i:s', $note["unixdate"]). ' GMT';
		//$date = gmdate('Y-m-d\TH:i:s', $note["unixdate"]). '+00:00';
		$author = stripslashes($note["username"]).' &lt;'. stripslashes($note['useraddress']).'&gt;';

		echo "     <item>\n";
		echo "       <title>$title</title>\n";
		echo "       <link>$link</link>\n";
		#
		# modify & uncomment below to add a description.  Note that the example only shows #
		# of 1st level replies to the news item.  It's dumb so I didn't use it.  You can make
		# it smarter, or have it use the first paragraph of your news item, or whatever. I
		# think you're limited to 500 characters though.
		#
		# echo "  <description>$replies replies</description>\n";
		echo "       <description>$description</description>\n";
		echo "       <author>$author</author>\n";
		echo "       <pubDate>$date</pubDate>\n";
		echo "       <guid isPermaLink=\"true\">$link</guid>\n";
		echo "     </item>\n";
	}

	echo $button;
?>

   </channel>
   
 </rss>
